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
feat: RBAC (#37107)
Wu Tianwei33edf97f8181
diff --git a/.github/workflows/build-push.yml b/.github/workflows/build-push.ymlindex 247e0a57a67..2ff4e8c2123 100644--- a/.github/workflows/build-push.yml+++ b/.github/workflows/build-push.yml@@ -9,6 +9,7 @@ on:- "release/e-*"- "hotfix/**"- "feat/hitl-backend"+ - "feat/rbac"tags:- "*"diff --git a/api/commands/__init__.py b/api/commands/__init__.pyindex ea4c5aaa2a8..94321ed1e49 100644--- a/api/commands/__init__.py+++ b/api/commands/__init__.py@@ -22,6 +22,7 @@ from .plugin import (setup_system_trigger_oauth_client,transform_datasource_credentials,)+from .rbac import migrate_member_roles_to_rbacfrom .retention import (archive_workflow_runs,clean_expired_messages,@@ -74,6 +75,7 @@ __all__ = ["migrate_annotation_vector_database","migrate_data_for_plugin","migrate_knowledge_vector_database",+ "migrate_member_roles_to_rbac","migrate_oss","migration_data_wizard","old_metadata_migration",diff --git a/api/commands/rbac.py b/api/commands/rbac.pynew file mode 100644index 00000000000..33eb5858da4--- /dev/null+++ b/api/commands/rbac.py@@ -0,0 +1,112 @@+from __future__ import annotations++import click+from sqlalchemy import select++from core.db.session_factory import session_factory+from models import TenantAccountJoin, TenantAccountRole+from services.enterprise.rbac_service import ListOption, RBACService+++def _resolve_builtin_role_id(tenant_id: str, operator_account_id: str, legacy_role: str) -> str:+ """Resolve a legacy workspace role to the current tenant's builtin RBAC role id.++ The migration replays the old `TenantAccountJoin.role` values onto the+ RBAC member-role binding API. Builtin RBAC roles are tenant-scoped and+ identified by runtime ids, so the command must look them up per tenant.+ """+ expected_builtin_tag = {+ TenantAccountRole.OWNER.value: "owner",+ TenantAccountRole.ADMIN.value: "admin",+ TenantAccountRole.EDITOR.value: "editor",+ TenantAccountRole.NORMAL.value: "normal",+ TenantAccountRole.DATASET_OPERATOR.value: "dataset_operator",+ }.get(legacy_role)+ if not expected_builtin_tag:+ raise ValueError(f"Unsupported legacy workspace role: {legacy_role}")++ roles = RBACService.Roles.list(+ tenant_id=tenant_id,+ account_id=operator_account_id,+ options=ListOption(page_number=1, results_per_page=100),+ ).data+ for role in roles:+ if role.is_builtin and role.category == "global_system_default" and role.role_tag == expected_builtin_tag:+ return str(role.id)++ raise ValueError(f"Builtin RBAC role not found for tenant={tenant_id}, legacy_role={legacy_role}")+++ "rbac-migrate-member-roles", help="Migrate legacy workspace member roles into RBAC member-role bindings."+)[email protected]("--tenant-id", help="Only migrate a single workspace.")[email protected]("--dry-run", is_flag=True, default=False, help="Preview the migration without writing RBAC bindings.")+def migrate_member_roles_to_rbac(tenant_id: str | None, dry_run: bool) -> None:+ """Backfill RBAC member-role bindings from legacy `TenantAccountJoin.role` data.++ This is an offline migration command for workspaces that already have+ members in the legacy role model but need matching records in the RBAC+ member-role binding store.+ """+ click.echo(click.style("Starting RBAC member-role migration.", fg="green"))++ with session_factory.create_session() as session:+ stmt = select(TenantAccountJoin).order_by(TenantAccountJoin.tenant_id.asc(), TenantAccountJoin.id.asc())+ if tenant_id:+ stmt = stmt.where(TenantAccountJoin.tenant_id == tenant_id)++ joins = list(session.scalars(stmt).all())++ if not joins:+ click.echo(click.style("No workspace members found for migration.", fg="yellow"))+ return++ owner_account_by_tenant: dict[str, str] = {}+ resolved_role_ids: dict[tuple[str, str], str] = {}+ migrated_count = 0++ for join in joins:+ workspace_id = str(join.tenant_id)+ member_account_id = str(join.account_id)+ legacy_role = str(join.role)++ if workspace_id not in owner_account_by_tenant:+ owner_join = next(+ (+ item+ for item in joins+ if str(item.tenant_id) == workspace_id and str(item.role) == TenantAccountRole.OWNER.value+ ),+ None,+ )+ if not owner_join:+ raise ValueError(f"Workspace owner not found for tenant={workspace_id}")+ owner_account_by_tenant[workspace_id] = str(owner_join.account_id)++ operator_account_id = owner_account_by_tenant[workspace_id]+ cache_key = (workspace_id, legacy_role)+ if cache_key not in resolved_role_ids:+ resolved_role_ids[cache_key] = _resolve_builtin_role_id(workspace_id, operator_account_id, legacy_role)++ resolved_role_id = resolved_role_ids[cache_key]+ click.echo(+ f"tenant={workspace_id} member={member_account_id} "+ f"legacy_role={legacy_role} -> rbac_role_id={resolved_role_id}"+ )++ if dry_run:+ continue++ RBACService.MemberRoles.replace(+ tenant_id=workspace_id,+ account_id=operator_account_id,+ member_account_id=member_account_id,+ role_ids=[resolved_role_id],+ )+ migrated_count += 1++ if dry_run:+ click.echo(click.style("Dry run completed. No RBAC bindings were written.", fg="yellow"))+ else:+ click.echo(click.style(f"RBAC member-role migration completed. Migrated {migrated_count} members.", fg="green"))diff --git a/api/configs/enterprise/__init__.py b/api/configs/enterprise/__init__.pyindex 705ea67bcbc..2c0eaeeb81b 100644--- a/api/configs/enterprise/__init__.py+++ b/api/configs/enterprise/__init__.py@@ -29,6 +29,11 @@ class EnterpriseFeatureConfig(BaseSettings):"This helps gain runtime performance by trading off consistency.",)+ RBAC_ENABLED: bool = Field(+ description="Enable enterprise RBAC APIs. When disabled, compatibility responses fall back to legacy roles.",+ default=False,+ )+class EnterpriseTelemetryConfig(BaseSettings):"""diff --git a/api/controllers/common/fields.py b/api/controllers/common/fields.pyindex 06d68a5df16..6a0b35aa633 100644--- a/api/controllers/common/fields.py+++ b/api/controllers/common/fields.py@@ -153,6 +153,7 @@ class ApiBaseUrlResponse(ResponseModel):class NewAppResponse(ResponseModel):new_app_id: str+ permission_keys: list[str] = Field(default_factory=list)class Parameters(BaseModel):diff --git a/api/controllers/common/wraps.py b/api/controllers/common/wraps.pyindex c481f6eca94..7e39b4f37cd 100644--- a/api/controllers/common/wraps.py+++ b/api/controllers/common/wraps.py@@ -1,7 +1,36 @@+"""Shared decorator utilities for Dify controller layers.++This module provides decorators that are not tied to any single API group (e.g.+console, inner, service). Currently it exposes the RBAC permission gate, which+can be applied to any blueprint.++Key exports+-----------+``rbac_permission_required`` – decorator that enforces enterprise RBAC access+ control. When ``RBAC_ENABLED`` is ``False`` it is a no-op.++``RBACPermission``, ``RBACResourceScope`` – re-exported from ``core.rbac`` so+ callers only need a single import site.++Private helpers+---------------+``_extract_resource_id``, ``_is_resource_owned_by_current_user`` – kept module-+ private but accessible via the module namespace for unit-test patching.+"""+from collections.abc import Callablefrom functools import wraps+from sqlalchemy import select+from werkzeug.exceptions import Forbidden, NotFound++from configs import dify_configfrom core.rbac import RBACPermission, RBACResourceScope+from extensions.ext_database import db+from libs.login import current_account_with_tenant+from models.dataset import Dataset+from models.model import App+from services.enterprise.rbac_service import RBACService__all__ = ["RBACPermission", "RBACResourceScope", "rbac_permission_required"]@@ -14,17 +43,105 @@ def rbac_permission_required[**P, R]() -> Callable[[Callable[P, R]], Callable[P, R]]:"""Check enterprise RBAC permissions for the current user.+ When ``RBAC_ENABLED`` is ``False`` the decorator is a no-op and the+ request passes through unchanged. When enabled it extracts the resource ID+ from ``request.view_args`` for resource-scoped checks, calls the RBAC+ service ``check-access`` endpoint, and raises ``Forbidden`` if the access+ is denied. For workspace-level checks, set ``resource_required=False`` so+ the RBAC request omits ``resource_id``.+Args:resource_type: The :class:`RBACResourceScope` member (app/dataset/workspace).- scene: The :class:`RBACPermission` permission point.+ scene: The :class:`RBACPermission` permission point, e.g. ``RBACPermission.APP_DELETE``.resource_required: Whether a concrete resource ID is required."""def decorator(view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs) -> R:+ if not dify_config.RBAC_ENABLED:+ return view(*args, **kwargs)++ current_user, current_tenant_id = current_account_with_tenant()+ check_resource_type = None if resource_type == RBACResourceScope.WORKSPACE else resource_type+ resource_id = None+ if resource_required and check_resource_type:+ resource_id = _extract_resource_id(resource_type, kwargs)+ if _is_resource_owned_by_current_user(current_tenant_id, current_user.id, resource_type, resource_id):+ return view(*args, **kwargs)+ allowed = RBACService.CheckAccess.check(+ current_tenant_id,+ current_user.id,+ scene=scene,+ resource_type=check_resource_type,+ resource_id=resource_id,+ )++ if not allowed:+ raise Forbidden()+return view(*args, **kwargs)return decoratedreturn decorator+++def _is_resource_owned_by_current_user(+ tenant_id: str, account_id: str, resource_type: RBACResourceScope, resource_id: str+) -> bool:+ if resource_type == RBACResourceScope.APP:+ maintainer = db.session.scalar(+ select(App.maintainer).where(+ App.id == resource_id,+ App.tenant_id == tenant_id,+ App.status == "normal",+ )+ )+ return maintainer == account_id++ if resource_type == RBACResourceScope.DATASET:+ maintainer = db.session.scalar(+ select(Dataset.maintainer).where(+ Dataset.id == resource_id,+ Dataset.tenant_id == tenant_id,+ )+ )+ return maintainer == account_id++ return False+++def _extract_resource_id(resource_type: RBACResourceScope, path_args: dict[str, object] | None = None) -> str:+ """Extract the resource ID from matched path arguments.++ Some legacy route classes use neutral names such as ``resource_id`` for+ app/dataset resources, and Agent App routes use ``agent_id`` as the app id.+ Dataset endpoints behind a rag-pipeline route contain ``pipeline_id``+ instead of ``dataset_id``. In that case we look up the associated+ ``Dataset`` row via ``Dataset.pipeline_id``.+ """+ from flask import request++ view_args = request.view_args or {}+ matched_args = {**view_args, **(path_args or {})}++ if resource_type == RBACResourceScope.APP:+ app_id = matched_args.get("app_id") or matched_args.get("agent_id") or matched_args.get("resource_id")+ if not app_id:+ raise ValueError("Missing app_id in request path")+ return str(app_id)++ if resource_type == RBACResourceScope.DATASET:+ dataset_id = matched_args.get("dataset_id") or matched_args.get("resource_id")+ if dataset_id:+ return str(dataset_id)++ pipeline_id = matched_args.get("pipeline_id")+ if pipeline_id:+ dataset = db.session.scalar(select(Dataset).where(Dataset.pipeline_id == str(pipeline_id)))+ if not dataset:+ raise NotFound("Dataset not found for pipeline")+ return str(dataset.id)+ raise ValueError("Missing dataset_id or pipeline_id in request path")+ raise ValueError(f"Unknown resource_type: {resource_type}")diff --git a/api/controllers/console/__init__.py b/api/controllers/console/__init__.pyindex e2bf0bd22ce..cd8d6e0ab46 100644--- a/api/controllers/console/__init__.py+++ b/api/controllers/console/__init__.py@@ -139,6 +139,7 @@ from .workspace import (model_providers,models,plugin,+ rbac,snippets,tool_providers,trigger_providers,@@ -212,6 +213,7 @@ __all__ = ["rag_pipeline_draft_variable","rag_pipeline_import","rag_pipeline_workflow",+ "rbac","recommended_app","saved_message","setup",diff --git a/api/controllers/console/agent/composer.py b/api/controllers/console/agent/composer.pyindex 6915a54db93..2cd01e427f7 100644--- a/api/controllers/console/agent/composer.py+++ b/api/controllers/console/agent/composer.py@@ -7,8 +7,11 @@ from controllers.console import console_nsfrom controllers.console.agent.app_helpers import resolve_agent_app_modelfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user_id,@@ -70,6 +73,7 @@ class WorkflowAgentComposerApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@get_app_model(mode=[AppMode.WORKFLOW, AppMode.ADVANCED_CHAT])@with_current_user_id@with_current_tenant_id@@ -166,6 +170,7 @@ class WorkflowAgentComposerSaveToRosterApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@get_app_model(mode=[AppMode.WORKFLOW, AppMode.ADVANCED_CHAT])@with_current_user_id@with_current_tenant_id@@ -203,6 +208,7 @@ class AgentComposerApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user_id@with_current_tenant_iddef put(self, tenant_id: str, account_id: str, agent_id: UUID):diff --git a/api/controllers/console/apikey.py b/api/controllers/console/apikey.pyindex 57470dc9770..dcea303d7cc 100644--- a/api/controllers/console/apikey.py+++ b/api/controllers/console/apikey.py@@ -9,6 +9,7 @@ from sqlalchemy import delete, func, selectfrom sqlalchemy.orm import sessionmakerfrom werkzeug.exceptions import Forbidden+from configs import dify_configfrom controllers.common.schema import register_response_schema_modelsfrom extensions.ext_database import dbfrom fields.base import ResponseModel@@ -22,8 +23,11 @@ from services.api_token_service import ApiTokenCachefrom . import console_nsfrom .wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -143,7 +147,7 @@ class BaseApiKeyResource(Resource):assert self.resource_id_field is not None, "resource_id_field must be set"_get_resource(resource_id, current_tenant_id, self.resource_model)- if not current_user.is_admin_or_owner:+ if not dify_config.RBAC_ENABLED and not current_user.is_admin_or_owner:raise Forbidden()key = db.session.scalar(@@ -186,6 +190,7 @@ class AppApiKeyListResource(BaseApiKeyListResource):@console_ns.response(400, "Maximum keys exceeded")@with_current_tenant_id@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)def post(self, current_tenant_id: str, resource_id: UUID) -> tuple[dict[str, object], int]:"""Create a new API key for an app"""return dump_response(ApiKeyItem, self._create_api_key(str(resource_id), current_tenant_id)), 201@@ -204,6 +209,7 @@ class AppApiKeyResource(BaseApiKeyResource):@console_ns.response(204, "API key deleted successfully")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)def delete(self, current_tenant_id: str, current_user: Account, resource_id: UUID, api_key_id: UUID) -> tuple[str, int]:@@ -234,6 +240,7 @@ class DatasetApiKeyListResource(BaseApiKeyListResource):@console_ns.response(400, "Maximum keys exceeded")@with_current_tenant_id@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE)def post(self, current_tenant_id: str, resource_id: UUID) -> tuple[dict[str, object], int]:"""Create a new API key for a dataset"""return dump_response(ApiKeyItem, self._create_api_key(str(resource_id), current_tenant_id)), 201@@ -252,6 +259,7 @@ class DatasetApiKeyResource(BaseApiKeyResource):@console_ns.response(204, "API key deleted successfully")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE)def delete(self, current_tenant_id: str, current_user: Account, resource_id: UUID, api_key_id: UUID) -> tuple[str, int]:diff --git a/api/controllers/console/app/agent.py b/api/controllers/console/app/agent.pyindex 6731be67831..a53a174da42 100644--- a/api/controllers/console/app/agent.py+++ b/api/controllers/console/app/agent.py@@ -17,7 +17,10 @@ from controllers.console import console_nsfrom controllers.console.agent.app_helpers import resolve_agent_app_modelfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -351,6 +354,7 @@ class AgentLogApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.AGENT_CHAT])def get(self, app_model: App):"""Get agent logs"""diff --git a/api/controllers/console/app/agent_app_feature.py b/api/controllers/console/app/agent_app_feature.pyindex 79d7589873c..5d2b77c97f1 100644--- a/api/controllers/console/app/agent_app_feature.py+++ b/api/controllers/console/app/agent_app_feature.py@@ -19,8 +19,11 @@ from controllers.common.schema import register_response_schema_models, register_from controllers.console import console_nsfrom controllers.console.agent.app_helpers import resolve_agent_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -78,6 +81,7 @@ class AgentAppFeatureConfigResource(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@account_initialization_required@with_current_user@with_current_tenant_iddiff --git a/api/controllers/console/app/annotation.py b/api/controllers/console/app/annotation.pyindex dd0b7e9ef5f..edf3a98af8c 100644--- a/api/controllers/console/app/annotation.py+++ b/api/controllers/console/app/annotation.py@@ -9,11 +9,14 @@ from controllers.common.errors import NoFileUploadedError, TooManyFilesErrorfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,annotation_import_concurrency_limit,annotation_import_rate_limit,cloud_edition_billing_resource_check,edit_permission_required,+ rbac_permission_required,setup_required,)from extensions.ext_redis import redis_client@@ -155,6 +158,7 @@ class AnnotationReplyActionApi(Resource):@account_initialization_required@cloud_edition_billing_resource_check("annotation")@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)def post(self, app_id: UUID, action: Literal["enable", "disable"]):args = AnnotationReplyPayload.model_validate(console_ns.payload)match action:@@ -185,6 +189,7 @@ class AppAnnotationSettingDetailApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, app_id: UUID):result = AppAnnotationService.get_app_annotation_setting_by_app_id(str(app_id))return result, 200@@ -202,6 +207,7 @@ class AppAnnotationSettingUpdateApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)def post(self, app_id: UUID, annotation_setting_id: UUID):annotation_setting_id_str = str(annotation_setting_id)@@ -230,6 +236,7 @@ class AnnotationReplyActionStatusApi(Resource):@account_initialization_required@cloud_edition_billing_resource_check("annotation")@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, app_id: UUID, job_id: UUID, action: str):job_id_str = str(job_id)app_annotation_job_key = f"{action}_app_annotation_job_{job_id_str}"@@ -258,6 +265,7 @@ class AnnotationApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, app_id: UUID):args = AnnotationListQuery.model_validate(request.args.to_dict(flat=True))page = args.page@@ -286,6 +294,7 @@ class AnnotationApi(Resource):@account_initialization_required@cloud_edition_billing_resource_check("annotation")@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)def post(self, app_id: UUID):args = CreateAnnotationPayload.model_validate(console_ns.payload)upsert_args: UpsertAnnotationArgs = {}@@ -304,6 +313,7 @@ class AnnotationApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@console_ns.response(204, "Annotations deleted successfully")def delete(self, app_id: UUID):@@ -342,6 +352,7 @@ class AnnotationExportApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, app_id: UUID):annotation_list = AppAnnotationService.export_annotation_list_by_app_id(str(app_id))annotation_models = TypeAdapter(list[Annotation]).validate_python(annotation_list, from_attributes=True)@@ -369,6 +380,7 @@ class AnnotationUpdateDeleteApi(Resource):@account_initialization_required@cloud_edition_billing_resource_check("annotation")@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)def post(self, app_id: UUID, annotation_id: UUID):args = UpdateAnnotationPayload.model_validate(console_ns.payload)update_args: UpdateAnnotationArgs = {}@@ -383,6 +395,7 @@ class AnnotationUpdateDeleteApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@console_ns.response(204, "Annotation deleted successfully")def delete(self, app_id: UUID, annotation_id: UUID):AppAnnotationService.delete_app_annotation(str(app_id), str(annotation_id))@@ -410,6 +423,7 @@ class AnnotationBatchImportApi(Resource):@annotation_import_rate_limit@annotation_import_concurrency_limit@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)def post(self, app_id: UUID):from configs import dify_config@@ -462,6 +476,7 @@ class AnnotationBatchImportStatusApi(Resource):@account_initialization_required@cloud_edition_billing_resource_check("annotation")@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, app_id: UUID, job_id: UUID):indexing_cache_key = f"app_annotation_batch_import_{str(job_id)}"cache_result = redis_client.get(indexing_cache_key)@@ -492,6 +507,7 @@ class AnnotationHitHistoryListApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, app_id: UUID, annotation_id: UUID):page = request.args.get("page", default=1, type=int)limit = request.args.get("limit", default=20, type=int)diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.pyindex 0e897ac44de..cd8d9ff3785 100644--- a/api/controllers/console/app/app.py+++ b/api/controllers/console/app/app.py@@ -3,7 +3,7 @@ import reimport uuidfrom collections.abc import Sequencefrom datetime import datetime-from typing import Any, Literal, cast+from typing import Any, Literalfrom flask import requestfrom flask_restx import Resource@@ -11,8 +11,9 @@ from pydantic import AliasChoices, BaseModel, Field, computed_field, field_validfrom sqlalchemy import selectfrom sqlalchemy.orm import Sessionfrom werkzeug.datastructures import MultiDict-from werkzeug.exceptions import BadRequest+from werkzeug.exceptions import BadRequest, NotFound+from configs import dify_configfrom controllers.common.fields import RedirectUrlResponse, SimpleResultResponsefrom controllers.common.helpers import FileInfofrom controllers.common.schema import (@@ -25,11 +26,14 @@ from controllers.console import console_nsfrom controllers.console.app.wraps import get_app_model, with_sessionfrom controllers.console.workspace.models import LoadBalancingPayloadfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,cloud_edition_billing_resource_check,edit_permission_required,enterprise_license_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -48,6 +52,7 @@ from models import Account, App, DatasetPermissionEnum, Workflowfrom models.model import IconTypefrom services.app_dsl_service import AppDslServicefrom services.app_service import AppListParams, AppListSortBy, AppService, CreateAppParams, StarredAppListParams+from services.enterprise import rbac_service as enterprise_rbac_servicefrom services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.dsl_entities import ImportMode, ImportStatusfrom services.entities.knowledge_entities.knowledge_entities import (@@ -72,12 +77,14 @@ _logger = logging.getLogger(__name__)_TAG_IDS_BRACKET_PATTERN = re.compile(r"^tag_ids\[(\d+)\]$")_CREATOR_IDS_BRACKET_PATTERN = re.compile(r"^creator_ids\[(\d+)\]$")AppListMode = Literal["completion", "chat", "advanced-chat", "workflow", "agent-chat", "agent", "channel", "all"]+DEFAULT_APP_LIST_MODE: AppListMode = "all"+APP_LIST_PERMISSION_KEYS = frozenset({"app.preview", "app.acl.preview", "app.full_access"})class AppListBaseQuery(BaseModel):page: int = Field(default=1, ge=1, le=99999, description="Page number (1-99999)")limit: int = Field(default=20, ge=1, le=100, description="Page size (1-100)")- mode: AppListMode = Field(default=cast(AppListMode, "all"), description="App mode filter")+ mode: AppListMode = Field(default=DEFAULT_APP_LIST_MODE, description="App mode filter")sort_by: AppListSortBy = Field(default="last_modified",description="Sort apps by last modified, recently created, or earliest created",@@ -160,6 +167,10 @@ def _normalize_app_list_query_args(query_args: MultiDict[str, str]) -> dict[str,return normalized+def _has_app_list_permission(permission_keys: Sequence[str]) -> bool:+ return any(permission_key in APP_LIST_PERMISSION_KEYS for permission_key in permission_keys)++class CreateAppPayload(BaseModel):name: str = Field(..., min_length=1, description="App name")description: str | None = Field(default=None, description="App description (max 400 chars)", max_length=400)@@ -398,11 +409,13 @@ class AppPartial(ResponseModel):create_user_name: str | None = Noneauthor_name: str | None = Nonehas_draft_trigger: bool | None = None+ permission_keys: list[str] = Field(default_factory=list)# For Agent App type: the roster Agent backing this app (None otherwise).bound_agent_id: str | None = None# For Agent App responses exposed through /agent.app_id: str | None = Noneis_starred: bool = False+ maintainer: str | None = None@computed_field(return_type=str | None) # type: ignore@property@@ -438,6 +451,8 @@ class AppDetail(ResponseModel):updated_at: int | None = Noneaccess_mode: str | None = Nonetags: list[Tag] = Field(default_factory=list)+ permission_keys: list[str] = Field(default_factory=list)+ maintainer: str | None = None@field_validator("created_at", "updated_at", mode="before")@classmethod@@ -592,6 +607,44 @@ class AppListApi(Resource):is_created_by_me=args.is_created_by_me,)+ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(+ str(current_tenant_id),+ current_user_id,+ )+ if dify_config.RBAC_ENABLED:+ whitelist_scope = enterprise_rbac_service.RBACService.AppAccess.whitelist_resources(+ str(current_tenant_id),+ current_user_id,+ )+ can_manage_own_apps = "app.create_and_management" in permissions.workspace.permission_keys+ has_default_preview = _has_app_list_permission(+ permissions.app.default_permission_keys+ ) or _has_app_list_permission(permissions.workspace.permission_keys)+ permission_app_ids: set[str] | None = None+ if not has_default_preview:+ permission_app_ids = {+ override.resource_id+ for override in permissions.app.overrides+ if _has_app_list_permission(override.permission_keys)+ }++ if getattr(whitelist_scope, "unrestricted", False):+ accessible_app_ids = permission_app_ids+ else:+ accessible_app_ids = set(whitelist_scope.resource_ids)+ if permission_app_ids is not None:+ accessible_app_ids |= permission_app_ids+ elif has_default_preview:+ accessible_app_ids = None++ if accessible_app_ids:+ params.accessible_app_ids = sorted(accessible_app_ids)+ params.include_own_apps = can_manage_own_apps+ elif accessible_app_ids is not None and can_manage_own_apps:+ params.is_created_by_me = True+ elif accessible_app_ids is not None:+ params.accessible_app_ids = []+# get app listapp_service = AppService()app_pagination = app_service.get_paginate_apps(current_user_id, current_tenant_id, params, db.session)@@ -599,9 +652,20 @@ class AppListApi(Resource):empty = AppPagination(page=args.page, limit=args.limit, total=0, has_more=False, data=[])return empty.model_dump(mode="json"), 200+ app_ids = [str(app.id) for app in app_pagination.items]+ permission_keys_map = permissions.app.permission_keys_by_resource_ids(app_ids)_enrich_app_list_items(session, apps=app_pagination.items, tenant_id=current_tenant_id)pagination_model = AppPagination.model_validate(app_pagination, from_attributes=True)+ if app_pagination.items:+ pagination_model = pagination_model.model_copy(+ update={+ "data": [+ item.model_copy(update={"permission_keys": permission_keys_map.get(str(item.id), [])})+ for item in pagination_model.data+ ]+ }+ )return pagination_model.model_dump(mode="json"), 200@console_ns.doc("create_app")@@ -613,6 +677,7 @@ class AppListApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT, resource_required=False)@cloud_edition_billing_resource_check("apps")@edit_permission_required@with_current_user@@ -631,7 +696,14 @@ class AppListApi(Resource):app_service = AppService()app = app_service.create_app(current_tenant_id, params, current_user)- app_detail = AppDetailWithSite.model_validate(app, from_attributes=True)+ permission_keys_map = enterprise_rbac_service.RBACService.AppPermissions.batch_get(+ str(current_tenant_id),+ current_user.id,+ [str(app.id)],+ )+ app_detail = AppDetailWithSite.model_validate(app, from_attributes=True).model_copy(+ update={"permission_keys": permission_keys_map.get(str(app.id), [])}+ )return app_detail.model_dump(mode="json"), 201@@ -717,8 +789,11 @@ class AppApi(Resource):@login_required@account_initialization_required@enterprise_license_required+ @with_current_user+ @with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=None)- def get(self, app_model: App):+ def get(self, current_tenant_id: str, current_user: Account, app_model: App):"""Get app detail"""app_service = AppService()@@ -728,7 +803,16 @@ class AppApi(Resource):app_setting = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=str(app_model.id))app_model.access_mode = app_setting.access_mode- response_model = AppDetailWithSite.model_validate(app_model, from_attributes=True)+ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(+ str(current_tenant_id),+ current_user.id,+ app_id=str(app_model.id),+ )+ permission_keys_map = permissions.app.permission_keys_by_resource_ids([str(app_model.id)])++ response_model = AppDetailWithSite.model_validate(app_model, from_attributes=True).model_copy(+ update={"permission_keys": permission_keys_map.get(str(app_model.id), [])}+ )return response_model.model_dump(mode="json")@console_ns.doc("update_app")@@ -741,8 +825,9 @@ class AppApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=None)@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)+ @get_app_model(mode=None)def put(self, app_model: App):"""Update app"""args = UpdateAppPayload.model_validate(console_ns.payload)@@ -767,11 +852,12 @@ class AppApi(Resource):@console_ns.doc(params={"app_id": "Application ID"})@console_ns.response(204, "App deleted successfully")@console_ns.response(403, "Insufficient permissions")- @get_app_model@setup_required@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_DELETE)+ @get_app_modeldef delete(self, app_model: App):"""Delete app"""app_service = AppService()@@ -791,10 +877,12 @@ class AppCopyApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=None)@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@with_current_user- def post(self, current_user: Account, app_model: App):+ @with_current_tenant_id+ @get_app_model(mode=None)+ def post(self, current_tenant_id: str, current_user: Account, app_model: App):"""Copy app"""# The role of the current user in the ta table must be admin, owner, or editorargs = CopyAppPayload.model_validate(console_ns.payload or {})@@ -836,7 +924,17 @@ class AppCopyApi(Resource):stmt = select(App).where(App.id == result.app_id)app = session.scalar(stmt)- response_model = AppDetailWithSite.model_validate(app, from_attributes=True)+ if not app:+ raise NotFound("App not found")++ permission_keys_map = enterprise_rbac_service.RBACService.AppPermissions.batch_get(+ str(current_tenant_id),+ current_user.id,+ [str(app.id)],+ )+ response_model = AppDetailWithSite.model_validate(app, from_attributes=True).model_copy(+ update={"permission_keys": permission_keys_map.get(str(app.id), [])}+ )return response_model.model_dump(mode="json"), 201@@ -848,11 +946,12 @@ class AppExportApi(Resource):@console_ns.doc(params=query_params_from_model(AppExportQuery))@console_ns.response(200, "App exported successfully", console_ns.models[AppExportResponse.__name__])@console_ns.response(403, "Insufficient permissions")- @get_app_model@setup_required@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL)+ @get_app_modeldef get(self, app_model: App):"""Export app"""args = AppExportQuery.model_validate(request.args.to_dict(flat=True))@@ -873,12 +972,12 @@ class AppPublishToCreatorsPlatformApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=None)@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL)@with_current_user_id+ @get_app_model(mode=None)def post(self, current_user_id: str, app_model: App):"""Publish app to Creators Platform"""- from configs import dify_configfrom core.helper.creators import get_redirect_url, upload_dslif not dify_config.CREATORS_PLATFORM_FEATURES_ENABLED:@@ -903,8 +1002,9 @@ class AppNameApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=None)@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)+ @get_app_model(mode=None)def post(self, app_model: App):args = AppNamePayload.model_validate(console_ns.payload)@@ -925,8 +1025,9 @@ class AppIconApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=None)@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)+ @get_app_model(mode=None)def post(self, app_model: App):args = AppIconPayload.model_validate(console_ns.payload or {})@@ -952,8 +1053,9 @@ class AppSiteStatus(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=None)@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)+ @get_app_model(mode=None)def post(self, app_model: App):args = AppSiteStatusPayload.model_validate(console_ns.payload)@@ -975,6 +1077,7 @@ class AppApiStatus(Resource):@login_required@is_admin_or_owner_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)@get_app_model(mode=None)def post(self, app_model: App):args = AppApiStatusPayload.model_validate(console_ns.payload)@@ -999,6 +1102,7 @@ class AppTraceApi(Resource):@login_required@account_initialization_required@with_session+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_modeldef get(self, session: Session, app_model: App):"""Get app trace"""@@ -1020,6 +1124,7 @@ class AppTraceApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)@get_app_modeldef post(self, app_model: App):# add app tracediff --git a/api/controllers/console/app/app_import.py b/api/controllers/console/app/app_import.pyindex cbdcdc8f10b..d58c5df1e96 100644--- a/api/controllers/console/app/app_import.py+++ b/api/controllers/console/app/app_import.py@@ -2,25 +2,36 @@ from flask_restx import Resourcefrom pydantic import BaseModel, Fieldfrom sqlalchemy.orm import Session+from configs import dify_configfrom controllers.common.schema import register_enum_models, register_schema_modelsfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,cloud_edition_billing_resource_check,edit_permission_required,+ rbac_permission_required,setup_required,with_current_user,)from extensions.ext_database import db-from libs.login import login_required+from extensions.ext_redis import redis_client+from libs.login import current_account_with_tenant, login_requiredfrom models.account import Accountfrom models.model import App-from services.app_dsl_service import AppDslService, Import+from services.app_dsl_service import (+ IMPORT_INFO_REDIS_KEY_PREFIX,+ AppDslService,+ Import,+ PendingData,+)from services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.dsl_entities import CheckDependenciesResult, ImportStatusfrom services.feature_service import FeatureServicefrom .. import console_ns+from .permission_keys import get_app_permission_keysclass AppImportPayload(BaseModel):@@ -39,6 +50,24 @@ register_enum_models(console_ns, ImportStatus)register_schema_models(console_ns, AppImportPayload, Import, CheckDependenciesResult)+def _current_user_and_tenant_id(current_user: Account | None) -> tuple[Account, str | None]:+ if current_user is None:+ account, tenant_id = current_account_with_tenant()+ return account, str(tenant_id) if tenant_id else None++ current_tenant_id = getattr(current_user, "current_tenant_id", None)+ if current_tenant_id:+ return current_user, str(current_tenant_id)++ current_tenant = getattr(current_user, "current_tenant", None)+ current_tenant_object_id = getattr(current_tenant, "id", None)+ if current_tenant_object_id:+ return current_user, str(current_tenant_object_id)++ account, fallback_tenant_id = current_account_with_tenant()+ return account, str(fallback_tenant_id) if fallback_tenant_id else None++@console_ns.route("/apps/imports")class AppImportApi(Resource):@console_ns.expect(console_ns.models[AppImportPayload.__name__])@@ -50,10 +79,11 @@ class AppImportApi(Resource):@account_initialization_required@cloud_edition_billing_resource_check("apps")@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL, resource_required=False)@with_current_user- def post(self, current_user: Account):- # Check user role first+ def post(self, current_user: Account | None = None):args = AppImportPayload.model_validate(console_ns.payload)+ current_user = current_user if current_user is not None else _current_user_and_tenant_id(None)[0]# AppDslService performs internal commits for some creation paths, so use a plain# Session here instead of nesting it inside sessionmaker(...).begin().@@ -77,6 +107,20 @@ class AppImportApi(Resource):session.rollback()else:session.commit()++ is_created_app = args.app_id is None and result.status in {+ ImportStatus.COMPLETED,+ ImportStatus.COMPLETED_WITH_WARNINGS,+ }+ if dify_config.RBAC_ENABLED and is_created_app and result.app_id:+ current_user, current_tenant_id = _current_user_and_tenant_id(current_user)+ if current_tenant_id:+ result.permission_keys = get_app_permission_keys(+ current_tenant_id,+ current_user.id,+ result.app_id,+ )+if result.app_id and FeatureService.get_system_features().webapp_auth.enabled:# update web app setting as privateEnterpriseService.WebAppAuth.update_app_access_mode(result.app_id, "private")@@ -99,9 +143,16 @@ class AppImportConfirmApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL, resource_required=False)@with_current_user- def post(self, current_user: Account, import_id: str):- # Check user role first+ def post(self, current_user: Account | None = None, import_id: str = ""):+ current_user = current_user if current_user is not None else _current_user_and_tenant_id(None)[0]+ redis_key = f"{IMPORT_INFO_REDIS_KEY_PREFIX}{import_id}"+ pending_data_raw = redis_client.get(redis_key)+ pending_data: PendingData | None = None+ if pending_data_raw:+ pending_data = PendingData.model_validate_json(pending_data_raw)+with Session(db.engine, expire_on_commit=False) as session:import_service = AppDslService(session)# Confirm import@@ -112,6 +163,24 @@ class AppImportConfirmApi(Resource):else:session.commit()+ is_created_app = bool(+ pending_data+ and pending_data.app_id is None+ and result.status+ in {+ ImportStatus.COMPLETED,+ ImportStatus.COMPLETED_WITH_WARNINGS,+ }+ )+ if dify_config.RBAC_ENABLED and is_created_app and result.app_id:+ current_user, current_tenant_id = _current_user_and_tenant_id(current_user)+ if current_tenant_id:+ result.permission_keys = get_app_permission_keys(+ current_tenant_id,+ current_user.id,+ result.app_id,+ )+# Return appropriate status code based on resultif result.status == ImportStatus.FAILED:return result.model_dump(mode="json"), 400@@ -120,12 +189,17 @@ class AppImportConfirmApi(Resource):@console_ns.route("/apps/imports/<string:app_id>/check-dependencies")class AppImportCheckDependenciesApi(Resource):- @console_ns.response(200, "Dependencies checked", console_ns.models[CheckDependenciesResult.__name__])+ @console_ns.response(+ 200,+ "Dependencies checked",+ console_ns.models[CheckDependenciesResult.__name__],+ )@setup_required@login_required@get_app_model@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, app_model: App):with Session(db.engine, expire_on_commit=False) as session:import_service = AppDslService(session)diff --git a/api/controllers/console/app/audio.py b/api/controllers/console/app/audio.pyindex 7ef43570c2f..43b41903f60 100644--- a/api/controllers/console/app/audio.py+++ b/api/controllers/console/app/audio.py@@ -22,7 +22,13 @@ from controllers.console.app.error import (UnsupportedAudioTypeError,)from controllers.console.app.wraps import get_app_model-from controllers.console.wraps import account_initialization_required, setup_required+from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+)from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededErrorfrom graphon.model_runtime.errors.invoke import InvokeErrorfrom libs.login import login_required@@ -126,10 +132,10 @@ class ChatMessageTextApi(Resource):console_ns.models[AudioBinaryResponse.__name__],)@console_ns.response(400, "Bad request - Invalid parameters")- @get_app_model@setup_required@login_required@account_initialization_required+ @get_app_modeldef post(self, app_model: App):try:payload = TextToSpeechPayload.model_validate(console_ns.payload)@@ -180,10 +186,11 @@ class TextModesApi(Resource):console_ns.models[TextToSpeechVoiceListResponse.__name__],)@console_ns.response(400, "Invalid language parameter")- @get_app_model@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_modeldef get(self, app_model: App):try:args = TextToSpeechVoiceQuery.model_validate(request.args.to_dict(flat=True))diff --git a/api/controllers/console/app/completion.py b/api/controllers/console/app/completion.pyindex 853f7b023ff..62b95ad22e4 100644--- a/api/controllers/console/app/completion.py+++ b/api/controllers/console/app/completion.py@@ -22,8 +22,11 @@ from controllers.console.app.error import ()from controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -113,8 +116,9 @@ class CompletionMessageApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.COMPLETION)@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)+ @get_app_model(mode=AppMode.COMPLETION)def post(self, current_user: Account, app_model: App):args_model = CompletionMessagePayload.model_validate(console_ns.payload)args = args_model.model_dump(exclude_none=True, by_alias=True)@@ -159,8 +163,8 @@ class CompletionMessageStopApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.COMPLETION)@with_current_user_id+ @get_app_model(mode=AppMode.COMPLETION)def post(self, current_user_id: str, app_model: App, task_id: str):AppTaskService.stop_task(@@ -185,9 +189,10 @@ class ChatMessageApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.AGENT])@edit_permission_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.AGENT])def post(self, current_user: Account, app_model: App):return _create_chat_message(current_user=current_user, app_model=app_model)@@ -205,6 +210,7 @@ class AgentChatMessageApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@with_current_user@with_current_tenant_iddef post(self, current_tenant_id: str, current_user: Account, agent_id: UUID):@@ -221,8 +227,8 @@ class ChatMessageStopApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])@with_current_user_id+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])def post(self, current_user_id: str, app_model: App, task_id: str):return _stop_chat_message(current_user_id=current_user_id, app_model=app_model, task_id=task_id)diff --git a/api/controllers/console/app/conversation.py b/api/controllers/console/app/conversation.pyindex b9fcf2073d7..ec34c26fedd 100644--- a/api/controllers/console/app/conversation.py+++ b/api/controllers/console/app/conversation.py@@ -13,8 +13,11 @@ from controllers.common.schema import query_params_from_model, register_schema_mfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_user,)@@ -97,9 +100,10 @@ class CompletionConversationApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.COMPLETION)@edit_permission_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=AppMode.COMPLETION)def get(self, current_user: Account, app_model: App):args = CompletionConversationQuery.model_validate(request.args.to_dict(flat=True))@@ -169,9 +173,10 @@ class CompletionConversationDetailApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.COMPLETION)@edit_permission_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=AppMode.COMPLETION)def get(self, current_user: Account, app_model: App, conversation_id: UUID):conversation_id_str = str(conversation_id)return ConversationMessageDetailResponse.model_validate(@@ -187,9 +192,10 @@ class CompletionConversationDetailApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.COMPLETION)@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user+ @get_app_model(mode=AppMode.COMPLETION)def delete(self, current_user: Account, app_model: App, conversation_id: UUID):conversation_id_str = str(conversation_id)@@ -212,9 +218,10 @@ class ChatConversationApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])@edit_permission_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])def get(self, current_user: Account, app_model: App):args = ChatConversationQuery.model_validate(request.args.to_dict(flat=True))@@ -323,9 +330,10 @@ class ChatConversationDetailApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])@edit_permission_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])def get(self, current_user: Account, app_model: App, conversation_id: UUID):conversation_id_str = str(conversation_id)return ConversationDetailResponse.model_validate(@@ -340,10 +348,11 @@ class ChatConversationDetailApi(Resource):@console_ns.response(404, "Conversation not found")@setup_required@login_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])def delete(self, current_user: Account, app_model: App, conversation_id: UUID):conversation_id_str = str(conversation_id)diff --git a/api/controllers/console/app/conversation_variables.py b/api/controllers/console/app/conversation_variables.pyindex 9cf3f278eac..3069dd3011c 100644--- a/api/controllers/console/app/conversation_variables.py+++ b/api/controllers/console/app/conversation_variables.py@@ -12,7 +12,13 @@ from sqlalchemy.orm import sessionmakerfrom controllers.common.schema import query_params_from_model, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_model-from controllers.console.wraps import account_initialization_required, setup_required+from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+)from extensions.ext_database import dbfrom fields._value_type_serializer import serialize_value_typefrom fields.base import ResponseModel@@ -93,6 +99,7 @@ class ConversationVariablesApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@get_app_model(mode=AppMode.ADVANCED_CHAT)def get(self, app_model: App):args = ConversationVariablesQuery.model_validate(request.args.to_dict(flat=True))diff --git a/api/controllers/console/app/mcp_server.py b/api/controllers/console/app/mcp_server.pyindex 8d1eb700739..6d6a56b5e1d 100644--- a/api/controllers/console/app/mcp_server.py+++ b/api/controllers/console/app/mcp_server.py@@ -12,8 +12,11 @@ from controllers.common.schema import register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,)@@ -83,6 +86,7 @@ class AppMCPServerController(Resource):@login_required@account_initialization_required@setup_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_modeldef get(self, app_model: App):server = db.session.scalar(select(AppMCPServer).where(AppMCPServer.app_id == app_model.id).limit(1))@@ -99,11 +103,12 @@ class AppMCPServerController(Resource):)@console_ns.response(403, "Insufficient permissions")@account_initialization_required- @get_app_model@login_required@setup_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_tenant_id+ @get_app_modeldef post(self, current_tenant_id: str, app_model: App):payload = MCPServerCreatePayload.model_validate(console_ns.payload or {})@@ -133,11 +138,12 @@ class AppMCPServerController(Resource):)@console_ns.response(403, "Insufficient permissions")@console_ns.response(404, "Server not found")- @get_app_model@login_required@setup_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)+ @get_app_modeldef put(self, app_model: App):payload = MCPServerUpdatePayload.model_validate(console_ns.payload or {})server = db.session.get(AppMCPServer, payload.id)@@ -174,6 +180,7 @@ class AppMCPServerRefreshController(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@with_current_tenant_iddef get(self, current_tenant_id: str, server_id: UUID):server = db.session.scalar(diff --git a/api/controllers/console/app/message.py b/api/controllers/console/app/message.pyindex ef112b1b1e4..1406fbc634b 100644--- a/api/controllers/console/app/message.py+++ b/api/controllers/console/app/message.py@@ -23,8 +23,11 @@ from controllers.console.app.error import (from controllers.console.app.wraps import get_app_modelfrom controllers.console.explore.error import AppSuggestedQuestionsAfterAnswerDisabledErrorfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -182,8 +185,9 @@ class ChatMessageListApi(Resource):@login_required@account_initialization_required@setup_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])def get(self, app_model: App):return _list_chat_messages(app_model=app_model)@@ -200,6 +204,7 @@ class AgentChatMessageListApi(Resource):@account_initialization_required@setup_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@with_current_tenant_iddef get(self, current_tenant_id: str, agent_id: UUID):app_model = resolve_agent_app_model(tenant_id=current_tenant_id, agent_id=agent_id)@@ -215,11 +220,11 @@ class MessageFeedbackApi(Resource):@console_ns.response(200, "Feedback updated successfully", console_ns.models[SimpleResultResponse.__name__])@console_ns.response(404, "Message not found")@console_ns.response(403, "Insufficient permissions")- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @get_app_modeldef post(self, current_user: Account, app_model: App):return _update_message_feedback(current_user=current_user, app_model=app_model)@@ -252,10 +257,11 @@ class MessageAnnotationCountApi(Resource):"Annotation count retrieved successfully",console_ns.models[AnnotationCountResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_modeldef get(self, app_model: App):count = db.session.scalar(select(func.count(MessageAnnotation.id)).where(MessageAnnotation.app_id == app_model.id)@@ -278,8 +284,9 @@ class MessageSuggestedQuestionApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])def get(self, current_user: Account, app_model: App, message_id: UUID):return _get_message_suggested_questions(current_user=current_user, app_model=app_model, message_id=message_id)@@ -318,10 +325,11 @@ class MessageFeedbackExportApi(Resource):)@console_ns.response(400, "Invalid parameters")@console_ns.response(500, "Internal server error")- @get_app_model@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_modeldef get(self, app_model: App):args = FeedbackExportQuery.model_validate(request.args.to_dict())@@ -356,10 +364,11 @@ class MessageApi(Resource):@console_ns.doc(params={"app_id": "Application ID", "message_id": "Message ID"})@console_ns.response(200, "Message retrieved successfully", console_ns.models[MessageDetailResponse.__name__])@console_ns.response(404, "Message not found")- @get_app_model@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_modeldef get(self, app_model: App, message_id: UUID):return _get_message_detail(app_model=app_model, message_id=message_id)diff --git a/api/controllers/console/app/model_config.py b/api/controllers/console/app/model_config.pyindex 6e2e20c0a35..3a016e3b9b2 100644--- a/api/controllers/console/app/model_config.py+++ b/api/controllers/console/app/model_config.py@@ -10,8 +10,11 @@ from controllers.common.schema import register_response_schema_models, register_from controllers.console import console_nsfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user_id,@@ -86,10 +89,11 @@ class ModelConfigResource(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@account_initialization_required- @get_app_model(mode=[AppMode.AGENT_CHAT, AppMode.CHAT, AppMode.COMPLETION])@with_current_user_id@with_current_tenant_id+ @get_app_model(mode=[AppMode.AGENT_CHAT, AppMode.CHAT, AppMode.COMPLETION])def post(self, current_tenant_id: str, current_user_id: str, app_model: App):"""Modify app model config"""# validate configdiff --git a/api/controllers/console/app/ops_trace.py b/api/controllers/console/app/ops_trace.pyindex c9f9308c2ea..d350ff52770 100644--- a/api/controllers/console/app/ops_trace.py+++ b/api/controllers/console/app/ops_trace.py@@ -9,7 +9,13 @@ from controllers.common.schema import query_params_from_model, register_responsefrom controllers.console import console_nsfrom controllers.console.app.error import TracingConfigCheckError, TracingConfigIsExist, TracingConfigNotExistfrom controllers.console.app.wraps import get_app_model-from controllers.console.wraps import account_initialization_required, setup_required+from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+)from fields.base import ResponseModelfrom libs.login import login_requiredfrom models import App@@ -64,6 +70,7 @@ class TraceAppConfigApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)@get_app_modeldef get(self, app_model: App):args = TraceProviderQuery.model_validate(request.args.to_dict(flat=True)) # type: ignorediff --git a/api/controllers/console/app/permission_keys.py b/api/controllers/console/app/permission_keys.pynew file mode 100644index 00000000000..810ea04e377--- /dev/null+++ b/api/controllers/console/app/permission_keys.py@@ -0,0 +1,6 @@+from services.enterprise import rbac_service as enterprise_rbac_service+++def get_app_permission_keys(tenant_id: str, account_id: str | None, app_id: str) -> list[str]:+ permission_keys_map = enterprise_rbac_service.RBACService.AppPermissions.batch_get(tenant_id, account_id, [app_id])+ return permission_keys_map.get(app_id, [])diff --git a/api/controllers/console/app/site.py b/api/controllers/console/app/site.pyindex df398fa7b9c..edc79f8fbc6 100644--- a/api/controllers/console/app/site.py+++ b/api/controllers/console/app/site.py@@ -10,9 +10,12 @@ from controllers.common.schema import register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_user,)@@ -85,9 +88,10 @@ class AppSite(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)@account_initialization_required- @get_app_model@with_current_user+ @get_app_modeldef post(self, current_user: Account, app_model: App):args = AppSiteUpdatePayload.model_validate(console_ns.payload or {})site = db.session.scalar(select(Site).where(Site.app_id == app_model.id).limit(1))@@ -134,9 +138,10 @@ class AppSiteAccessTokenReset(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)@account_initialization_required- @get_app_model@with_current_user+ @get_app_modeldef post(self, current_user: Account, app_model: App):site = db.session.scalar(select(Site).where(Site.app_id == app_model.id).limit(1))diff --git a/api/controllers/console/app/statistic.py b/api/controllers/console/app/statistic.pyindex bc0120fe4f8..fbb6d3e987f 100644--- a/api/controllers/console/app/statistic.py+++ b/api/controllers/console/app/statistic.py@@ -8,7 +8,14 @@ from pydantic import BaseModel, Field, field_validatorfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_model-from controllers.console.wraps import account_initialization_required, setup_required, with_current_user+from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+ with_current_user,+)from core.app.entities.app_invoke_entities import InvokeFromfrom extensions.ext_database import dbfrom fields.base import ResponseModel@@ -131,11 +138,12 @@ class DailyMessageStatistic(Resource):"Daily message statistics retrieved successfully",console_ns.models[DailyMessageStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))@@ -191,11 +199,12 @@ class DailyConversationStatistic(Resource):"Daily conversation statistics retrieved successfully",console_ns.models[DailyConversationStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))@@ -250,11 +259,12 @@ class DailyTerminalsStatistic(Resource):"Daily terminal statistics retrieved successfully",console_ns.models[DailyTerminalStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))@@ -310,11 +320,12 @@ class DailyTokenCostStatistic(Resource):"Daily token cost statistics retrieved successfully",console_ns.models[DailyTokenCostStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))@@ -376,8 +387,9 @@ class AverageSessionInteractionStatistic(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT])def get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))@@ -452,11 +464,12 @@ class UserSatisfactionRateStatistic(Resource):"User satisfaction rate statistics retrieved successfully",console_ns.models[UserSatisfactionRateStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))@@ -524,8 +537,9 @@ class AverageResponseTimeStatistic(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.COMPLETION)@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_model(mode=AppMode.COMPLETION)def get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))@@ -581,11 +595,12 @@ class TokensPerSecondStatistic(Resource):"Tokens per second statistics retrieved successfully",console_ns.models[TokensPerSecondStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = StatisticTimeRangeQuery.model_validate(request.args.to_dict(flat=True))diff --git a/api/controllers/console/app/workflow.py b/api/controllers/console/app/workflow.pyindex a8969f4d5ec..aff32035233 100644--- a/api/controllers/console/app/workflow.py+++ b/api/controllers/console/app/workflow.py@@ -26,10 +26,14 @@ from controllers.console.app.error import (DraftWorkflowNotExist,DraftWorkflowNotSync,)+from controllers.console.app.permission_keys import get_app_permission_keysfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -436,8 +440,9 @@ class DraftWorkflowApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App):"""Get draft workflow@@ -483,6 +488,7 @@ class DraftWorkflowApi(Resource):@console_ns.response(403, "Permission denied")@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def post(self, current_user: Account, app_model: App):"""Sync draft workflow@@ -548,6 +554,7 @@ class AdvancedChatDraftWorkflowRunApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.ADVANCED_CHAT])@with_current_user@edit_permission_required@@ -597,6 +604,7 @@ class AdvancedChatDraftRunIterationNodeApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.ADVANCED_CHAT])@with_current_user@edit_permission_required@@ -639,6 +647,7 @@ class WorkflowDraftRunIterationNodeApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -677,6 +686,7 @@ class AdvancedChatDraftRunLoopNodeApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.ADVANCED_CHAT])@with_current_user@edit_permission_required@@ -719,6 +729,7 @@ class WorkflowDraftRunLoopNodeApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -793,6 +804,7 @@ class AdvancedChatDraftHumanInputFormPreviewApi(Resource):@get_app_model(mode=[AppMode.ADVANCED_CHAT])@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def post(self, current_user: Account, app_model: App, node_id: str):"""Preview human input form content and placeholders@@ -824,6 +836,7 @@ class AdvancedChatDraftHumanInputFormRunApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.ADVANCED_CHAT])@with_current_user@edit_permission_required@@ -857,6 +870,7 @@ class WorkflowDraftHumanInputFormPreviewApi(Resource):@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def post(self, current_user: Account, app_model: App, node_id: str):"""Preview human input form content and placeholders@@ -888,6 +902,7 @@ class WorkflowDraftHumanInputFormRunApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -921,6 +936,7 @@ class WorkflowDraftHumanInputDeliveryTestApi(Resource):@get_app_model(mode=[AppMode.WORKFLOW, AppMode.ADVANCED_CHAT])@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)def post(self, current_user: Account, app_model: App, node_id: str):"""Test human input delivery@@ -952,6 +968,7 @@ class DraftWorkflowRunApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -990,8 +1007,9 @@ class WorkflowTaskStopApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)+ @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def post(self, app_model: App, task_id: str):"""Stop workflow task@@ -1022,6 +1040,7 @@ class DraftWorkflowNodeRunApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -1072,8 +1091,9 @@ class PublishedWorkflowApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App):"""Get published workflow@@ -1093,6 +1113,7 @@ class PublishedWorkflowApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -1141,8 +1162,9 @@ class DefaultBlockConfigsApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App):"""Get default block config@@ -1167,8 +1189,9 @@ class DefaultBlockConfigApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, block_type: str):"""Get default block config@@ -1205,14 +1228,15 @@ class ConvertToWorkflowApi(Resource):@account_initialization_required@get_app_model(mode=[AppMode.CHAT, AppMode.COMPLETION])@with_current_user+ @with_current_tenant_id@edit_permission_required- def post(self, current_user: Account, app_model: App):+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)+ def post(self, current_tenant_id: str, current_user: Account, app_model: App):"""Convert basic mode of chatbot app to workflow modeConvert expert mode of chatbot app to workflow modeConvert Completion App to Workflow App"""-payload = console_ns.payload or {}args = ConvertToWorkflowPayload.model_validate(payload).model_dump(exclude_none=True)@@ -1223,6 +1247,7 @@ class ConvertToWorkflowApi(Resource):# return app idreturn {"new_app_id": new_app_model.id,+ "permission_keys": get_app_permission_keys(str(current_tenant_id), current_user.id, str(new_app_model.id)),}@@ -1245,6 +1270,7 @@ class WorkflowFeaturesApi(Resource):@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def post(self, current_user: Account, app_model: App):args = WorkflowFeaturesPayload.model_validate(console_ns.payload or {})@@ -1270,6 +1296,7 @@ class PublishedAllWorkflowApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -1322,6 +1349,7 @@ class DraftWorkflowRestoreApi(Resource):@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION)def post(self, current_user: Account, app_model: App, workflow_id: str):workflow_service = WorkflowService()@@ -1360,6 +1388,7 @@ class WorkflowByIdApi(Resource):@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)def patch(self, current_user: Account, app_model: App, workflow_id: str):"""Update workflow attributes@@ -1398,6 +1427,7 @@ class WorkflowByIdApi(Resource):@account_initialization_required@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@console_ns.response(204, "Workflow deleted successfully")def delete(self, app_model: App, workflow_id: str):"""@@ -1436,6 +1466,7 @@ class DraftWorkflowNodeLastRunApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, node_id: str):srv = WorkflowService()@@ -1480,6 +1511,7 @@ class DraftWorkflowTriggerRunApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -1548,6 +1580,7 @@ class DraftWorkflowTriggerNodeApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required@@ -1631,6 +1664,7 @@ class DraftWorkflowTriggerRunAllApi(Resource):@get_app_model(mode=[AppMode.WORKFLOW])@with_current_user@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN)def post(self, current_user: Account, app_model: App):"""Full workflow debug when the start node is a triggerdiff --git a/api/controllers/console/app/workflow_app_log.py b/api/controllers/console/app/workflow_app_log.pyindex 72bececd999..cf94ceff853 100644--- a/api/controllers/console/app/workflow_app_log.py+++ b/api/controllers/console/app/workflow_app_log.py@@ -10,7 +10,13 @@ from sqlalchemy.orm import sessionmakerfrom controllers.common.schema import query_params_from_model, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_model-from controllers.console.wraps import account_initialization_required, setup_required+from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+)from extensions.ext_database import dbfrom fields.base import ResponseModelfrom fields.end_user_fields import SimpleEndUser@@ -175,6 +181,7 @@ class WorkflowAppLogApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)@get_app_model(mode=[AppMode.WORKFLOW])def get(self, app_model: App):"""@@ -218,6 +225,7 @@ class WorkflowArchivedLogApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)@get_app_model(mode=[AppMode.WORKFLOW])def get(self, app_model: App):"""diff --git a/api/controllers/console/app/workflow_comment.py b/api/controllers/console/app/workflow_comment.pyindex 3cecd450545..a9bf85ed36c 100644--- a/api/controllers/console/app/workflow_comment.py+++ b/api/controllers/console/app/workflow_comment.py@@ -8,8 +8,11 @@ from controllers.common.schema import register_response_schema_models, register_from controllers.console import console_nsfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -218,8 +221,9 @@ class WorkflowCommentListApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model()def get(self, current_tenant_id: str, app_model: App):"""Get all comments for a workflow."""comments = WorkflowCommentService.get_comments(tenant_id=current_tenant_id, app_id=app_model.id)@@ -234,10 +238,11 @@ class WorkflowCommentListApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user@with_current_tenant_id+ @get_app_model()def post(self, current_tenant_id: str, current_user: Account, app_model: App):"""Create a new workflow comment."""payload = WorkflowCommentCreatePayload.model_validate(console_ns.payload or {})@@ -266,8 +271,9 @@ class WorkflowCommentDetailApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model()def get(self, current_tenant_id: str, app_model: App, comment_id: str):"""Get a specific workflow comment."""comment = WorkflowCommentService.get_comment(@@ -284,10 +290,11 @@ class WorkflowCommentDetailApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user@with_current_tenant_id+ @get_app_model()def put(self, current_tenant_id: str, current_user: Account, app_model: App, comment_id: str):"""Update a workflow comment."""payload = WorkflowCommentUpdatePayload.model_validate(console_ns.payload or {})@@ -312,10 +319,11 @@ class WorkflowCommentDetailApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user@with_current_tenant_id+ @get_app_model()def delete(self, current_tenant_id: str, current_user: Account, app_model: App, comment_id: str):"""Delete a workflow comment."""WorkflowCommentService.delete_comment(@@ -339,10 +347,11 @@ class WorkflowCommentResolveApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user@with_current_tenant_id+ @get_app_model()def post(self, current_tenant_id: str, current_user: Account, app_model: App, comment_id: str):"""Resolve a workflow comment."""comment = WorkflowCommentService.resolve_comment(@@ -367,10 +376,11 @@ class WorkflowCommentReplyApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user@with_current_tenant_id+ @get_app_model()def post(self, current_tenant_id: str, current_user: Account, app_model: App, comment_id: str):"""Add a reply to a workflow comment."""# Validate comment access first@@ -402,10 +412,11 @@ class WorkflowCommentReplyDetailApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user@with_current_tenant_id+ @get_app_model()def put(self, current_tenant_id: str, current_user: Account, app_model: App, comment_id: str, reply_id: str):"""Update a comment reply."""# Validate comment access first@@ -434,10 +445,11 @@ class WorkflowCommentReplyDetailApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user@with_current_tenant_id+ @get_app_model()def delete(self, current_tenant_id: str, current_user: Account, app_model: App, comment_id: str, reply_id: str):"""Delete a comment reply."""# Validate comment access first@@ -469,8 +481,9 @@ class WorkflowCommentMentionUsersApi(Resource):@login_required@setup_required@account_initialization_required- @get_app_model()@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model()def get(self, current_user: Account, app_model: App):"""Get all users in current tenant for mentions."""current_tenant = current_user.current_tenant # need the tenant object herediff --git a/api/controllers/console/app/workflow_draft_variable.py b/api/controllers/console/app/workflow_draft_variable.pyindex 11411115c1b..ff82572b87e 100644--- a/api/controllers/console/app/workflow_draft_variable.py+++ b/api/controllers/console/app/workflow_draft_variable.py@@ -18,8 +18,11 @@ from controllers.console.app.error import ()from controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_user,)@@ -283,6 +286,7 @@ def _api_prerequisite[T, **P, R](@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user@wraps(f)@@ -304,6 +308,7 @@ class WorkflowVariableCollectionApi(Resource):)@_api_prerequisite@marshal_with(workflow_draft_variable_list_without_value_model)+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, current_user: Account, app_model: App):"""Get draft workflow@@ -368,6 +373,7 @@ class NodeVariableCollectionApi(Resource):@console_ns.response(200, "Node variables retrieved successfully", workflow_draft_variable_list_model)@_api_prerequisite@marshal_with(workflow_draft_variable_list_model)+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, current_user: Account, app_model: App, node_id: str):validate_node_id(node_id)with sessionmaker(bind=db.engine, expire_on_commit=False).begin() as session:@@ -402,6 +408,7 @@ class VariableApi(Resource):@console_ns.response(404, "Variable not found")@_api_prerequisite@marshal_with(workflow_draft_variable_model)+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, current_user: Account, app_model: App, variable_id: UUID):draft_var_srv = WorkflowDraftVariableService(session=db.session(),@@ -574,6 +581,7 @@ class ConversationVariableCollectionApi(Resource):@console_ns.response(404, "Draft workflow not found")@_api_prerequisite@marshal_with(workflow_draft_variable_list_model)+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, current_user: Account, app_model: App):# NOTE(QuantumGhost): Prefill conversation variables into the draft variables table# so their IDs can be returned to the caller.@@ -599,8 +607,9 @@ class ConversationVariableCollectionApi(Resource):@login_required@account_initialization_required@edit_permission_required- @get_app_model(mode=AppMode.ADVANCED_CHAT)+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user+ @get_app_model(mode=AppMode.ADVANCED_CHAT)def post(self, current_user: Account, app_model: App):payload = ConversationVariableUpdatePayload.model_validate(console_ns.payload or {})@@ -628,6 +637,7 @@ class SystemVariableCollectionApi(Resource):@console_ns.response(200, "System variables retrieved successfully", workflow_draft_variable_list_model)@_api_prerequisite@marshal_with(workflow_draft_variable_list_model)+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, current_user: Account, app_model: App):return _get_variable_list(app_model, SYSTEM_VARIABLE_NODE_ID, current_user.id)@@ -644,6 +654,7 @@ class EnvironmentVariableCollectionApi(Resource):)@console_ns.response(404, "Draft workflow not found")@_api_prerequisite+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)def get(self, _current_user: Account, app_model: App):"""Get draft workflow@@ -688,8 +699,9 @@ class EnvironmentVariableCollectionApi(Resource):@login_required@account_initialization_required@edit_permission_required- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@with_current_user+ @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def post(self, current_user: Account, app_model: App):payload = EnvironmentVariableUpdatePayload.model_validate(console_ns.payload or {})diff --git a/api/controllers/console/app/workflow_node_output_inspector.py b/api/controllers/console/app/workflow_node_output_inspector.pyindex 98f86ad7cb6..6ed59d6c566 100644--- a/api/controllers/console/app/workflow_node_output_inspector.py+++ b/api/controllers/console/app/workflow_node_output_inspector.py@@ -34,7 +34,13 @@ from controllers.common.fields import EventStreamResponsefrom controllers.common.schema import register_response_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_model-from controllers.console.wraps import account_initialization_required, setup_required+from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+)from libs.exception import BaseHTTPExceptionfrom libs.login import login_requiredfrom models import App, AppMode@@ -146,6 +152,7 @@ class WorkflowDraftRunNodeOutputsApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID):return _serve_snapshot(app_model, run_id)@@ -169,6 +176,7 @@ class WorkflowDraftRunNodeOutputDetailApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID, node_id: str):return _serve_node_detail(app_model, run_id, node_id)@@ -195,6 +203,7 @@ class WorkflowDraftRunNodeOutputPreviewApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID, node_id: str, output_name: str):return _serve_output_preview(app_model, run_id, node_id, output_name)@@ -338,6 +347,7 @@ class WorkflowDraftRunNodeOutputEventsApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID):return Response(@@ -368,6 +378,7 @@ class WorkflowPublishedRunNodeOutputsApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID):return _serve_snapshot(app_model, run_id)@@ -391,6 +402,7 @@ class WorkflowPublishedRunNodeOutputDetailApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID, node_id: str):return _serve_node_detail(app_model, run_id, node_id)@@ -418,6 +430,7 @@ class WorkflowPublishedRunNodeOutputPreviewApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID, node_id: str, output_name: str):return _serve_output_preview(app_model, run_id, node_id, output_name)@@ -439,6 +452,7 @@ class WorkflowPublishedRunNodeOutputEventsApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID):return Response(diff --git a/api/controllers/console/app/workflow_run.py b/api/controllers/console/app/workflow_run.pyindex 359daa12c20..374537229ca 100644--- a/api/controllers/console/app/workflow_run.py+++ b/api/controllers/console/app/workflow_run.py@@ -14,7 +14,10 @@ from controllers.common.schema import query_params_from_model, register_responsefrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_modelfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -155,6 +158,7 @@ class AdvancedChatAppWorkflowRunListApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@get_app_model(mode=[AppMode.ADVANCED_CHAT])def get(self, app_model: App):"""@@ -193,6 +197,7 @@ class WorkflowRunExportApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@get_app_model()def get(self, app_model: App, run_id: UUID):tenant_id = app_model.tenant_id@@ -251,6 +256,7 @@ class AdvancedChatAppWorkflowRunCountApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@get_app_model(mode=[AppMode.ADVANCED_CHAT])def get(self, app_model: App):"""@@ -291,6 +297,7 @@ class WorkflowRunListApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App):"""@@ -332,6 +339,7 @@ class WorkflowRunCountApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App):"""@@ -372,6 +380,7 @@ class WorkflowRunDetailApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)@get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, app_model: App, run_id: UUID):"""@@ -401,8 +410,9 @@ class WorkflowRunNodeExecutionListApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT)+ @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])def get(self, current_user: Account, app_model: App, run_id: UUID):"""Get workflow run node execution listdiff --git a/api/controllers/console/app/workflow_statistic.py b/api/controllers/console/app/workflow_statistic.pyindex ec2a5ffce11..0346d510fbc 100644--- a/api/controllers/console/app/workflow_statistic.py+++ b/api/controllers/console/app/workflow_statistic.py@@ -6,7 +6,14 @@ from sqlalchemy.orm import sessionmakerfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.wraps import get_app_model-from controllers.console.wraps import account_initialization_required, setup_required, with_current_user+from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+ with_current_user,+)from extensions.ext_database import dbfrom fields.base import ResponseModelfrom libs.datetime_utils import parse_time_range@@ -91,11 +98,12 @@ class WorkflowDailyRunsStatistic(Resource):"Daily runs statistics retrieved successfully",console_ns.models[WorkflowDailyRunsStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = WorkflowStatisticQuery.model_validate(request.args.to_dict(flat=True))@@ -134,11 +142,12 @@ class WorkflowDailyTerminalsStatistic(Resource):"Daily terminals statistics retrieved successfully",console_ns.models[WorkflowDailyTerminalsStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = WorkflowStatisticQuery.model_validate(request.args.to_dict(flat=True))@@ -177,11 +186,12 @@ class WorkflowDailyTokenCostStatistic(Resource):"Daily token cost statistics retrieved successfully",console_ns.models[WorkflowDailyTokenCostStatisticResponse.__name__],)- @get_app_model@setup_required@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_modeldef get(self, account: Account, app_model: App):args = WorkflowStatisticQuery.model_validate(request.args.to_dict(flat=True))@@ -223,8 +233,9 @@ class WorkflowAverageAppInteractionStatistic(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=[AppMode.WORKFLOW])@with_current_user+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_MONITOR)+ @get_app_model(mode=[AppMode.WORKFLOW])def get(self, account: Account, app_model: App):args = WorkflowStatisticQuery.model_validate(request.args.to_dict(flat=True))diff --git a/api/controllers/console/app/workflow_trigger.py b/api/controllers/console/app/workflow_trigger.pyindex 6a1bd843ee2..8bd41b3e429 100644--- a/api/controllers/console/app/workflow_trigger.py+++ b/api/controllers/console/app/workflow_trigger.py@@ -19,7 +19,15 @@ from models.trigger import AppTrigger, WorkflowWebhookTriggerfrom .. import console_nsfrom ..app.wraps import get_app_model-from ..wraps import account_initialization_required, edit_permission_required, setup_required, with_current_tenant_id+from ..wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ edit_permission_required,+ rbac_permission_required,+ setup_required,+ with_current_tenant_id,+)logger = logging.getLogger(__name__)@@ -90,8 +98,9 @@ class WebhookTriggerApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.WORKFLOW)@console_ns.response(200, "Success", console_ns.models[WebhookTriggerResponse.__name__])+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=AppMode.WORKFLOW)def get(self, app_model: App):"""Get webhook trigger for a node"""args = Parser.model_validate(request.args.to_dict(flat=True))@@ -122,9 +131,10 @@ class AppTriggersApi(Resource):@setup_required@login_required@account_initialization_required- @get_app_model(mode=AppMode.WORKFLOW)@console_ns.response(200, "Success", console_ns.models[WorkflowTriggerListResponse.__name__])@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)+ @get_app_model(mode=AppMode.WORKFLOW)def get(self, current_tenant_id: str, app_model: App):"""Get app triggers list"""with sessionmaker(db.engine, expire_on_commit=False).begin() as session:@@ -162,9 +172,10 @@ class AppTriggerEnableApi(Resource):@login_required@account_initialization_required@edit_permission_required- @get_app_model(mode=AppMode.WORKFLOW)+ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)@console_ns.response(200, "Success", console_ns.models[WorkflowTriggerResponse.__name__])@with_current_tenant_id+ @get_app_model(mode=AppMode.WORKFLOW)def post(self, current_tenant_id: str, app_model: App):"""Update app trigger (enable/disable)"""args = ParserEnable.model_validate(console_ns.payload)diff --git a/api/controllers/console/auth/data_source_bearer_auth.py b/api/controllers/console/auth/data_source_bearer_auth.pyindex f06db799498..a9c97401105 100644--- a/api/controllers/console/auth/data_source_bearer_auth.py+++ b/api/controllers/console/auth/data_source_bearer_auth.py@@ -11,7 +11,15 @@ from services.auth.api_key_auth_service import ApiKeyAuthServicefrom .. import console_nsfrom ..auth.error import ApiKeyAuthFailedError-from ..wraps import account_initialization_required, is_admin_or_owner_required, setup_required, with_current_tenant_id+from ..wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ is_admin_or_owner_required,+ rbac_permission_required,+ setup_required,+ with_current_tenant_id,+)class ApiKeyAuthBindingPayload(BaseModel):@@ -75,6 +83,7 @@ class ApiKeyAuthDataSourceBinding(Resource):@login_required@account_initialization_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@console_ns.expect(console_ns.models[ApiKeyAuthBindingPayload.__name__])@with_current_tenant_iddef post(self, current_tenant_id: str):@@ -95,6 +104,7 @@ class ApiKeyAuthDataSourceBindingDelete(Resource):@login_required@account_initialization_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@console_ns.response(204, "Binding deleted successfully")@with_current_tenant_iddef delete(self, current_tenant_id: str, binding_id: UUID):diff --git a/api/controllers/console/auth/data_source_oauth.py b/api/controllers/console/auth/data_source_oauth.pyindex f1493b5e6f4..6ad2efa360a 100644--- a/api/controllers/console/auth/data_source_oauth.py+++ b/api/controllers/console/auth/data_source_oauth.py@@ -13,7 +13,14 @@ from libs.login import login_requiredfrom libs.oauth_data_source import NotionOAuthfrom .. import console_ns-from ..wraps import account_initialization_required, is_admin_or_owner_required, setup_required+from ..wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ is_admin_or_owner_required,+ rbac_permission_required,+ setup_required,+)logger = logging.getLogger(__name__)@@ -75,6 +82,7 @@ class OAuthDataSource(Resource):@console_ns.response(400, "Invalid provider")@console_ns.response(403, "Admin privileges required")@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)def get(self, provider: str):# The role of the current user in the table must be admin or ownerOAUTH_DATASOURCE_PROVIDERS = get_oauth_providers()diff --git a/api/controllers/console/datasets/data_source.py b/api/controllers/console/datasets/data_source.pyindex 07db712fba1..6dd13b485bc 100644--- a/api/controllers/console/datasets/data_source.py+++ b/api/controllers/console/datasets/data_source.py@@ -31,7 +31,15 @@ from services.datasource_provider_service import DatasourceProviderServicefrom tasks.document_indexing_sync_task import document_indexing_sync_taskfrom .. import console_ns-from ..wraps import account_initialization_required, setup_required, with_current_tenant_id, with_current_user+from ..wraps import (+ RBACPermission,+ RBACResourceScope,+ account_initialization_required,+ rbac_permission_required,+ setup_required,+ with_current_tenant_id,+ with_current_user,+)class NotionEstimatePayload(BaseModel):@@ -390,6 +398,7 @@ class DataSourceNotionDatasetSyncApi(Resource):@login_required@account_initialization_required@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, dataset_id: UUID) -> tuple[dict[str, str], int]:dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -408,6 +417,7 @@ class DataSourceNotionDocumentSyncApi(Resource):@login_required@account_initialization_required@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, dataset_id: UUID, document_id: UUID) -> tuple[dict[str, str], int]:dataset_id_str = str(dataset_id)document_id_str = str(document_id)diff --git a/api/controllers/console/datasets/datasets.py b/api/controllers/console/datasets/datasets.pyindex 623c02631c0..55bc85483d5 100644--- a/api/controllers/console/datasets/datasets.py+++ b/api/controllers/console/datasets/datasets.py@@ -17,10 +17,13 @@ from controllers.console.apikey import ApiKeyItem, ApiKeyListfrom controllers.console.app.error import ProviderNotInitializeErrorfrom controllers.console.datasets.error import DatasetInUseError, DatasetNameDuplicateError, IndexingEstimateErrorfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,cloud_edition_billing_rate_limit_check,enterprise_license_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -46,9 +49,16 @@ from models.enums import ApiTokenType, SegmentStatusfrom models.provider_ids import ModelProviderIDfrom services.api_token_service import ApiTokenCachefrom services.dataset_service import DatasetPermissionService, DatasetService, DocumentService+from services.enterprise import rbac_service as enterprise_rbac_serviceregister_response_schema_models(console_ns, ApiBaseUrlResponse, SimpleResultResponse, UsageCheckResponse)+DATASET_LIST_PERMISSION_KEYS = frozenset({"dataset.preview", "dataset.acl.preview", "dataset.full_access"})+++def _has_dataset_list_permission(permission_keys: list[str]) -> bool:+ return any(permission_key in DATASET_LIST_PERMISSION_KEYS for permission_key in permission_keys)+def _validate_indexing_technique(value: str | None) -> str | None:if value is None:@@ -402,9 +412,49 @@ class DatasetListApi(Resource):if "tag_ids" in request.args:query_params["tag_ids"] = request.args.getlist("tag_ids")query = ConsoleDatasetListQuery.model_validate(query_params)- # provider = request.args.get("provider", default="vendor")++ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(+ str(current_tenant_id),+ current_user.id,+ )++ accessible_dataset_ids: list[str] | None = None+ include_own_datasets = False+ if dify_config.RBAC_ENABLED:+ whitelist_scope = enterprise_rbac_service.RBACService.DatasetAccess.whitelist_resources(+ str(current_tenant_id),+ current_user.id,+ )+ has_default_readonly = _has_dataset_list_permission(+ permissions.dataset.default_permission_keys+ ) or _has_dataset_list_permission(permissions.workspace.permission_keys)+ permission_dataset_ids: set[str] | None = None+ if not has_default_readonly:+ permission_dataset_ids = {+ override.resource_id+ for override in permissions.dataset.overrides+ if _has_dataset_list_permission(override.permission_keys)+ }+ if getattr(whitelist_scope, "unrestricted", False):+ filtered_dataset_ids = permission_dataset_ids+ else:+ filtered_dataset_ids = set(whitelist_scope.resource_ids)+ if permission_dataset_ids is not None:+ filtered_dataset_ids |= permission_dataset_ids+ elif has_default_readonly:+ filtered_dataset_ids = None+ if filtered_dataset_ids is not None:+ accessible_dataset_ids = sorted(filtered_dataset_ids)+ include_own_datasets = "dataset.create_and_management" in permissions.workspace.permission_keys+if query.ids:- datasets, total = DatasetService.get_datasets_by_ids(query.ids, current_tenant_id)+ datasets, total = DatasetService.get_datasets_by_ids(+ query.ids,+ current_tenant_id,+ user=current_user,+ accessible_dataset_ids=accessible_dataset_ids,+ include_own_datasets=include_own_datasets,+ )else:datasets, total = DatasetService.get_datasets(query.page,@@ -415,8 +465,15 @@ class DatasetListApi(Resource):query.keyword,query.tag_ids,query.include_all,+ accessible_dataset_ids=accessible_dataset_ids,+ include_own_datasets=include_own_datasets,)+ permission_keys_map = {}+ if datasets:+ dataset_ids = [str(dataset.id) for dataset in datasets]+ permission_keys_map = permissions.dataset.permission_keys_by_resource_ids(dataset_ids)+# check embedding settingprovider_manager = create_plugin_provider_manager(tenant_id=current_tenant_id)configurations = provider_manager.get_configurations(tenant_id=current_tenant_id)@@ -431,13 +488,13 @@ class DatasetListApi(Resource):dataset_ids = [item["id"] for item in data if item.get("permission") == "partial_members"]partial_members_map: dict[str, list[str]] = {}if dataset_ids:- permissions = db.session.execute(+ partial_member_rows = db.session.execute(select(DatasetPermission.dataset_id, DatasetPermission.account_id).where(DatasetPermission.dataset_id.in_(dataset_ids))).all()- for dataset_id, account_id in permissions:+ for dataset_id, account_id in partial_member_rows:partial_members_map.setdefault(dataset_id, []).append(account_id)for item in data:@@ -456,6 +513,7 @@ class DatasetListApi(Resource):item.update({"partial_member_list": partial_members_map.get(item["id"], [])})else:item.update({"partial_member_list": []})+ item["permission_keys"] = permission_keys_map.get(str(item["id"]), [])response = {"data": data,@@ -474,6 +532,9 @@ class DatasetListApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(+ RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False+ )@cloud_edition_billing_rate_limit_check("knowledge")@with_current_user@with_current_tenant_id@@ -484,6 +545,11 @@ class DatasetListApi(Resource):if not current_user.is_dataset_editor:raise Forbidden()+ if dify_config.RBAC_ENABLED:+ permission = DatasetPermissionEnum.ALL_TEAM+ else:+ permission = payload.permission or DatasetPermissionEnum.ONLY_ME+try:dataset = DatasetService.create_empty_dataset(tenant_id=current_tenant_id,@@ -491,7 +557,7 @@ class DatasetListApi(Resource):description=payload.description,indexing_technique=payload.indexing_technique,account=current_user,- permission=payload.permission or DatasetPermissionEnum.ONLY_ME,+ permission=permission,provider=payload.provider,external_knowledge_api_id=payload.external_knowledge_api_id,external_knowledge_id=payload.external_knowledge_id,@@ -499,7 +565,17 @@ class DatasetListApi(Resource):except services.errors.dataset.DatasetNameDuplicateError:raise DatasetNameDuplicateError()- return dump_response(DatasetDetailResponse, dataset), 201+ permission_keys_map = enterprise_rbac_service.RBACService.DatasetPermissions.batch_get(+ str(current_tenant_id),+ current_user.id,+ [str(dataset.id)],+ )++ item = DatasetDetailWithPartialMembersResponse.model_validate(dataset, from_attributes=True).model_dump(+ mode="json"+ )+ item["permission_keys"] = permission_keys_map.get(str(dataset.id), [])+ return item, 201@console_ns.route("/datasets/<uuid:dataset_id>")@@ -517,6 +593,7 @@ class DatasetApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)@with_current_user@with_current_tenant_iddef get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID):@@ -528,7 +605,14 @@ class DatasetApi(Resource):DatasetService.check_dataset_permission(dataset, current_user)except services.errors.account.NoPermissionError as e:raise Forbidden(str(e))+ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(+ str(current_tenant_id),+ current_user.id,+ dataset_id=dataset_id_str,+ )+ permission_keys_map = permissions.dataset.permission_keys_by_resource_ids([dataset_id_str])data = dump_response(DatasetDetailResponse, dataset)+ data["permission_keys"] = permission_keys_map.get(dataset_id_str, [])if dataset.indexing_technique == IndexTechniqueType.HIGH_QUALITY:if dataset.embedding_model_provider:provider_id = ModelProviderID(dataset.embedding_model_provider)@@ -574,6 +658,7 @@ class DatasetApi(Resource):@cloud_edition_billing_rate_limit_check("knowledge")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self, current_tenant_id: str, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -593,16 +678,23 @@ class DatasetApi(Resource):payload.is_multimodal = is_multimodalpayload_data = payload.model_dump(exclude_unset=True)# The role of the current user in the ta table must be admin, owner, editor, or dataset_operator- DatasetPermissionService.check_permission(- current_user, dataset, payload.permission, payload.partial_member_list- )+ if not dify_config.RBAC_ENABLED:+ DatasetPermissionService.check_permission(+ current_user, dataset, payload.permission, payload.partial_member_list+ )dataset = DatasetService.update_dataset(dataset_id_str, payload_data, current_user)if dataset is None:raise NotFound("Dataset not found.")+ permission_keys_map = enterprise_rbac_service.RBACService.DatasetPermissions.batch_get(+ str(current_tenant_id),+ current_user.id,+ [dataset_id_str],+ )result_data = dump_response(DatasetDetailResponse, dataset)+ result_data["permission_keys"] = permission_keys_map.get(dataset_id_str, [])tenant_id = current_tenant_idif payload.partial_member_list is not None and payload.permission == DatasetPermissionEnum.PARTIAL_TEAM:@@ -622,6 +714,7 @@ class DatasetApi(Resource):@cloud_edition_billing_rate_limit_check("knowledge")@console_ns.response(204, "Dataset deleted successfully")@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def delete(self, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)@@ -651,6 +744,7 @@ class DatasetUseCheckApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, dataset_id: UUID):dataset_id_str = str(dataset_id)@@ -672,6 +766,7 @@ class DatasetQueryApi(Resource):@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -812,6 +907,7 @@ class DatasetRelatedAppListApi(Resource):@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -848,6 +944,7 @@ class DatasetIndexingStatusApi(Resource):@login_required@account_initialization_required@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, current_tenant_id: str, dataset_id: UUID):dataset_id_str = str(dataset_id)documents = db.session.scalars(@@ -917,6 +1014,7 @@ class DatasetApiKeyApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, current_tenant_id: str):@@ -957,6 +1055,7 @@ class DatasetApiDeleteApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef delete(self, current_tenant_id: str, api_key_id: UUID):@@ -991,6 +1090,7 @@ class DatasetEnableApiApi(Resource):@login_required@account_initialization_required@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, dataset_id: UUID, status: str):dataset_id_str = str(dataset_id)@@ -1060,6 +1160,7 @@ class DatasetErrorDocs(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -1086,6 +1187,7 @@ class DatasetPermissionUserListApi(Resource):@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -1115,6 +1217,7 @@ class DatasetAutoDisableLogApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)diff --git a/api/controllers/console/datasets/datasets_document.py b/api/controllers/console/datasets/datasets_document.pyindex d4d50600a09..07e150617bf 100644--- a/api/controllers/console/datasets/datasets_document.py+++ b/api/controllers/console/datasets/datasets_document.py@@ -19,6 +19,7 @@ from controllers.common.controller_schemas import DocumentBatchDownloadZipPayloafrom controllers.common.fields import BinaryFileResponse, SimpleResultMessageResponse, SimpleResultResponse, UrlResponsefrom controllers.common.schema import register_response_schema_models, register_schema_modelsfrom controllers.console import console_ns+from controllers.console.wraps import RBACPermission, RBACResourceScope, rbac_permission_requiredfrom core.errors.error import (LLMBadRequestError,ModelCurrentlyNotSupportError,@@ -289,6 +290,7 @@ class DatasetDocumentListApi(Resource):@account_initialization_required@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)raw_args = request.args.to_dict()@@ -415,6 +417,7 @@ class DatasetDocumentListApi(Resource):@console_ns.expect(console_ns.models[KnowledgeConfig.__name__])@console_ns.response(200, "Documents created successfully", console_ns.models[DatasetAndDocumentResponse.__name__])@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)@@ -458,6 +461,7 @@ class DatasetDocumentListApi(Resource):@account_initialization_required@cloud_edition_billing_rate_limit_check("knowledge")@console_ns.response(204, "Documents deleted successfully")+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def delete(self, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -555,6 +559,7 @@ class DocumentIndexingEstimateApi(DocumentResource):@account_initialization_required@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):dataset_id_str = str(dataset_id)document_id_str = str(document_id)@@ -626,6 +631,7 @@ class DocumentBatchIndexingEstimateApi(DocumentResource):@account_initialization_required@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, batch: str):dataset_id_str = str(dataset_id)documents = self.get_batch_documents(dataset_id_str, batch, current_user)@@ -726,6 +732,7 @@ class DocumentBatchIndexingStatusApi(DocumentResource):@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_user: Account, dataset_id: UUID, batch: str):dataset_id_str = str(dataset_id)documents = self.get_batch_documents(dataset_id_str, batch, current_user)@@ -783,6 +790,7 @@ class DocumentIndexingStatusApi(DocumentResource):@account_initialization_required@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):dataset_id_str = str(dataset_id)document_id_str = str(document_id)@@ -846,6 +854,7 @@ class DocumentApi(DocumentResource):@account_initialization_required@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):dataset_id_str = str(dataset_id)document_id_str = str(document_id)@@ -937,6 +946,7 @@ class DocumentApi(DocumentResource):@console_ns.response(204, "Document deleted successfully")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def delete(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):dataset_id_str = str(dataset_id)document_id_str = str(document_id)@@ -969,6 +979,7 @@ class DocumentDownloadApi(DocumentResource):@cloud_edition_billing_rate_limit_check("knowledge")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_DOCUMENT_DOWNLOAD)def get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID) -> dict[str, Any]:# Reuse the shared permission/tenant checks implemented in DocumentResource.document = self.get_document(str(dataset_id), str(document_id), current_user, current_tenant_id)@@ -989,6 +1000,7 @@ class DocumentBatchDownloadZipApi(DocumentResource):@console_ns.expect(console_ns.models[DocumentBatchDownloadZipPayload.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_tenant_id: str, current_user: Account, dataset_id: UUID):"""Stream a ZIP archive containing the requested uploaded documents."""# Parse and validate request payload.@@ -1037,6 +1049,7 @@ class DocumentProcessingApi(DocumentResource):@cloud_edition_billing_rate_limit_check("knowledge")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self,current_tenant_id: str,@@ -1093,6 +1106,7 @@ class DocumentMetadataApi(DocumentResource):@account_initialization_required@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def put(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):dataset_id_str = str(dataset_id)document_id_str = str(document_id)@@ -1142,6 +1156,7 @@ class DocumentStatusApi(DocumentResource):@cloud_edition_billing_rate_limit_check("knowledge")@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self, current_user: Account, dataset_id: UUID, action: Literal["enable", "disable", "archive", "un_archive"]):@@ -1181,6 +1196,7 @@ class DocumentPauseApi(DocumentResource):@account_initialization_required@cloud_edition_billing_rate_limit_check("knowledge")@console_ns.response(204, "Document paused successfully")+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self, dataset_id: UUID, document_id: UUID):"""pause document."""dataset_id_str = str(dataset_id)@@ -1216,6 +1232,7 @@ class DocumentRecoverApi(DocumentResource):@account_initialization_required@cloud_edition_billing_rate_limit_check("knowledge")@console_ns.response(204, "Document resumed successfully")+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self, dataset_id: UUID, document_id: UUID):"""recover document."""dataset_id_str = str(dataset_id)@@ -1249,6 +1266,7 @@ class DocumentRetryApi(DocumentResource):@cloud_edition_billing_rate_limit_check("knowledge")@console_ns.expect(console_ns.models[DocumentRetryPayload.__name__])@console_ns.response(204, "Documents retry started successfully")+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, dataset_id: UUID):"""retry document."""payload = DocumentRetryPayload.model_validate(console_ns.payload or {})@@ -1290,6 +1308,7 @@ class DocumentRenameApi(DocumentResource):@console_ns.response(200, "Document renamed successfully", console_ns.models[DocumentResponse.__name__])@console_ns.expect(console_ns.models[DocumentRenamePayload.__name__])@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_user: Account, dataset_id: UUID, document_id: UUID):# The role of the current user in the ta table must be admin, owner, editor, or dataset_operatorif not current_user.is_dataset_editor:@@ -1315,6 +1334,7 @@ class WebsiteDocumentSyncApi(DocumentResource):@account_initialization_required@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_tenant_id: str, dataset_id: UUID, document_id: UUID):"""sync website document."""dataset_id_str = str(dataset_id)@@ -1348,6 +1368,7 @@ class DocumentPipelineExecutionLogApi(DocumentResource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, dataset_id: UUID, document_id: UUID):dataset_id_str = str(dataset_id)document_id_str = str(document_id)@@ -1398,6 +1419,7 @@ class DocumentGenerateSummaryApi(Resource):@account_initialization_required@cloud_edition_billing_rate_limit_check("knowledge")@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_user: Account, dataset_id: UUID):"""Generate summary index for specified documents.@@ -1491,6 +1513,7 @@ class DocumentSummaryStatusApi(DocumentResource):@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, current_user: Account, dataset_id: UUID, document_id: UUID):"""Get summary index generation status for a document.diff --git a/api/controllers/console/datasets/datasets_segments.py b/api/controllers/console/datasets/datasets_segments.pyindex 4e521100abe..4858b5ff6b0 100644--- a/api/controllers/console/datasets/datasets_segments.py+++ b/api/controllers/console/datasets/datasets_segments.py@@ -28,10 +28,13 @@ from controllers.console.datasets.error import (InvalidActionError,)from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,cloud_edition_billing_knowledge_limit_check,cloud_edition_billing_rate_limit_check,cloud_edition_billing_resource_check,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -169,6 +172,7 @@ class DatasetDocumentSegmentListApi(Resource):@account_initialization_required@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):dataset_id_str = str(dataset_id)document_id_str = str(document_id)@@ -278,6 +282,7 @@ class DatasetDocumentSegmentListApi(Resource):@console_ns.doc(params=query_params_from_model(SegmentIdListQuery))@console_ns.response(204, "Segments deleted successfully")@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def delete(self, current_user: Account, dataset_id: UUID, document_id: UUID):# check datasetdataset_id_str = str(dataset_id)@@ -316,6 +321,7 @@ class DatasetDocumentSegmentApi(Resource):@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self,current_tenant_id: str,@@ -384,6 +390,7 @@ class DatasetDocumentSegmentAddApi(Resource):@console_ns.response(200, "Segment created successfully", console_ns.models[SegmentDetailResponse.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):# check datasetdataset_id_str = str(dataset_id)@@ -442,6 +449,7 @@ class DatasetDocumentSegmentUpdateApi(Resource):@console_ns.response(200, "Segment updated successfully", console_ns.models[SegmentDetailResponse.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID, segment_id: UUID):@@ -513,6 +521,7 @@ class DatasetDocumentSegmentUpdateApi(Resource):@console_ns.response(204, "Segment deleted successfully")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def delete(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID, segment_id: UUID):@@ -563,6 +572,7 @@ class DatasetDocumentSegmentBatchImportApi(Resource):@console_ns.expect(console_ns.models[BatchImportPayload.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID):# check datasetdataset_id_str = str(dataset_id)@@ -608,6 +618,7 @@ class DatasetDocumentSegmentBatchImportApi(Resource):@setup_required@login_required@account_initialization_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, job_id=None, dataset_id: UUID | None = None, document_id: UUID | None = None):if job_id is None:raise NotFound("The job does not exist.")@@ -634,6 +645,7 @@ class ChildChunkAddApi(Resource):@console_ns.response(200, "Child chunk created successfully", console_ns.models[ChildChunkDetailResponse.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID, segment_id: UUID):@@ -693,6 +705,7 @@ class ChildChunkAddApi(Resource):@login_required@account_initialization_required@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, current_tenant_id: str, dataset_id: UUID, document_id: UUID, segment_id: UUID):# check datasetdataset_id_str = str(dataset_id)@@ -747,6 +760,7 @@ class ChildChunkAddApi(Resource):@console_ns.expect(console_ns.models[ChildChunkBatchUpdatePayload.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID, segment_id: UUID):@@ -799,6 +813,7 @@ class ChildChunkUpdateApi(Resource):@console_ns.response(204, "Child chunk deleted successfully")@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def delete(self,current_tenant_id: str,@@ -866,6 +881,7 @@ class ChildChunkUpdateApi(Resource):@console_ns.response(200, "Child chunk updated successfully", console_ns.models[ChildChunkDetailResponse.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self,current_tenant_id: str,diff --git a/api/controllers/console/datasets/external.py b/api/controllers/console/datasets/external.pyindex fb19ad81c67..033c9a69af6 100644--- a/api/controllers/console/datasets/external.py+++ b/api/controllers/console/datasets/external.py@@ -17,8 +17,11 @@ from controllers.common.schema import (from controllers.console import console_nsfrom controllers.console.datasets.error import DatasetNameDuplicateErrorfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -40,6 +43,7 @@ from fields.dataset_fields import (from libs.login import login_requiredfrom models import Accountfrom services.dataset_service import DatasetService+from services.enterprise import rbac_service as enterprise_rbac_servicefrom services.external_knowledge_service import ExternalDatasetServicefrom services.hit_testing_service import HitTestingServicefrom services.knowledge_service import BedrockRetrievalSetting, ExternalDatasetTestService@@ -319,6 +323,7 @@ class ExternalDatasetCreateApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EXTERNAL_CONNECT)@with_current_user@with_current_tenant_iddef post(self, current_tenant_id: str, current_user: Account):@@ -339,7 +344,16 @@ class ExternalDatasetCreateApi(Resource):except services.errors.dataset.DatasetNameDuplicateError:raise DatasetNameDuplicateError()- return marshal(dataset, dataset_detail_fields), 201+ item = marshal(dataset, dataset_detail_fields)+ dataset_id_str = item["id"]+ permission_keys_map = enterprise_rbac_service.RBACService.DatasetPermissions.batch_get(+ str(current_tenant_id),+ current_user.id,+ [dataset_id_str],+ )+ item["permission_keys"] = permission_keys_map.get(dataset_id_str, [])++ return item, 201@console_ns.route("/datasets/<uuid:dataset_id>/external-hit-testing")@@ -359,6 +373,7 @@ class ExternalKnowledgeHitTestingApi(Resource):@login_required@account_initialization_required@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_PIPELINE_TEST)def post(self, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)diff --git a/api/controllers/console/datasets/hit_testing.py b/api/controllers/console/datasets/hit_testing.pyindex c08ed2fe9f0..739f0250333 100644--- a/api/controllers/console/datasets/hit_testing.py+++ b/api/controllers/console/datasets/hit_testing.py@@ -5,6 +5,7 @@ from uuid import UUIDfrom flask_restx import Resourcefrom controllers.common.schema import register_response_schema_models, register_schema_models+from controllers.console.wraps import RBACPermission, RBACResourceScope, rbac_permission_requiredfrom fields.hit_testing_fields import HitTestingResponsefrom libs.helper import dump_responsefrom libs.login import login_required@@ -43,6 +44,7 @@ class HitTestingApi(Resource, DatasetsHitTestingBase):@cloud_edition_billing_rate_limit_check("knowledge")@with_current_tenant_id@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_PIPELINE_TEST)def post(self, current_user: Account, current_tenant_id: str, dataset_id: UUID) -> dict[str, object]:dataset_id_str = str(dataset_id)diff --git a/api/controllers/console/datasets/metadata.py b/api/controllers/console/datasets/metadata.pyindex ec4c5bedb61..7195fe066fd 100644--- a/api/controllers/console/datasets/metadata.py+++ b/api/controllers/console/datasets/metadata.py@@ -8,8 +8,11 @@ from controllers.common.controller_schemas import MetadataUpdatePayloadfrom controllers.common.schema import register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,enterprise_license_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -52,6 +55,7 @@ class DatasetMetadataCreateApi(Resource):@console_ns.expect(console_ns.models[MetadataArgs.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_tenant_id: str, current_user: Account, dataset_id: UUID):metadata_args = MetadataArgs.model_validate(console_ns.payload or {})@@ -71,6 +75,7 @@ class DatasetMetadataCreateApi(Resource):@console_ns.response(200, "Metadata retrieved successfully", console_ns.models[DatasetMetadataListResponse.__name__])+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT)def get(self, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -90,6 +95,7 @@ class DatasetMetadataApi(Resource):@console_ns.expect(console_ns.models[MetadataUpdatePayload.__name__])@with_current_user@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def patch(self, current_tenant_id: str, current_user: Account, dataset_id: UUID, metadata_id: UUID):payload = MetadataUpdatePayload.model_validate(console_ns.payload or {})name = payload.name@@ -112,6 +118,7 @@ class DatasetMetadataApi(Resource):@enterprise_license_required@console_ns.response(204, "Metadata deleted successfully")@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def delete(self, current_user: Account, dataset_id: UUID, metadata_id: UUID):dataset_id_str = str(dataset_id)metadata_id_str = str(metadata_id)@@ -149,6 +156,7 @@ class DatasetMetadataBuiltInFieldActionApi(Resource):@enterprise_license_required@console_ns.response(204, "Action completed successfully")@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_user: Account, dataset_id: UUID, action: Literal["enable", "disable"]):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)@@ -177,6 +185,7 @@ class DocumentMetadataEditApi(Resource):"Documents metadata updated successfully",)@with_current_user+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_user: Account, dataset_id: UUID):dataset_id_str = str(dataset_id)dataset = DatasetService.get_dataset(dataset_id_str)diff --git a/api/controllers/console/datasets/rag_pipeline/datasource_auth.py b/api/controllers/console/datasets/rag_pipeline/datasource_auth.pyindex 980f116e216..c5ca1d155de 100644--- a/api/controllers/console/datasets/rag_pipeline/datasource_auth.py+++ b/api/controllers/console/datasets/rag_pipeline/datasource_auth.py@@ -10,8 +10,11 @@ from controllers.common.fields import RedirectResponse, SimpleResultResponsefrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -104,6 +107,7 @@ class DatasourcePluginOAuthAuthorizationUrl(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@with_current_user@with_current_tenant_iddef get(self, current_tenant_id: str, current_user: Account, provider_id: str):@@ -218,6 +222,7 @@ class DatasourceAuth(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@with_current_tenant_iddef post(self, current_tenant_id: str, provider_id: str):payload = DatasourceCredentialPayload.model_validate(console_ns.payload or {})@@ -262,6 +267,7 @@ class DatasourceAuthDeleteApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@with_current_tenant_iddef post(self, current_tenant_id: str, provider_id: str):datasource_provider_id = DatasourceProviderID(provider_id)@@ -287,6 +293,7 @@ class DatasourceAuthUpdateApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@with_current_tenant_iddef post(self, current_tenant_id: str, provider_id: str):datasource_provider_id = DatasourceProviderID(provider_id)@@ -338,6 +345,7 @@ class DatasourceAuthOauthCustomClient(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@with_current_tenant_iddef post(self, current_tenant_id: str, provider_id: str):payload = DatasourceCustomClientPayload.model_validate(console_ns.payload or {})@@ -374,6 +382,7 @@ class DatasourceAuthDefaultApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@with_current_tenant_iddef post(self, current_tenant_id: str, provider_id: str):payload = DatasourceDefaultPayload.model_validate(console_ns.payload or {})@@ -395,6 +404,7 @@ class DatasourceUpdateProviderNameApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@with_current_tenant_iddef post(self, current_tenant_id: str, provider_id: str):payload = DatasourceUpdateNamePayload.model_validate(console_ns.payload or {})diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.pyindex e0c8d95b766..0b83dc9312d 100644--- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.py+++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.py@@ -13,8 +13,11 @@ from controllers.common.schema import (from controllers.console import console_nsfrom controllers.console.datasets.wraps import get_rag_pipelinefrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_user,)@@ -78,6 +81,9 @@ class RagPipelineImportApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False+ )@with_current_userdef post(self, current_user: Account) -> JsonResponseWithStatus:# Check user role first@@ -122,6 +128,9 @@ class RagPipelineImportConfirmApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False+ )@with_current_userdef post(self, current_user: Account, import_id: str) -> JsonResponseWithStatus:with Session(db.engine, expire_on_commit=False) as session:@@ -151,6 +160,7 @@ class RagPipelineImportCheckDependenciesApi(Resource):@get_rag_pipeline@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY)def get(self, pipeline: Pipeline) -> JsonResponseWithStatus:with Session(db.engine, expire_on_commit=False) as session:import_service = RagPipelineDslService(session)@@ -168,6 +178,7 @@ class RagPipelineExportApi(Resource):@get_rag_pipeline@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_IMPORT_EXPORT_DSL)def get(self, pipeline: Pipeline) -> JsonResponseWithStatus:# Add include_secret paramsquery = IncludeSecretQuery.model_validate(request.args.to_dict())diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.pyindex 7c941e14368..fdc55ea9737 100644--- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py+++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py@@ -28,8 +28,11 @@ from controllers.console.app.workflow import ()from controllers.console.datasets.wraps import get_rag_pipelinefrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -186,6 +189,7 @@ class DraftRagPipelineApi(Resource):@account_initialization_required@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def get(self, pipeline: Pipeline):"""Get draft rag pipeline's workflow@@ -206,6 +210,7 @@ class DraftRagPipelineApi(Resource):@with_current_user@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@console_ns.expect(console_ns.models[DraftWorkflowSyncPayload.__name__])@console_ns.response(200, "Success", console_ns.models[RagPipelineWorkflowSyncResponse.__name__])def post(self, current_user: Account, pipeline: Pipeline):@@ -266,6 +271,7 @@ class RagPipelineDraftRunIterationNodeApi(Resource):@with_current_user@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_user: Account, pipeline: Pipeline, node_id: str):"""Run draft workflow iteration node@@ -298,6 +304,7 @@ class RagPipelineDraftRunLoopNodeApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipelinedef post(self, current_user: Account, pipeline: Pipeline, node_id: str):@@ -332,6 +339,7 @@ class DraftRagPipelineRunApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipelinedef post(self, current_user: Account, pipeline: Pipeline):@@ -363,6 +371,7 @@ class PublishedRagPipelineRunApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipelinedef post(self, current_user: Account, pipeline: Pipeline):@@ -395,6 +404,7 @@ class RagPipelinePublishedDatasourceNodeRunApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipelinedef post(self, current_user: Account, pipeline: Pipeline, node_id: str):@@ -426,6 +436,7 @@ class RagPipelineDraftDatasourceNodeRunApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@account_initialization_required@with_current_user@get_rag_pipeline@@ -462,6 +473,7 @@ class RagPipelineDraftNodeRunApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@account_initialization_required@with_current_user@get_rag_pipeline@@ -491,6 +503,7 @@ class RagPipelineTaskStopApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@account_initialization_required@with_current_user@get_rag_pipeline@@ -514,6 +527,7 @@ class PublishedRagPipelineApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@get_rag_pipelinedef get(self, pipeline: Pipeline):"""@@ -537,6 +551,7 @@ class PublishedRagPipelineApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipelinedef post(self, current_user: Account, pipeline: Pipeline):@@ -571,6 +586,7 @@ class DefaultRagPipelineBlockConfigsApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@get_rag_pipelinedef get(self, pipeline: Pipeline):"""@@ -593,6 +609,7 @@ class DefaultRagPipelineBlockConfigApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@get_rag_pipelinedef get(self, pipeline: Pipeline, block_type: str):"""@@ -625,6 +642,7 @@ class PublishedAllRagPipelineApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipelinedef get(self, current_user: Account, pipeline: Pipeline):@@ -670,6 +688,7 @@ class RagPipelineDraftWorkflowRestoreApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipelinedef post(self, current_user: Account, pipeline: Pipeline, workflow_id: str):@@ -704,6 +723,7 @@ class RagPipelineByIdApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@with_current_user@get_rag_pipeline@console_ns.expect(console_ns.models[WorkflowUpdatePayload.__name__])@@ -739,6 +759,7 @@ class RagPipelineByIdApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)@get_rag_pipelinedef delete(self, pipeline: Pipeline, workflow_id: str):"""@@ -775,6 +796,7 @@ class PublishedRagPipelineSecondStepApi(Resource):@account_initialization_required@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def get(self, pipeline: Pipeline):"""Get second step parameters of rag pipeline@@ -797,6 +819,7 @@ class PublishedRagPipelineFirstStepApi(Resource):@account_initialization_required@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def get(self, pipeline: Pipeline):"""Get first step parameters of rag pipeline@@ -819,6 +842,7 @@ class DraftRagPipelineFirstStepApi(Resource):@account_initialization_required@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def get(self, pipeline: Pipeline):"""Get first step parameters of rag pipeline@@ -841,6 +865,7 @@ class DraftRagPipelineSecondStepApi(Resource):@account_initialization_required@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def get(self, pipeline: Pipeline):"""Get second step parameters of rag pipeline@@ -1012,6 +1037,7 @@ class RagPipelineDatasourceVariableApi(Resource):@with_current_user@get_rag_pipeline@edit_permission_required+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)def post(self, current_user: Account, pipeline: Pipeline):"""Set datasource variablesdiff --git a/api/controllers/console/snippets/snippet_workflow.py b/api/controllers/console/snippets/snippet_workflow.pyindex 243c29e6719..5af885ab91b 100644--- a/api/controllers/console/snippets/snippet_workflow.py+++ b/api/controllers/console/snippets/snippet_workflow.py@@ -31,8 +31,11 @@ from controllers.console.snippets.payloads import (WorkflowRunQuery,)from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_user,)@@ -154,6 +157,7 @@ class SnippetDraftWorkflowApi(Resource):@account_initialization_required@get_snippet@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False)def get(self, snippet: CustomizedSnippet):"""Get draft workflow for snippet."""snippet_service = _snippet_service()@@ -181,6 +185,9 @@ class SnippetDraftWorkflowApi(Resource):@with_current_user@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, current_user: Account, snippet: CustomizedSnippet):"""Sync draft workflow for snippet."""payload = SnippetDraftSyncPayload.model_validate(console_ns.payload or {})@@ -219,6 +226,7 @@ class SnippetDraftConfigApi(Resource):@account_initialization_required@get_snippet@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False)def get(self, snippet: CustomizedSnippet):"""Get snippet draft workflow configuration limits."""return {@@ -240,6 +248,7 @@ class SnippetPublishedWorkflowApi(Resource):@account_initialization_required@get_snippet@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False)def get(self, snippet: CustomizedSnippet):"""Get published workflow for snippet."""if not snippet.is_published:@@ -265,6 +274,9 @@ class SnippetPublishedWorkflowApi(Resource):@with_current_user@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, current_user: Account, snippet: CustomizedSnippet):"""Publish snippet workflow."""snippet_service = _snippet_service()@@ -301,6 +313,7 @@ class SnippetDefaultBlockConfigsApi(Resource):@account_initialization_required@get_snippet@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False)def get(self, snippet: CustomizedSnippet):"""Get default block configurations for snippet workflow."""snippet_service = _snippet_service()@@ -323,6 +336,7 @@ class SnippetPublishedAllWorkflowApi(Resource):@account_initialization_required@get_snippet@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False)def get(self, snippet: CustomizedSnippet):"""Get all published workflow versions for snippet."""args = SnippetWorkflowListQuery.model_validate(request.args.to_dict(flat=True))@@ -361,6 +375,9 @@ class SnippetDraftWorkflowRestoreApi(Resource):@with_current_user@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, current_user: Account, snippet: CustomizedSnippet, workflow_id: str):"""Restore a published snippet workflow version into the draft workflow."""snippet_service = _snippet_service()@@ -486,6 +503,9 @@ class SnippetDraftNodeRunApi(Resource):@with_current_user@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, current_user: Account, snippet: CustomizedSnippet, node_id: str):"""Run a single node in snippet draft workflow.@@ -574,6 +594,9 @@ class SnippetDraftRunIterationNodeApi(Resource):@with_current_user@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, current_user: Account, snippet: CustomizedSnippet, node_id: str):"""Run a draft workflow iteration node for snippet.@@ -619,6 +642,9 @@ class SnippetDraftRunLoopNodeApi(Resource):@with_current_user@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, current_user: Account, snippet: CustomizedSnippet, node_id: str):"""Run a draft workflow loop node for snippet.@@ -662,6 +688,9 @@ class SnippetDraftWorkflowRunApi(Resource):@with_current_user@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, current_user: Account, snippet: CustomizedSnippet):"""Run draft workflow for snippet.@@ -700,6 +729,9 @@ class SnippetWorkflowTaskStopApi(Resource):@account_initialization_required@get_snippet@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def post(self, snippet: CustomizedSnippet, task_id: str):"""Stop a running snippet workflow task.diff --git a/api/controllers/console/snippets/snippet_workflow_draft_variable.py b/api/controllers/console/snippets/snippet_workflow_draft_variable.pyindex a28ba07b5dd..4befd259666 100644--- a/api/controllers/console/snippets/snippet_workflow_draft_variable.py+++ b/api/controllers/console/snippets/snippet_workflow_draft_variable.py@@ -34,8 +34,11 @@ from controllers.console.app.workflow_draft_variable import ()from controllers.console.snippets.snippet_workflow import get_snippetfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_user,)@@ -102,6 +105,7 @@ class SnippetWorkflowVariableCollectionApi(Resource):)@_snippet_draft_var_prerequisite@marshal_with(workflow_draft_variable_list_without_value_model)+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False)def get(self, current_user: Account, snippet: CustomizedSnippet) -> WorkflowDraftVariableList:args = WorkflowDraftVariableListQuery.model_validate(request.args.to_dict(flat=True)) # type: ignore@@ -125,6 +129,9 @@ class SnippetWorkflowVariableCollectionApi(Resource):@console_ns.doc(description="Delete all draft workflow variables for the current user (snippet scope)")@console_ns.response(204, "Workflow variables deleted successfully")@_snippet_draft_var_prerequisite+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )def delete(self, current_user: Account, snippet: CustomizedSnippet) -> Response:draft_var_srv = WorkflowDraftVariableService(session=db.session())draft_var_srv.delete_user_workflow_variables(snippet.id, user_id=current_user.id)diff --git a/api/controllers/console/workspace/endpoint.py b/api/controllers/console/workspace/endpoint.pyindex 9c5aa166bc0..821e30ee7e3 100644--- a/api/controllers/console/workspace/endpoint.py+++ b/api/controllers/console/workspace/endpoint.py@@ -15,8 +15,11 @@ from pydantic import BaseModel, Fieldfrom controllers.common.schema import query_params_from_model, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user_id,@@ -166,6 +169,7 @@ class EndpointCollectionApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_id@@ -194,6 +198,7 @@ class DeprecatedEndpointCreateApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_id@@ -285,6 +290,7 @@ class EndpointItemApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_id@@ -304,6 +310,7 @@ class EndpointItemApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_id@@ -333,6 +340,7 @@ class DeprecatedEndpointDeleteApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_id@@ -363,6 +371,7 @@ class DeprecatedEndpointUpdateApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_id@@ -385,6 +394,7 @@ class EndpointEnableApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_id@@ -412,6 +422,7 @@ class EndpointDisableApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user_id@with_current_tenant_iddiff --git a/api/controllers/console/workspace/members.py b/api/controllers/console/workspace/members.pyindex 59fd3e2c5b5..b3230d77e69 100644--- a/api/controllers/console/workspace/members.py+++ b/api/controllers/console/workspace/members.py@@ -32,16 +32,17 @@ from extensions.ext_redis import redis_clientfrom fields.base import ResponseModelfrom fields.member_fields import AccountWithRole, AccountWithRoleListfrom libs.helper import extract_remote_ip-from libs.login import login_required+from libs.login import current_account_with_tenant, login_requiredfrom models.account import Account, TenantAccountJoin, TenantAccountRolefrom services.account_service import AccountService, RegisterService, TenantService+from services.enterprise import rbac_service as enterprise_rbac_servicefrom services.errors.account import AccountAlreadyInTenantErrorfrom services.feature_service import FeatureServiceclass MemberInvitePayload(BaseModel):emails: list[str] = Field(default_factory=list)- role: TenantAccountRole+ role: strlanguage: str | None = None@@ -107,6 +108,22 @@ def _is_role_enabled(role: TenantAccountRole | str, tenant_id: str) -> bool:return FeatureService.get_features(tenant_id=tenant_id, exclude_vector_space=True).dataset_operator_enabled+def _serialize_member_roles(+ current_role: str | None, member_roles: list[enterprise_rbac_service.RBACRole]+) -> list[dict[str, str]]:+ if dify_config.RBAC_ENABLED:+ return [{"id": role.id, "name": role.name} for role in member_roles]+ else:+ if current_role:+ return [{"id": current_role, "name": current_role}]+ return []+++def _normalize_enum_value(value: object) -> str:+ normalized = getattr(value, "value", value)+ return str(normalized) if normalized is not None else ""++def _normalize_invitee_emails(emails: list[str]) -> list[str]:return list(dict.fromkeys(email.lower() for email in emails))@@ -164,11 +181,42 @@ class MemberListApi(Resource):@account_initialization_required@console_ns.response(200, "Success", console_ns.models[AccountWithRoleList.__name__])@with_current_user- def get(self, current_user: Account):+ def get(self, current_user: Account | None = None):+ if current_user is None:+ current_user, _ = current_account_with_tenant()if not current_user.current_tenant:raise ValueError("No current tenant")members = TenantService.get_tenant_members(current_user.current_tenant)- member_models = TypeAdapter(list[AccountWithRole]).validate_python(members, from_attributes=True)+ if dify_config.RBAC_ENABLED:+ member_ids = [member.id for member in members]+ member_roles = enterprise_rbac_service.RBACService.MemberRoles.batch_get(+ str(current_user.current_tenant.id),+ current_user.id,+ member_ids,+ )+ roles_map = {item.account_id: item.roles for item in member_roles}+ else:+ roles_map = {}++ serialized_members = []+ for member in members:+ current_role = _normalize_enum_value(member.current_role)+ serialized_members.append(+ {+ "id": member.id,+ "name": member.name,+ "email": member.email,+ "avatar": member.avatar,+ "last_login_at": member.last_login_at,+ "last_active_at": member.last_active_at,+ "created_at": member.created_at,+ "role": current_role,+ "roles": _serialize_member_roles(current_role, roles_map.get(member.id, [])),+ "status": _normalize_enum_value(member.status),+ }+ )++ member_models = TypeAdapter(list[AccountWithRole]).validate_python(serialized_members)response = AccountWithRoleList(accounts=member_models)return response.model_dump(mode="json"), 200@@ -190,8 +238,11 @@ class MemberInviteEmailApi(Resource):invitee_emails = _normalize_invitee_emails(args.emails)invitee_role = args.roleinterface_language = args.language- if not TenantAccountRole.is_non_owner_role(invitee_role):- return {"code": "invalid-role", "message": "Invalid role"}, 400+ if not dify_config.RBAC_ENABLED:+ if not TenantAccountRole.is_valid_role(invitee_role):+ return {"code": "invalid-role", "message": "Invalid role"}, 400+ if not TenantAccountRole.is_non_owner_role(TenantAccountRole(invitee_role)):+ return {"code": "invalid-role", "message": "Invalid role"}, 400inviter = current_userif not inviter.current_tenant:raise ValueError("No current tenant")@@ -208,8 +259,9 @@ class MemberInviteEmailApi(Resource):tenant_id = inviter.current_tenant.idwith redis_client.lock(f"workspace_member_invite:{tenant_id}", timeout=60):- new_member_count = _count_new_member_invites(tenant_id, invitee_emails)- _check_member_invite_limits(tenant_id, new_member_count)+ if dify_config.ENTERPRISE_ENABLED is True or dify_config.BILLING_ENABLED is True:+ new_member_count = _count_new_member_invites(tenant_id, invitee_emails)+ _check_member_invite_limits(tenant_id, new_member_count)for invitee_email in invitee_emails:try:diff --git a/api/controllers/console/workspace/model_providers.py b/api/controllers/console/workspace/model_providers.pyindex 07c124890cf..8fda67f4ef8 100644--- a/api/controllers/console/workspace/model_providers.py+++ b/api/controllers/console/workspace/model_providers.py@@ -9,8 +9,11 @@ from controllers.common.fields import BinaryFileResponse, SimpleResultResponsefrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -166,6 +169,7 @@ class ModelProviderCredentialApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, current_tenant_id: str, provider: str):@@ -191,6 +195,7 @@ class ModelProviderCredentialApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef put(self, current_tenant_id: str, provider: str):@@ -217,6 +222,7 @@ class ModelProviderCredentialApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef delete(self, current_tenant_id: str, provider: str):@@ -238,6 +244,7 @@ class ModelProviderCredentialSwitchApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, current_tenant_id: str, provider: str):@@ -319,6 +326,7 @@ class PreferredProviderTypeUpdateApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, provider: str):diff --git a/api/controllers/console/workspace/models.py b/api/controllers/console/workspace/models.pyindex 2139d6f18e0..e82c0fbc2db 100644--- a/api/controllers/console/workspace/models.py+++ b/api/controllers/console/workspace/models.py@@ -14,8 +14,11 @@ from controllers.common.schema import ()from controllers.console import console_nsfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -217,6 +220,7 @@ class DefaultModelApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str):@@ -263,6 +267,7 @@ class ModelProviderModelApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, provider: str):@@ -310,6 +315,7 @@ class ModelProviderModelApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_tenant_iddef delete(self, tenant_id: str, provider: str):@@ -389,6 +395,7 @@ class ModelProviderModelCredentialApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, provider: str):@@ -421,6 +428,7 @@ class ModelProviderModelCredentialApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef put(self, current_tenant_id: str, provider: str):@@ -448,6 +456,7 @@ class ModelProviderModelCredentialApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef delete(self, current_tenant_id: str, provider: str):@@ -472,6 +481,7 @@ class ModelProviderModelCredentialSwitchApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, current_tenant_id: str, provider: str):@@ -498,6 +508,7 @@ class ModelProviderModelEnableApi(Resource):@login_required@account_initialization_required@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)def patch(self, tenant_id: str, provider: str):args = ParserDeleteModels.model_validate(console_ns.payload)@@ -519,6 +530,7 @@ class ModelProviderModelDisableApi(Resource):@login_required@account_initialization_required@with_current_tenant_id+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)def patch(self, tenant_id: str, provider: str):args = ParserDeleteModels.model_validate(console_ns.payload)diff --git a/api/controllers/console/workspace/plugin.py b/api/controllers/console/workspace/plugin.pyindex 94979e25b36..d599466002d 100644--- a/api/controllers/console/workspace/plugin.py+++ b/api/controllers/console/workspace/plugin.py@@ -20,8 +20,11 @@ from controllers.common.schema import (from controllers.console import console_nsfrom controllers.console.workspace import plugin_permission_requiredfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -975,6 +978,7 @@ class PluginFetchDynamicSelectOptionsApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -1005,6 +1009,7 @@ class PluginFetchDynamicSelectOptionsWithCredentialsApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_iddiff --git a/api/controllers/console/workspace/rbac.py b/api/controllers/console/workspace/rbac.pynew file mode 100644index 00000000000..1b213a4f741--- /dev/null+++ b/api/controllers/console/workspace/rbac.py@@ -0,0 +1,939 @@+from __future__ import annotations++from enum import StrEnum+from typing import Any++from flask import request+from flask_restx import Resource+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationError, field_validator+from sqlalchemy import select+from werkzeug.exceptions import NotFound++from configs import dify_config+from controllers.common.schema import register_response_schema_models+from controllers.console import console_ns+from controllers.console.wraps import RBACPermission, RBACResourceScope, rbac_permission_required+from core.db.session_factory import session_factory+from libs.login import current_account_with_tenant, login_required+from models import Account+from services.enterprise import rbac_service as svc+++class _RBACRoleList(svc.Paginated[svc.RBACRole]):+ pass+++class _RBACRoleAccountList(svc.Paginated[svc.RBACRoleAccount]):+ pass+++class _AccessPolicyList(svc.Paginated[svc.AccessPolicy]):+ pass+++class _MembersInRoleList(svc.Paginated[svc.MembersInRole]):+ pass+++register_response_schema_models(+ console_ns,+ svc.PermissionCatalogResponse,+ svc.RBACRole,+ _RBACRoleList,+ _RBACRoleAccountList,+ _MembersInRoleList,+ svc.AccessPolicy,+ _AccessPolicyList,+ svc.AccessPolicyBindingState,+ svc.MyPermissionsResponse,+ svc.AppAccessMatrix,+ svc.DatasetAccessMatrix,+ svc.WorkspaceAccessMatrix,+ svc.ResourceWhitelist,+ svc.ResourceUserAccessPoliciesResponse,+ svc.ReplaceUserAccessPoliciesResponse,+ svc.RoleBindingsResponse,+ svc.MemberBindingsResponse,+ svc.MemberRolesResponse,+ svc.AccessMatrixItem,+)++_LEGACY_ROLE_PERMISSION_KEYS: dict[str, list[str]] = {+ # This is a compatibility projection from the pre-RBAC workspace roles into+ # the 2.0 permission matrix documented in "权限整理2.0". It intentionally+ # models the product-facing role surface for the new RBAC UI instead of the+ # legacy backend's exact hard-authorization checks.+ "owner": [+ *svc._LEGACY_WORKSPACE_OWNER_KEYS,+ *svc._LEGACY_APP_OWNER_KEYS,+ *svc._LEGACY_DATASET_OWNER_KEYS,+ ],+ "admin": [+ *svc._LEGACY_WORKSPACE_ADMIN_KEYS,+ *svc._LEGACY_APP_ADMIN_KEYS,+ *svc._LEGACY_DATASET_ADMIN_KEYS,+ ],+ "editor": [+ *svc._LEGACY_WORKSPACE_EDITOR_KEYS,+ *svc._LEGACY_APP_EDITOR_KEYS,+ *svc._LEGACY_DATASET_EDITOR_KEYS,+ ],+ "normal": [+ *svc._LEGACY_WORKSPACE_NORMAL_KEYS,+ *svc._LEGACY_APP_NORMAL_KEYS,+ ],+ "dataset_operator": [+ *svc._LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS,+ *svc._LEGACY_DATASET_DATASET_OPERATOR_KEYS,+ ],+}+++def _current_ids() -> tuple[str, str]:+ """Return ``(tenant_id, account_id)`` for the authenticated user, or+ raise a 404 when no tenant is associated with the session.+ """++ user, tenant_id = current_account_with_tenant()+ if not tenant_id:+ raise NotFound("Current workspace not found")+ return tenant_id, user.id+++def _payload(model: type[BaseModel]) -> Any:+ """Validate the JSON body against ``model`` or raise ``ValidationError``.++ ``ValidationError`` bubbles up as HTTP 400 thanks to+ ``controllers/common/helpers.py`` error handling.+ """+ try:+ return model.model_validate(console_ns.payload or {})+ except ValidationError as exc:+ # Re-raise as-is so the upstream error handler renders a 400.+ raise exc+++def _dump(model: BaseModel) -> dict[str, Any]:+ return model.model_dump(mode="json")+++def _account_names_by_ids(account_ids: list[str]) -> dict[str, dict[str, str]]:+ ids = sorted({account_id.strip() for account_id in account_ids if account_id and account_id.strip()})+ if not ids:+ return {}++ with session_factory.create_session() as session:+ rows = session.execute(+ select(Account.id, Account.name, Account.avatar, Account.email).where(Account.id.in_(ids))+ ).all()++ return {+ account_id: {+ "name": name or "",+ "avatar": avatar or "",+ "email": email or "",+ }+ for account_id, name, avatar, email in rows+ }+++def _hydrate_access_matrix_account_names(items: list[svc.AccessMatrixItem]) -> None:+ account_ids: list[str] = []+ for item in items:+ for account in item.accounts:+ account_id = account.account_id+ if account_id and not account.account_name:+ account_ids.append(account_id)++ account_names = _account_names_by_ids(account_ids)+ if not account_names:+ return++ for item in items:+ for account in item.accounts:+ account_id = str(account.account_id or "").strip()+ if account_id and not account.account_name:+ account.account_name = account_names.get(account_id, {}).get("name", "")+ account.avatar = account_names.get(account_id, {}).get("avatar", "")+ account.email = account_names.get(account_id, {}).get("email", "")+++def _hydrate_resource_user_account_names(items: list[svc.ResourceUserAccessPolicies]) -> None:+ account_names = _account_names_by_ids([item.account.account_id for item in items])+ for item in items:+ account_id = item.account.account_id+ if account_id and not item.account.account_name:+ item.account.account_name = account_names.get(account_id, {}).get("name", "")+ item.account.avatar = account_names.get(account_id, {}).get("avatar", "")+ item.account.email = account_names.get(account_id, {}).get("email", "")+++class _PaginationQuery(BaseModel):+ model_config = ConfigDict(extra="ignore")++ page_number: int | None = Field(default=None, ge=1, validation_alias=AliasChoices("page", "page_number"))+ results_per_page: int | None = Field(+ default=None, ge=1, le=99999, validation_alias=AliasChoices("limit", "results_per_page")+ )+ reverse: bool | None = None++ def to_inner_options(self) -> svc.ListOption:+ return svc.ListOption.model_validate(self.model_dump())+++class _RolesListQuery(_PaginationQuery):+ include_owner: int = Field(default=0, ge=0, le=1)+++class CopyRoleParam(BaseModel):+ copy_member: bool = True+++def _pagination_options() -> svc.ListOption:+ return _PaginationQuery.model_validate(request.args.to_dict(flat=True)).to_inner_options()+++def _legacy_workspace_roles(+ options: svc.ListOption | None = None, *, include_owner: int = 0+) -> svc.Paginated[svc.RBACRole]:+ """Return the built-in legacy workspace roles in the RBAC list shape.++ This keeps the new `/rbac/roles` endpoint compatible with the original+ Dify role model when enterprise RBAC is disabled.+ """++ legacy_roles = [+ svc.RBACRole(+ id=role_name,+ tenant_id="",+ type=svc.RBACRoleType.WORKSPACE.value,+ category="global_system_default",+ name=role_name,+ description="",+ is_builtin=True,+ permission_keys=list(_LEGACY_ROLE_PERMISSION_KEYS[role_name]),+ role_tag="owner" if role_name == "owner" else "",+ )+ for role_name in ("owner", "admin", "editor", "normal", "dataset_operator")+ ]++ if not include_owner:+ legacy_roles = [r for r in legacy_roles if r.name != "owner"]++ page_number = options.page_number if options and options.page_number is not None else 1+ results_per_page = (+ options.results_per_page if options and options.results_per_page is not None else len(legacy_roles)+ )+ reverse = options.reverse if options and options.reverse is not None else False++ ordered_roles = list(reversed(legacy_roles)) if reverse else legacy_roles+ start = max(page_number - 1, 0) * results_per_page+ end = start + results_per_page+ paged_roles = ordered_roles[start:end]+ total_count = len(legacy_roles)+ total_pages = (total_count + results_per_page - 1) // results_per_page if results_per_page > 0 else 0++ return svc.Paginated[svc.RBACRole](+ data=paged_roles,+ pagination=svc.Pagination(+ total_count=total_count,+ per_page=results_per_page,+ current_page=page_number,+ total_pages=total_pages,+ ),+ )+++# ---------------------------------------------------------------------------+# Permission catalogs.+# ---------------------------------------------------------------------------+++@console_ns.route("/workspaces/current/rbac/role-permissions/catalog")+class RBACWorkspaceCatalogApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.PermissionCatalogResponse.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.Catalog.workspace(tenant_id, account_id))+++@console_ns.route("/workspaces/current/rbac/role-permissions/catalog/app")+class RBACAppCatalogApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.PermissionCatalogResponse.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.Catalog.app(tenant_id, account_id))+++@console_ns.route("/workspaces/current/rbac/role-permissions/catalog/dataset")+class RBACDatasetCatalogApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.PermissionCatalogResponse.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.Catalog.dataset(tenant_id, account_id))+++# ---------------------------------------------------------------------------+# Roles.+# ---------------------------------------------------------------------------+++class _RoleUpsertRequest(BaseModel):+ """Accepts the payload sent by the Create/Edit Role dialog."""++ name: str+ description: str = ""+ permission_keys: list[str] = []++ def to_mutation(self) -> svc.RoleMutation:+ return svc.RoleMutation(+ name=self.name,+ description=self.description,+ permission_keys=list(self.permission_keys),+ )+++@console_ns.route("/workspaces/current/rbac/roles")+class RBACRolesApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[_RBACRoleList.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ query = _RolesListQuery.model_validate(request.args.to_dict(flat=True))+ options = query.to_inner_options()+ if not dify_config.RBAC_ENABLED:+ result = _legacy_workspace_roles(options, include_owner=query.include_owner)+ else:+ result = svc.RBACService.Roles.list(+ tenant_id, account_id, include_owner=query.include_owner, options=options+ )++ return _dump(result)++ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(201, "Role created", console_ns.models[svc.RBACRole.__name__])+ def post(self):+ tenant_id, account_id = _current_ids()+ request = _payload(_RoleUpsertRequest)+ role = svc.RBACService.Roles.create(tenant_id, account_id, request.to_mutation())+ return _dump(role), 201+++@console_ns.route("/workspaces/current/rbac/roles/<uuid:role_id>")+class RBACRoleItemApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.RBACRole.__name__])+ def get(self, role_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.Roles.get(tenant_id, account_id, str(role_id)))++ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.RBACRole.__name__])+ def put(self, role_id):+ tenant_id, account_id = _current_ids()+ request = _payload(_RoleUpsertRequest)+ role = svc.RBACService.Roles.update(tenant_id, account_id, str(role_id), request.to_mutation())+ return _dump(role)++ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.RBACRole.__name__])+ def delete(self, role_id):+ tenant_id, account_id = _current_ids()+ svc.RBACService.Roles.delete(tenant_id, account_id, str(role_id))+ return {"result": "success"}+++@console_ns.route("/workspaces/current/rbac/roles/<uuid:role_id>/copy")+class RBACRoleCopyApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(201, "Role copied", console_ns.models[svc.RBACRole.__name__])+ def post(self, role_id):+ tenant_id, account_id = _current_ids()+ request = _payload(CopyRoleParam)+ role = svc.RBACService.Roles.copy(tenant_id, account_id, str(role_id), copy_member=request.copy_member)+ return _dump(role), 201+++@console_ns.route("/workspaces/current/rbac/roles/<uuid:role_id>/members")+class RBACRoleMembersApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[_RBACRoleAccountList.__name__])+ def get(self, role_id):+ tenant_id, account_id = _current_ids()+ return _dump(+ svc.RBACService.Roles.members(+ tenant_id,+ account_id,+ str(role_id),+ options=_pagination_options(),+ )+ )+++# ---------------------------------------------------------------------------+# Access policies (tenant-level permission sets).+# ---------------------------------------------------------------------------+++class _AccessPolicyCreateRequest(BaseModel):+ name: str+ resource_type: svc.RBACResourceType+ description: str = ""+ permission_keys: list[str] = []+++class _AccessPolicyUpdateRequest(BaseModel):+ name: str+ description: str = ""+ permission_keys: list[str] = []+++@console_ns.route("/workspaces/current/rbac/access-policies")+class RBACAccessPoliciesApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[_AccessPolicyList.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ # `resource_type` is exposed as a query argument so the UI can show+ # only app-scoped or only dataset-scoped permission sets.+ resource_type = request.args.get("resource_type") or None+ return _dump(+ svc.RBACService.AccessPolicies.list(+ tenant_id,+ account_id,+ resource_type=resource_type,+ options=_pagination_options(),+ )+ )++ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(201, "Policy created", console_ns.models[svc.AccessPolicy.__name__])+ def post(self):+ tenant_id, account_id = _current_ids()+ request = _payload(_AccessPolicyCreateRequest)+ policy = svc.RBACService.AccessPolicies.create(+ tenant_id,+ account_id,+ svc.AccessPolicyCreate(+ name=request.name,+ resource_type=request.resource_type,+ description=request.description,+ permission_keys=list(request.permission_keys),+ ),+ )+ return _dump(policy), 201+++@console_ns.route("/workspaces/current/rbac/access-policies/<uuid:policy_id>")+class RBACAccessPolicyItemApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicy.__name__])+ def get(self, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.AccessPolicies.get(tenant_id, account_id, str(policy_id)))++ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicy.__name__])+ def put(self, policy_id):+ tenant_id, account_id = _current_ids()+ request = _payload(_AccessPolicyUpdateRequest)+ policy = svc.RBACService.AccessPolicies.update(+ tenant_id,+ account_id,+ str(policy_id),+ svc.AccessPolicyUpdate(+ name=request.name,+ description=request.description,+ permission_keys=list(request.permission_keys),+ ),+ )+ return _dump(policy)++ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicy.__name__])+ def delete(self, policy_id):+ tenant_id, account_id = _current_ids()+ svc.RBACService.AccessPolicies.delete(tenant_id, account_id, str(policy_id))+ return {"result": "success"}+++@console_ns.route("/workspaces/current/rbac/access-policies/<uuid:policy_id>/copy")+class RBACAccessPolicyCopyApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(201, "Policy copied", console_ns.models[svc.AccessPolicy.__name__])+ def post(self, policy_id):+ tenant_id, account_id = _current_ids()+ policy = svc.RBACService.AccessPolicies.copy(tenant_id, account_id, str(policy_id))+ return _dump(policy), 201+++@console_ns.route("/workspaces/current/rbac/access-policy-bindings/<uuid:binding_id>/lock")+class RBACAccessPolicyBindingLockApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicyBindingState.__name__])+ def put(self, binding_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.AccessPolicyBindings.lock(tenant_id, account_id, str(binding_id)))+++@console_ns.route("/workspaces/current/rbac/access-policy-bindings/<uuid:binding_id>/unlock")+class RBACAccessPolicyBindingUnlockApi(Resource):+ @login_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicyBindingState.__name__])+ def put(self, binding_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.AccessPolicyBindings.unlock(tenant_id, account_id, str(binding_id)))+++# ---------------------------------------------------------------------------+# Per-app access (App Access Config).+# ---------------------------------------------------------------------------+++class _AccessScope(StrEnum):+ ALL = "all"+ SPECIFIC = "specific"+ ONLY_ME = "only_me"+++class _ResourceAccessScopeRequest(BaseModel):+ scope: _AccessScope+++class _ReplaceBindingsRequest(BaseModel):+ role_ids: list[str] = Field(default_factory=list)+ account_ids: list[str] = Field(default_factory=list)++ @field_validator("role_ids", "account_ids", mode="before")+ @classmethod+ def _coerce_bindings(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class _DeleteMemberBindingsRequest(BaseModel):+ account_ids: list[str] = Field(default_factory=list)++ @field_validator("account_ids", mode="before")+ @classmethod+ def _coerce_account_ids(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++@console_ns.route("/workspaces/current/rbac/my-permissions")+class RBACMyPermissionsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MyPermissionsResponse.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ return _dump(+ svc.RBACService.MyPermissions.get(+ tenant_id,+ account_id,+ app_id=request.args.get("app_id") or None,+ dataset_id=request.args.get("dataset_id") or None,+ )+ )+++@console_ns.route("/workspaces/current/rbac/apps/<uuid:app_id>/access-policy")+class RBACAppMatrixApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.AppAccessMatrix.__name__])+ def get(self, app_id):+ tenant_id, account_id = _current_ids()+ result = svc.RBACService.AppAccess.matrix(tenant_id, account_id, str(app_id))+ _hydrate_access_matrix_account_names(result.items)+ return _dump(result)+++@console_ns.route("/workspaces/current/rbac/apps/<uuid:app_id>/whitelist")+class RBACAppWhitelistApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__])+ def get(self, app_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.AppAccess.whitelist(tenant_id, account_id, str(app_id)))++ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__])+ def put(self, app_id):+ tenant_id, account_id = _current_ids()+ request = _payload(_ResourceAccessScopeRequest)+ return _dump(+ svc.RBACService.AppAccess.replace_whitelist(+ tenant_id,+ account_id,+ str(app_id),+ svc.ReplaceMemberBindings(scope=request.scope.value),+ )+ )+++@console_ns.route("/workspaces/current/rbac/apps/<uuid:app_id>/user-access-policies")+class RBACAppUserAccessPoliciesApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ResourceUserAccessPoliciesResponse.__name__])+ def get(self, app_id):+ tenant_id, account_id = _current_ids()+ result = svc.RBACService.AppAccess.user_access_policies(tenant_id, account_id, str(app_id))+ _hydrate_resource_user_account_names(result.data)+ return _dump(result)+++@console_ns.route("/workspaces/current/rbac/apps/<uuid:app_id>/users/<uuid:target_account_id>/access-policies")+class RBACAppUserAccessPolicyAssignmentApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ReplaceUserAccessPoliciesResponse.__name__])+ def put(self, app_id, target_account_id):+ tenant_id, account_id = _current_ids()+ payload = _payload(svc.ReplaceUserAccessPolicies)+ return _dump(+ svc.RBACService.AppAccess.replace_user_access_policies(+ tenant_id,+ account_id,+ str(app_id),+ str(target_account_id),+ payload,+ )+ )+++@console_ns.route("/workspaces/current/rbac/apps/<uuid:app_id>/access-policies/<uuid:policy_id>/role-bindings")+class RBACAppRoleBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__])+ def get(self, app_id, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.AppAccess.list_role_bindings(tenant_id, account_id, str(app_id), str(policy_id)))+++@console_ns.route("/workspaces/current/rbac/apps/<uuid:app_id>/access-policies/<string:policy_id>/member-bindings")+class RBACAppMemberBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__])+ def get(self, app_id, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.AppAccess.list_member_bindings(tenant_id, account_id, str(app_id), str(policy_id)))++ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__])+ def delete(self, app_id, policy_id):+ tenant_id, account_id = _current_ids()+ request_body = _payload(_DeleteMemberBindingsRequest)+ svc.RBACService.AppAccess.delete_member_bindings(+ tenant_id,+ account_id,+ str(app_id),+ str(policy_id),+ svc.DeleteMemberBindings(account_ids=request_body.account_ids),+ )+ return {"result": "success"}+++# ---------------------------------------------------------------------------+# Per-dataset access (Knowledge Base Access Config).+# ---------------------------------------------------------------------------+++@console_ns.route("/workspaces/current/rbac/datasets/<uuid:dataset_id>/access-policy")+class RBACDatasetMatrixApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.DatasetAccessMatrix.__name__])+ def get(self, dataset_id):+ tenant_id, account_id = _current_ids()+ result = svc.RBACService.DatasetAccess.matrix(tenant_id, account_id, str(dataset_id))+ _hydrate_access_matrix_account_names(result.items)+ return _dump(result)+++@console_ns.route("/workspaces/current/rbac/datasets/<uuid:dataset_id>/whitelist")+class RBACDatasetWhitelistApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__])+ def get(self, dataset_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.DatasetAccess.whitelist(tenant_id, account_id, str(dataset_id)))++ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__])+ def put(self, dataset_id):+ tenant_id, account_id = _current_ids()+ request = _payload(_ResourceAccessScopeRequest)+ return _dump(+ svc.RBACService.DatasetAccess.replace_whitelist(+ tenant_id,+ account_id,+ str(dataset_id),+ svc.ReplaceMemberBindings(scope=request.scope.value),+ )+ )+++@console_ns.route("/workspaces/current/rbac/datasets/<uuid:dataset_id>/user-access-policies")+class RBACDatasetUserAccessPoliciesApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ResourceUserAccessPoliciesResponse.__name__])+ def get(self, dataset_id):+ tenant_id, account_id = _current_ids()+ result = svc.RBACService.DatasetAccess.user_access_policies(tenant_id, account_id, str(dataset_id))+ _hydrate_resource_user_account_names(result.data)+ return _dump(result)+++@console_ns.route("/workspaces/current/rbac/datasets/<uuid:dataset_id>/users/<uuid:target_account_id>/access-policies")+class RBACDatasetUserAccessPolicyAssignmentApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.ReplaceUserAccessPoliciesResponse.__name__])+ def put(self, dataset_id, target_account_id):+ tenant_id, account_id = _current_ids()+ payload = _payload(svc.ReplaceUserAccessPolicies)+ return _dump(+ svc.RBACService.DatasetAccess.replace_user_access_policies(+ tenant_id,+ account_id,+ str(dataset_id),+ str(target_account_id),+ payload,+ )+ )+++@console_ns.route("/workspaces/current/rbac/datasets/<uuid:dataset_id>/access-policies/<uuid:policy_id>/role-bindings")+class RBACDatasetRoleBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__])+ def get(self, dataset_id, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(+ svc.RBACService.DatasetAccess.list_role_bindings(tenant_id, account_id, str(dataset_id), str(policy_id))+ )+++@console_ns.route(+ "/workspaces/current/rbac/datasets/<uuid:dataset_id>/access-policies/<string:policy_id>/member-bindings"+)+class RBACDatasetMemberBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__])+ def get(self, dataset_id, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(+ svc.RBACService.DatasetAccess.list_member_bindings(tenant_id, account_id, str(dataset_id), str(policy_id))+ )++ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__])+ def delete(self, dataset_id, policy_id):+ tenant_id, account_id = _current_ids()+ request_body = _payload(_DeleteMemberBindingsRequest)+ svc.RBACService.DatasetAccess.delete_member_bindings(+ tenant_id,+ account_id,+ str(dataset_id),+ str(policy_id),+ svc.DeleteMemberBindings(account_ids=request_body.account_ids),+ )+ return {"result": "success"}+++# ---------------------------------------------------------------------------+# Workspace-level access (Settings > Access Rules).+# ---------------------------------------------------------------------------+++@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policy")+class RBACWorkspaceAppMatrixApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.WorkspaceAccessMatrix.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ options = _pagination_options()+ result = svc.RBACService.WorkspaceAccess.app_matrix(tenant_id, account_id, options=options)+ _hydrate_access_matrix_account_names(result.items)+ return _dump(result)+++@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policies/<uuid:policy_id>/role-bindings")+class RBACWorkspaceAppRoleBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__])+ def get(self, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.WorkspaceAccess.list_app_role_bindings(tenant_id, account_id, str(policy_id)))+++@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policies/<uuid:policy_id>/bindings")+class RBACWorkspaceAppBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.AccessMatrixItem.__name__])+ def put(self, policy_id):+ tenant_id, account_id = _current_ids()+ request = _payload(_ReplaceBindingsRequest)+ return _dump(+ svc.RBACService.WorkspaceAccess.replace_app_bindings(+ tenant_id,+ account_id,+ str(policy_id),+ svc.ReplaceBindings(role_ids=list(request.role_ids), account_ids=list(request.account_ids)),+ )+ )+++@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policies/<uuid:policy_id>/member-bindings")+class RBACWorkspaceAppMemberBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__])+ def get(self, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.WorkspaceAccess.list_app_member_bindings(tenant_id, account_id, str(policy_id)))+++@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policy")+class RBACWorkspaceDatasetMatrixApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.WorkspaceAccessMatrix.__name__])+ def get(self):+ tenant_id, account_id = _current_ids()+ options = _pagination_options()+ result = svc.RBACService.WorkspaceAccess.dataset_matrix(tenant_id, account_id, options=options)+ _hydrate_access_matrix_account_names(result.items)+ return _dump(result)+++@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policies/<uuid:policy_id>/role-bindings")+class RBACWorkspaceDatasetRoleBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__])+ def get(self, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.WorkspaceAccess.list_dataset_role_bindings(tenant_id, account_id, str(policy_id)))+++@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policies/<uuid:policy_id>/bindings")+class RBACWorkspaceDatasetBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.AccessMatrixItem.__name__])+ def put(self, policy_id):+ tenant_id, account_id = _current_ids()+ request = _payload(_ReplaceBindingsRequest)+ return _dump(+ svc.RBACService.WorkspaceAccess.replace_dataset_bindings(+ tenant_id,+ account_id,+ str(policy_id),+ svc.ReplaceBindings(role_ids=list(request.role_ids), account_ids=list(request.account_ids)),+ )+ )+++@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policies/<uuid:policy_id>/member-bindings")+class RBACWorkspaceDatasetMemberBindingsApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__])+ def get(self, policy_id):+ tenant_id, account_id = _current_ids()+ return _dump(+ svc.RBACService.WorkspaceAccess.list_dataset_member_bindings(tenant_id, account_id, str(policy_id))+ )+++# ---------------------------------------------------------------------------+# Member ↔ role bindings (Settings > Members > Assign roles).+# ---------------------------------------------------------------------------+++class _ReplaceMemberRolesRequest(BaseModel):+ role_ids: list[str] = []++ @field_validator("role_ids", mode="before")+ @classmethod+ def _coerce_role_ids(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++@console_ns.route("/workspaces/current/rbac/members/<uuid:member_id>/rbac-roles")+class RBACMemberRolesApi(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberRolesResponse.__name__])+ def get(self, member_id):+ tenant_id, account_id = _current_ids()+ return _dump(svc.RBACService.MemberRoles.get(tenant_id, account_id, str(member_id)))++ @login_required+ @console_ns.response(200, "Success", console_ns.models[svc.MemberRolesResponse.__name__])+ def put(self, member_id):+ tenant_id, account_id = _current_ids()+ request = _payload(_ReplaceMemberRolesRequest)+ return _dump(+ svc.RBACService.MemberRoles.replace(+ tenant_id,+ account_id,+ str(member_id),+ role_ids=list(request.role_ids),+ )+ )+++@console_ns.route("/workspaces/current/rbac/roles/<uuid:role_id>/members")+class ListMembersByRole(Resource):+ @login_required+ @console_ns.response(200, "Success", console_ns.models[_MembersInRoleList.__name__])+ def get(self, role_id):+ tenant_id, account_id = _current_ids()+ return _dump(+ svc.RBACService.Roles.list_members_by_role(tenant_id, role_id=role_id, options=_pagination_options())+ )diff --git a/api/controllers/console/workspace/snippets.py b/api/controllers/console/workspace/snippets.pyindex 7fcca1f79e8..e8f0b228c8b 100644--- a/api/controllers/console/workspace/snippets.py+++ b/api/controllers/console/workspace/snippets.py@@ -21,8 +21,11 @@ from controllers.console.snippets.payloads import (UpdateSnippetPayload,)from controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -151,6 +154,9 @@ class CustomizedSnippetsApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )@with_current_user@with_current_tenant_iddef post(self, current_tenant_id: str, current_user: Account):@@ -213,6 +219,9 @@ class CustomizedSnippetDetailApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )@with_current_user@with_current_tenant_iddef patch(self, current_tenant_id: str, current_user: Account, snippet_id: str):@@ -257,6 +266,7 @@ class CustomizedSnippetDetailApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False)@with_current_tenant_iddef delete(self, current_tenant_id: str, snippet_id: str):"""Delete customized snippet."""@@ -292,6 +302,9 @@ class CustomizedSnippetExportApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )@with_current_tenant_iddef get(self, current_tenant_id: str, snippet_id: str):"""Export snippet as DSL."""@@ -337,6 +350,9 @@ class CustomizedSnippetImportApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )@with_current_userdef post(self, current_user: Account):"""Import snippet from DSL."""@@ -375,6 +391,9 @@ class CustomizedSnippetImportConfirmApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )@with_current_userdef post(self, current_user: Account, import_id: str):"""Confirm a pending snippet import."""@@ -403,6 +422,9 @@ class CustomizedSnippetCheckDependenciesApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )@with_current_tenant_iddef get(self, current_tenant_id: str, snippet_id: str):"""Check dependencies for a snippet."""@@ -433,6 +455,9 @@ class CustomizedSnippetUseCountIncrementApi(Resource):@login_required@account_initialization_required@edit_permission_required+ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False+ )@with_current_tenant_iddef post(self, current_tenant_id: str, snippet_id: str):"""Increment snippet use count when it is inserted into a workflow."""diff --git a/api/controllers/console/workspace/tool_providers.py b/api/controllers/console/workspace/tool_providers.pyindex 94600f38860..9a92571594c 100644--- a/api/controllers/console/workspace/tool_providers.py+++ b/api/controllers/console/workspace/tool_providers.py@@ -14,9 +14,12 @@ from controllers.common.fields import BinaryFileResponse, RedirectResponse, Simpfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,enterprise_license_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -369,6 +372,7 @@ class ToolBuiltinProviderDeleteApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, provider: str):@@ -411,6 +415,7 @@ class ToolBuiltinProviderUpdateApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -471,6 +476,7 @@ class ToolApiProviderAddApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -540,6 +546,7 @@ class ToolApiProviderUpdateApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -568,6 +575,7 @@ class ToolApiProviderDeleteApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -659,6 +667,7 @@ class ToolWorkflowProviderCreateApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -686,6 +695,7 @@ class ToolWorkflowProviderUpdateApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -713,6 +723,7 @@ class ToolWorkflowProviderDeleteApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -858,6 +869,7 @@ class ToolPluginOAuthApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -959,6 +971,7 @@ class ToolBuiltinProviderSetDefaultApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, current_tenant_id: str, provider: str):@@ -975,6 +988,7 @@ class ToolOAuthCustomClient(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, provider: str):diff --git a/api/controllers/console/workspace/trigger_providers.py b/api/controllers/console/workspace/trigger_providers.pyindex ff1a5c18bd9..b960a5eb9c3 100644--- a/api/controllers/console/workspace/trigger_providers.py+++ b/api/controllers/console/workspace/trigger_providers.py@@ -27,9 +27,12 @@ from services.trigger.trigger_subscription_operator_service import TriggerSubscrfrom .. import console_nsfrom ..wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,edit_permission_required,is_admin_or_owner_required,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -143,6 +146,7 @@ class TriggerSubscriptionListApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -172,6 +176,7 @@ class TriggerSubscriptionBuilderCreateApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -201,6 +206,7 @@ class TriggerSubscriptionBuilderGetApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_requireddef get(self, provider: str, subscription_builder_id: str):"""Get a subscription instance for a trigger provider"""@@ -218,6 +224,7 @@ class TriggerSubscriptionBuilderVerifyApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -250,6 +257,7 @@ class TriggerSubscriptionBuilderUpdateApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, provider: str, subscription_builder_id: str):@@ -282,6 +290,7 @@ class TriggerSubscriptionBuilderLogsApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_requireddef get(self, provider: str, subscription_builder_id: str):"""Get the request logs for a subscription instance for a trigger provider"""@@ -302,6 +311,7 @@ class TriggerSubscriptionBuilderBuildApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_id@@ -336,6 +346,7 @@ class TriggerSubscriptionUpdateApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, subscription_id: str):@@ -393,6 +404,7 @@ class TriggerSubscriptionDeleteApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, subscription_id: str):@@ -581,6 +593,7 @@ class TriggerOAuthClientManageApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_tenant_iddef get(self, tenant_id: str, provider: str):@@ -626,6 +639,7 @@ class TriggerOAuthClientManageApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_tenant_iddef post(self, tenant_id: str, provider: str):@@ -650,6 +664,7 @@ class TriggerOAuthClientManageApi(Resource):@setup_required@login_required@is_admin_or_owner_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])@with_current_tenant_id@@ -678,6 +693,7 @@ class TriggerSubscriptionVerifyApi(Resource):@setup_required@login_required@edit_permission_required+ @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False)@account_initialization_required@with_current_user@with_current_tenant_iddiff --git a/api/controllers/console/wraps.py b/api/controllers/console/wraps.pyindex 1c0f210123a..017793ffe0b 100644--- a/api/controllers/console/wraps.py+++ b/api/controllers/console/wraps.py@@ -9,9 +9,14 @@ from typing import Any, Concatenate, overloadfrom flask import abort, requestfrom pydantic import BaseModel, ValidationErrorfrom sqlalchemy import select-from werkzeug.exceptions import UnprocessableEntity+from werkzeug.exceptions import Forbidden, UnprocessableEntityfrom configs import dify_config+from controllers.common.wraps import (+ RBACPermission,+ RBACResourceScope,+ rbac_permission_required,+)from controllers.console.auth.error import AuthenticationFailedError, EmailCodeErrorfrom controllers.console.workspace.error import AccountNotInitializedErrorfrom enums.cloud_plan import CloudPlan@@ -28,6 +33,10 @@ from services.operation_service import OperationService, UtmInfofrom .error import NotInitValidateError, NotSetupError, UnauthorizedAndForceLogout+# Re-exported so controllers can import the RBAC enums and decorator alongside+# other console wraps from this module.+__all__ = ["RBACPermission", "RBACResourceScope", "rbac_permission_required"]+# Field names for decryptionFIELD_NAME_PASSWORD = "password"FIELD_NAME_CODE = "code"@@ -335,15 +344,15 @@ def knowledge_pipeline_publish_enabled[**P, R](view: Callable[P, R]) -> Callabledef edit_permission_required[**P, R](f: Callable[P, R]) -> Callable[P, R]:@wraps(f)def decorated_function(*args: P.args, **kwargs: P.kwargs):- from werkzeug.exceptions import Forbiddenfrom libs.login import current_user- user = current_user._get_current_object() # type: ignore- if not isinstance(user, Account):- raise Forbidden()- if not current_user.has_edit_permission:- raise Forbidden()+ if not dify_config.RBAC_ENABLED:+ user = current_user._get_current_object() # type: ignore+ if not isinstance(user, Account):+ raise Forbidden()+ if not current_user.has_edit_permission:+ raise Forbidden()return f(*args, **kwargs)return decorated_function@@ -352,13 +361,13 @@ def edit_permission_required[**P, R](f: Callable[P, R]) -> Callable[P, R]:def is_admin_or_owner_required[**P, R](f: Callable[P, R]) -> Callable[P, R]:@wraps(f)def decorated_function(*args: P.args, **kwargs: P.kwargs):- from werkzeug.exceptions import Forbiddenfrom libs.login import current_user- user = current_user._get_current_object()- if not isinstance(user, Account) or not user.is_admin_or_owner:- raise Forbidden()+ if not dify_config.RBAC_ENABLED:+ user = current_user._get_current_object()+ if not isinstance(user, Account) or not user.is_admin_or_owner:+ raise Forbidden()return f(*args, **kwargs)return decorated_functiondiff --git a/api/controllers/service_api/dataset/dataset.py b/api/controllers/service_api/dataset/dataset.pyindex c8f95f3acd4..292c39f69bc 100644--- a/api/controllers/service_api/dataset/dataset.py+++ b/api/controllers/service_api/dataset/dataset.py@@ -1,4 +1,4 @@-from typing import Annotated, Literal, override+from typing import Annotated, Any, Literal, overridefrom uuid import UUIDfrom flask import request@@ -15,6 +15,7 @@ from pydantic import (from werkzeug.exceptions import Forbidden, NotFoundimport services+from configs import dify_configfrom controllers.common.fields import SimpleResultResponsefrom controllers.common.schema import (query_params_from_model,@@ -84,6 +85,32 @@ PartialMemberList = Annotated[]+_SERVICE_DATASET_DETAIL_EXCLUDE = {"permission_keys"}+_SERVICE_DATASET_LIST_EXCLUDE = {"data": {"__all__": _SERVICE_DATASET_DETAIL_EXCLUDE}}+++def _dump_service_dataset_detail(dataset: Any) -> dict[str, Any]:+ return DatasetDetailResponse.model_validate(dataset, from_attributes=True).model_dump(+ mode="json",+ exclude=_SERVICE_DATASET_DETAIL_EXCLUDE,+ )+++def _dump_service_dataset_list(response: dict[str, Any]) -> dict[str, Any]:+ return DatasetListResponse.model_validate(response).model_dump(+ mode="json",+ exclude=_SERVICE_DATASET_LIST_EXCLUDE,+ )+++def _dump_service_dataset_with_partial_members(data: dict[str, Any]) -> dict[str, Any]:+ exclude: set[str] = set(_SERVICE_DATASET_DETAIL_EXCLUDE)+ if "partial_member_list" not in data:+ exclude.add("partial_member_list")++ return DatasetDetailWithPartialMembersResponse.model_validate(data).model_dump(mode="json", exclude=exclude)++class DatasetCreatePayload(BaseModel):name: str = Field(..., min_length=1, max_length=40, description="Name of the knowledge base.")description: str = Field(default="", description="Description of the knowledge base.", max_length=400)@@ -383,7 +410,14 @@ class DatasetListApi(DatasetApiResource):# provider = request.args.get("provider", default="vendor")datasets, total = DatasetService.get_datasets(- query.page, query.limit, tenant_id, current_user, query.keyword, query.tag_ids, query.include_all+ query.page,+ query.limit,+ db.session,+ tenant_id,+ current_user,+ query.keyword,+ query.tag_ids,+ query.include_all,)# check embedding settingassert isinstance(current_user, Account)@@ -398,7 +432,7 @@ class DatasetListApi(DatasetApiResource):for embedding_model in embedding_models:model_names.append(f"{embedding_model.model}:{embedding_model.provider.provider}")- data = [dump_response(DatasetDetailResponse, dataset) for dataset in datasets]+ data = [_dump_service_dataset_detail(dataset) for dataset in datasets]for item in data:if item["indexing_technique"] == IndexTechniqueType.HIGH_QUALITY and item["embedding_model_provider"]:item["embedding_model_provider"] = str(ModelProviderID(item["embedding_model_provider"]))@@ -416,7 +450,7 @@ class DatasetListApi(DatasetApiResource):"total": total,"page": query.page,}- return dump_response(DatasetListResponse, response), 200+ return _dump_service_dataset_list(response), 200@service_api_ns.doc(summary="Create an Empty Knowledge Base",@@ -489,7 +523,7 @@ class DatasetListApi(DatasetApiResource):except services.errors.dataset.DatasetNameDuplicateError:raise DatasetNameDuplicateError()- return dump_response(DatasetDetailResponse, dataset), 200+ return _dump_service_dataset_detail(dataset), 200@service_api_ns.route("/datasets/<uuid:dataset_id>")@@ -534,7 +568,7 @@ class DatasetApi(DatasetApiResource):DatasetService.check_dataset_permission(dataset, current_user)except services.errors.account.NoPermissionError as e:raise Forbidden(str(e))- data = dump_response(DatasetDetailResponse, dataset)+ data = _dump_service_dataset_detail(dataset)# check embedding settingassert isinstance(current_user, Account)cid = current_user.current_tenant_id@@ -566,13 +600,7 @@ class DatasetApi(DatasetApiResource):part_users_list = DatasetPermissionService.get_dataset_partial_member_list(dataset_id_str)data.update({"partial_member_list": part_users_list})- return (- DatasetDetailWithPartialMembersResponse.model_validate(data).model_dump(- mode="json",- exclude={"partial_member_list"} if "partial_member_list" not in data else set(),- ),- 200,- )+ return _dump_service_dataset_with_partial_members(data), 200@service_api_ns.doc(summary="Update Knowledge Base",@@ -641,20 +669,21 @@ class DatasetApi(DatasetApiResource):retrieval_model.reranking_model.reranking_model_name,)- # The role of the current user in the ta table must be admin, owner, editor, or dataset_operator- DatasetPermissionService.check_permission(- current_user,- dataset,- str(payload.permission) if payload.permission else None,- payload.partial_member_list,- )+ if not dify_config.RBAC_ENABLED:+ # The role of the current user in the ta table must be admin, owner, editor, or dataset_operator+ DatasetPermissionService.check_permission(+ current_user,+ dataset,+ str(payload.permission) if payload.permission else None,+ payload.partial_member_list,+ )dataset = DatasetService.update_dataset(dataset_id_str, update_data, current_user)if dataset is None:raise NotFound("Dataset not found.")- result_data = dump_response(DatasetDetailResponse, dataset)+ result_data = _dump_service_dataset_detail(dataset)assert isinstance(current_user, Account)tenant_id = current_user.current_tenant_id@@ -667,7 +696,7 @@ class DatasetApi(DatasetApiResource):partial_member_list = DatasetPermissionService.get_dataset_partial_member_list(dataset_id_str)result_data.update({"partial_member_list": partial_member_list})- return DatasetDetailWithPartialMembersResponse.model_validate(result_data).model_dump(mode="json"), 200+ return _dump_service_dataset_with_partial_members(result_data), 200@service_api_ns.doc(summary="Delete Knowledge Base",diff --git a/api/core/rbac/entities.py b/api/core/rbac/entities.pyindex 5389e16eefc..7f08a530f57 100644--- a/api/core/rbac/entities.py+++ b/api/core/rbac/entities.py@@ -25,6 +25,7 @@ class RBACPermission(StrEnum):APP_CREATE_AND_MANAGEMENT = "app_create_and_management"APP_RELEASE_AND_VERSION = "app_release_and_version"APP_IMPORT_EXPORT_DSL = "app_import_export_dsl"+ APP_EDIT = "app_edit"APP_MONITOR = "app_monitor"APP_DELETE = "app_delete"@@ -33,5 +34,22 @@ class RBACPermission(StrEnum):DATASET_CREATE_AND_MANAGEMENT = "dataset_create_and_management"DATASET_PIPELINE_TEST = "dataset_pipeline_test"DATASET_DOCUMENT_DOWNLOAD = "dataset_document_download"+ DATASET_API_KEY_MANAGE = "dataset_api_key_manage"+ DATASET_EXTERNAL_CONNECT = "dataset_external_connect"+ DATASET_IMPORT_EXPORT_DSL = "dataset_import_export_dsl"WORKSPACE_ROLE_MANAGE = "workspace_role_manage"++ SNIPPETS_CREATE_AND_MODIFY = "snippets_create_and_modify"+ SNIPPETS_MANAGE = "snippets_management"++ PLUGIN_INSTALL = "plugin_install"+ PLUGIN_PREFERENCES = "plugin_preferences"+ PLUGIN_MANAGE = "plugin_manage"+ PLUGIN_DEBUG = "plugin_debug"++ CREDENTIAL_USE = "credential_use"+ CREDENTIAL_MANAGE = "credential_manage"++ TOOL_MANAGE = "tool_manage"+ MCP_MANAGE = "mcp_manage"diff --git a/api/extensions/ext_commands.py b/api/extensions/ext_commands.pyindex 4d60bdb5f65..6cd4b08b900 100644--- a/api/extensions/ext_commands.py+++ b/api/extensions/ext_commands.py@@ -26,6 +26,7 @@ def init_app(app: DifyApp):install_plugins,install_rag_pipeline_plugins,migrate_data_for_plugin,+ migrate_member_roles_to_rbac,migrate_oss,migration_data_wizard,old_metadata_migration,@@ -54,6 +55,7 @@ def init_app(app: DifyApp):upgrade_db,fix_app_site_missing,migrate_data_for_plugin,+ migrate_member_roles_to_rbac,backfill_plugin_auto_upgrade,extract_plugins,extract_unique_plugins,diff --git a/api/fields/app_fields.py b/api/fields/app_fields.pyindex 9b197da4433..96d8fbdf34c 100644--- a/api/fields/app_fields.py+++ b/api/fields/app_fields.py@@ -100,6 +100,7 @@ app_detail_fields = {"updated_at": TimestampField,"access_mode": fields.String,"tags": fields.List(fields.Nested(tag_fields)),+ "permission_keys": fields.List(fields.String()),}prompt_config_fields = {@@ -137,6 +138,7 @@ app_partial_fields = {"create_user_name": fields.String,"author_name": fields.String,"has_draft_trigger": fields.Boolean,+ "permission_keys": fields.List(fields.String()),}@@ -217,6 +219,7 @@ app_detail_fields_with_site = {"deleted_tools": fields.List(fields.Nested(deleted_tool_fields)),"access_mode": fields.String,"tags": fields.List(fields.Nested(tag_fields)),+ "permission_keys": fields.List(fields.String()),"site": fields.Nested(site_fields),}diff --git a/api/fields/dataset_fields.py b/api/fields/dataset_fields.pyindex 35a22ea4044..ea506d2a7e4 100644--- a/api/fields/dataset_fields.py+++ b/api/fields/dataset_fields.py@@ -15,6 +15,7 @@ dataset_fields = {"indexing_technique": fields.String,"created_by": fields.String,"created_at": TimestampField,+ "permission_keys": fields.List(fields.String()),}@@ -143,6 +144,7 @@ dataset_detail_fields = {"total_available_documents": fields.Integer,"enable_api": fields.Boolean,"is_multimodal": fields.Boolean,+ "permission_keys": fields.List(fields.String()),}@@ -267,6 +269,8 @@ class DatasetDetailResponse(ResponseModel):total_available_documents: intenable_api: boolis_multimodal: bool+ permission_keys: list[str] = Field(default_factory=list)+ maintainer: str | None = None@field_validator("created_at", "updated_at", mode="before")@classmethoddiff --git a/api/fields/member_fields.py b/api/fields/member_fields.pyindex 7ae5e3b652b..9bbcbef8429 100644--- a/api/fields/member_fields.py+++ b/api/fields/member_fields.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom datetime import datetimefrom flask_restx import fields-from pydantic import computed_field, field_validator+from pydantic import Field, computed_field, field_validatorfrom fields.base import ResponseModelfrom libs.helper import build_avatar_url, to_timestamp@@ -56,6 +56,7 @@ class AccountWithRole(_AccountAvatar):last_active_at: int | None = Nonecreated_at: int | None = Nonerole: str+ roles: list[dict[str, str]] = Field(default_factory=list)status: str@field_validator("last_login_at", "last_active_at", "created_at", mode="before")diff --git a/api/libs/oauth_bearer.py b/api/libs/oauth_bearer.pyindex 7433c6c177a..36de4b85ae0 100644--- a/api/libs/oauth_bearer.py+++ b/api/libs/oauth_bearer.py@@ -490,7 +490,8 @@ def check_workspace_membership(account_id: uuid.UUID | str,tenant_id: str,token_hash: str,- membership_cache: dict[str, bool],+ membership_cache: dict[str, bool] | None = None,+ cached_verdicts: dict[str, bool] | None = None,) -> None:"""Layer-0 enforcement core. Raises `Forbidden` on deny, returns on allow.@@ -499,7 +500,8 @@ def check_workspace_membership(short-circuiting on EE / SSO subjects before invoking — this functionruns the membership + active-status checks unconditionally."""- cached = membership_cache.get(tenant_id)+ cache = membership_cache if membership_cache is not None else cached_verdicts or {}+ cached = cache.get(tenant_id)if cached is True:returnif cached is False:diff --git a/api/migrations/versions/2026_06_15_1200-a7c4e9d2f681_add_resource_maintainers.py b/api/migrations/versions/2026_06_15_1200-a7c4e9d2f681_add_resource_maintainers.pynew file mode 100644index 00000000000..06731d5c42e--- /dev/null+++ b/api/migrations/versions/2026_06_15_1200-a7c4e9d2f681_add_resource_maintainers.py@@ -0,0 +1,41 @@+"""add resource maintainers++Revision ID: a7c4e9d2f681+Revises: 9f4b7c2d1a80+Create Date: 2026-06-15 12:00:00.000000++"""++import sqlalchemy as sa+from alembic import op++import models.types++# revision identifiers, used by Alembic.+revision = "a7c4e9d2f681"+down_revision = "d2f1a4b8c3e0"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ with op.batch_alter_table("apps", schema=None) as batch_op:+ batch_op.add_column(sa.Column("maintainer", models.types.StringUUID(), nullable=True))+ batch_op.create_index("app_tenant_maintainer_idx", ["tenant_id", "maintainer"], unique=False)++ with op.batch_alter_table("datasets", schema=None) as batch_op:+ batch_op.add_column(sa.Column("maintainer", models.types.StringUUID(), nullable=True))+ batch_op.create_index("dataset_tenant_maintainer_idx", ["tenant_id", "maintainer"], unique=False)++ op.execute(sa.text("UPDATE apps SET maintainer = created_by WHERE maintainer IS NULL"))+ op.execute(sa.text("UPDATE datasets SET maintainer = created_by WHERE maintainer IS NULL"))+++def downgrade() -> None:+ with op.batch_alter_table("datasets", schema=None) as batch_op:+ batch_op.drop_index("dataset_tenant_maintainer_idx")+ batch_op.drop_column("maintainer")++ with op.batch_alter_table("apps", schema=None) as batch_op:+ batch_op.drop_index("app_tenant_maintainer_idx")+ batch_op.drop_column("maintainer")diff --git a/api/models/account.py b/api/models/account.pyindex 66766693a5b..df152e1783c 100644--- a/api/models/account.py+++ b/api/models/account.py@@ -11,6 +11,8 @@ from sqlalchemy import DateTime, String, func, selectfrom sqlalchemy.orm import Mapped, Session, mapped_columnfrom typing_extensions import deprecated+from configs import dify_config+from .base import TypeBasefrom .engine import dbfrom .types import EnumText, LongText, StringUUID@@ -187,10 +189,14 @@ class Account(UserMixin, TypeBase):# check current_user.current_tenant.current_role in ['admin', 'owner']@propertydef is_admin_or_owner(self):+ if dify_config.RBAC_ENABLED:+ return Truereturn TenantAccountRole.is_privileged_role(self.role)@propertydef is_admin(self):+ if dify_config.RBAC_ENABLED:+ return Truereturn TenantAccountRole.is_admin_role(self.role)@property@@ -216,14 +222,20 @@ class Account(UserMixin, TypeBase):- `ADMIN`- `EDITOR`"""+ if dify_config.RBAC_ENABLED:+ return Truereturn TenantAccountRole.is_editing_role(self.role)@propertydef is_dataset_editor(self):+ if dify_config.RBAC_ENABLED:+ return Truereturn TenantAccountRole.is_dataset_edit_role(self.role)@propertydef is_dataset_operator(self):+ if dify_config.RBAC_ENABLED:+ return Truereturn self.role == TenantAccountRole.DATASET_OPERATORdiff --git a/api/models/dataset.py b/api/models/dataset.pyindex 1644551925b..998bc02ee85 100644--- a/api/models/dataset.py+++ b/api/models/dataset.py@@ -167,6 +167,7 @@ class Dataset(Base):__table_args__ = (sa.PrimaryKeyConstraint("id", name="dataset_pkey"),sa.Index("dataset_tenant_idx", "tenant_id"),+ sa.Index("dataset_tenant_maintainer_idx", "tenant_id", "maintainer"),adjusted_json_index("retrieval_model_idx", "retrieval_model"),)@@ -188,6 +189,7 @@ class Dataset(Base):indexing_technique: Mapped[IndexTechniqueType | None] = mapped_column(EnumText(IndexTechniqueType, length=255))index_struct = mapped_column(LongText, nullable=True)created_by = mapped_column(StringUUID, nullable=False)+ maintainer: Mapped[str | None] = mapped_column(StringUUID, nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())updated_by = mapped_column(StringUUID, nullable=True)updated_at = mapped_column(diff --git a/api/models/model.py b/api/models/model.pyindex 69d2a4a7f19..ebcadbb05ac 100644--- a/api/models/model.py+++ b/api/models/model.py@@ -395,7 +395,11 @@ class IconType(StrEnum):class App(Base):__tablename__ = "apps"- __table_args__ = (sa.PrimaryKeyConstraint("id", name="app_pkey"), sa.Index("app_tenant_id_idx", "tenant_id"))+ __table_args__ = (+ sa.PrimaryKeyConstraint("id", name="app_pkey"),+ sa.Index("app_tenant_id_idx", "tenant_id"),+ sa.Index("app_tenant_maintainer_idx", "tenant_id", "maintainer"),+ )if TYPE_CHECKING:# Response-only attributes attached by app list/detail enrichers.@@ -426,6 +430,7 @@ class App(Base):tracing = mapped_column(LongText, nullable=True)max_active_requests: Mapped[int | None]created_by = mapped_column(StringUUID, nullable=True)+ maintainer: Mapped[str | None] = mapped_column(StringUUID, nullable=True)created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())updated_by = mapped_column(StringUUID, nullable=True)updated_at: Mapped[datetime] = mapped_column(diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.mdindex 32bc41e945d..123a2e6e04b 100644--- a/api/openapi/markdown/console-openapi.md+++ b/api/openapi/markdown/console-openapi.md@@ -10202,6 +10202,539 @@ Returns permission flags that control workspace features like member invitations| ---- | ----------- | ------ || 200 | Success | **application/json**: [PluginCategoryListResponse](#plugincategorylistresponse)<br> |+### [GET] /workspaces/current/rbac/access-policies+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [_AccessPolicyList](#_accesspolicylist)<br> |++### [POST] /workspaces/current/rbac/access-policies+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 201 | Policy created | **application/json**: [AccessPolicy](#accesspolicy)<br> |++### [DELETE] /workspaces/current/rbac/access-policies/{policy_id}+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AccessPolicy](#accesspolicy)<br> |++### [GET] /workspaces/current/rbac/access-policies/{policy_id}+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AccessPolicy](#accesspolicy)<br> |++### [PUT] /workspaces/current/rbac/access-policies/{policy_id}+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AccessPolicy](#accesspolicy)<br> |++### [POST] /workspaces/current/rbac/access-policies/{policy_id}/copy+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 201 | Policy copied | **application/json**: [AccessPolicy](#accesspolicy)<br> |++### [PUT] /workspaces/current/rbac/access-policy-bindings/{binding_id}/lock+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| binding_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AccessPolicyBindingState](#accesspolicybindingstate)<br> |++### [PUT] /workspaces/current/rbac/access-policy-bindings/{binding_id}/unlock+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| binding_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AccessPolicyBindingState](#accesspolicybindingstate)<br> |++### [DELETE] /workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |+| policy_id | path | | Yes | string |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)<br> |++### [GET] /workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |+| policy_id | path | | Yes | string |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)<br> |++### [GET] /workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/role-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [RoleBindingsResponse](#rolebindingsresponse)<br> |++### [GET] /workspaces/current/rbac/apps/{app_id}/access-policy+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AppAccessMatrix](#appaccessmatrix)<br> |++### [GET] /workspaces/current/rbac/apps/{app_id}/user-access-policies+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ResourceUserAccessPoliciesResponse](#resourceuseraccesspoliciesresponse)<br> |++### [PUT] /workspaces/current/rbac/apps/{app_id}/users/{target_account_id}/access-policies+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |+| target_account_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ReplaceUserAccessPoliciesResponse](#replaceuseraccesspoliciesresponse)<br> |++### [GET] /workspaces/current/rbac/apps/{app_id}/whitelist+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ResourceWhitelist](#resourcewhitelist)<br> |++### [PUT] /workspaces/current/rbac/apps/{app_id}/whitelist+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| app_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ResourceWhitelist](#resourcewhitelist)<br> |++### [DELETE] /workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/member-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |+| policy_id | path | | Yes | string |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)<br> |++### [GET] /workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/member-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |+| policy_id | path | | Yes | string |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)<br> |++### [GET] /workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/role-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [RoleBindingsResponse](#rolebindingsresponse)<br> |++### [GET] /workspaces/current/rbac/datasets/{dataset_id}/access-policy+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [DatasetAccessMatrix](#datasetaccessmatrix)<br> |++### [GET] /workspaces/current/rbac/datasets/{dataset_id}/user-access-policies+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ResourceUserAccessPoliciesResponse](#resourceuseraccesspoliciesresponse)<br> |++### [PUT] /workspaces/current/rbac/datasets/{dataset_id}/users/{target_account_id}/access-policies+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |+| target_account_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ReplaceUserAccessPoliciesResponse](#replaceuseraccesspoliciesresponse)<br> |++### [GET] /workspaces/current/rbac/datasets/{dataset_id}/whitelist+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ResourceWhitelist](#resourcewhitelist)<br> |++### [PUT] /workspaces/current/rbac/datasets/{dataset_id}/whitelist+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| dataset_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [ResourceWhitelist](#resourcewhitelist)<br> |++### [GET] /workspaces/current/rbac/members/{member_id}/rbac-roles+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| member_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberRolesResponse](#memberrolesresponse)<br> |++### [PUT] /workspaces/current/rbac/members/{member_id}/rbac-roles+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| member_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberRolesResponse](#memberrolesresponse)<br> |++### [GET] /workspaces/current/rbac/my-permissions+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MyPermissionsResponse](#mypermissionsresponse)<br> |++### [GET] /workspaces/current/rbac/role-permissions/catalog+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [PermissionCatalogResponse](#permissioncatalogresponse)<br> |++### [GET] /workspaces/current/rbac/role-permissions/catalog/app+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [PermissionCatalogResponse](#permissioncatalogresponse)<br> |++### [GET] /workspaces/current/rbac/role-permissions/catalog/dataset+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [PermissionCatalogResponse](#permissioncatalogresponse)<br> |++### [GET] /workspaces/current/rbac/roles+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [_RBACRoleList](#_rbacrolelist)<br> |++### [POST] /workspaces/current/rbac/roles+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 201 | Role created | **application/json**: [RBACRole](#rbacrole)<br> |++### [DELETE] /workspaces/current/rbac/roles/{role_id}+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| role_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [RBACRole](#rbacrole)<br> |++### [GET] /workspaces/current/rbac/roles/{role_id}+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| role_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [RBACRole](#rbacrole)<br> |++### [PUT] /workspaces/current/rbac/roles/{role_id}+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| role_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [RBACRole](#rbacrole)<br> |++### [POST] /workspaces/current/rbac/roles/{role_id}/copy+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| role_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 201 | Role copied | **application/json**: [RBACRole](#rbacrole)<br> |++### [GET] /workspaces/current/rbac/roles/{role_id}/members+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| role_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [_MembersInRoleList](#_membersinrolelist)<br> |++### [PUT] /workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AccessMatrixItem](#accessmatrixitem)<br> |++### [GET] /workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/member-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)<br> |++### [GET] /workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/role-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [RoleBindingsResponse](#rolebindingsresponse)<br> |++### [GET] /workspaces/current/rbac/workspace/apps/access-policy+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [WorkspaceAccessMatrix](#workspaceaccessmatrix)<br> |++### [PUT] /workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [AccessMatrixItem](#accessmatrixitem)<br> |++### [GET] /workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/member-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)<br> |++### [GET] /workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/role-bindings+#### Parameters++| Name | Located in | Description | Required | Schema |+| ---- | ---------- | ----------- | -------- | ------ |+| policy_id | path | | Yes | string (uuid) |++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [RoleBindingsResponse](#rolebindingsresponse)<br> |++### [GET] /workspaces/current/rbac/workspace/datasets/access-policy+#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [WorkspaceAccessMatrix](#workspaceaccessmatrix)<br> |+### [GET] /workspaces/current/tool-labels#### Responses@@ -11130,6 +11663,84 @@ Default namespace| id | string | | Yes || name | string | | Yes |+#### AccessMatrixItem++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| accounts | [ [AccessPolicyAccount](#accesspolicyaccount) ] | | No |+| policy | [AccessPolicy](#accesspolicy) | | No |+| roles | [ [AccessPolicyRole](#accesspolicyrole) ] | | No |++#### AccessPolicy++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| category | string | | No |+| created_at | integer | | No |+| description | string | | No |+| id | string | | Yes |+| is_builtin | boolean | | No |+| name | string | | Yes |+| permission_keys | [ string ] | | No |+| policy_key | string | | No |+| resource_type | string | | Yes |+| tenant_id | string | | No |+| updated_at | integer | | No |++#### AccessPolicyAccount++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| account_id | string | | Yes |+| account_name | string | | Yes |+| avatar | string | | No |+| binding_id | string | | Yes |+| email | string | | No |+| is_locked | boolean | | No |++#### AccessPolicyBindingState++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| binding_id | string | | Yes |+| is_locked | boolean | | No |++#### AccessPolicyMemberBinding++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| access_policy_id | string | | Yes |+| account_id | string | | Yes |+| account_name | string | | No |+| created_at | integer | | No |+| id | string | | Yes |+| resource_id | string | | No |+| resource_type | string | | Yes |+| tenant_id | string | | No |++#### AccessPolicyRole++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| binding_id | string | | Yes |+| is_locked | boolean | | No |+| role_id | string | | Yes |+| role_name | string | | Yes |+| role_tag | string | | No |++#### AccessPolicyRoleBinding++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| access_policy_id | string | | Yes |+| created_at | integer | | No |+| id | string | | Yes |+| resource_id | string | | No |+| resource_type | string | | Yes |+| role_id | string | | Yes |+| role_name | string | | No |+| tenant_id | string | | No |+#### Account| Name | Type | Description | Required |@@ -11240,6 +11851,7 @@ Default namespace| last_login_at | integer | | No || name | string | | Yes || role | string | | Yes |+| roles | [ object ] | | No || status | string | | Yes |#### AccountWithRoleList@@ -11384,10 +11996,12 @@ Default namespace| icon_type | string | | No || icon_url | string | | Yes || id | string | | Yes |+| maintainer | string | | No || max_active_requests | integer | | No || mode | string | | Yes || model_config | [ModelConfig](#modelconfig) | | No || name | string | | Yes |+| permission_keys | [ string ] | | No || role | string | | No || site | [Site](#site) | | No || tags | [ [Tag](#tag) ] | | No |@@ -11444,10 +12058,12 @@ default (the config form sends the full desired feature state on save).| icon_url | string | | Yes || id | string | | Yes || is_starred | boolean | | No |+| maintainer | string | | No || max_active_requests | integer | | No || mode | string | | Yes || model_config | [ModelConfigPartial](#modelconfigpartial) | | No || name | string | | Yes |+| permission_keys | [ string ] | | No || published_reference_count | integer | | No || published_references | [ [AgentAppPublishedReferenceResponse](#agentapppublishedreferenceresponse) ] | | No || role | string | | No |@@ -12850,6 +13466,13 @@ Enum class for api provider schema type.| schema_type | [ApiProviderSchemaType](#apiproviderschematype) | | Yes || tool_name | string | | Yes |+#### AppAccessMatrix++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| app_id | string | | No |+| items | [ [AccessMatrixItem](#accessmatrixitem) ] | | No |+#### AppApiStatusPayload| Name | Type | Description | Required |@@ -12870,8 +13493,10 @@ Enum class for api provider schema type.| icon | string | | No || icon_background | string | | No || id | string | | Yes |+| maintainer | string | | No || mode_compatible_with_agent | string | | Yes || name | string | | Yes |+| permission_keys | [ string ] | | No || tags | [ [Tag](#tag) ] | | No || tracing | [JSONValue](#jsonvalue) | | No || updated_at | integer | | No |@@ -12898,10 +13523,12 @@ Enum class for api provider schema type.| icon_type | string | | No || icon_url | string | | Yes || id | string | | Yes |+| maintainer | string | | No || max_active_requests | integer | | No || mode | string | | Yes || model_config | [ModelConfig](#modelconfig) | | No || name | string | | Yes |+| permission_keys | [ string ] | | No || site | [Site](#site) | | No || tags | [ [Tag](#tag) ] | | No || tracing | [JSONValue](#jsonvalue) | | No |@@ -13020,10 +13647,12 @@ AppMCPServer Status Enum| icon_url | string | | Yes || id | string | | Yes || is_starred | boolean | | No |+| maintainer | string | | No || max_active_requests | integer | | No || mode | string | | Yes || model_config | [ModelConfigPartial](#modelconfigpartial) | | No || name | string | | Yes |+| permission_keys | [ string ] | | No || tags | [ [Tag](#tag) ] | | No || updated_at | integer | | No || updated_by | string | | No |@@ -14019,6 +14648,13 @@ Model class for provider custom model configuration.| workspace_id | string | | Yes || workspace_name | string | | Yes |+#### DatasetAccessMatrix++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| dataset_id | string | | No |+| items | [ [AccessMatrixItem](#accessmatrixitem) ] | | No |+#### DatasetAndDocumentResponse| Name | Type | Description | Required |@@ -14067,6 +14703,7 @@ Model class for provider custom model configuration.| is_published | boolean | | No || name | string | | No || permission | string | | No |+| permission_keys | [ string ] | | No || pipeline_id | string | | No || provider | string | | No || retrieval_model_dict | [DatasetRetrievalModel](#datasetretrievalmodel) | | No |@@ -14105,8 +14742,10 @@ Model class for provider custom model configuration.| indexing_technique | string | | Yes || is_multimodal | boolean | | Yes || is_published | boolean | | Yes |+| maintainer | string | | No || name | string | | Yes || permission | string | | Yes |+| permission_keys | [ string ] | | No || pipeline_id | string | | Yes || provider | string | | Yes || retrieval_model_dict | [DatasetRetrievalModelResponse](#datasetretrievalmodelresponse) | | Yes |@@ -14145,9 +14784,11 @@ Model class for provider custom model configuration.| indexing_technique | string | | Yes || is_multimodal | boolean | | Yes || is_published | boolean | | Yes |+| maintainer | string | | No || name | string | | Yes || partial_member_list | [ string ] | | No || permission | string | | Yes |+| permission_keys | [ string ] | | No || pipeline_id | string | | Yes || provider | string | | Yes || retrieval_model_dict | [DatasetRetrievalModelResponse](#datasetretrievalmodelresponse) | | Yes |@@ -14249,9 +14890,11 @@ Model class for provider custom model configuration.| indexing_technique | string | | Yes || is_multimodal | boolean | | Yes || is_published | boolean | | Yes |+| maintainer | string | | No || name | string | | Yes || partial_member_list | [ string ] | | Yes || permission | string | | Yes |+| permission_keys | [ string ] | | No || pipeline_id | string | | Yes || provider | string | | Yes || retrieval_model_dict | [DatasetRetrievalModelResponse](#datasetretrievalmodelresponse) | | Yes |@@ -15677,6 +16320,7 @@ How Dify forwards the end-user's identity to an MCP server.| error | string | | No || id | string | | Yes || imported_dsl_version | string | | No |+| permission_keys | [ string ] | | No || status | [ImportStatus](#importstatus) | | Yes |#### ImportStatus@@ -16066,13 +16710,19 @@ Enum class for large language model mode.| result | string | | Yes || tenant_id | string | | Yes |+#### MemberBindingsResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| data | [ [AccessPolicyMemberBinding](#accesspolicymemberbinding) ] | | No |+#### MemberInvitePayload| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || emails | [ string ] | | No || language | string | | No |-| role | [TenantAccountRole](#tenantaccountrole) | | Yes |+| role | string | | Yes |#### MemberInviteResponse@@ -16097,6 +16747,20 @@ Enum class for large language model mode.| ---- | ---- | ----------- | -------- || role | string | | Yes |+#### MemberRolesResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| account_id | string | | Yes |+| roles | [ [RBACRole](#rbacrole) ] | | No |++#### MembersInRole++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| account_id | string | | No |+| account_name | string | | No |+#### MessageDetail| Name | Type | Description | Required |@@ -16407,11 +17071,20 @@ Model with provider entity.| ---- | ---- | ----------- | -------- || response_mode | string, <br>**Available values:** "blocking", "streaming" | *Enum:* `"blocking"`, `"streaming"` | Yes |+#### MyPermissionsResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| app | [ResourcePermissionSnapshot](#resourcepermissionsnapshot) | | No |+| dataset | [ResourcePermissionSnapshot](#resourcepermissionsnapshot) | | No |+| workspace | [WorkspacePermissionSnapshot](#workspacepermissionsnapshot) | | No |+#### NewAppResponse| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || new_app_id | string | | Yes |+| permission_keys | [ string ] | | No |#### NodeIdQuery@@ -16717,6 +17390,15 @@ output check fails and any configured retry attempts have been exhausted.| page | integer | | Yes || total | integer | | Yes |+#### Pagination++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| current_page | integer | | No |+| per_page | integer | | No |+| total_count | integer | | No |+| total_pages | integer | | No |+#### PaginationQuery| Name | Type | Description | Required |@@ -17092,6 +17774,29 @@ Enum class for parameter type.| node_title | string | | Yes || pause_type | [HumanInputPauseTypeResponse](#humaninputpausetyperesponse) | | Yes |+#### PermissionCatalogGroup++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| description | string | | No |+| group_key | string | | Yes |+| group_name | string | | Yes |+| permissions | [ [PermissionCatalogItem](#permissioncatalogitem) ] | | No |++#### PermissionCatalogItem++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| description | string | | No |+| key | string | | Yes |+| name | string | | Yes |++#### PermissionCatalogResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| groups | [ [PermissionCatalogGroup](#permissioncataloggroup) ] | | No |+#### PermissionEnumShared permission levels for resources (datasets, credentials, etc.)@@ -17650,6 +18355,29 @@ Model class for provider quota configuration.| ---- | ---- | ----------- | -------- || QuotaUnit | string | | |+#### RBACRole++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| category | string | | No |+| description | string | | No |+| id | string | | Yes |+| is_builtin | boolean | | No |+| name | string | | Yes |+| permission_keys | [ string ] | | No |+| role_tag | string | | No |+| tenant_id | string | | No |+| type | string | | Yes |++#### RBACRoleAccount++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| account_id | string | | Yes |+| account_name | string | | No |+| avatar | string | | No |+| email | string | | No |+#### RagPipelineDatasetImportPayload| Name | Type | Description | Required |@@ -17811,6 +18539,12 @@ Model class for provider quota configuration.| ---- | ---- | ----------- | -------- || url | string | URL to fetch | Yes |+#### ReplaceUserAccessPoliciesResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| access_policies | [ [AccessPolicy](#accesspolicy) ] | | No |+#### RerankingModel| Name | Type | Description | Required |@@ -17818,6 +18552,41 @@ Model class for provider quota configuration.| reranking_model_name | string | Name of the reranking model. | No || reranking_provider_name | string | Provider name of the reranking model. | No |+#### ResourcePermissionKeys++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| permission_keys | [ string ] | | No |+| resource_id | string | | Yes |++#### ResourcePermissionSnapshot++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| default_permission_keys | [ string ] | | No |+| overrides | [ [ResourcePermissionKeys](#resourcepermissionkeys) ] | | No |++#### ResourceUserAccessPolicies++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| access_policies | [ [AccessPolicy](#accesspolicy) ] | | No |+| account | [RBACRoleAccount](#rbacroleaccount) | | Yes |+| roles | [ [RBACRole](#rbacrole) ] | | No |++#### ResourceUserAccessPoliciesResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| data | [ [ResourceUserAccessPolicies](#resourceuseraccesspolicies) ] | | No |+| scope | string | | Yes |++#### ResourceWhitelist++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| account_ids | [ string ] | | No |+#### RestrictModel| Name | Type | Description | Required |@@ -17880,6 +18649,12 @@ Model class for provider quota configuration.| summary | string | | No || word_count | integer | | No |+#### RoleBindingsResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| data | [ [AccessPolicyRoleBinding](#accesspolicyrolebinding) ] | | No |+#### RosterListQuery| Name | Type | Description | Required |@@ -18575,6 +19350,7 @@ Model class for provider system configuration response.| max_plugin_package_size | integer, <br>**Default:** 15728640 | | Yes || plugin_installation_permission | [PluginInstallationPermissionModel](#plugininstallationpermissionmodel) | | Yes || plugin_manager | [PluginManagerModel](#pluginmanagermodel) | | Yes |+| rbac_enabled | boolean | | Yes || sso_enforced_for_signin | boolean | | Yes || sso_enforced_for_signin_protocol | string | | Yes || webapp_auth | [WebAppAuthModel](#webappauthmodel) | | Yes |@@ -18848,6 +19624,7 @@ Enum class for tool provider| mode | string | | No || model_config | [TrialAppModelConfig](#trialappmodelconfig) | | No || name | string | | No |+| permission_keys | [ string ] | | No || site | [TrialSite](#trialsite) | | No || tags | [ [TrialTag](#trialtag) ] | | No || updated_at | long | | No |@@ -18906,6 +19683,7 @@ Enum class for tool provider| indexing_technique | string | | No || name | string | | No || permission | string | | No |+| permission_keys | [ string ] | | No |#### TrialDatasetList@@ -20107,6 +20885,13 @@ Workflow tool configuration| marked_comment | string | | No || marked_name | string | | No |+#### WorkspaceAccessMatrix++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| items | [ [AccessMatrixItem](#accessmatrixitem) ] | | No |+| pagination | [Pagination](#pagination) | | No |+#### WorkspaceCustomConfigPayload| Name | Type | Description | Required |@@ -20174,6 +20959,19 @@ Workflow tool configuration| allow_owner_transfer | boolean | | Yes || workspace_id | string | | Yes |+#### WorkspacePermissionSnapshot++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| permission_keys | [ string ] | | No |++#### _AccessPolicyList++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| data | [ [AccessPolicy](#accesspolicy) ] | | No |+| pagination | [Pagination](#pagination) | | No |+#### _AnonymousInlineModel_744ff9cc03e6| Name | Type | Description | Required |@@ -20218,6 +21016,27 @@ Workflow tool configuration| model_provider_name | string | | No || summary_prompt | string | | No |+#### _MembersInRoleList++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| data | [ [MembersInRole](#membersinrole) ] | | No |+| pagination | [Pagination](#pagination) | | No |++#### _RBACRoleAccountList++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| data | [ [RBACRoleAccount](#rbacroleaccount) ] | | No |+| pagination | [Pagination](#pagination) | | No |++#### _RBACRoleList++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| data | [ [RBACRole](#rbacrole) ] | | No |+| pagination | [Pagination](#pagination) | | No |+#### core__tools__entities__common_entities__I18nObjectModel class for i18n object.diff --git a/api/openapi/markdown/openapi-openapi.md b/api/openapi/markdown/openapi-openapi.mdindex 4b1da3f1c59..ce0150e8e88 100644--- a/api/openapi/markdown/openapi-openapi.md+++ b/api/openapi/markdown/openapi-openapi.md@@ -805,6 +805,7 @@ Liveness payload for `GET /openapi/v1/_health` — no auth required.| error | string | | No || id | string | | Yes || imported_dsl_version | string | | No |+| permission_keys | [ string ] | | No || status | [ImportStatus](#importstatus) | | Yes |#### ImportStatusdiff --git a/api/openapi/markdown/service-openapi.md b/api/openapi/markdown/service-openapi.mdindex a58ca2766d7..8fc5e75e3cf 100644--- a/api/openapi/markdown/service-openapi.md+++ b/api/openapi/markdown/service-openapi.md@@ -2701,8 +2701,10 @@ Enum class for custom configuration status.| indexing_technique | string | | Yes || is_multimodal | boolean | | Yes || is_published | boolean | | Yes |+| maintainer | string | | No || name | string | | Yes || permission | string | | Yes |+| permission_keys | [ string ] | | No || pipeline_id | string | | Yes || provider | string | | Yes || retrieval_model_dict | [DatasetRetrievalModelResponse](#datasetretrievalmodelresponse) | | Yes |@@ -2741,9 +2743,11 @@ Enum class for custom configuration status.| indexing_technique | string | | Yes || is_multimodal | boolean | | Yes || is_published | boolean | | Yes |+| maintainer | string | | No || name | string | | Yes || partial_member_list | [ string ] | | No || permission | string | | Yes |+| permission_keys | [ string ] | | No || pipeline_id | string | | Yes || provider | string | | Yes || retrieval_model_dict | [DatasetRetrievalModelResponse](#datasetretrievalmodelresponse) | | Yes |diff --git a/api/openapi/markdown/web-openapi.md b/api/openapi/markdown/web-openapi.mdindex bedaf964748..569e3706caa 100644--- a/api/openapi/markdown/web-openapi.md+++ b/api/openapi/markdown/web-openapi.md@@ -1613,6 +1613,7 @@ Default configuration for form inputs.| max_plugin_package_size | integer, <br>**Default:** 15728640 | | Yes || plugin_installation_permission | [PluginInstallationPermissionModel](#plugininstallationpermissionmodel) | | Yes || plugin_manager | [PluginManagerModel](#pluginmanagermodel) | | Yes |+| rbac_enabled | boolean | | Yes || sso_enforced_for_signin | boolean | | Yes || sso_enforced_for_signin_protocol | string | | Yes || webapp_auth | [WebAppAuthModel](#webappauthmodel) | | Yes |diff --git a/api/services/account_service.py b/api/services/account_service.pyindex 5c55c8bfc46..a608f544747 100644--- a/api/services/account_service.py+++ b/api/services/account_service.py@@ -10,23 +10,11 @@ from typing import Any, NotRequired, TypedDict, castfrom pydantic import BaseModel, TypeAdapter, ValidationErrorfrom sqlalchemy import Row, delete, func, select, updatefrom sqlalchemy.orm import Session, scoped_session--from core.db.session_factory import session_factory---class InvitationData(TypedDict):- account_id: str- email: str- workspace_id: str- role: NotRequired[str]- requires_setup: NotRequired[bool]---_invitation_adapter: TypeAdapter[InvitationData] = TypeAdapter(InvitationData)from werkzeug.exceptions import Unauthorizedfrom configs import dify_configfrom constants.languages import get_valid_language, language_timezone_mapping+from core.db.session_factory import session_factoryfrom events.tenant_event import tenant_was_createdfrom extensions.ext_database import dbfrom extensions.ext_redis import redis_client, redis_fallback@@ -47,8 +35,10 @@ from models.account import (TenantPluginAutoUpgradeStrategy,TenantStatus,)-from models.model import DifySetup+from models.dataset import Dataset+from models.model import App, DifySetupfrom services.billing_service import BillingService+from services.enterprise.rbac_service import ListOption, RBACServicefrom services.entities.auth_entities import (ChangeEmailNewEmailToken,ChangeEmailOldEmailToken,@@ -92,6 +82,17 @@ from tasks.mail_reset_password_task import (send_reset_password_mail_task_when_account_not_exist,)++class InvitationData(TypedDict):+ account_id: str+ email: str+ workspace_id: str+ role: NotRequired[str]+ requires_setup: NotRequired[bool]+++_invitation_adapter: TypeAdapter[InvitationData] = TypeAdapter(InvitationData)+logger = logging.getLogger(__name__)_change_email_token_adapter: TypeAdapter[ChangeEmailTokenData] = TypeAdapter(ChangeEmailTokenData)@@ -149,6 +150,67 @@ class AccountService:OWNER_TRANSFER_MAX_ERROR_LIMITS = 5EMAIL_REGISTER_MAX_ERROR_LIMITS = 5+ @staticmethod+ def _resolve_legacy_role_id(tenant_id: str, account_id: str, role: TenantAccountRole) -> str:+ """Resolve a legacy workspace role to the corresponding RBAC role id.++ Looks up the builtin RBAC role whose tag matches the legacy role name+ (e.g. ``TenantAccountRole.ADMIN`` → builtin role with tag ``"admin"``).+ """+ options = ListOption(page_number=1, results_per_page=100)+ roles = RBACService.Roles.list(tenant_id, account_id, options=options).data++ expected_tag = {+ TenantAccountRole.OWNER: "owner",+ TenantAccountRole.ADMIN: "admin",+ TenantAccountRole.EDITOR: "editor",+ TenantAccountRole.NORMAL: "normal",+ TenantAccountRole.DATASET_OPERATOR: "dataset_operator",+ }[role]+ for rbac_role in roles:+ if (+ rbac_role.is_builtin+ and rbac_role.category == "global_system_default"+ and rbac_role.role_tag == expected_tag+ ):+ return str(rbac_role.id)++ raise ValueError(f"Builtin RBAC role not found for {role.value} in tenant {tenant_id}")++ @staticmethod+ def get_workspace_permission_keys(tenant_id: str, account_id: str) -> set[str]:+ permissions = RBACService.MyPermissions.get(tenant_id, account_id)+ return set(getattr(getattr(permissions, "workspace", None), "permission_keys", []) or [])++ @staticmethod+ def get_rbac_workspace_owner_account_id(tenant_id: str, actor_account_id: str) -> str:+ """Return the account id bound to the workspace owner RBAC role."""+ owner_role_id = AccountService._resolve_legacy_role_id(+ tenant_id=tenant_id,+ account_id=actor_account_id,+ role=TenantAccountRole.OWNER,+ )+ owner_members = RBACService.Roles.members(+ tenant_id=tenant_id,+ account_id=actor_account_id,+ role_id=owner_role_id,+ options=ListOption(page_number=1, results_per_page=1),+ ).data+ if not owner_members:+ raise ValueError(f"Workspace RBAC owner not found for tenant {tenant_id}.")+ return owner_members[0].account_id++ @staticmethod+ def is_rbac_workspace_owner(tenant_id: str, actor_account_id: str, member_account_id: str) -> bool:+ roles = RBACService.MemberRoles.get(+ tenant_id=tenant_id,+ account_id=actor_account_id,+ member_account_id=member_account_id,+ ).roles+ return any(+ role.is_builtin and role.category == "global_system_default" and role.role_tag == "owner" for role in roles+ )+@staticmethoddef _get_refresh_token_key(refresh_token: str) -> str:return f"{REFRESH_TOKEN_PREFIX}{refresh_token}"@@ -1219,6 +1281,14 @@ class TenantService:else:tenant = TenantService.create_tenant(name=f"{account.name}'s Workspace", is_setup=is_setup)TenantService.create_tenant_member(tenant, account, role="owner")+ if dify_config.RBAC_ENABLED:+ owner_role_id = AccountService._resolve_legacy_role_id(str(tenant.id), account.id, TenantAccountRole.OWNER)+ RBACService.MemberRoles.replace(+ tenant_id=str(tenant.id),+ account_id=account.id,+ member_account_id=account.id,+ role_ids=[owner_role_id],+ )account.current_tenant = tenantdb.session.commit()tenant_was_created.send(tenant)@@ -1347,6 +1417,7 @@ class TenantService:"""if not account_id:return None+role = session.execute(select(TenantAccountJoin.role).where(TenantAccountJoin.tenant_id == tenant_id,@@ -1533,11 +1604,6 @@ class TenantService:@staticmethoddef check_member_permission(tenant: Tenant, operator: Account, member: Account | None, action: str):"""Check member permission"""- perms = {- "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],- "remove": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],- "update": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],- }if action not in {"add", "remove", "update"}:raise InvalidActionError("Invalid action.")@@ -1545,6 +1611,31 @@ class TenantService:if operator.id == member.id:raise CannotOperateSelfError("Cannot operate self.")+ if dify_config.RBAC_ENABLED:+ workspace_permission_keys = AccountService.get_workspace_permission_keys(+ str(tenant.id),+ str(operator.id),+ )+ required_permission_key = (+ "workspace.member.manage" if action in {"add", "remove"} else "workspace.role.manage"+ )+ if required_permission_key not in workspace_permission_keys:+ raise NoPermissionError(f"No permission to {action} member.")++ if (+ action == "remove"+ and member+ and AccountService.is_rbac_workspace_owner(str(tenant.id), str(operator.id), str(member.id))+ ):+ raise NoPermissionError(f"No permission to {action} member.")+ return++ perms = {+ "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],+ "remove": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],+ "update": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],+ }+ta_operator = db.session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == operator.id)@@ -1567,6 +1658,8 @@ class TenantService:def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account):"""Remove member from tenant.+ Apps and datasets maintained by the removed member are reassigned to+ the workspace owner without changing their immutable creator records.If the removed member has ``AccountStatus.PENDING`` (invited but neveractivated) and no remaining workspace memberships, the orphaned accountrecord is deleted as well.@@ -1589,6 +1682,37 @@ class TenantService:account_id = account.idaccount_email = account.email+ owner_id: str | None+ if dify_config.RBAC_ENABLED:+ owner_id = AccountService.get_rbac_workspace_owner_account_id(str(tenant.id), str(operator.id))+ else:+ owner_id = db.session.scalar(+ select(TenantAccountJoin.account_id)+ .where(+ TenantAccountJoin.tenant_id == tenant.id,+ TenantAccountJoin.role == TenantAccountRole.OWNER,+ )+ .limit(1)+ )+ if owner_id is None:+ raise ValueError(f"Workspace owner not found for tenant {tenant.id}.")++ db.session.execute(+ update(App)+ .where(+ App.tenant_id == tenant.id,+ App.maintainer == account_id,+ )+ .values(maintainer=owner_id)+ )+ db.session.execute(+ update(Dataset)+ .where(+ Dataset.tenant_id == tenant.id,+ Dataset.maintainer == account_id,+ )+ .values(maintainer=owner_id)+ )db.session.delete(ta)# Clean up orphaned pending accounts (invited but never activated)@@ -1660,11 +1784,37 @@ class TenantService:.where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role == "owner").limit(1))- if current_owner_join:- current_owner_join.role = TenantAccountRole.ADMIN+ if not dify_config.RBAC_ENABLED:+ if current_owner_join:+ current_owner_join.role = TenantAccountRole.ADMIN+ elif current_owner_join:+ admin_role_id = AccountService._resolve_legacy_role_id(+ tenant_id=str(tenant.id),+ account_id=operator.id,+ role=TenantAccountRole.ADMIN,+ )+ RBACService.MemberRoles.replace(+ tenant_id=str(tenant.id),+ account_id=operator.id,+ member_account_id=str(current_owner_join.account_id),+ role_ids=[admin_role_id],+ )# Update the role of the target member- target_member_join.role = new_tenant_role+ if dify_config.RBAC_ENABLED:+ resolved_role_id = AccountService._resolve_legacy_role_id(+ tenant_id=str(tenant.id),+ account_id=operator.id,+ role=TenantAccountRole.OWNER,+ )+ RBACService.MemberRoles.replace(+ tenant_id=str(tenant.id),+ account_id=operator.id,+ member_account_id=member.id,+ role_ids=[resolved_role_id],+ )+ else:+ target_member_join.role = new_tenant_roledb.session.commit()@staticmethod@@ -1798,6 +1948,7 @@ class RegisterService:raise ValueError("Inviter is required")normalized_email = email.lower()+ tenant_join_role = TenantAccountRole.NORMAL.value if dify_config.RBAC_ENABLED else role"""Invite new member"""# Check workspace permission for member invitations@@ -1819,8 +1970,7 @@ class RegisterService:status=AccountStatus.PENDING,is_setup=True,)- # Create new tenant member for invited tenant- TenantService.create_tenant_member(tenant, account, role)+ TenantService.create_tenant_member(tenant, account, tenant_join_role)TenantService.switch_tenant(account, tenant.id)requires_setup = Trueelse:@@ -1832,12 +1982,29 @@ class RegisterService:)requires_setup = account.status == AccountStatus.PENDING- if not ta and account.status == AccountStatus.PENDING:- TenantService.create_tenant_member(tenant, account, role)+ if not ta and (account.status == AccountStatus.PENDING or dify_config.RBAC_ENABLED):+ TenantService.create_tenant_member(tenant, account, tenant_join_role)# Support resend invitation email when the account is pending status- if ta and account.status != AccountStatus.PENDING:- raise AccountAlreadyInTenantError("Account already in tenant.")+ if account.status != AccountStatus.PENDING:+ if dify_config.RBAC_ENABLED and not ta:+ RBACService.MemberRoles.replace(+ tenant_id=str(tenant.id),+ account_id=inviter.id,+ member_account_id=account.id,+ role_ids=[role],+ )+ if ta or dify_config.RBAC_ENABLED:+ raise AccountAlreadyInTenantError("Account already in tenant.")++ # Assign RBAC role if RBAC is enabled+ if dify_config.RBAC_ENABLED:+ RBACService.MemberRoles.replace(+ tenant_id=str(tenant.id),+ account_id=inviter.id,+ member_account_id=account.id,+ role_ids=[role],+ )token = cls.generate_invite_token(tenant, account, role, requires_setup=requires_setup)language = account.interface_language or "en-US"diff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.pyindex e69cff6a294..52e936bf1ee 100644--- a/api/services/app_dsl_service.py+++ b/api/services/app_dsl_service.py@@ -11,7 +11,7 @@ import yamlfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadfrom packaging.version import parse as parse_version-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom sqlalchemy import selectfrom sqlalchemy.orm import Session@@ -60,6 +60,7 @@ class Import(BaseModel):status: ImportStatusapp_id: str | None = Noneapp_mode: str | None = None+ permission_keys: list[str] = Field(default_factory=list)current_dsl_version: str = CURRENT_DSL_VERSIONimported_dsl_version: str = ""error: str = ""@@ -433,6 +434,7 @@ class AppDslService:app.enable_api = Trueapp.use_icon_as_answer_icon = app_data.get("use_icon_as_answer_icon", False)app.created_by = account.id+ app.maintainer = account.idapp.updated_by = account.idself._session.add(app)diff --git a/api/services/app_service.py b/api/services/app_service.pyindex cd0d08bf3e7..0f346433265 100644--- a/api/services/app_service.py+++ b/api/services/app_service.py@@ -7,7 +7,7 @@ from typing import Any, Literal, NotRequired, TypedDict, cast, overrideimport sqlalchemy as safrom flask_sqlalchemy.pagination import Paginationfrom pydantic import BaseModel, Field-from sqlalchemy import select+from sqlalchemy import ColumnElement, selectfrom sqlalchemy.orm import Session, scoped_sessionfrom configs import dify_config@@ -28,6 +28,7 @@ from models.agent import Agent, AgentIconType, AgentScope, AgentSource, AgentStafrom models.model import App, AppMode, AppModelConfig, IconType, Sitefrom models.tools import ApiToolProviderfrom services.billing_service import BillingService+from services.enterprise import rbac_service as enterprise_rbac_servicefrom services.enterprise.enterprise_service import EnterpriseServicefrom services.feature_service import FeatureServicefrom services.openapi.visibility import apply_openapi_gate, is_openapi_visible@@ -48,6 +49,8 @@ class AppListBaseParams(BaseModel):tag_ids: list[str] | None = Nonecreator_ids: list[str] | None = Noneis_created_by_me: bool | None = None+ accessible_app_ids: list[str] | None = None+ include_own_apps: bool = Falseclass AppListParams(AppListBaseParams):@@ -106,6 +109,11 @@ class AppService:if params.is_created_by_me:filters.append(App.created_by == user_id)+ elif params.accessible_app_ids is not None:+ accessible_filter: ColumnElement[bool] = App.id.in_(params.accessible_app_ids)+ if params.include_own_apps:+ accessible_filter = sa.or_(App.maintainer == user_id, accessible_filter)+ filters.append(accessible_filter)if params.creator_ids:filters.append(App.created_by.in_(params.creator_ids))if params.name:@@ -375,6 +383,7 @@ class AppService:app.api_rpm = params.api_rpmapp.max_active_requests = params.max_active_requestsapp.created_by = account.id+ app.maintainer = account.idapp.updated_by = account.iddb.session.add(app)@@ -426,6 +435,12 @@ class AppService:db.session.commit()app_was_created.send(app, account=account)+ enterprise_rbac_service.try_sync_creator_access_policy_member_bindings(+ tenant_id,+ account.id,+ enterprise_rbac_service.RBACResourceType.APP,+ app.id,+ )if FeatureService.get_system_features().webapp_auth.enabled:# update web app setting as privatediff --git a/api/services/dataset_service.py b/api/services/dataset_service.pyindex e8b17a137f9..125f3a8e6b8 100644--- a/api/services/dataset_service.py+++ b/api/services/dataset_service.py@@ -12,7 +12,7 @@ from typing import Annotated, Any, Literal, TypedDict, castimport sqlalchemy as safrom pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validatorfrom redis.exceptions import LockNotOwnedError-from sqlalchemy import delete, exists, func, select, update+from sqlalchemy import ColumnElement, delete, exists, func, select, updatefrom sqlalchemy.orm import Session, scoped_session, sessionmakerfrom werkzeug.exceptions import Forbidden, NotFound@@ -67,6 +67,7 @@ from models.source import DataSourceOauthBindingfrom models.workflow import Workflowfrom services.document_indexing_proxy.document_indexing_task_proxy import DocumentIndexingTaskProxyfrom services.document_indexing_proxy.duplicate_document_indexing_task_proxy import DuplicateDocumentIndexingTaskProxy+from services.enterprise import rbac_service as enterprise_rbac_servicefrom services.entities.knowledge_entities.knowledge_entities import (ChildChunkUpdateArgs,KnowledgeConfig,@@ -234,12 +235,37 @@ class _EstimateArgs(BaseModel):class DatasetService:+ @staticmethod+ def _can_manage_all_datasets(tenant_id: str, account_id: str) -> bool:+ if not dify_config.RBAC_ENABLED:+ return False++ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(tenant_id, account_id)+ workspace_permission_keys = getattr(getattr(permissions, "workspace", None), "permission_keys", []) or []+ return "dataset.create_and_management" in workspace_permission_keys+@staticmethoddef get_datasets(- page, per_page, session: scoped_session, tenant_id=None, user=None, search=None, tag_ids=None, include_all=False+ page,+ per_page,+ session: scoped_session | Session | None = None,+ tenant_id=None,+ user=None,+ search=None,+ tag_ids=None,+ include_all=False,+ accessible_dataset_ids: list[str] | None = None,+ include_own_datasets: bool = False,):+ session = session or db.sessionquery = select(Dataset).where(Dataset.tenant_id == tenant_id).order_by(Dataset.created_at.desc(), Dataset.id)+ if dify_config.RBAC_ENABLED and accessible_dataset_ids is not None:+ accessible_filter: ColumnElement[bool] = Dataset.id.in_(accessible_dataset_ids)+ if include_own_datasets and user:+ accessible_filter = sa.or_(Dataset.maintainer == user.id, accessible_filter)+ query = query.where(accessible_filter)+if user:# get permitted dataset idsdataset_permission = db.session.scalars(@@ -248,8 +274,7 @@ class DatasetService:)).all()permitted_dataset_ids = {dp.dataset_id for dp in dataset_permission} if dataset_permission else None-- if user.current_role == TenantAccountRole.DATASET_OPERATOR:+ if not dify_config.RBAC_ENABLED and user.current_role == TenantAccountRole.DATASET_OPERATOR:# only show datasets that the user has permission to access# Check if permitted_dataset_ids is not empty to avoid WHERE false conditionif permitted_dataset_ids and len(permitted_dataset_ids) > 0:@@ -257,34 +282,50 @@ class DatasetService:else:return [], 0else:- if user.current_role != TenantAccountRole.OWNER or not include_all:- # show all datasets that the user has permission to access- # Check if permitted_dataset_ids is not empty to avoid WHERE false condition- if permitted_dataset_ids and len(permitted_dataset_ids) > 0:- query = query.where(- sa.or_(- Dataset.permission == DatasetPermissionEnum.ALL_TEAM,- sa.and_(- Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id- ),- sa.and_(- Dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM,- Dataset.id.in_(permitted_dataset_ids),- ),- )- )+ if dify_config.RBAC_ENABLED:+ can_manage_all_datasets = DatasetService._can_manage_all_datasets(str(tenant_id), str(user.id))+ should_show_all_datasets = include_all and can_manage_all_datasets+ else:+ should_show_all_datasets = user.current_role == TenantAccountRole.OWNER and include_all++ if not should_show_all_datasets:+ if dify_config.RBAC_ENABLED:+ # RBAC mode: show all datasets. Permission control is enforced+ # via permission_keys on each item and @rbac_permission_required decorators.+ passelse:- query = query.where(- sa.or_(- Dataset.permission == DatasetPermissionEnum.ALL_TEAM,- sa.and_(- Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id- ),+ # Keep legacy visibility rules when RBAC is disabled.+ if permitted_dataset_ids and len(permitted_dataset_ids) > 0:+ query = query.where(+ sa.or_(+ Dataset.permission == DatasetPermissionEnum.ALL_TEAM,+ sa.and_(+ Dataset.permission == DatasetPermissionEnum.ONLY_ME,+ Dataset.maintainer == user.id,+ ),+ sa.and_(+ Dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM,+ Dataset.id.in_(permitted_dataset_ids),+ ),+ )+ )+ else:+ query = query.where(+ sa.or_(+ Dataset.permission == DatasetPermissionEnum.ALL_TEAM,+ sa.and_(+ Dataset.permission == DatasetPermissionEnum.ONLY_ME,+ Dataset.maintainer == user.id,+ ),+ ))- )else:- # if no user, only show datasets that are shared with all team members- query = query.where(Dataset.permission == DatasetPermissionEnum.ALL_TEAM)+ if dify_config.RBAC_ENABLED:+ # Without an account we cannot resolve RBAC resource visibility.+ query = query.where(sa.false())+ else:+ # if no user, only show datasets that are shared with all team members+ query = query.where(Dataset.permission == DatasetPermissionEnum.ALL_TEAM)if search:escaped_search = helper.escape_like_pattern(search)@@ -329,12 +370,28 @@ class DatasetService:return {"mode": mode, "rules": rules}@staticmethod- def get_datasets_by_ids(ids, tenant_id):+ def get_datasets_by_ids(+ ids,+ tenant_id,+ user=None,+ accessible_dataset_ids: list[str] | None = None,+ include_own_datasets: bool = False,+ ):# Check if ids is not empty to avoid WHERE false conditionif not ids or len(ids) == 0:return [], 0stmt = select(Dataset).where(Dataset.id.in_(ids), Dataset.tenant_id == tenant_id)+ if dify_config.RBAC_ENABLED and accessible_dataset_ids is not None:+ requested_dataset_ids = set(ids)+ accessible_dataset_ids = [+ dataset_id for dataset_id in accessible_dataset_ids if dataset_id in requested_dataset_ids+ ]+ accessible_filter: ColumnElement[bool] = Dataset.id.in_(accessible_dataset_ids)+ if include_own_datasets and user:+ accessible_filter = sa.or_(Dataset.maintainer == user.id, accessible_filter)+ stmt = stmt.where(accessible_filter)+datasets = db.paginate(select=stmt, page=1, per_page=len(ids), max_per_page=len(ids), error_out=False)return datasets.items, datasets.total@@ -392,6 +449,7 @@ class DatasetService:# dataset = Dataset(name=name, provider=provider, config=config)dataset.description = descriptiondataset.created_by = account.id+ dataset.maintainer = account.iddataset.updated_by = account.iddataset.tenant_id = tenant_iddataset.embedding_model_provider = embedding_model.provider if embedding_model else None@@ -422,6 +480,12 @@ class DatasetService:db.session.add(external_knowledge_binding)db.session.commit()+ enterprise_rbac_service.try_sync_creator_access_policy_member_bindings(+ tenant_id,+ account.id,+ enterprise_rbac_service.RBACResourceType.DATASET,+ dataset.id,+ )return dataset@staticmethod@@ -467,6 +531,7 @@ class DatasetService:runtime_mode=DatasetRuntimeMode.RAG_PIPELINE,icon_info=rag_pipeline_dataset_create_entity.icon_info.model_dump(),created_by=current_user.id,+ maintainer=current_user.id,pipeline_id=pipeline.id,)db.session.add(dataset)@@ -1265,12 +1330,12 @@ class DatasetService:logger.debug("User %s does not have permission to access dataset %s", user.id, dataset.id)raise NoPermissionError("You do not have permission to access this dataset.")if user.current_role != TenantAccountRole.OWNER:- if dataset.permission == DatasetPermissionEnum.ONLY_ME and dataset.created_by != user.id:+ if dataset.permission == DatasetPermissionEnum.ONLY_ME and dataset.maintainer != user.id:logger.debug("User %s does not have permission to access dataset %s", user.id, dataset.id)raise NoPermissionError("You do not have permission to access this dataset.")if dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM:- # For partial team permission, user needs explicit permission or be the creator- if dataset.created_by != user.id:+ # For partial team permission, user needs explicit permission or be the maintainer.+ if dataset.maintainer != user.id:user_permission = db.session.scalar(select(DatasetPermission).where(DatasetPermission.dataset_id == dataset.id, DatasetPermission.account_id == user.id)@@ -1290,7 +1355,7 @@ class DatasetService:if user.current_role != TenantAccountRole.OWNER:if dataset.permission == DatasetPermissionEnum.ONLY_ME:- if dataset.created_by != user.id:+ if dataset.maintainer != user.id:raise NoPermissionError("You do not have permission to access this dataset.")elif dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM:@@ -2864,6 +2929,7 @@ class DocumentService:data_source_type=knowledge_config.data_source.info_list.data_source_type,indexing_technique=IndexTechniqueType(knowledge_config.indexing_technique),created_by=account.id,+ maintainer=account.id,embedding_model=knowledge_config.embedding_model,embedding_model_provider=knowledge_config.embedding_model_provider,collection_binding_id=dataset_collection_binding_id,diff --git a/api/services/enterprise/base.py b/api/services/enterprise/base.pyindex c1637847e25..71deec752e5 100644--- a/api/services/enterprise/base.py+++ b/api/services/enterprise/base.py@@ -36,6 +36,11 @@ class MCPIdentityRefreshError(MCPTokenError):logger = logging.getLogger(__name__)+# Headers recognised by dify-enterprise's /inner/api/rbac/* endpoints.+# Keep in sync with pkg/enterprise/service/rbac_inner_handlers.go.+INNER_TENANT_ID_HEADER = "X-Inner-Tenant-Id"+INNER_ACCOUNT_ID_HEADER = "X-Inner-Account-Id"+class BaseRequest:proxies: Mapping[str, str] | None = {@@ -69,8 +74,16 @@ class BaseRequest:*,timeout: float | httpx.Timeout | None = None,raise_for_status: bool = False,+ extra_headers: Mapping[str, str] | None = None,) -> Any:headers = {"Content-Type": "application/json", cls.secret_key_header: cls.secret_key}+ if extra_headers:+ # Explicitly ignore empty values so callers can pass optional+ # headers (e.g. `X-Inner-Account-Id`) without having to branch.+ for key, value in extra_headers.items():+ if value is None or value == "":+ continue+ headers[key] = valueurl = f"{cls.base_url}{endpoint}"mounts = cls._build_mounts()@@ -139,9 +152,60 @@ class BaseRequest:class EnterpriseRequest(BaseRequest):base_url = os.environ.get("ENTERPRISE_API_URL", "ENTERPRISE_API_URL")+ rbac_base_url = os.environ.get("ENTERPRISE_RBAC_API_URL", base_url)secret_key = os.environ.get("ENTERPRISE_API_SECRET_KEY", "ENTERPRISE_API_SECRET_KEY")secret_key_header = "Enterprise-Api-Secret-Key"+ @classmethod+ def send_inner_rbac_request(+ cls,+ method: str,+ endpoint: str,+ *,+ tenant_id: str,+ account_id: str | None = None,+ json: Any | None = None,+ params: Mapping[str, Any] | None = None,+ timeout: float | httpx.Timeout | None = None,+ ) -> Any:+ """Call an /inner/api/rbac/* endpoint on dify-enterprise.++ Inner RBAC endpoints require three headers on top of the standard+ Enterprise-Api-Secret-Key: the tenant the call targets and (optionally)+ the account acting on behalf of the workspace. This helper centralises+ both the assertions and the header wiring so callers only have to+ supply business payload.+ """+ if not tenant_id:+ raise ValueError("tenant_id must be provided for inner RBAC requests")++ inner_headers: dict[str, str] = {INNER_TENANT_ID_HEADER: tenant_id}+ if account_id:+ inner_headers[INNER_ACCOUNT_ID_HEADER] = account_id+ url = f"{cls.rbac_base_url}{endpoint}"+ mounts = cls._build_mounts()++ try:+ traceparent = generate_traceparent_header()+ if traceparent:+ inner_headers = dict(inner_headers)+ inner_headers["traceparent"] = traceparent+ except Exception:+ logger.debug("Failed to generate traceparent header", exc_info=True)++ with httpx.Client(mounts=mounts) as client:+ request_kwargs: dict[str, Any] = {+ "json": json,+ "params": params,+ "headers": {"Content-Type": "application/json", cls.secret_key_header: cls.secret_key, **inner_headers},+ }+ if timeout is not None:+ request_kwargs["timeout"] = timeout+ response = client.request(method, url, **request_kwargs)+ if not response.is_success:+ cls._handle_error_response(response)+ return response.json()+class EnterprisePluginManagerRequest(BaseRequest):base_url = os.environ.get("ENTERPRISE_PLUGIN_MANAGER_API_URL", "ENTERPRISE_PLUGIN_MANAGER_API_URL")diff --git a/api/services/enterprise/rbac_service.py b/api/services/enterprise/rbac_service.pynew file mode 100644index 00000000000..39a3a61a781--- /dev/null+++ b/api/services/enterprise/rbac_service.py@@ -0,0 +1,1713 @@+from __future__ import annotations++import logging+from collections.abc import Sequence+from enum import StrEnum+from typing import Any, TypeVar++from flask import has_request_context, request+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator+from sqlalchemy import select+from sqlalchemy.exc import SQLAlchemyError++from configs import dify_config+from core.db.session_factory import session_factory+from models import TenantAccountJoin, TenantAccountRole+from services.enterprise.base import EnterpriseRequest++T = TypeVar("T")+logger = logging.getLogger(__name__)+++class _RBACModel(BaseModel):+ model_config = ConfigDict(populate_by_name=True, extra="ignore")+++class Pagination(_RBACModel):+ total_count: int = 0+ per_page: int = 0+ current_page: int = 0+ total_pages: int = 0+++class Paginated[T](_RBACModel):+ data: list[T] = Field(default_factory=list)+ pagination: Pagination | None = None+++class MembersInRole(_RBACModel):+ account_id: str = ""+ account_name: str = ""+++class RBACResourceType(StrEnum):+ """Resource types understood by access policies."""++ APP = "app"+ DATASET = "dataset"+++class RBACRoleType(StrEnum):+ """The only concrete role type after the access-policy refactor."""++ WORKSPACE = "workspace"+++class PermissionCatalogItem(_RBACModel):+ key: str+ name: str+ description: str = ""+++class PermissionCatalogGroup(_RBACModel):+ group_key: str+ group_name: str+ description: str = ""+ permissions: list[PermissionCatalogItem] = Field(default_factory=list)+++class PermissionCatalogResponse(_RBACModel):+ groups: list[PermissionCatalogGroup] = Field(default_factory=list)+++class RBACRole(_RBACModel):+ id: str+ tenant_id: str | None = None+ type: str+ category: str = ""+ name: str+ description: str = ""+ is_builtin: bool = False+ permission_keys: list[str] = Field(default_factory=list)+ role_tag: str = ""++ @field_validator("permission_keys", mode="before")+ @classmethod+ def _coerce_permission_keys(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class RBACRoleAccount(_RBACModel):+ account_id: str+ account_name: str = ""+ email: str = ""+ avatar: str = ""+++class MemberRoleSummary(_RBACModel):+ id: str+ name: str+++class ResourcePermissionKeys(_RBACModel):+ resource_id: str+ permission_keys: list[str] = Field(default_factory=list)+++class ResourcePermissionKeysBatchResponse(_RBACModel):+ data: list[ResourcePermissionKeys] = Field(default_factory=list)+++class AccessPolicy(_RBACModel):+ id: str+ tenant_id: str = ""+ resource_type: str+ policy_key: str = ""+ name: str+ description: str = ""+ permission_keys: list[str] = Field(default_factory=list)+ is_builtin: bool = False+ category: str = ""+ created_at: int = 0+ updated_at: int = 0++ @field_validator("permission_keys", mode="before")+ @classmethod+ def _coerce_permission_keys(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class AccessPolicyRoleBinding(_RBACModel):+ id: str+ tenant_id: str = ""+ access_policy_id: str+ resource_type: str+ resource_id: str = ""+ role_id: str+ role_name: str = ""+ created_at: int = 0+++class AccessPolicyMemberBinding(_RBACModel):+ id: str+ tenant_id: str = ""+ access_policy_id: str+ resource_type: str+ resource_id: str = ""+ account_id: str+ account_name: str = ""+ created_at: int = 0+++class AccessPolicyBindingState(_RBACModel):+ binding_id: str+ is_locked: bool = False+++class AccessPolicyRole(BaseModel):+ role_id: str+ role_name: str+ binding_id: str+ is_locked: bool = False+ role_tag: str = ""+++class AccessPolicyAccount(BaseModel):+ account_id: str+ account_name: str+ binding_id: str+ is_locked: bool = False+ avatar: str = ""+ email: str = ""+++class AccessMatrixItem(_RBACModel):+ policy: AccessPolicy | None = None+ roles: list[AccessPolicyRole] = Field(default_factory=list)+ accounts: list[AccessPolicyAccount] = Field(default_factory=list)++ @field_validator("roles", "accounts", mode="before")+ @classmethod+ def _coerce_empty_lists(cls, value: Any) -> list[dict[str, Any]]:+ if value is None:+ return []+ return value+++class AppAccessMatrix(_RBACModel):+ app_id: str = Field(default="", validation_alias=AliasChoices("app_id", "resource_id"))+ items: list[AccessMatrixItem] = Field(default_factory=list)+++class DatasetAccessMatrix(_RBACModel):+ dataset_id: str = Field(default="", validation_alias=AliasChoices("dataset_id", "resource_id"))+ items: list[AccessMatrixItem] = Field(default_factory=list)+++class WorkspaceAccessMatrix(_RBACModel):+ items: list[AccessMatrixItem] = Field(default_factory=list)+ pagination: Pagination | None = None+++class RoleBindingsResponse(_RBACModel):+ data: list[AccessPolicyRoleBinding] = Field(default_factory=list)+++class MemberBindingsResponse(_RBACModel):+ data: list[AccessPolicyMemberBinding] = Field(default_factory=list)+++class ResourceWhitelist(_RBACModel):+ account_ids: list[str] = Field(default_factory=list)++ @field_validator("account_ids", mode="before")+ @classmethod+ def _coerce_account_ids(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class ResourceWhitelistResources(_RBACModel):+ unrestricted: bool = False+ resource_ids: list[str] = Field(default_factory=list)++ @field_validator("resource_ids", mode="before")+ @classmethod+ def _coerce_resource_ids(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class ResourceUserAccessPolicies(_RBACModel):+ account: RBACRoleAccount+ roles: list[RBACRole] = Field(default_factory=list)+ access_policies: list[AccessPolicy] = Field(default_factory=list)++ @field_validator("access_policies", "roles", mode="before")+ @classmethod+ def _coerce_none_to_list(cls, value: Any) -> Any:+ if value is None:+ return []+ return value+++class ResourceUserAccessPoliciesResponse(_RBACModel):+ scope: str+ data: list[ResourceUserAccessPolicies] = Field(default_factory=list)+++class ReplaceUserAccessPolicies(_RBACModel):+ access_policy_ids: list[str] = Field(default_factory=list)++ @field_validator("access_policy_ids", mode="before")+ @classmethod+ def _coerce_access_policy_ids(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class ReplaceUserAccessPoliciesResponse(_RBACModel):+ access_policies: list[AccessPolicy] = Field(default_factory=list)+++class MemberRolesResponse(_RBACModel):+ account_id: str+ roles: list[RBACRole] = Field(default_factory=list)+++class MemberRolesBatchResponse(_RBACModel):+ data: list[MemberRolesResponse] = Field(default_factory=list)+++class WorkspacePermissionSnapshot(_RBACModel):+ permission_keys: list[str] = Field(default_factory=list)+++class ResourcePermissionSnapshot(_RBACModel):+ default_permission_keys: list[str] = Field(default_factory=list)+ overrides: list[ResourcePermissionKeys] = Field(default_factory=list)++ def permission_keys_by_resource_ids(self, resource_ids: list[str]) -> dict[str, list[str]]:+ result = {str(resource_id): list(self.default_permission_keys) for resource_id in resource_ids}+ for override in self.overrides:+ resource_id = str(override.resource_id)+ if resource_id in result:+ result[resource_id] = list(override.permission_keys)+ return result+++class MyPermissionsResponse(_RBACModel):+ workspace: WorkspacePermissionSnapshot = Field(default_factory=WorkspacePermissionSnapshot)+ app: ResourcePermissionSnapshot = Field(default_factory=ResourcePermissionSnapshot)+ dataset: ResourcePermissionSnapshot = Field(default_factory=ResourcePermissionSnapshot)+++# Fallback permission snapshots for legacy Dify tenant roles when external RBAC is disabled.+# Keep these keys aligned with langgenius/rbac's built-in workspace roles and access policies.+_LEGACY_WORKSPACE_OWNER_KEYS: list[str] = [+ "workspace.member.manage",+ "workspace.role.manage",+ "data_source.manage",+ "api_extension.manage",+ "customization.manage",+ "plugin.install",+ "plugin.plugin_preferences",+ "plugin.manage",+ "plugin.debug",+ "credential.use",+ "credential.manage",+ "app_library.access",+ "app.create_and_management",+ "app.tag.manage",+ "dataset.create_and_management",+ "dataset.tag.manage",+ "dataset.external.connect",+ "tool.manage",+ "mcp.manage",+]++_LEGACY_WORKSPACE_ADMIN_KEYS: list[str] = [+ "workspace.member.manage",+ "workspace.role.manage",+ "data_source.manage",+ "api_extension.manage",+ "customization.manage",+ "plugin.install",+ "plugin.plugin_preferences",+ "plugin.manage",+ "plugin.debug",+ "credential.use",+ "credential.manage",+ "app_library.access",+ "app.create_and_management",+ "app.tag.manage",+ "dataset.create_and_management",+ "dataset.tag.manage",+ "dataset.external.connect",+ "tool.manage",+ "mcp.manage",+]++_LEGACY_WORKSPACE_EDITOR_KEYS: list[str] = [+ "workspace.member.manage",+ "api_extension.manage",+ "plugin.install",+ "credential.use",+ "app_library.access",+ "app.create_and_management",+ "app.tag.manage",+ "dataset.create_and_management",+ "dataset.tag.manage",+ "dataset.external.connect",+ "tool.manage",+]++_LEGACY_WORKSPACE_NORMAL_KEYS: list[str] = [+ "api_extension.manage",+ "plugin.install",+ "credential.use",+ "app_library.access",+]++_LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS: list[str] = [+ "plugin.install",+ "dataset.create_and_management",+ "dataset.external.connect",+]++_LEGACY_APP_OWNER_KEYS: list[str] = [+ "app.acl.view_layout",+ "app.acl.test_and_run",+ "app.acl.edit",+ "app.acl.import_export_dsl",+ "app.acl.delete",+ "app.acl.release_and_version",+ "app.acl.monitor",+ "app.acl.access_config",+]++_LEGACY_APP_ADMIN_KEYS: list[str] = [+ "app.acl.view_layout",+ "app.acl.test_and_run",+ "app.acl.edit",+ "app.acl.import_export_dsl",+ "app.acl.delete",+ "app.acl.release_and_version",+ "app.acl.monitor",+ "app.acl.access_config",+]++_LEGACY_APP_EDITOR_KEYS: list[str] = [+ "app.acl.view_layout",+ "app.acl.test_and_run",+ "app.acl.edit",+ "app.acl.import_export_dsl",+ "app.acl.delete",+ "app.acl.release_and_version",+ "app.acl.monitor",+ "app.acl.access_config",+]++_LEGACY_APP_NORMAL_KEYS: list[str] = [+ "app.acl.view_layout",+ "app.acl.test_and_run",+ "app.acl.monitor",+]++_LEGACY_DATASET_OWNER_KEYS: list[str] = [+ "dataset.acl.readonly",+ "dataset.acl.edit",+ "dataset.acl.import_export_dsl",+ "dataset.acl.pipeline_test",+ "dataset.acl.document_download",+ "dataset.acl.retrieval_recall",+ "dataset.acl.use",+ "dataset.acl.delete_file",+ "dataset.acl.pipeline_release",+ "dataset.acl.delete",+ "dataset.acl.access_config",+ "dataset.api_key.manage",+]++_LEGACY_DATASET_ADMIN_KEYS: list[str] = [+ "dataset.acl.readonly",+ "dataset.acl.edit",+ "dataset.acl.import_export_dsl",+ "dataset.acl.pipeline_test",+ "dataset.acl.document_download",+ "dataset.acl.retrieval_recall",+ "dataset.acl.use",+ "dataset.acl.delete_file",+ "dataset.acl.pipeline_release",+ "dataset.acl.delete",+ "dataset.acl.access_config",+ "dataset.api_key.manage",+]++_LEGACY_DATASET_EDITOR_KEYS: list[str] = [+ "dataset.acl.readonly",+ "dataset.acl.edit",+ "dataset.acl.import_export_dsl",+ "dataset.acl.pipeline_test",+ "dataset.acl.document_download",+ "dataset.acl.retrieval_recall",+ "dataset.acl.use",+ "dataset.acl.delete_file",+ "dataset.acl.pipeline_release",+]++_LEGACY_DATASET_DATASET_OPERATOR_KEYS: list[str] = [+ "dataset.acl.readonly",+ "dataset.acl.edit",+ "dataset.acl.import_export_dsl",+ "dataset.acl.pipeline_test",+ "dataset.acl.document_download",+ "dataset.acl.retrieval_recall",+ "dataset.acl.use",+ "dataset.acl.delete_file",+ "dataset.acl.pipeline_release",+]++_LEGACY_MY_PERMISSIONS: dict[TenantAccountRole, dict[str, list[str]]] = {+ TenantAccountRole.OWNER: {+ "workspace": _LEGACY_WORKSPACE_OWNER_KEYS,+ "app": _LEGACY_APP_OWNER_KEYS,+ "dataset": _LEGACY_DATASET_OWNER_KEYS,+ },+ TenantAccountRole.ADMIN: {+ "workspace": _LEGACY_WORKSPACE_ADMIN_KEYS,+ "app": _LEGACY_APP_ADMIN_KEYS,+ "dataset": _LEGACY_DATASET_ADMIN_KEYS,+ },+ TenantAccountRole.EDITOR: {+ "workspace": _LEGACY_WORKSPACE_EDITOR_KEYS,+ "app": _LEGACY_APP_EDITOR_KEYS,+ "dataset": _LEGACY_DATASET_EDITOR_KEYS,+ },+ TenantAccountRole.NORMAL: {+ "workspace": _LEGACY_WORKSPACE_NORMAL_KEYS,+ "app": _LEGACY_APP_NORMAL_KEYS,+ },+ TenantAccountRole.DATASET_OPERATOR: {+ "workspace": _LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS,+ "dataset": _LEGACY_DATASET_DATASET_OPERATOR_KEYS,+ },+}+++def _legacy_my_permissions(tenant_id: str, account_id: str | None) -> MyPermissionsResponse:+ if not account_id:+ return MyPermissionsResponse()++ try:+ with session_factory.create_session() as session:+ role = session.scalar(+ select(TenantAccountJoin.role).where(+ TenantAccountJoin.tenant_id == tenant_id,+ TenantAccountJoin.account_id == account_id,+ )+ )+ if not role:+ return MyPermissionsResponse()++ try:+ tenant_role = TenantAccountRole(role)+ except ValueError:+ return MyPermissionsResponse()+ except SQLAlchemyError:+ return MyPermissionsResponse()++ permissions = _LEGACY_MY_PERMISSIONS.get(tenant_role, {})+ return MyPermissionsResponse(+ workspace=WorkspacePermissionSnapshot(permission_keys=list(permissions.get("workspace", []))),+ app=ResourcePermissionSnapshot(default_permission_keys=list(permissions.get("app", []))),+ dataset=ResourcePermissionSnapshot(default_permission_keys=list(permissions.get("dataset", []))),+ )+++def _legacy_resource_permission_keys_batch(+ tenant_id: str,+ account_id: str | None,+ resource_ids: list[str],+ resource_type: RBACResourceType,+) -> dict[str, list[str]]:+ snapshot = _legacy_my_permissions(tenant_id, account_id)+ if resource_type == RBACResourceType.APP:+ permission_keys = snapshot.app.default_permission_keys+ else:+ permission_keys = snapshot.dataset.default_permission_keys+ return {str(resource_id): list(permission_keys) for resource_id in resource_ids}+++# ---------- Mutation request models ----------+++class RoleMutation(_RBACModel):+ """Payload shared by role create & update.++ ``type`` defaults to ``workspace`` because that is the only concrete role+ type supported by the enterprise backend today (see biz.RBACRoleType).+ """++ name: str+ description: str = ""+ permission_keys: list[str] = Field(default_factory=list)+ type: RBACRoleType = RBACRoleType.WORKSPACE+++class AccessPolicyCreate(_RBACModel):+ name: str+ resource_type: RBACResourceType+ description: str = ""+ permission_keys: list[str] = Field(default_factory=list)+++class AccessPolicyUpdate(_RBACModel):+ name: str+ description: str = ""+ permission_keys: list[str] = Field(default_factory=list)+++class ReplaceRoleBindings(_RBACModel):+ role_ids: list[str] = Field(default_factory=list)++ @field_validator("role_ids", mode="before")+ @classmethod+ def _coerce_role_ids(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class ReplaceMemberBindings(_RBACModel):+ scope: str = "specific"++ @field_validator("scope")+ @classmethod+ def _normalize_scope(cls, value: Any) -> str:+ scope = str(value or "").strip().lower()+ if scope in {"", "specific"}:+ return "specific"+ if scope in {"all", "only_me"}:+ return scope+ raise ValueError(f"invalid scope: {value}")+++class DeleteMemberBindings(_RBACModel):+ account_ids: list[str] = Field(default_factory=list)++ @field_validator("account_ids", mode="before")+ @classmethod+ def _coerce_account_ids(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class ReplaceBindings(_RBACModel):+ role_ids: list[str] = Field(default_factory=list)+ account_ids: list[str] = Field(default_factory=list)++ @field_validator("role_ids", "account_ids", mode="before")+ @classmethod+ def _coerce_bindings(cls, value: Any) -> list[str]:+ if value is None:+ return []+ return value+++class ListOption(_RBACModel):+ page_number: int | None = None+ results_per_page: int | None = None+ reverse: bool | None = None++ def to_params(self, extra: dict[str, Any] | None = None) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if self.page_number is not None:+ params["page_number"] = self.page_number+ if self.results_per_page is not None:+ params["results_per_page"] = self.results_per_page+ if self.reverse is not None:+ # httpx renders `True` as the string "True"; we want the inner+ # handler to match on the lowercase form it compares against.+ params["reverse"] = "true" if self.reverse else "false"+ if extra:+ params.update({k: v for k, v in extra.items() if v is not None})+ return params+++_INNER_PREFIX = "/rbac"+++def _request_language_param() -> str | None:+ if not has_request_context():+ return None+ language = (request.args.get("language") or "").strip().lower()+ if language in {"en", "ja", "zh"}:+ return language+ return None+++def _inner_call(+ method: str,+ endpoint: str,+ *,+ tenant_id: str,+ account_id: str | None = None,+ json: Any | None = None,+ params: dict[str, Any] | None = None,+) -> Any:+ """Thin wrapper around `EnterpriseRequest.send_inner_rbac_request`.++ Kept as a module-level helper (rather than a nested-class method) so that+ unit tests can monkey-patch this single entry point instead of every+ individual `Roles.*`, `AccessPolicies.*`, … method.+ """+ language = _request_language_param()+ if language and (not params or "language" not in params):+ params = dict(params or {})+ params["language"] = language+ return EnterpriseRequest.send_inner_rbac_request(+ method,+ endpoint,+ tenant_id=tenant_id,+ account_id=account_id,+ json=json,+ params=params,+ )+++def _resource_id_params(resource_type: RBACResourceType | str, resource_id: str) -> dict[str, str]:+ resource_type_value = resource_type.value if isinstance(resource_type, RBACResourceType) else str(resource_type)+ resource_id = resource_id.strip()+ if resource_type_value == RBACResourceType.APP.value:+ return {"resource_type": resource_type_value, "app_id": resource_id}+ if resource_type_value == RBACResourceType.DATASET.value:+ return {"resource_type": resource_type_value, "dataset_id": resource_id}+ raise ValueError(f"unsupported resource_type: {resource_type_value}")+++def try_sync_creator_access_policy_member_bindings(+ tenant_id: str,+ account_id: str,+ resource_type: RBACResourceType | str,+ resource_id: str,+) -> None:+ if not dify_config.RBAC_ENABLED:+ return+ try:+ RBACService.AccessPolicies.sync_creator_access_policy_member_bindings(+ tenant_id,+ account_id,+ resource_type=resource_type,+ resource_id=resource_id,+ )+ except Exception:+ logger.warning(+ "Failed to sync creator access policy member binding for "+ "tenant_id=%s resource_type=%s resource_id=%s account_id=%s",+ tenant_id,+ resource_type.value if isinstance(resource_type, RBACResourceType) else resource_type,+ resource_id,+ account_id,+ exc_info=True,+ )+++class RBACService:+ """Single entry point grouping every inner RBAC call by feature area.++ Each nested class keeps the classmethods tightly scoped to one URL family+ so call sites read naturally (e.g. ``RBACService.Roles.create(tenant_id,+ account_id, payload)``).+ """++ # ------------------------------------------------------------------+ # Permission catalog (screenshot 3: 新增/编辑角色 弹窗内的权限列表).+ # ------------------------------------------------------------------+ class Catalog:+ @staticmethod+ def workspace(tenant_id: str, account_id: str | None = None) -> PermissionCatalogResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/role-permissions/catalog",+ tenant_id=tenant_id,+ account_id=account_id,+ )+ return PermissionCatalogResponse.model_validate(data or {})++ @staticmethod+ def app(tenant_id: str, account_id: str | None = None) -> PermissionCatalogResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/role-permissions/catalog/app",+ tenant_id=tenant_id,+ account_id=account_id,+ )+ return PermissionCatalogResponse.model_validate(data or {})++ @staticmethod+ def dataset(tenant_id: str, account_id: str | None = None) -> PermissionCatalogResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/role-permissions/catalog/dataset",+ tenant_id=tenant_id,+ account_id=account_id,+ )+ return PermissionCatalogResponse.model_validate(data or {})++ # ------------------------------------------------------------------+ # Role CRUD (Settings > Permissions).+ # ------------------------------------------------------------------+ class Roles:+ @staticmethod+ def list(+ tenant_id: str,+ account_id: str | None = None,+ include_owner: int | None = None,+ *,+ options: ListOption | None = None,+ ) -> Paginated[RBACRole]:+ params = (options or ListOption()).to_params({"include_owner": include_owner})+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/roles",+ tenant_id=tenant_id,+ account_id=account_id,+ params=params or None,+ )+ data = data or {}+ return Paginated[RBACRole](+ data=[RBACRole.model_validate(item) for item in data.get("data") or []],+ pagination=Pagination.model_validate(data["pagination"]) if data.get("pagination") else None,+ )++ @staticmethod+ def list_members_by_role(+ tenant_id: str,+ role_id: str | None = None,+ *,+ options: ListOption | None = None,+ ) -> Paginated[MembersInRole]:+ params = (options or ListOption()).to_params({"role_id": role_id})+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/roles/members",+ tenant_id=tenant_id,+ params=params or None,+ )+ data = data or {}+ return Paginated[MembersInRole](+ data=[MembersInRole.model_validate(item) for item in data.get("data") or []],+ pagination=Pagination.model_validate(data["pagination"]) if data.get("pagination") else None,+ )++ @staticmethod+ def get(tenant_id: str, account_id: str | None, role_id: str) -> RBACRole:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/roles/item",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"id": role_id},+ )+ return RBACRole.model_validate(data or {})++ @staticmethod+ def create(tenant_id: str, account_id: str | None, payload: RoleMutation) -> RBACRole:+ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/roles",+ tenant_id=tenant_id,+ account_id=account_id,+ json=payload.model_dump(mode="json"),+ )+ return RBACRole.model_validate(data or {})++ @staticmethod+ def update(tenant_id: str, account_id: str | None, role_id: str, payload: RoleMutation) -> RBACRole:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/roles/item",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"id": role_id},+ json=payload.model_dump(mode="json"),+ )+ return RBACRole.model_validate(data or {})++ @staticmethod+ def delete(tenant_id: str, account_id: str | None, role_id: str) -> None:+ _inner_call(+ "DELETE",+ f"{_INNER_PREFIX}/roles/item",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"id": role_id},+ )++ @staticmethod+ def copy(tenant_id: str, account_id: str | None, role_id: str, copy_member: bool = True) -> RBACRole:+ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/roles/copy",+ tenant_id=tenant_id,+ account_id=account_id,+ json={"copy_member": copy_member},+ params={"id": role_id},+ )++ return RBACRole.model_validate(data or {})++ @staticmethod+ def members(+ tenant_id: str,+ account_id: str | None,+ role_id: str,+ *,+ options: ListOption | None = None,+ ) -> Paginated[RBACRoleAccount]:+ params = (options or ListOption()).to_params({"role_id": role_id})+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/roles/members",+ tenant_id=tenant_id,+ account_id=account_id,+ params=params,+ )+ data = data or {}+ return Paginated[RBACRoleAccount](+ data=[RBACRoleAccount.model_validate(item) for item in data.get("data") or []],+ pagination=Pagination.model_validate(data["pagination"]) if data.get("pagination") else None,+ )++ # ------------------------------------------------------------------+ # Access policies (Settings > Access Rules: create/edit permission sets).+ # ------------------------------------------------------------------+ class AccessPolicies:+ @staticmethod+ def list(+ tenant_id: str,+ account_id: str | None = None,+ *,+ resource_type: RBACResourceType | str | None = None,+ options: ListOption | None = None,+ ) -> Paginated[AccessPolicy]:+ extra: dict[str, Any] = {}+ if resource_type is not None:+ extra["resource_type"] = (+ resource_type.value if isinstance(resource_type, RBACResourceType) else resource_type+ )+ params = (options or ListOption()).to_params(extra)+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/access-policies",+ tenant_id=tenant_id,+ account_id=account_id,+ params=params or None,+ )+ data = data or {}+ return Paginated[AccessPolicy](+ data=[AccessPolicy.model_validate(item) for item in data.get("data") or []],+ pagination=Pagination.model_validate(data["pagination"]) if data.get("pagination") else None,+ )++ @staticmethod+ def get(tenant_id: str, account_id: str | None, policy_id: str) -> AccessPolicy:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/access-policies/item",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"id": policy_id},+ )+ return AccessPolicy.model_validate(data or {})++ @staticmethod+ def create(tenant_id: str, account_id: str | None, payload: AccessPolicyCreate) -> AccessPolicy:+ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/access-policies",+ tenant_id=tenant_id,+ account_id=account_id,+ json=payload.model_dump(mode="json"),+ )+ return AccessPolicy.model_validate(data or {})++ @staticmethod+ def update(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ payload: AccessPolicyUpdate,+ ) -> AccessPolicy:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/access-policies/item",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return AccessPolicy.model_validate(data or {})++ @staticmethod+ def copy(tenant_id: str, account_id: str | None, policy_id: str) -> AccessPolicy:+ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/access-policies/copy",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"id": policy_id},+ )+ return AccessPolicy.model_validate(data or {})++ @staticmethod+ def delete(tenant_id: str, account_id: str | None, policy_id: str) -> None:+ _inner_call(+ "DELETE",+ f"{_INNER_PREFIX}/access-policies/item",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"id": policy_id},+ )++ @staticmethod+ def sync_creator_access_policy_member_bindings(+ tenant_id: str,+ account_id: str | None,+ *,+ resource_type: RBACResourceType | str,+ resource_id: str,+ ) -> Sequence[AccessPolicyMemberBinding]:+ params = _resource_id_params(resource_type, resource_id)+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/access-policies/creator-member-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params=params,+ )+ items: list[Any] = []+ if isinstance(data, dict):+ items = data.get("data") or []+ return [AccessPolicyMemberBinding.model_validate(item) for item in items]++ # ------------------------------------------------------------------+ # Access-policy bindings (lock / unlock a single binding).+ # ------------------------------------------------------------------+ class AccessPolicyBindings:+ @staticmethod+ def lock(tenant_id: str, account_id: str | None, binding_id: str) -> AccessPolicyBindingState:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/access-policy-bindings/lock",+ tenant_id=tenant_id,+ account_id=account_id,+ json={"binding_id": binding_id},+ )+ return AccessPolicyBindingState.model_validate(data or {})++ @staticmethod+ def unlock(tenant_id: str, account_id: str | None, binding_id: str) -> AccessPolicyBindingState:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/access-policy-bindings/unlock",+ tenant_id=tenant_id,+ account_id=account_id,+ json={"binding_id": binding_id},+ )+ return AccessPolicyBindingState.model_validate(data or {})++ # ------------------------------------------------------------------+ # Per-app access (screenshot 1: App Access Config).+ # ------------------------------------------------------------------+ class AppAccess:+ @staticmethod+ def whitelist_resources(tenant_id: str, account_id: str | None) -> ResourceWhitelistResources:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/apps/whitelist/resources",+ tenant_id=tenant_id,+ account_id=account_id,+ )+ return ResourceWhitelistResources.model_validate(data or {})++ @staticmethod+ def user_access_policies(+ tenant_id: str, account_id: str | None, app_id: str+ ) -> ResourceUserAccessPoliciesResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/apps/user-access-policies",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id},+ )+ return ResourceUserAccessPoliciesResponse.model_validate(data or {})++ @staticmethod+ def replace_user_access_policies(+ tenant_id: str,+ account_id: str | None,+ app_id: str,+ target_account_id: str,+ payload: ReplaceUserAccessPolicies,+ ) -> ReplaceUserAccessPoliciesResponse:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/apps/user-access-policies",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id, "account_id": target_account_id},+ json=payload.model_dump(mode="json"),+ )+ return ReplaceUserAccessPoliciesResponse.model_validate(data or {})++ @staticmethod+ def whitelist(tenant_id: str, account_id: str | None, app_id: str) -> ResourceWhitelist:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/apps/whitelist",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id},+ )+ return ResourceWhitelist.model_validate(data or {})++ @staticmethod+ def replace_whitelist(+ tenant_id: str,+ account_id: str | None,+ app_id: str,+ payload: ReplaceMemberBindings,+ ) -> ResourceWhitelist:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/apps/whitelist",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id},+ json=payload.model_dump(mode="json"),+ )+ return ResourceWhitelist.model_validate(data or {})++ @staticmethod+ def matrix(tenant_id: str, account_id: str | None, app_id: str) -> AppAccessMatrix:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/apps/access-policy",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id},+ )+ return AppAccessMatrix.model_validate(data or {})++ @staticmethod+ def list_role_bindings(+ tenant_id: str,+ account_id: str | None,+ app_id: str,+ policy_id: str,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/apps/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id, "policy_id": policy_id},+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def replace_role_bindings(+ tenant_id: str,+ account_id: str | None,+ app_id: str,+ policy_id: str,+ payload: ReplaceRoleBindings,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/apps/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id, "policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def list_member_bindings(+ tenant_id: str,+ account_id: str | None,+ app_id: str,+ policy_id: str,+ ) -> MemberBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/apps/access-policy/member-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id, "policy_id": policy_id},+ )+ return MemberBindingsResponse.model_validate(data or {})++ @staticmethod+ def delete_member_bindings(+ tenant_id: str,+ account_id: str | None,+ app_id: str,+ policy_id: str,+ payload: DeleteMemberBindings,+ ) -> None:+ _inner_call(+ "DELETE",+ f"{_INNER_PREFIX}/apps/access-policy/member-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id, "policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )++ @staticmethod+ def replace_bindings(+ tenant_id: str,+ account_id: str | None,+ app_id: str,+ policy_id: str,+ payload: ReplaceBindings,+ ) -> AccessMatrixItem:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/apps/access-policy/bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"app_id": app_id, "policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return AccessMatrixItem.model_validate(data or {})++ # ------------------------------------------------------------------+ # Per-dataset access (screenshot 1: Knowledge Base Access Config).+ # ------------------------------------------------------------------+ class DatasetAccess:+ @staticmethod+ def whitelist_resources(tenant_id: str, account_id: str | None) -> ResourceWhitelistResources:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/datasets/whitelist/resources",+ tenant_id=tenant_id,+ account_id=account_id,+ )+ return ResourceWhitelistResources.model_validate(data or {})++ @staticmethod+ def user_access_policies(+ tenant_id: str, account_id: str | None, dataset_id: str+ ) -> ResourceUserAccessPoliciesResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/datasets/user-access-policies",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id},+ )+ return ResourceUserAccessPoliciesResponse.model_validate(data or {})++ @staticmethod+ def replace_user_access_policies(+ tenant_id: str,+ account_id: str | None,+ dataset_id: str,+ target_account_id: str,+ payload: ReplaceUserAccessPolicies,+ ) -> ReplaceUserAccessPoliciesResponse:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/datasets/user-access-policies",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id, "account_id": target_account_id},+ json=payload.model_dump(mode="json"),+ )+ return ReplaceUserAccessPoliciesResponse.model_validate(data or {})++ @staticmethod+ def whitelist(tenant_id: str, account_id: str | None, dataset_id: str) -> ResourceWhitelist:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/datasets/whitelist",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id},+ )+ return ResourceWhitelist.model_validate(data or {})++ @staticmethod+ def replace_whitelist(+ tenant_id: str,+ account_id: str | None,+ dataset_id: str,+ payload: ReplaceMemberBindings,+ ) -> ResourceWhitelist:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/datasets/whitelist",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id},+ json=payload.model_dump(mode="json"),+ )+ return ResourceWhitelist.model_validate(data or {})++ @staticmethod+ def matrix(tenant_id: str, account_id: str | None, dataset_id: str) -> DatasetAccessMatrix:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/datasets/access-policy",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id},+ )+ return DatasetAccessMatrix.model_validate(data or {})++ @staticmethod+ def list_role_bindings(+ tenant_id: str,+ account_id: str | None,+ dataset_id: str,+ policy_id: str,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/datasets/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id, "policy_id": policy_id},+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def replace_role_bindings(+ tenant_id: str,+ account_id: str | None,+ dataset_id: str,+ policy_id: str,+ payload: ReplaceRoleBindings,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/datasets/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id, "policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def list_member_bindings(+ tenant_id: str,+ account_id: str | None,+ dataset_id: str,+ policy_id: str,+ ) -> MemberBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/datasets/access-policy/member-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id, "policy_id": policy_id},+ )+ return MemberBindingsResponse.model_validate(data or {})++ @staticmethod+ def delete_member_bindings(+ tenant_id: str,+ account_id: str | None,+ dataset_id: str,+ policy_id: str,+ payload: DeleteMemberBindings,+ ) -> None:+ _inner_call(+ "DELETE",+ f"{_INNER_PREFIX}/datasets/access-policy/member-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id, "policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )++ @staticmethod+ def replace_bindings(+ tenant_id: str,+ account_id: str | None,+ dataset_id: str,+ policy_id: str,+ payload: ReplaceBindings,+ ) -> AccessMatrixItem:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/datasets/access-policy/bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"dataset_id": dataset_id, "policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return AccessMatrixItem.model_validate(data or {})++ # ------------------------------------------------------------------+ # Workspace-level access (screenshot 2: Settings > Access Rules).+ # ------------------------------------------------------------------+ class WorkspaceAccess:+ @staticmethod+ def app_matrix(+ tenant_id: str,+ account_id: str | None = None,+ *,+ options: ListOption | None = None,+ ) -> WorkspaceAccessMatrix:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/workspace/apps/access-policy",+ tenant_id=tenant_id,+ account_id=account_id,+ params=(options or ListOption()).to_params() or None,+ )+ return WorkspaceAccessMatrix.model_validate(data or {})++ @staticmethod+ def dataset_matrix(+ tenant_id: str,+ account_id: str | None = None,+ *,+ options: ListOption | None = None,+ ) -> WorkspaceAccessMatrix:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/workspace/datasets/access-policy",+ tenant_id=tenant_id,+ account_id=account_id,+ params=(options or ListOption()).to_params() or None,+ )+ return WorkspaceAccessMatrix.model_validate(data or {})++ @staticmethod+ def list_app_role_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/workspace/apps/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def replace_app_role_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ payload: ReplaceRoleBindings,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/workspace/apps/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def list_app_member_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ ) -> MemberBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/workspace/apps/access-policy/member-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ )+ return MemberBindingsResponse.model_validate(data or {})++ @staticmethod+ def replace_app_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ payload: ReplaceBindings,+ ) -> AccessMatrixItem:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/workspace/apps/access-policy/bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return AccessMatrixItem.model_validate(data or {})++ @staticmethod+ def list_dataset_role_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/workspace/datasets/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def replace_dataset_role_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ payload: ReplaceRoleBindings,+ ) -> RoleBindingsResponse:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/workspace/datasets/access-policy/role-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return RoleBindingsResponse.model_validate(data or {})++ @staticmethod+ def list_dataset_member_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ ) -> MemberBindingsResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/workspace/datasets/access-policy/member-bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ )+ return MemberBindingsResponse.model_validate(data or {})++ @staticmethod+ def replace_dataset_bindings(+ tenant_id: str,+ account_id: str | None,+ policy_id: str,+ payload: ReplaceBindings,+ ) -> AccessMatrixItem:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/workspace/datasets/access-policy/bindings",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"policy_id": policy_id},+ json=payload.model_dump(mode="json"),+ )+ return AccessMatrixItem.model_validate(data or {})++ # ------------------------------------------------------------------+ # Member ↔ role bindings (screenshot 3: Settings > Members > Assign roles).+ # ------------------------------------------------------------------+ class MemberRoles:+ @staticmethod+ def get(tenant_id: str, account_id: str | None, member_account_id: str) -> MemberRolesResponse:+ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/members/rbac-roles",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"account_id": member_account_id},+ )+ rst = MemberRolesResponse.model_validate(data or {})+ return rst++ @staticmethod+ def batch_get(+ tenant_id: str,+ account_id: str | None,+ member_account_ids: list[str],+ ) -> list[MemberRolesResponse]:+ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/members/rbac-roles/batch",+ tenant_id=tenant_id,+ account_id=account_id,+ json={"member_ids": member_account_ids},+ )+ items = []+ if isinstance(data, dict):+ items = [{"account_id": account_id, "roles": roles} for account_id, roles in data.items()]+ rst = []+ for item in items:+ tmp = MemberRolesResponse.model_validate(item)+ rst.append(tmp)+ return rst++ @staticmethod+ def replace(+ tenant_id: str,+ account_id: str | None,+ member_account_id: str,+ role_ids: list[str],+ ) -> MemberRolesResponse:+ data = _inner_call(+ "PUT",+ f"{_INNER_PREFIX}/members/rbac-roles",+ tenant_id=tenant_id,+ account_id=account_id,+ params={"account_id": member_account_id},+ json={"role_ids": role_ids},+ )+ return MemberRolesResponse.model_validate(data or {})++ class CheckAccess:+ """Call the ``/inner/api/rbac/check-access`` endpoint."""++ @staticmethod+ def check(+ tenant_id: str,+ account_id: str | None,+ *,+ scene: str,+ resource_type: str | None = None,+ resource_id: str | None = None,+ ) -> bool:+ """Return ``True`` if the account is allowed, ``False`` otherwise."""+ if not dify_config.RBAC_ENABLED:+ return True++ payload: dict[str, Any] = {+ "account_id": account_id or "",+ "tenant_id": tenant_id,+ "scene": scene,+ }+ if resource_type:+ payload["resource_type"] = resource_type+ if resource_id:+ payload["resource_id"] = resource_id++ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/check-access",+ tenant_id=tenant_id,+ account_id=account_id,+ json=payload,+ )+ return bool(data.get("allowed", False))++ class AppPermissions:+ @staticmethod+ def batch_get(+ tenant_id: str,+ account_id: str | None,+ app_ids: list[str],+ ) -> dict[str, list[str]]:+ if not app_ids:+ return {}+ if not dify_config.RBAC_ENABLED:+ return _legacy_resource_permission_keys_batch(tenant_id, account_id, app_ids, RBACResourceType.APP)+ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/apps/permission-keys/batch",+ tenant_id=tenant_id,+ account_id=account_id,+ json={"app_ids": app_ids},+ )+ return _parse_resource_permission_keys_batch(data, resource_id_key="app_id")++ class DatasetPermissions:+ @staticmethod+ def batch_get(+ tenant_id: str,+ account_id: str | None,+ dataset_ids: list[str],+ ) -> dict[str, list[str]]:+ if not dataset_ids:+ return {}+ if not dify_config.RBAC_ENABLED:+ return _legacy_resource_permission_keys_batch(+ tenant_id, account_id, dataset_ids, RBACResourceType.DATASET+ )+ data = _inner_call(+ "POST",+ f"{_INNER_PREFIX}/datasets/permission-keys/batch",+ tenant_id=tenant_id,+ account_id=account_id,+ json={"dataset_ids": dataset_ids},+ )+ return _parse_resource_permission_keys_batch(data, resource_id_key="dataset_id")++ class MyPermissions:+ @staticmethod+ def get(+ tenant_id: str,+ account_id: str | None,+ *,+ app_id: str | None = None,+ dataset_id: str | None = None,+ ) -> MyPermissionsResponse:+ if not dify_config.RBAC_ENABLED:+ return _legacy_my_permissions(tenant_id, account_id)++ data = _inner_call(+ "GET",+ f"{_INNER_PREFIX}/my-permissions",+ tenant_id=tenant_id,+ account_id=account_id,+ params={+ k: v+ for k, v in {+ "app_id": app_id,+ "dataset_id": dataset_id,+ }.items()+ if v is not None+ }+ or None,+ )+ return MyPermissionsResponse.model_validate(data or {})+++def _parse_resource_permission_keys_batch(data: Any, *, resource_id_key: str) -> dict[str, list[str]]:+ if not data:+ return {}++ if isinstance(data, dict):+ permissions = data.get("permissions")+ if isinstance(permissions, dict):+ return {str(key): [str(item) for item in (value or [])] for key, value in permissions.items()}++ items = data.get("data")+ if items is None:+ items = data.get("items")+ if items is None:+ items = data.get("apps") if resource_id_key == "app_id" else data.get("datasets")+ if isinstance(items, dict):+ items = [{"resource_id": key, "permission_keys": value} for key, value in items.items()]+ elif isinstance(data, list):+ items = data+ else:+ items = []++ result: dict[str, list[str]] = {}+ for item in items or []:+ if not isinstance(item, dict):+ continue+ resource_id = item.get("resource_id") or item.get(resource_id_key)+ if not resource_id:+ continue+ permission_keys = item.get("permission_keys") or []+ result[str(resource_id)] = [str(permission_key) for permission_key in permission_keys]+ return resultdiff --git a/api/services/external_knowledge_service.py b/api/services/external_knowledge_service.pyindex 8f89bca8e2b..c0aedfaceea 100644--- a/api/services/external_knowledge_service.py+++ b/api/services/external_knowledge_service.py@@ -280,6 +280,7 @@ class ExternalDatasetService:provider="external",retrieval_model=args.get("external_retrieval_model"),created_by=user_id,+ maintainer=user_id,)db.session.add(dataset)diff --git a/api/services/feature_service.py b/api/services/feature_service.pyindex 10a15a0492b..2ae0c63ff75 100644--- a/api/services/feature_service.py+++ b/api/services/feature_service.py@@ -181,6 +181,7 @@ class SystemFeatureModel(FeatureResponseModel):enable_creators_platform: bool = Falseenable_trial_app: bool = Falseenable_explore_banner: bool = False+ rbac_enabled: bool = Falseclass FeatureService:@@ -247,6 +248,7 @@ class FeatureService:@classmethoddef get_system_features(cls, is_authenticated: bool = False) -> SystemFeatureModel:system_features = SystemFeatureModel()+ system_features.rbac_enabled = dify_config.RBAC_ENABLEDcls._fulfill_system_params_from_env(system_features)diff --git a/api/services/rag_pipeline/rag_pipeline_dsl_service.py b/api/services/rag_pipeline/rag_pipeline_dsl_service.pyindex 52fe9108907..bdbf3e080e9 100644--- a/api/services/rag_pipeline/rag_pipeline_dsl_service.py+++ b/api/services/rag_pipeline/rag_pipeline_dsl_service.py@@ -283,6 +283,7 @@ class RagPipelineDslService:},indexing_technique=IndexTechniqueType(knowledge_configuration.indexing_technique),created_by=account.id,+ maintainer=account.id,retrieval_model=knowledge_configuration.retrieval_model.model_dump(),runtime_mode=DatasetRuntimeMode.RAG_PIPELINE,chunk_structure=knowledge_configuration.chunk_structure,@@ -415,6 +416,7 @@ class RagPipelineDslService:},indexing_technique=IndexTechniqueType(knowledge_configuration.indexing_technique),created_by=account.id,+ maintainer=account.id,retrieval_model=knowledge_configuration.retrieval_model.model_dump(),runtime_mode=DatasetRuntimeMode.RAG_PIPELINE,chunk_structure=knowledge_configuration.chunk_structure,diff --git a/api/services/tag_service.py b/api/services/tag_service.pyindex 59dd5f7bb36..b144c15e85e 100644--- a/api/services/tag_service.py+++ b/api/services/tag_service.py@@ -55,7 +55,12 @@ class TagService:@staticmethoddef get_target_ids_by_tag_ids(- tag_type: str, current_tenant_id: str, tag_ids: list[str], session: scoped_session, *, match_all: bool = False+ tag_type: str,+ current_tenant_id: str,+ tag_ids: list[str],+ session: scoped_session | Session,+ *,+ match_all: bool = False,):"""Return target IDs bound to tags for the given tenant and resource type.diff --git a/api/services/workflow/workflow_converter.py b/api/services/workflow/workflow_converter.pyindex 5dedb9e3729..e279f1daaa3 100644--- a/api/services/workflow/workflow_converter.py+++ b/api/services/workflow/workflow_converter.py@@ -95,6 +95,7 @@ class WorkflowConverter:new_app.is_demo = Falsenew_app.is_public = app_model.is_publicnew_app.created_by = account.id+ new_app.maintainer = account.idnew_app.updated_by = account.iddb.session.add(new_app)db.session.flush()diff --git a/api/tests/test_containers_integration_tests/controllers/service_api/dataset/test_dataset.py b/api/tests/test_containers_integration_tests/controllers/service_api/dataset/test_dataset.pyindex ac166df454f..1717fea789f 100644--- a/api/tests/test_containers_integration_tests/controllers/service_api/dataset/test_dataset.py+++ b/api/tests/test_containers_integration_tests/controllers/service_api/dataset/test_dataset.py@@ -20,13 +20,13 @@ from unittest.mock import ANY, Mock, PropertyMock, patchimport pytestfrom flask import Flask-from sqlalchemy.orm import Session+from sqlalchemy.orm import Session, scoped_sessionfrom werkzeug.exceptions import Forbidden, NotFoundclass SessionMatcher:def __eq__(self, other):- return isinstance(other, Session)+ return isinstance(other, (Session, scoped_session))import services@@ -366,6 +366,7 @@ DATASET_DETAIL_KEYS = {"total_available_documents","enable_api","is_multimodal",+ "maintainer",}@@ -468,6 +469,7 @@ class TestDatasetListApiGet:mock_dataset_svc.get_datasets.assert_called_once_with(1,20,+ SessionMatcher(),mock_tenant.id,mock_current_user,None,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 83d2e25d224..61dca361f3e 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@@ -9,7 +9,7 @@ from werkzeug.exceptions import Unauthorizedfrom configs import dify_configfrom controllers.console.error import AccountNotFound, NotAllowedCreateWorkspace-from models import AccountStatus, TenantAccountJoin, TenantStatus+from models import AccountStatus, App, Dataset, TenantAccountJoin, TenantStatusfrom services.account_service import AccountService, RegisterService, TenantService, TokenPairfrom services.errors.account import (AccountAlreadyInTenantError,@@ -1799,8 +1799,32 @@ class TestTenantService:TenantService.create_tenant_member(tenant, owner_account, role="owner")TenantService.create_tenant_member(tenant, member_account, role="normal")+ app = App(+ tenant_id=tenant.id,+ name="Member app",+ mode="chat",+ enable_site=True,+ enable_api=True,+ created_by=member_account.id,+ maintainer=member_account.id,+ )+ dataset = Dataset(+ tenant_id=tenant.id,+ name="Member dataset",+ created_by=member_account.id,+ maintainer=member_account.id,+ )+ db_session_with_containers.add_all([app, dataset])+ db_session_with_containers.commit()+# Remove member- with patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync:+ with (+ patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync,+ patch(+ "services.account_service.AccountService.get_rbac_workspace_owner_account_id",+ return_value=owner_account.id,+ ),+ ):mock_sync.return_value = TrueTenantService.remove_member_from_tenant(tenant, member_account, owner_account)@@ -1819,6 +1843,12 @@ class TestTenantService:.first())assert member_join is None+ db_session_with_containers.refresh(app)+ db_session_with_containers.refresh(dataset)+ assert app.created_by == member_account.id+ assert app.maintainer == owner_account.id+ assert dataset.created_by == member_account.id+ assert dataset.maintainer == owner_account.iddef test_remove_member_from_tenant_operate_self(self, db_session_with_containers: Session, mock_external_service_dependenciesdiff --git a/api/tests/test_containers_integration_tests/services/test_app_service.py b/api/tests/test_containers_integration_tests/services/test_app_service.pyindex 43c254d407d..0f5cd184430 100644--- a/api/tests/test_containers_integration_tests/services/test_app_service.py+++ b/api/tests/test_containers_integration_tests/services/test_app_service.py@@ -96,6 +96,7 @@ class TestAppService:assert app.api_rph == app_params.api_rphassert app.api_rpm == app_params.api_rpmassert app.created_by == account.id+ assert app.maintainer == account.idassert app.updated_by == account.idassert app.status == "normal"assert app.enable_site is Truediff --git a/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.py b/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.pyindex f9898e2cfac..1ea1b10a15d 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.py@@ -73,6 +73,7 @@ class DatasetPermissionTestDataFactory:data_source_type=DataSourceType.UPLOAD_FILE,indexing_technique=IndexTechniqueType.HIGH_QUALITY,created_by=created_by,+ maintainer=created_by,permission=permission,provider="vendor",retrieval_model={"top_k": 2},diff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service.py b/api/tests/test_containers_integration_tests/services/test_dataset_service.pyindex e6ee896a525..201b65b30d0 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_service.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_service.py@@ -441,6 +441,7 @@ class TestDatasetServiceCreateRagPipelineDataset:assert created_dataset.name == entity.nameassert created_dataset.runtime_mode == DatasetRuntimeMode.RAG_PIPELINEassert created_dataset.created_by == account.id+ assert created_dataset.maintainer == account.idassert created_dataset.permission == DatasetPermissionEnum.ONLY_MEassert created_pipeline is not Noneassert created_pipeline.name == entity.namediff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_document.pyindex 0c089e506bf..946ac661940 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py@@ -30,11 +30,13 @@ class DocumentServiceIntegrationFactory:created_by: str | None = None,name: str | None = None,) -> Dataset:+ resolved_created_by = created_by or str(uuid4())dataset = Dataset(tenant_id=tenant_id or str(uuid4()),name=name or f"dataset-{uuid4()}",data_source_type=DataSourceType.UPLOAD_FILE,- created_by=created_by or str(uuid4()),+ created_by=resolved_created_by,+ maintainer=resolved_created_by,)db_session_with_containers.add(dataset)db_session_with_containers.commit()diff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.pyindex 0603a1e27f1..d97c16668fd 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py@@ -100,6 +100,7 @@ class DatasetPermissionIntegrationFactory:data_source_type=DataSourceType.UPLOAD_FILE,indexing_technique=indexing_technique,created_by=created_by,+ maintainer=created_by,provider="vendor",permission=permission,retrieval_model={"top_k": 2},diff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_retrieval.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_retrieval.pyindex 27ab600871b..05632b1ec2a 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_service_retrieval.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_retrieval.py@@ -106,6 +106,7 @@ class DatasetRetrievalTestDataFactory:data_source_type=DataSourceType.UPLOAD_FILE,indexing_technique=IndexTechniqueType.HIGH_QUALITY,created_by=created_by,+ maintainer=created_by,permission=permission,provider="vendor",retrieval_model={"top_k": 2},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 0cccb34b08d..08273a6e1f7 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,13 +13,28 @@ from controllers.console.app import app_import as app_import_modulefrom services.app_dsl_service import ImportStatus+def _unwrap(func):+ bound_self = getattr(func, "__self__", None)+ while hasattr(func, "__wrapped__"):+ func = func.__wrapped__+ if bound_self is not None:+ return func.__get__(bound_self, bound_self.__class__)+ return func++class _Result:- def __init__(self, status: ImportStatus, app_id: str | None = "app-1"):+ def __init__(+ self,+ status: ImportStatus,+ app_id: str | None = "app-1",+ permission_keys: list[str] | None = None,+ ):self.status = statusself.app_id = app_id+ self.permission_keys = permission_keys or []def model_dump(self, mode: str = "json"):- return {"status": self.status, "app_id": self.app_id}+ return {"status": self.status, "app_id": self.app_id, "permission_keys": self.permission_keys}def _install_features(monkeypatch: pytest.MonkeyPatch, enabled: bool) -> None:@@ -107,6 +122,72 @@ class TestAppImportApi:assert status == 200assert response["status"] == ImportStatus.COMPLETED+ def test_import_post_attaches_permission_keys_when_creating_new_app_and_rbac_enabled(+ self, api, app: Flask, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ method = _unwrap(api.post)++ _install_features(monkeypatch, enabled=False)+ session = _mock_session(monkeypatch)+ monkeypatch.setattr(+ app_import_module,+ "current_account_with_tenant",+ lambda: (SimpleNamespace(id="u1"), "tenant-1"),+ )+ monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_import_module.AppDslService,+ "import_app",+ lambda *_args, **_kwargs: _Result(ImportStatus.COMPLETED, app_id="app-123"),+ )+ monkeypatch.setattr(+ app_import_module,+ "get_app_permission_keys",+ lambda tenant_id, account_id, app_id: ["app.acl.view_layout", "app.acl.edit"],+ )++ with app.test_request_context("/console/api/apps/imports", method="POST", json={"mode": "yaml-content"}):+ response, status = method()++ session.commit.assert_called_once_with()+ assert status == 200+ assert response["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"]++ def test_import_post_does_not_attach_permission_keys_when_overwriting_existing_app(+ self, api, app: Flask, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ method = _unwrap(api.post)++ _install_features(monkeypatch, enabled=False)+ session = _mock_session(monkeypatch)+ monkeypatch.setattr(+ app_import_module,+ "current_account_with_tenant",+ lambda: (SimpleNamespace(id="u1"), "tenant-1"),+ )+ monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_import_module.AppDslService,+ "import_app",+ lambda *_args, **_kwargs: _Result(ImportStatus.COMPLETED, app_id="app-123"),+ )+ monkeypatch.setattr(+ app_import_module,+ "get_app_permission_keys",+ lambda *_args, **_kwargs: ["app.acl.view_layout", "app.acl.edit"],+ )++ with app.test_request_context(+ "/console/api/apps/imports",+ method="POST",+ json={"mode": "yaml-content", "app_id": "existing-app"},+ ):+ response, status = method()++ session.commit.assert_called_once_with()+ assert status == 200+ assert response["permission_keys"] == []+class TestAppImportConfirmApi:@pytest.fixture@@ -132,3 +213,79 @@ class TestAppImportConfirmApi:session.commit.assert_not_called()assert status == 400assert response["status"] == ImportStatus.FAILED++ def test_import_confirm_attaches_permission_keys_when_creating_new_app_and_rbac_enabled(+ self, api, app: Flask, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ method = _unwrap(api.post)++ session = _mock_session(monkeypatch)+ monkeypatch.setattr(+ app_import_module,+ "current_account_with_tenant",+ lambda: (SimpleNamespace(id="u1"), "tenant-1"),+ )+ monkeypatch.setattr(+ app_import_module.redis_client,+ "get",+ lambda *_args, **_kwargs: (+ b'{"import_mode":"yaml-content","yaml_content":"app: {}","app_id":null,'+ b'"name":null,"description":null,"icon_type":null,"icon":null,"icon_background":null}'+ ),+ )+ monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_import_module.AppDslService,+ "confirm_import",+ lambda *_args, **_kwargs: _Result(ImportStatus.COMPLETED, app_id="app-456"),+ )+ monkeypatch.setattr(+ app_import_module,+ "get_app_permission_keys",+ lambda tenant_id, account_id, app_id: ["app.acl.view_layout", "app.acl.edit"],+ )++ with app.test_request_context("/console/api/apps/imports/import-1/confirm", method="POST"):+ response, status = method(import_id="import-1")++ session.commit.assert_called_once_with()+ assert status == 200+ assert response["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"]++ def test_import_confirm_does_not_attach_permission_keys_when_overwriting_existing_app(+ self, api, app: Flask, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ method = _unwrap(api.post)++ session = _mock_session(monkeypatch)+ monkeypatch.setattr(+ app_import_module,+ "current_account_with_tenant",+ lambda: (SimpleNamespace(id="u1"), "tenant-1"),+ )+ monkeypatch.setattr(+ app_import_module.redis_client,+ "get",+ lambda *_args, **_kwargs: (+ b'{"import_mode":"yaml-content","yaml_content":"app: {}","app_id":"existing-app",'+ b'"name":null,"description":null,"icon_type":null,"icon":null,"icon_background":null}'+ ),+ )+ monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_import_module.AppDslService,+ "confirm_import",+ lambda *_args, **_kwargs: _Result(ImportStatus.COMPLETED, app_id="app-456"),+ )+ monkeypatch.setattr(+ app_import_module,+ "get_app_permission_keys",+ lambda *_args, **_kwargs: ["app.acl.view_layout", "app.acl.edit"],+ )++ with app.test_request_context("/console/api/apps/imports/import-1/confirm", method="POST"):+ response, status = method(import_id="import-1")++ session.commit.assert_called_once_with()+ assert status == 200+ assert response["permission_keys"] == []diff --git a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py b/api/tests/unit_tests/controllers/console/app/test_app_response_models.pyindex 9cff0c8d3ee..48a19bb0364 100644--- a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py+++ b/api/tests/unit_tests/controllers/console/app/test_app_response_models.py@@ -14,6 +14,8 @@ from flask.views import MethodViewfrom pydantic import ValidationErrorfrom werkzeug.datastructures import MultiDict+from configs import dify_config+# kombu references MethodView as a global when importing celery/kombu pools.if not hasattr(builtins, "MethodView"):builtins.MethodView = MethodView # type: ignore[attr-defined]@@ -351,6 +353,7 @@ def test_app_partial_serialization_uses_aliases(app_models):create_user_name="Creator",author_name="Author",has_draft_trigger=True,+ permission_keys=["app.acl.view_layout"],role="Should stay agent-only",)@@ -364,6 +367,7 @@ def test_app_partial_serialization_uses_aliases(app_models):assert serialized["model_config"]["model"] == {"provider": "openai", "name": "gpt-4o"}assert serialized["workflow"]["id"] == "wf-1"assert serialized["tags"][0]["name"] == "Utilities"+ assert serialized["permission_keys"] == ["app.acl.view_layout"]assert "role" not in serialized@@ -402,6 +406,7 @@ def test_app_detail_with_site_includes_nested_serialization(app_models):updated_at=timestamp,access_mode="public",tags=[SimpleNamespace(id="tag-2", name="Prod", type="app")],+ permission_keys=["app.acl.view_layout", "app.acl.edit"],api_base_url="https://api.example.com/v1",max_active_requests=5,deleted_tools=[{"type": "api", "tool_name": "search", "provider_id": "prov"}],@@ -417,6 +422,7 @@ def test_app_detail_with_site_includes_nested_serialization(app_models):assert serialized["deleted_tools"][0]["tool_name"] == "search"assert serialized["site"]["icon_url"] == "signed:site-icon"assert serialized["site"]["created_at"] == int(timestamp.timestamp())+ assert serialized["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"]assert serialized["bound_agent_id"] == "agent-1"assert "role" not in serialized@@ -432,6 +438,7 @@ def test_app_pagination_aliases_per_page_and_has_next(app_models):icon="first-icon",created_at=_ts(15),updated_at=_ts(15),+ permission_keys=["app.acl.edit"],)item_two = SimpleNamespace(id="app-11",@@ -493,6 +500,20 @@ def test_app_list_uses_injected_session_for_draft_workflows("FeatureService",SimpleNamespace(get_system_features=lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))),)+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.MyPermissions,+ "get",+ lambda tenant_id, account_id: app_module.enterprise_rbac_service.MyPermissionsResponse(+ app=app_module.enterprise_rbac_service.ResourcePermissionSnapshot(+ overrides=[+ app_module.enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="app-1",+ permission_keys=["app.acl.edit"],+ )+ ]+ )+ ),+ )monkeypatch.setattr(app_module, "db", SimpleNamespace(session=scoped_session))with app.test_request_context("/console/api/apps?page=1&limit=20", method="GET"):@@ -502,3 +523,351 @@ def test_app_list_uses_injected_session_for_draft_workflows(assert response["data"][0]["has_draft_trigger"] is Truesession.execute.assert_called_once()scoped_session.execute.assert_not_called()+ assert response["data"][0]["permission_keys"] == ["app.acl.edit"]+++def test_app_create_api_attaches_permission_keys(app, app_module):+ method = app_module.AppListApi.post+ while hasattr(method, "__wrapped__"):+ method = method.__wrapped__++ app_obj = SimpleNamespace(+ id="app-new",+ name="Created App",+ description="Summary",+ mode_compatible_with_agent="advanced-chat",+ enable_site=True,+ enable_api=True,+ permission_keys=[],+ )++ with app.test_request_context("/apps", method="POST", json={}):+ with pytest.MonkeyPatch.context() as monkeypatch:+ app_module.console_ns.payload = {+ "name": "Created App",+ "description": "Summary",+ "mode": "advanced-chat",+ }+ monkeypatch.setattr(+ app_module,+ "AppService",+ lambda: SimpleNamespace(create_app=lambda tenant_id, params, user: app_obj),+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.AppPermissions,+ "batch_get",+ lambda tenant_id, account_id, app_ids: {"app-new": ["app.acl.view_layout", "app.acl.edit"]},+ )++ resp, status = method(app_module.AppListApi(), "tenant-1", SimpleNamespace(id="acct-1"))++ assert status == 201+ assert resp["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"]+++def test_app_list_api_attaches_permission_keys(app, app_module):+ method = app_module.AppListApi.get+ while hasattr(method, "__wrapped__"):+ method = method.__wrapped__++ app_obj = SimpleNamespace(+ id="app-1",+ name="List App",+ desc_or_prompt="Summary",+ mode_compatible_with_agent="chat",+ mode="chat",+ created_at=_ts(15),+ updated_at=_ts(15),+ permission_keys=[],+ )+ pagination = SimpleNamespace(page=1, per_page=20, total=1, has_next=False, items=[app_obj])+ get_paginate_apps = MagicMock(return_value=pagination)++ with app.test_request_context("/apps"):+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_module.AppService,+ "get_paginate_apps",+ get_paginate_apps,+ )+ monkeypatch.setattr(+ app_module.FeatureService,+ "get_system_features",+ lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.MyPermissions,+ "get",+ lambda tenant_id, account_id: app_module.enterprise_rbac_service.MyPermissionsResponse(+ app=app_module.enterprise_rbac_service.ResourcePermissionSnapshot(+ default_permission_keys=["app.preview", "app.acl.view_layout"],+ overrides=[+ app_module.enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="app-1",+ permission_keys=["app.acl.view_layout", "app.acl.edit"],+ )+ ],+ )+ ),+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.AppAccess,+ "whitelist_resources",+ lambda tenant_id, account_id: SimpleNamespace(unrestricted=True, resource_ids=[]),+ )++ session = MagicMock()+ session.execute.return_value.scalars.return_value.all.return_value = []+ resp, status = method(app_module.AppListApi(), "tenant-1", "acct-1", session)++ assert status == 200+ params = get_paginate_apps.call_args.args[2]+ assert params.accessible_app_ids is None+ assert params.is_created_by_me is None+ assert resp["data"][0]["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"]+++def test_app_list_api_limits_to_apps_created_by_current_user_without_view_permission(app, app_module):+ method = app_module.AppListApi.get+ while hasattr(method, "__wrapped__"):+ method = method.__wrapped__++ pagination = SimpleNamespace(page=1, per_page=20, total=0, has_next=False, items=[])+ get_paginate_apps = MagicMock(return_value=pagination)++ with app.test_request_context("/apps"):+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(app_module.AppService, "get_paginate_apps", get_paginate_apps)+ monkeypatch.setattr(app_module.dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.MyPermissions,+ "get",+ lambda tenant_id, account_id: app_module.enterprise_rbac_service.MyPermissionsResponse(+ workspace=app_module.enterprise_rbac_service.WorkspacePermissionSnapshot(+ permission_keys=["app.create_and_management"]+ )+ ),+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.AppAccess,+ "whitelist_resources",+ lambda tenant_id, account_id: SimpleNamespace(resource_ids=["app-shared", "app-not-permitted"]),+ )+ monkeypatch.setattr(+ app_module.FeatureService,+ "get_system_features",+ lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ )++ session = MagicMock()+ resp, status = method(app_module.AppListApi(), "tenant-1", "acct-1", session)++ assert status == 200+ assert resp["data"] == []+ params = get_paginate_apps.call_args.args[2]+ assert params.accessible_app_ids == ["app-not-permitted", "app-shared"]+ assert params.include_own_apps is True+ assert params.is_created_by_me is None+++def test_app_list_api_limits_to_preview_overrides_without_manage_own_permission(app, app_module):+ method = app_module.AppListApi.get+ while hasattr(method, "__wrapped__"):+ method = method.__wrapped__++ pagination = SimpleNamespace(page=1, per_page=20, total=0, has_next=False, items=[])+ get_paginate_apps = MagicMock(return_value=pagination)++ with app.test_request_context("/apps"):+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(app_module.AppService, "get_paginate_apps", get_paginate_apps)+ monkeypatch.setattr(app_module.dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.MyPermissions,+ "get",+ lambda tenant_id, account_id: app_module.enterprise_rbac_service.MyPermissionsResponse(+ app=app_module.enterprise_rbac_service.ResourcePermissionSnapshot(+ overrides=[+ app_module.enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="app-acl-shared",+ permission_keys=["app.acl.preview"],+ ),+ app_module.enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="app-full",+ permission_keys=["app.full_access"],+ ),+ app_module.enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="app-shared",+ permission_keys=["app.preview"],+ ),+ ]+ )+ ),+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.AppAccess,+ "whitelist_resources",+ lambda tenant_id, account_id: SimpleNamespace(+ resource_ids=["app-shared", "app-acl-shared", "app-full", "app-whitelist-only"]+ ),+ )+ monkeypatch.setattr(+ app_module.FeatureService,+ "get_system_features",+ lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ )++ session = MagicMock()+ method(app_module.AppListApi(), "tenant-1", "acct-1", session)++ params = get_paginate_apps.call_args.args[2]+ assert params.accessible_app_ids == ["app-acl-shared", "app-full", "app-shared", "app-whitelist-only"]+ assert params.include_own_apps is False+ assert params.is_created_by_me is None+++def test_app_list_api_returns_no_apps_without_workspace_or_resource_view_permission(app, app_module):+ method = app_module.AppListApi.get+ while hasattr(method, "__wrapped__"):+ method = method.__wrapped__++ pagination = SimpleNamespace(page=1, per_page=20, total=0, has_next=False, items=[])+ get_paginate_apps = MagicMock(return_value=pagination)++ with app.test_request_context("/apps"):+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(app_module.AppService, "get_paginate_apps", get_paginate_apps)+ monkeypatch.setattr(app_module.dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.MyPermissions,+ "get",+ lambda tenant_id, account_id: app_module.enterprise_rbac_service.MyPermissionsResponse(),+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.AppAccess,+ "whitelist_resources",+ lambda tenant_id, account_id: SimpleNamespace(resource_ids=["app-not-permitted"]),+ )+ monkeypatch.setattr(+ app_module.FeatureService,+ "get_system_features",+ lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ )++ session = MagicMock()+ method(app_module.AppListApi(), "tenant-1", "acct-1", session)++ params = get_paginate_apps.call_args.args[2]+ assert params.accessible_app_ids == ["app-not-permitted"]+ assert params.include_own_apps is False+ assert params.is_created_by_me is None+++def test_app_detail_api_attaches_current_user_permission_keys(app, app_module):+ method = app_module.AppApi.get+ while hasattr(method, "__wrapped__"):+ method = method.__wrapped__++ app_obj = SimpleNamespace(+ id="app-1",+ name="Detail App",+ description="Summary",+ mode_compatible_with_agent="chat",+ enable_site=True,+ enable_api=True,+ permission_keys=[],+ )++ with app.test_request_context("/apps/app-1"):+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(app_module, "AppService", lambda: SimpleNamespace(get_app=lambda app_model: app_obj))+ monkeypatch.setattr(+ app_module.FeatureService,+ "get_system_features",+ lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ )+ get_permissions = MagicMock(+ return_value=app_module.enterprise_rbac_service.MyPermissionsResponse(+ app=app_module.enterprise_rbac_service.ResourcePermissionSnapshot(+ overrides=[+ app_module.enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="app-1",+ permission_keys=["app.acl.view_layout", "app.acl.edit", "app.acl.monitor"],+ )+ ]+ )+ )+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.MyPermissions,+ "get",+ get_permissions,+ )++ resp = method(app_module.AppApi(), "tenant-1", SimpleNamespace(id="acct-1"), app_model=app_obj)++ get_permissions.assert_called_once_with("tenant-1", "acct-1", app_id="app-1")+ assert resp["permission_keys"] == ["app.acl.view_layout", "app.acl.edit", "app.acl.monitor"]+++def test_app_copy_api_attaches_permission_keys(app, app_module):+ method = app_module.AppCopyApi.post+ while hasattr(method, "__wrapped__"):+ method = method.__wrapped__++ app_obj = SimpleNamespace(+ id="app-new",+ name="Copied App",+ description="Summary",+ mode_compatible_with_agent="workflow",+ enable_site=True,+ enable_api=True,+ permission_keys=[],+ )++ import_result = SimpleNamespace(status=app_module.ImportStatus.COMPLETED, app_id="app-new")+ fake_session = MagicMock()+ fake_session.__enter__.return_value = fake_session+ fake_session.__exit__.return_value = None+ fake_session.scalar.return_value = app_obj++ with app.test_request_context("/apps/app-original/copy", method="POST", json={}):+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(dify_config, "RBAC_ENABLED", True)+ monkeypatch.setattr(+ app_module,+ "AppDslService",+ lambda *_args, **_kwargs: SimpleNamespace(+ export_dsl=lambda **_kwargs: "dsl",+ import_app=lambda **_kwargs: import_result,+ ),+ )+ monkeypatch.setattr(+ app_module.FeatureService,+ "get_system_features",+ lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ )+ monkeypatch.setattr(app_module, "db", SimpleNamespace(engine=object()))+ monkeypatch.setattr(+ app_module,+ "Session",+ lambda *_args, **_kwargs: fake_session,+ )+ monkeypatch.setattr(+ app_module.enterprise_rbac_service.RBACService.AppPermissions,+ "batch_get",+ lambda tenant_id, account_id, app_ids: {"app-new": ["app.acl.view_layout", "app.acl.edit"]},+ )++ resp, status = method(+ app_module.AppCopyApi(),+ "tenant-1",+ SimpleNamespace(id="acct-1"),+ app_model=SimpleNamespace(id="app-original"),+ )++ assert status == 201+ assert fake_session.scalar.called+ assert resp["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"]diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_convert_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_convert_api.pynew file mode 100644index 00000000000..dd254a31f63--- /dev/null+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_convert_api.py@@ -0,0 +1,55 @@+"""Unit tests for convert-to-workflow endpoint."""++from __future__ import annotations++from types import SimpleNamespace++import pytest+from flask import Flask++from controllers.console.app import workflow as workflow_module+++def _unwrap(func):+ bound_self = getattr(func, "__self__", None)+ while hasattr(func, "__wrapped__"):+ func = func.__wrapped__+ if bound_self is not None:+ return func.__get__(bound_self, bound_self.__class__)+ return func+++class TestConvertToWorkflowApi:+ @pytest.fixture+ def api(self):+ return workflow_module.ConvertToWorkflowApi()++ def test_convert_to_workflow_attaches_permission_keys_when_rbac_enabled(+ self, api, app: Flask, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ method = _unwrap(api.post)++ monkeypatch.setattr(+ workflow_module,+ "WorkflowService",+ lambda: SimpleNamespace(convert_to_workflow=lambda **_kwargs: SimpleNamespace(id="new-app-1")),+ )+ monkeypatch.setattr(+ workflow_module,+ "get_app_permission_keys",+ lambda tenant_id, account_id, app_id: ["app.acl.view_layout", "app.acl.edit"],+ )++ with app.test_request_context(+ "/console/api/apps/app-1/convert-to-workflow",+ method="POST",+ json={},+ ):+ response = method(+ current_tenant_id="tenant-1",+ current_user=SimpleNamespace(id="u1"),+ app_model=SimpleNamespace(id="app-1"),+ )++ assert response["new_app_id"] == "new-app-1"+ assert response["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"]diff --git a/api/tests/unit_tests/controllers/console/datasets/test_datasets.py b/api/tests/unit_tests/controllers/console/datasets/test_datasets.pyindex 101a640699f..76a09558987 100644--- a/api/tests/unit_tests/controllers/console/datasets/test_datasets.py+++ b/api/tests/unit_tests/controllers/console/datasets/test_datasets.py@@ -2,6 +2,7 @@ import datetimeimport jsonfrom contextlib import ExitStackfrom inspect import unwrap+from types import SimpleNamespacefrom unittest.mock import MagicMock, PropertyMock, patchimport pytest@@ -39,6 +40,7 @@ from models.dataset import Dataset, DatasetQuery, Documentfrom models.enums import CreatorUserRole, DataSourceType, DocumentCreatedFrom, IndexingStatusfrom models.model import ApiToken, App, AppMode, IconType, UploadFilefrom services.dataset_service import DatasetPermissionService, DatasetService+from services.enterprise import rbac_service as enterprise_rbac_service@pytest.fixture(autouse=True)@@ -211,6 +213,201 @@ class TestDatasetList:assert status == 200assert resp["total"] == 2+ def test_get_attaches_current_user_permission_keys(self, app: Flask):+ api = DatasetListApi()+ method = unwrap(api.get)+ current_user = self._mock_user()+ dataset = make_dataset(id="dataset-1")+ permissions = enterprise_rbac_service.MyPermissionsResponse(+ dataset=enterprise_rbac_service.ResourcePermissionSnapshot(+ default_permission_keys=["dataset.acl.readonly"],+ overrides=[+ enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="dataset-1",+ permission_keys=["dataset.acl.readonly", "dataset.acl.edit"],+ )+ ],+ )+ )++ with app.test_request_context("/datasets"):+ with (+ patch.object(DatasetService, "get_datasets", return_value=([dataset], 1)),+ patch.object(+ ProviderManager,+ "get_configurations",+ return_value=MagicMock(get_models=lambda **_: []),+ ),+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=permissions,+ ) as get_permissions,+ ):+ resp, status = method(api, "tenant-1", current_user)++ get_permissions.assert_called_once_with("tenant-1", current_user.id)+ assert status == 200+ assert resp["data"][0]["permission_keys"] == ["dataset.acl.readonly", "dataset.acl.edit"]++ def test_get_limits_to_own_datasets_without_default_read_permission(self, app: Flask):+ api = DatasetListApi()+ method = unwrap(api.get)+ current_user = self._mock_user()+ permissions = enterprise_rbac_service.MyPermissionsResponse(+ workspace=enterprise_rbac_service.WorkspacePermissionSnapshot(+ permission_keys=["dataset.create_and_management"]+ )+ )++ with app.test_request_context("/datasets"):+ with (+ patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),+ patch.object(DatasetService, "get_datasets", return_value=([], 0)) as get_datasets,+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=permissions,+ ),+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.DatasetAccess.whitelist_resources",+ return_value=SimpleNamespace(resource_ids=[]),+ ),+ patch.object(+ ProviderManager,+ "get_configurations",+ return_value=MagicMock(get_models=lambda **_: []),+ ),+ ):+ method(api, "tenant-1", current_user)++ assert get_datasets.call_args.kwargs["accessible_dataset_ids"] == []+ assert get_datasets.call_args.kwargs["include_own_datasets"] is True++ def test_get_workspace_owner_bypasses_dataset_whitelist(self, app: Flask):+ api = DatasetListApi()+ method = unwrap(api.get)+ current_user = self._mock_user()+ permissions = enterprise_rbac_service.MyPermissionsResponse(+ dataset=enterprise_rbac_service.ResourcePermissionSnapshot(default_permission_keys=["dataset.preview"])+ )++ with app.test_request_context("/datasets"):+ with (+ patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),+ patch.object(DatasetService, "get_datasets", return_value=([], 0)) as get_datasets,+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=permissions,+ ),+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.DatasetAccess.whitelist_resources",+ return_value=SimpleNamespace(unrestricted=True, resource_ids=[]),+ ),+ patch.object(+ ProviderManager,+ "get_configurations",+ return_value=MagicMock(get_models=lambda **_: []),+ ),+ ):+ method(api, "tenant-1", current_user)++ assert get_datasets.call_args.kwargs["accessible_dataset_ids"] is None++ def test_get_limits_to_dataset_read_overrides(self, app: Flask):+ api = DatasetListApi()+ method = unwrap(api.get)+ current_user = self._mock_user()+ permissions = enterprise_rbac_service.MyPermissionsResponse(+ dataset=enterprise_rbac_service.ResourcePermissionSnapshot(+ overrides=[+ enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="dataset-acl-shared",+ permission_keys=["dataset.acl.preview"],+ ),+ enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="dataset-full",+ permission_keys=["dataset.full_access"],+ ),+ enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="dataset-shared",+ permission_keys=["dataset.preview"],+ ),+ enterprise_rbac_service.ResourcePermissionKeys(+ resource_id="dataset-hidden",+ permission_keys=[],+ ),+ ]+ )+ )++ with app.test_request_context("/datasets"):+ with (+ patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),+ patch.object(DatasetService, "get_datasets", return_value=([], 0)) as get_datasets,+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=permissions,+ ),+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.DatasetAccess.whitelist_resources",+ return_value=SimpleNamespace(+ resource_ids=[+ "dataset-shared",+ "dataset-acl-shared",+ "dataset-full",+ "dataset-whitelist-only",+ ]+ ),+ ),+ patch.object(+ ProviderManager,+ "get_configurations",+ return_value=MagicMock(get_models=lambda **_: []),+ ),+ ):+ method(api, "tenant-1", current_user)++ assert get_datasets.call_args.kwargs["accessible_dataset_ids"] == [+ "dataset-acl-shared",+ "dataset-full",+ "dataset-shared",+ "dataset-whitelist-only",+ ]+ assert get_datasets.call_args.kwargs["include_own_datasets"] is False++ def test_get_with_ids_applies_dataset_visibility(self, app: Flask):+ api = DatasetListApi()+ method = unwrap(api.get)+ current_user = self._mock_user()+ permissions = enterprise_rbac_service.MyPermissionsResponse()++ with app.test_request_context("/datasets?ids=dataset-1"):+ with (+ patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),+ patch.object(DatasetService, "get_datasets_by_ids", return_value=([], 0)) as get_datasets_by_ids,+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=permissions,+ ),+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.DatasetAccess.whitelist_resources",+ return_value=SimpleNamespace(resource_ids=[]),+ ),+ patch.object(+ ProviderManager,+ "get_configurations",+ return_value=MagicMock(get_models=lambda **_: []),+ ),+ ):+ method(api, "tenant-1", current_user)++ get_datasets_by_ids.assert_called_once_with(+ ["dataset-1"],+ "tenant-1",+ user=current_user,+ accessible_dataset_ids=[],+ include_own_datasets=False,+ )+def test_get_with_tag_ids(self, app: Flask):api = DatasetListApi()method = unwrap(api.get)@@ -504,6 +701,51 @@ class TestDatasetApiGet:assert status == 200assert data["embedding_available"] is True+ def test_get_attaches_permission_keys_when_rbac_enabled(self, app: Flask):+ api = DatasetApi()+ method = unwrap(api.get)++ dataset_id = "123e4567-e89b-12d3-a456-426614174000"+ user = MagicMock(id="account-1")+ tenant_id = "tenant-1"+ dataset = make_dataset(id=dataset_id)++ with (+ app.test_request_context(f"/datasets/{dataset_id}"),+ patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),+ patch.object(+ DatasetService,+ "get_dataset",+ return_value=dataset,+ ),+ patch.object(+ DatasetService,+ "check_dataset_permission",+ return_value=None,+ ),+ patch(+ "controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=enterprise_rbac_service.MyPermissionsResponse(+ dataset=enterprise_rbac_service.ResourcePermissionSnapshot(+ overrides=[+ enterprise_rbac_service.ResourcePermissionKeys(+ resource_id=dataset_id,+ permission_keys=["dataset.acl.readonly", "dataset.acl.edit"],+ )+ ]+ )+ ),+ ) as get_permissions,+ patch("controllers.console.datasets.datasets.create_plugin_provider_manager") as provider_manager_mock,+ ):+ provider_manager_mock.return_value.get_configurations.return_value.get_models.return_value = []++ data, status = method(api, tenant_id, user, dataset_id)++ get_permissions.assert_called_once_with(tenant_id, user.id, dataset_id=dataset_id)+ assert status == 200+ assert data["permission_keys"] == ["dataset.acl.readonly", "dataset.acl.edit"]+def test_get_uses_default_external_retrieval_model(self, app: Flask):api = DatasetApi()method = unwrap(api.get)diff --git a/api/tests/unit_tests/controllers/console/datasets/test_external.py b/api/tests/unit_tests/controllers/console/datasets/test_external.pyindex 7cb41dc99cd..b7e16b91fb7 100644--- a/api/tests/unit_tests/controllers/console/datasets/test_external.py+++ b/api/tests/unit_tests/controllers/console/datasets/test_external.py@@ -171,6 +171,7 @@ class TestExternalDatasetCreateApi:dataset.external_retrieval_model = Nonedataset.doc_metadata = []dataset.icon_info = None+ dataset.permission_keys = []dataset.summary_index_setting = MagicMock()dataset.summary_index_setting.enable = Falsediff --git a/api/tests/unit_tests/controllers/console/test_workspace_members.py b/api/tests/unit_tests/controllers/console/test_workspace_members.pyindex d8d1d02a169..cb06dbc27cd 100644--- a/api/tests/unit_tests/controllers/console/test_workspace_members.py+++ b/api/tests/unit_tests/controllers/console/test_workspace_members.py@@ -49,6 +49,7 @@ class TestMemberInviteEmailApi:inviter = SimpleNamespace(email="[email protected]", current_tenant=tenant, status="active")with (+ patch("controllers.console.workspace.members.dify_config.RBAC_ENABLED", False),patch("controllers.console.workspace.members.dify_config.CONSOLE_WEB_URL", "https://console.example.com"),patch("controllers.console.workspace.members._count_new_member_invites", return_value=1),patch("controllers.console.workspace.members.dify_config.ENTERPRISE_ENABLED", False),@@ -76,3 +77,116 @@ class TestMemberInviteEmailApi:assert call_args.kwargs["role"] == TenantAccountRole.EDITORassert call_args.kwargs["inviter"] == accountmock_csrf.assert_called_once_with(ANY, account.id)++ @patch("controllers.console.workspace.members.FeatureService.get_features")+ @patch("controllers.console.workspace.members.RegisterService.invite_new_member")+ @patch("controllers.console.workspace.members.current_account_with_tenant")+ @patch("controllers.console.wraps.db")+ @patch("libs.login.check_csrf_token", return_value=None)+ def test_invite_rbac_enabled_accepts_rbac_role_id(+ self,+ mock_csrf,+ mock_db,+ mock_current_account,+ mock_invite_member,+ mock_get_features,+ app,+ ):+ """When RBAC is enabled, any non-empty role string should be accepted."""+ mock_get_features.return_value = _build_feature_flags()+ mock_invite_member.return_value = "rbac-token"++ tenant = SimpleNamespace(id="tenant-1", name="Test Tenant")+ inviter = SimpleNamespace(email="[email protected]", current_tenant=tenant, status="active")+ mock_current_account.return_value = (inviter, tenant.id)++ with patch("controllers.console.workspace.members.dify_config") as mock_config:+ mock_config.RBAC_ENABLED = True+ mock_config.CONSOLE_WEB_URL = "https://console.example.com"+ with app.test_request_context(+ "/workspaces/current/members/invite-email",+ method="POST",+ json={"emails": ["[email protected]"], "role": "rbac-role-id-abc", "language": "en-US"},+ ):+ account = Account(name="tester", email="[email protected]")+ account._current_tenant = tenant+ g._login_user = account+ g._current_tenant = tenant+ response, status_code = MemberInviteEmailApi().post()++ assert status_code == 201+ mock_invite_member.assert_called_once()+ call_args = mock_invite_member.call_args+ assert call_args.kwargs["role"] == "rbac-role-id-abc"++ @patch("controllers.console.workspace.members.FeatureService.get_features")+ @patch("controllers.console.workspace.members.current_account_with_tenant")+ @patch("controllers.console.wraps.db")+ @patch("libs.login.check_csrf_token", return_value=None)+ def test_invite_rbac_disabled_rejects_invalid_role(+ self,+ mock_csrf,+ mock_db,+ mock_current_account,+ mock_get_features,+ app,+ ):+ """When RBAC is disabled, an invalid role string should be rejected."""+ mock_get_features.return_value = _build_feature_flags()++ tenant = SimpleNamespace(id="tenant-1", name="Test Tenant")+ inviter = SimpleNamespace(email="[email protected]", current_tenant=tenant, status="active")+ mock_current_account.return_value = (inviter, tenant.id)++ with patch("controllers.console.workspace.members.dify_config") as mock_config:+ mock_config.RBAC_ENABLED = False+ mock_config.CONSOLE_WEB_URL = "https://console.example.com"+ with app.test_request_context(+ "/workspaces/current/members/invite-email",+ method="POST",+ json={"emails": ["[email protected]"], "role": "invalid-role", "language": "en-US"},+ ):+ account = Account(name="tester", email="[email protected]")+ account._current_tenant = tenant+ g._login_user = account+ g._current_tenant = tenant+ response, status_code = MemberInviteEmailApi().post()++ assert status_code == 400+ assert response["code"] == "invalid-role"++ @patch("controllers.console.workspace.members.FeatureService.get_features")+ @patch("controllers.console.workspace.members.current_account_with_tenant")+ @patch("controllers.console.wraps.db")+ @patch("libs.login.check_csrf_token", return_value=None)+ def test_invite_rbac_disabled_rejects_owner_role(+ self,+ mock_csrf,+ mock_db,+ mock_current_account,+ mock_get_features,+ app,+ ):+ """When RBAC is disabled, owner role should be rejected for invite."""+ mock_get_features.return_value = _build_feature_flags()++ tenant = SimpleNamespace(id="tenant-1", name="Test Tenant")+ inviter = SimpleNamespace(email="[email protected]", current_tenant=tenant, status="active")+ mock_current_account.return_value = (inviter, tenant.id)++ with patch("controllers.console.workspace.members.dify_config") as mock_config:+ mock_config.RBAC_ENABLED = False+ mock_config.CONSOLE_WEB_URL = "https://console.example.com"+ with app.test_request_context(+ "/workspaces/current/members/invite-email",+ method="POST",+ json={"emails": ["[email protected]"], "role": "owner", "language": "en-US"},+ ):+ account = Account(name="tester", email="[email protected]")+ account._current_tenant = tenant+ g._login_user = account+ g._current_tenant = tenant+ response, status_code = MemberInviteEmailApi().post()++ assert status_code == 400+ assert response["code"] == "invalid-role"diff --git a/api/tests/unit_tests/controllers/console/test_wraps.py b/api/tests/unit_tests/controllers/console/test_wraps.pyindex 937505dab28..96f55c85fe5 100644--- a/api/tests/unit_tests/controllers/console/test_wraps.py+++ b/api/tests/unit_tests/controllers/console/test_wraps.py@@ -2,24 +2,29 @@ from typing import overridefrom unittest.mock import MagicMock, patchimport pytest-from flask import Flask+from flask import Flask, requestfrom flask_login import LoginManager, UserMixinfrom pydantic import BaseModelfrom werkzeug.exceptions import HTTPException+from controllers.common.wraps import _extract_resource_idfrom controllers.console.error import NotInitValidateError, NotSetupError, UnauthorizedAndForceLogoutfrom controllers.console.workspace.error import AccountNotInitializedErrorfrom controllers.console.wraps import (+ RBACPermission,+ RBACResourceScope,account_initialization_required,cloud_edition_billing_enabled,cloud_edition_billing_rate_limit_check,cloud_edition_billing_resource_check,cloud_utm_record,enterprise_license_required,+ is_admin_or_owner_required,model_validate,only_edition_cloud,only_edition_enterprise,only_edition_self_hosted,+ rbac_permission_required,setup_required,with_current_tenant_id,with_current_user,@@ -165,6 +170,165 @@ class TestCurrentContextInjection:assert Handler().get() == ("user-99", "tenant-456")+class TestRbacPermissionRequired:+ """Test enterprise RBAC decorator."""++ def test_resource_scoped_check_uses_resource_id(self):+ current_user = make_account("account-1")++ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_DELETE)+ def protected_view(**kwargs):+ return "ok"++ with (+ patch("controllers.common.wraps.dify_config.RBAC_ENABLED", True),+ patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-1")),+ patch("controllers.common.wraps._extract_resource_id", return_value="app-123") as mock_extract,+ patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=False) as mock_owned,+ patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=True) as mock_check,+ ):+ assert protected_view(app_id="app-123") == "ok"++ mock_extract.assert_called_once_with("app", {"app_id": "app-123"})+ mock_owned.assert_called_once_with("tenant-1", "account-1", "app", "app-123")+ mock_check.assert_called_once_with(+ "tenant-1",+ "account-1",+ scene="app_delete",+ resource_type="app",+ resource_id="app-123",+ )++ def test_workspace_scoped_check_skips_resource_id_extraction(self):+ current_user = make_account("account-2")++ @rbac_permission_required(+ RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False+ )+ def protected_view():+ return "ok"++ with (+ patch("controllers.common.wraps.dify_config.RBAC_ENABLED", True),+ patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-2")),+ patch("controllers.common.wraps._extract_resource_id") as mock_extract,+ patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=False) as mock_owned,+ patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=True) as mock_check,+ ):+ assert protected_view() == "ok"++ mock_extract.assert_not_called()+ mock_owned.assert_not_called()+ mock_check.assert_called_once_with(+ "tenant-2",+ "account-2",+ scene="dataset_create_and_management",+ resource_type="dataset",+ resource_id=None,+ )++ def test_workspace_scene_omits_resource_type(self):+ current_user = make_account("account-3")++ @rbac_permission_required(+ RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False+ )+ def protected_view():+ return "ok"++ with (+ patch("controllers.common.wraps.dify_config.RBAC_ENABLED", True),+ patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-3")),+ patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=True) as mock_check,+ ):+ assert protected_view() == "ok"++ mock_check.assert_called_once_with(+ "tenant-3",+ "account-3",+ scene="workspace_role_manage",+ resource_type=None,+ resource_id=None,+ )++ def test_resource_owned_app_skips_rbac_check(self):+ current_user = make_account("account-4")++ @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_DELETE)+ def protected_view(**kwargs):+ return "ok"++ with (+ patch("controllers.common.wraps.dify_config.RBAC_ENABLED", True),+ patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-4")),+ patch("controllers.common.wraps._extract_resource_id", return_value="app-123"),+ patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=True) as mock_owned,+ patch("controllers.common.wraps.RBACService.CheckAccess.check") as mock_check,+ ):+ assert protected_view(app_id="app-123") == "ok"++ mock_owned.assert_called_once_with("tenant-4", "account-4", "app", "app-123")+ mock_check.assert_not_called()++ def test_resource_owned_dataset_skips_rbac_check(self):+ current_user = make_account("account-5")++ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)+ def protected_view(**kwargs):+ return "ok"++ with (+ patch("controllers.common.wraps.dify_config.RBAC_ENABLED", True),+ patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-5")),+ patch("controllers.common.wraps._extract_resource_id", return_value="dataset-123"),+ patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=True) as mock_owned,+ patch("controllers.common.wraps.RBACService.CheckAccess.check") as mock_check,+ ):+ assert protected_view(dataset_id="dataset-123") == "ok"++ mock_owned.assert_called_once_with("tenant-5", "account-5", "dataset", "dataset-123")+ mock_check.assert_not_called()++ def test_extract_resource_id_prefers_path_args(self):+ app = Flask(__name__)++ with app.test_request_context("/"):+ request.view_args = {"app_id": "view-app"}++ assert _extract_resource_id("app", {"app_id": "path-app"}) == "path-app"++ def test_extract_resource_id_falls_back_to_request_view_args(self):+ app = Flask(__name__)++ with app.test_request_context("/"):+ request.view_args = {"app_id": "view-app"}++ assert _extract_resource_id("app") == "view-app"++ def test_extract_resource_id_supports_legacy_route_aliases(self):+ app = Flask(__name__)++ with app.test_request_context("/apps/app-1/api-keys"):+ request.view_args = {"resource_id": "app-1"}+ assert _extract_resource_id(RBACResourceScope.APP) == "app-1"++ with app.test_request_context("/agent/agent-1/features"):+ request.view_args = {"agent_id": "agent-1"}+ assert _extract_resource_id(RBACResourceScope.APP) == "agent-1"++ with app.test_request_context("/datasets/dataset-1/api-keys"):+ request.view_args = {"resource_id": "dataset-1"}+ assert _extract_resource_id(RBACResourceScope.DATASET) == "dataset-1"++ def test_legacy_admin_decorator_noops_when_rbac_enabled(self):+ @is_admin_or_owner_required+ def protected_view():+ return "ok"++ with patch("controllers.console.wraps.dify_config.RBAC_ENABLED", True):+ assert protected_view() == "ok"++class TestModelValidationInjection:"""Test request model validation decorator."""diff --git a/api/tests/unit_tests/controllers/console/workspace/test_members.py b/api/tests/unit_tests/controllers/console/workspace/test_members.pyindex 6c7879c8050..2048e3717d9 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_members.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_members.py@@ -1,4 +1,5 @@from contextlib import nullcontext+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytest@@ -43,8 +44,8 @@ class TestMemberListApi:member.name = "Member"member.email = "[email protected]"member.avatar = "avatar.png"- member.role = "admin"- member.status = "active"+ member.current_role = SimpleNamespace(value="admin")+ member.status = SimpleNamespace(value="active")members = [member]with (@@ -55,6 +56,53 @@ class TestMemberListApi:assert status == 200assert len(result["accounts"]) == 1+ assert result["accounts"][0]["role"] == "admin"+ assert result["accounts"][0]["roles"] == [{"id": "admin", "name": "admin"}]++ def test_get_with_rbac_enabled_fetches_roles_in_batch(self, app):+ api = MemberListApi()+ method = unwrap(api.get)++ tenant = MagicMock(id="tenant-1")+ user = MagicMock(id="acct-1", current_tenant=tenant)+ member = SimpleNamespace(+ id="m1",+ name="Member",+ email="[email protected]",+ avatar=None,+ last_login_at=1,+ last_active_at=2,+ created_at=3,+ current_role=SimpleNamespace(value="editor"),+ status=SimpleNamespace(value="active"),+ )+ role_item = SimpleNamespace(+ account_id="m1",+ roles=[+ SimpleNamespace(id="workspace.owner", name="Owner"),+ SimpleNamespace(id="workspace.editor", name="Editor"),+ ],+ )++ with (+ app.test_request_context("/"),+ patch("controllers.console.workspace.members.current_account_with_tenant", return_value=(user, "tenant-1")),+ patch("controllers.console.workspace.members.dify_config.RBAC_ENABLED", True),+ patch("controllers.console.workspace.members.TenantService.get_tenant_members", return_value=[member]),+ patch(+ "controllers.console.workspace.members.enterprise_rbac_service.RBACService.MemberRoles.batch_get",+ return_value=[role_item],+ ) as mock_batch_get,+ ):+ result, status = method(api)++ assert status == 200+ assert result["accounts"][0]["role"] == "editor"+ assert result["accounts"][0]["roles"] == [+ {"id": "workspace.owner", "name": "Owner"},+ {"id": "workspace.editor", "name": "Editor"},+ ]+ mock_batch_get.assert_called_once_with("tenant-1", "acct-1", ["m1"])def test_get_no_tenant(self, app: Flask):api = MemberListApi()diff --git a/api/tests/unit_tests/controllers/console/workspace/test_rbac.py b/api/tests/unit_tests/controllers/console/workspace/test_rbac.pynew file mode 100644index 00000000000..1ad9637b7bb--- /dev/null+++ b/api/tests/unit_tests/controllers/console/workspace/test_rbac.py@@ -0,0 +1,503 @@+"""Controller tests for ``controllers.console.workspace.rbac``.++The controllers here are thin: almost every non-trivial behaviour lives in+``services.enterprise.rbac_service`` (covered by its own suite). These tests+therefore focus on the Flask-layer concerns the service layer cannot exercise:++* ``_current_ids`` raises 404 when the session has no tenant.+* The pydantic request models accept / reject bodies as expected.++We explicitly avoid "happy-path" integration tests through the full+decorator stack — those belong in e2e tests where a real Dify session is+available — to keep this suite fast and resilient to ancillary auth wiring+changes.+"""++from __future__ import annotations++import inspect+from types import SimpleNamespace+from unittest.mock import patch++import pytest+from flask import Flask+from pydantic import ValidationError+from werkzeug.exceptions import Forbidden, NotFound++from controllers.console.workspace import rbac as rbac_mod+++def app():+ flask_app = Flask(__name__)+ flask_app.config["TESTING"] = True+ return flask_app+++def _enabled(enabled: bool):+ return patch("controllers.console.workspace.rbac.dify_config.ENTERPRISE_ENABLED", enabled)+++class TestCurrentIds:+ def test_rejects_missing_tenant(self):+ with patch("controllers.console.workspace.rbac.current_account_with_tenant") as mock_user:+ mock_user.return_value = (SimpleNamespace(id="acct-1"), None)+ with pytest.raises(NotFound):+ rbac_mod._current_ids()++ def test_returns_tuple(self):+ with patch("controllers.console.workspace.rbac.current_account_with_tenant") as mock_user:+ mock_user.return_value = (SimpleNamespace(id="acct-1"), "tenant-1")+ assert rbac_mod._current_ids() == ("tenant-1", "acct-1")+++class TestAccessMatrixAccountNames:+ def test_hydrates_missing_account_names(self):+ items = [+ rbac_mod.svc.AccessMatrixItem(+ accounts=[+ {"account_id": "acct-1", "account_name": "Alice", "binding_id": "binding-1"},+ {"account_id": "acct-2", "account_name": "", "binding_id": "binding-2"},+ ]+ )+ ]++ with patch(+ "controllers.console.workspace.rbac._account_names_by_ids",+ return_value={"acct-2": {"name": "Bob", "avatar": "ava"}},+ ) as mock_names:+ rbac_mod._hydrate_access_matrix_account_names(items)++ mock_names.assert_called_once_with(["acct-2"])+ assert items[0].accounts[0].account_id == "acct-1"+ assert items[0].accounts[0].account_name == "Alice"+ assert items[0].accounts[1].account_id == "acct-2"+ assert items[0].accounts[1].account_name == "Bob"+ assert items[0].accounts[1].avatar == "ava"++ def test_hydrates_resource_user_account_names(self):+ items = [+ rbac_mod.svc.ResourceUserAccessPolicies(+ account={"account_id": "acct-1", "account_name": ""},+ roles=[],+ access_policies=[],+ )+ ]++ with patch(+ "controllers.console.workspace.rbac._account_names_by_ids",+ return_value={"acct-1": {"name": "Alice", "avatar": ""}},+ ):+ rbac_mod._hydrate_resource_user_account_names(items)++ assert items[0].account.account_name == "Alice"+++class TestPydanticModels:+ """The internal `_…Request` models are the contract between the browser+ and the controllers. We only check non-obvious branches (enum parsing,+ missing required fields) — trivial `str` fields are not worth asserting.+ """++ def test_role_upsert_requires_name(self):+ with pytest.raises(ValidationError):+ rbac_mod._RoleUpsertRequest.model_validate({})++ def test_role_upsert_to_mutation_preserves_fields(self):+ payload = rbac_mod._RoleUpsertRequest.model_validate(+ {+ "name": "Owner",+ "description": "full access",+ "permission_keys": ["workspace.member.manage"],+ }+ )+ mutation = payload.to_mutation()+ assert mutation.description == "full access"+ assert mutation.permission_keys == ["workspace.member.manage"]++ def test_access_policy_create_parses_resource_type_enum(self):+ parsed = rbac_mod._AccessPolicyCreateRequest.model_validate(+ {+ "name": "Full access",+ "resource_type": "app",+ "description": "",+ "permission_keys": [],+ }+ )+ assert parsed.resource_type is rbac_mod.svc.RBACResourceType.APP++ def test_access_policy_create_rejects_unknown_resource_type(self):+ with pytest.raises(ValidationError):+ rbac_mod._AccessPolicyCreateRequest.model_validate({"name": "bad", "resource_type": "unknown"})++ def test_resource_access_scope_requires_scope(self):+ with pytest.raises(ValidationError):+ rbac_mod._ResourceAccessScopeRequest.model_validate({})++ def test_resource_access_scope_defaults_empty_account_ids(self):+ parsed = rbac_mod._ResourceAccessScopeRequest.model_validate({"scope": "specific"})+ assert parsed.scope is rbac_mod._AccessScope.SPECIFIC++ def test_resource_access_scope_coerce_null_account_ids(self):+ rbac_mod._ResourceAccessScopeRequest.model_validate({"scope": "all"})++ def test_resource_access_scope_rejects_unknown_scope(self):+ with pytest.raises(ValidationError):+ rbac_mod._ResourceAccessScopeRequest.model_validate({"scope": "team"})++ def test_replace_bindings_keeps_role_binding_contract(self):+ parsed = rbac_mod._ReplaceBindingsRequest.model_validate({"role_ids": None})+ assert parsed.role_ids == []++ def test_replace_member_roles_coerce_null_list(self):+ parsed = rbac_mod._ReplaceMemberRolesRequest.model_validate({"role_ids": None})+ assert parsed.role_ids == []++ def test_pagination_query_accepts_page_and_limit_aliases(self):+ parsed = rbac_mod._PaginationQuery.model_validate({"page": 3, "limit": 25, "reverse": True})+ assert parsed.page_number == 3+ assert parsed.results_per_page == 25+ assert parsed.reverse is True++ def test_pagination_query_accepts_legacy_inner_names(self):+ parsed = rbac_mod._PaginationQuery.model_validate({"page_number": 4, "results_per_page": 30, "reverse": False})+ assert parsed.page_number == 4+ assert parsed.results_per_page == 30+ assert parsed.reverse is False+++class TestPaginationMapping:+ def test_roles_get_returns_legacy_compatible_roles_when_rbac_disabled(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/roles?page=1&limit=2&include_owner=1"),+ patch("controllers.console.workspace.rbac.dify_config.RBAC_ENABLED", False),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.list") as mock_list,+ ):+ response = inspect.unwrap(rbac_mod.RBACRolesApi.get)(rbac_mod.RBACRolesApi())++ assert response["data"] == [+ {+ "id": "owner",+ "tenant_id": "",+ "type": "workspace",+ "category": "global_system_default",+ "name": "owner",+ "description": "",+ "is_builtin": True,+ "permission_keys": list(rbac_mod._LEGACY_ROLE_PERMISSION_KEYS["owner"]),+ "role_tag": "owner",+ },+ {+ "id": "admin",+ "tenant_id": "",+ "type": "workspace",+ "category": "global_system_default",+ "name": "admin",+ "description": "",+ "is_builtin": True,+ "permission_keys": list(rbac_mod._LEGACY_ROLE_PERMISSION_KEYS["admin"]),+ "role_tag": "",+ },+ ]+ assert response["pagination"] == {+ "total_count": 5,+ "per_page": 2,+ "current_page": 1,+ "total_pages": 3,+ }+ mock_list.assert_not_called()++ def test_roles_get_filters_out_owner_when_include_owner_is_zero(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/roles?include_owner=0"),+ patch("controllers.console.workspace.rbac.dify_config.RBAC_ENABLED", False),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.list"),+ ):+ response = inspect.unwrap(rbac_mod.RBACRolesApi.get)(rbac_mod.RBACRolesApi())++ names = [r["name"] for r in response["data"]]+ assert "owner" not in names++ def test_roles_get_keeps_owner_when_include_owner_is_one(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/roles?include_owner=1"),+ patch("controllers.console.workspace.rbac.dify_config.RBAC_ENABLED", False),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.list"),+ ):+ response = inspect.unwrap(rbac_mod.RBACRolesApi.get)(rbac_mod.RBACRolesApi())++ names = [r["name"] for r in response["data"]]+ assert "owner" in names++ def test_roles_get_filters_out_owner_by_default(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/roles"),+ patch("controllers.console.workspace.rbac.dify_config.RBAC_ENABLED", False),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.list"),+ ):+ response = inspect.unwrap(rbac_mod.RBACRolesApi.get)(rbac_mod.RBACRolesApi())++ names = [r["name"] for r in response["data"]]+ assert "owner" not in names++ def test_roles_get_forwards_outer_pagination_params(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/roles?page=2&limit=50&reverse=true&include_owner=1"),+ patch("controllers.console.workspace.rbac.dify_config.RBAC_ENABLED", True),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.list") as mock_list,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACRolesApi.get)(rbac_mod.RBACRolesApi())++ _, kwargs = mock_list.call_args+ options = kwargs["options"]+ assert options.page_number == 2+ assert options.results_per_page == 50+ assert options.reverse is True+++class TestResourceAccessScopeBindings:+ def test_app_user_access_policy_assignment_forwards_ids(self, app):+ with (+ app.test_request_context(+ "/workspaces/current/rbac/apps/app-1/users/acct-target/access-policies",+ method="PUT",+ json={"access_policy_ids": ["policy-1", "policy-2"]},+ ),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")),+ patch(+ "controllers.console.workspace.rbac.svc.RBACService.AppAccess.replace_user_access_policies"+ ) as mock_replace,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACAppUserAccessPolicyAssignmentApi.put)(+ rbac_mod.RBACAppUserAccessPolicyAssignmentApi(),+ "app-1",+ "acct-target",+ )++ tenant_id, actor_id, app_id, target_id, payload = mock_replace.call_args.args+ assert (tenant_id, actor_id, app_id, target_id) == (+ "tenant-1",+ "acct-actor",+ "app-1",+ "acct-target",+ )+ assert payload.access_policy_ids == ["policy-1", "policy-2"]++ def test_app_member_bindings_delete_forwards_account_ids(self, app):+ with (+ app.test_request_context(+ "/workspaces/current/rbac/apps/app-1/access-policies/policy-1/member-bindings",+ method="DELETE",+ json={"account_ids": ["acct-2", "acct-3"]},+ ),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")),+ patch("controllers.console.workspace.rbac.svc.RBACService.AppAccess.delete_member_bindings") as mock_delete,+ ):+ response = inspect.unwrap(rbac_mod.RBACAppMemberBindingsApi.delete)(+ rbac_mod.RBACAppMemberBindingsApi(),+ "app-1",+ "policy-1",+ )++ assert response == {"result": "success"}+ tenant_id, actor_id, app_id, policy_id, payload = mock_delete.call_args.args+ assert (tenant_id, actor_id, app_id, policy_id) == ("tenant-1", "acct-actor", "app-1", "policy-1")+ assert payload.account_ids == ["acct-2", "acct-3"]++ def test_dataset_member_bindings_delete_forwards_account_ids(self, app):+ with (+ app.test_request_context(+ "/workspaces/current/rbac/datasets/dataset-1/access-policies/policy-1/member-bindings",+ method="DELETE",+ json={"account_ids": ["acct-2"]},+ ),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")),+ patch(+ "controllers.console.workspace.rbac.svc.RBACService.DatasetAccess.delete_member_bindings"+ ) as mock_delete,+ ):+ response = inspect.unwrap(rbac_mod.RBACDatasetMemberBindingsApi.delete)(+ rbac_mod.RBACDatasetMemberBindingsApi(),+ "dataset-1",+ "policy-1",+ )++ assert response == {"result": "success"}+ tenant_id, actor_id, dataset_id, policy_id, payload = mock_delete.call_args.args+ assert (tenant_id, actor_id, dataset_id, policy_id) == ("tenant-1", "acct-actor", "dataset-1", "policy-1")+ assert payload.account_ids == ["acct-2"]+++class TestPaginationForwarding:+ def test_role_members_get_forwards_outer_pagination_params(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/roles/role-1/members?page=2&limit=50&reverse=true"),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.members") as mock_members,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACRoleMembersApi.get)(rbac_mod.RBACRoleMembersApi(), "role-1")++ _, _, role_id = mock_members.call_args.args+ _, kwargs = mock_members.call_args+ assert role_id == "role-1"+ options = kwargs["options"]+ assert options.page_number == 2+ assert options.results_per_page == 50+ assert options.reverse is True++ def test_access_policies_get_forwards_outer_pagination_params(self, app):+ with (+ app.test_request_context(+ "/workspaces/current/rbac/access-policies?resource_type=app&page=3&limit=25&reverse=false"+ ),+ _enabled(True),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.AccessPolicies.list") as mock_list,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACAccessPoliciesApi.get)(rbac_mod.RBACAccessPoliciesApi())++ _, kwargs = mock_list.call_args+ assert kwargs["resource_type"] == "app"+ options = kwargs["options"]+ assert options.page_number == 3+ assert options.results_per_page == 25+ assert options.reverse is False++ def test_workspace_app_matrix_forwards_outer_pagination_params(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/workspace/apps/access-policy?page=4&limit=10"),+ _enabled(True),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.WorkspaceAccess.app_matrix") as mock_list,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACWorkspaceAppMatrixApi.get)(rbac_mod.RBACWorkspaceAppMatrixApi())++ _, kwargs = mock_list.call_args+ options = kwargs["options"]+ assert options.page_number == 4+ assert options.results_per_page == 10+ assert options.reverse is None++ def test_workspace_dataset_matrix_forwards_outer_pagination_params(self, app):+ with (+ app.test_request_context(+ "/workspaces/current/rbac/workspace/datasets/access-policy?page=5&limit=15&reverse=true"+ ),+ _enabled(True),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.WorkspaceAccess.dataset_matrix") as mock_list,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACWorkspaceDatasetMatrixApi.get)(rbac_mod.RBACWorkspaceDatasetMatrixApi())++ _, kwargs = mock_list.call_args+ options = kwargs["options"]+ assert options.page_number == 5+ assert options.results_per_page == 15+ assert options.reverse is True+++class TestAccessPolicyBindingLockUnlock:+ def test_lock_forwards_binding_id(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/access-policy-bindings/binding-1/lock", method="PUT"),+ _enabled(True),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.AccessPolicyBindings.lock") as mock_lock,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACAccessPolicyBindingLockApi.put)(+ rbac_mod.RBACAccessPolicyBindingLockApi(), "binding-1"+ )++ mock_lock.assert_called_once_with("tenant-1", "acct-1", "binding-1")++ def test_unlock_forwards_binding_id(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/access-policy-bindings/binding-1/unlock", method="PUT"),+ _enabled(True),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.AccessPolicyBindings.unlock") as mock_unlock,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACAccessPolicyBindingUnlockApi.put)(+ rbac_mod.RBACAccessPolicyBindingUnlockApi(), "binding-1"+ )++ mock_unlock.assert_called_once_with("tenant-1", "acct-1", "binding-1")+++class TestRoleCopy:+ def test_role_copy_forwards_path_id(self, app):+ with (+ app.test_request_context("/workspaces/current/rbac/roles/role-1/copy", method="POST", json={}),+ _enabled(True),+ patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.copy") as mock_copy,+ patch("controllers.console.workspace.rbac._dump", return_value={}),+ ):+ inspect.unwrap(rbac_mod.RBACRoleCopyApi.post)(rbac_mod.RBACRoleCopyApi(), "role-1")++ mock_copy.assert_called_once_with("tenant-1", "acct-1", "role-1", copy_member=True)+++class TestWorkspaceRbacGuards:+ def test_role_create_requires_workspace_role_manage(self, app):+ with (+ app.test_request_context(+ "/workspaces/current/rbac/roles",+ method="POST",+ json={"name": "test_role", "permission_keys": []},+ ),+ patch("libs.login.dify_config.LOGIN_DISABLED", True),+ patch("controllers.console.wraps.dify_config.RBAC_ENABLED", True),+ patch(+ "controllers.common.wraps.current_account_with_tenant",+ return_value=(SimpleNamespace(id="acct-1"), "tenant-1"),+ ),+ patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=False),+ patch("controllers.console.workspace.rbac.svc.RBACService.Roles.create") as mock_create,+ ):+ with pytest.raises(Forbidden):+ rbac_mod.RBACRolesApi().post()++ mock_create.assert_not_called()++ def test_access_policy_create_requires_workspace_role_manage(self, app):+ with (+ app.test_request_context(+ "/workspaces/current/rbac/access-policies",+ method="POST",+ json={"name": "full_access", "resource_type": "app", "permission_keys": []},+ ),+ patch("libs.login.dify_config.LOGIN_DISABLED", True),+ patch("controllers.console.wraps.dify_config.RBAC_ENABLED", True),+ patch(+ "controllers.common.wraps.current_account_with_tenant",+ return_value=(SimpleNamespace(id="acct-1"), "tenant-1"),+ ),+ patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=False),+ patch("controllers.console.workspace.rbac.svc.RBACService.AccessPolicies.create") as mock_create,+ ):+ with pytest.raises(Forbidden):+ rbac_mod.RBACAccessPoliciesApi().post()++ mock_create.assert_not_called()+++class TestDumpHelper:+ def test_dump_returns_plain_dict(self):+ role = rbac_mod.svc.RBACRole(id="role-1", type="workspace", name="Owner")+ dumped = rbac_mod._dump(role)+ assert isinstance(dumped, dict)+ assert "role_id" not in dumpeddiff --git a/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin_wraps.py b/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin_wraps.pyindex cc581c0c759..c958034126d 100644--- a/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin_wraps.py+++ b/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin_wraps.py@@ -237,9 +237,10 @@ class TestGetUserTenant:monkeypatch.setattr(app, "login_manager", MagicMock(), raising=False)with patch("controllers.inner_api.plugin.wraps.db.session.get") as mock_get:with patch("controllers.inner_api.plugin.wraps.get_user") as mock_get_user:- mock_get.return_value = mock_tenant- mock_get_user.return_value = mock_user- result = protected_view()+ with patch("controllers.inner_api.plugin.wraps.user_logged_in"):+ mock_get.return_value = mock_tenant+ mock_get_user.return_value = mock_user+ result = protected_view()# Assertassert result["tenant"] == mock_tenant@@ -293,9 +294,10 @@ class TestGetUserTenant:monkeypatch.setattr(app, "login_manager", MagicMock(), raising=False)with patch("controllers.inner_api.plugin.wraps.db.session.get") as mock_get:with patch("controllers.inner_api.plugin.wraps.get_user") as mock_get_user:- mock_get.return_value = mock_tenant- mock_get_user.return_value = mock_user- result = protected_view()+ with patch("controllers.inner_api.plugin.wraps.user_logged_in"):+ mock_get.return_value = mock_tenant+ mock_get_user.return_value = mock_user+ result = protected_view()# Assertassert result["tenant"] == mock_tenantdiff --git a/api/tests/unit_tests/controllers/openapi/__init__.py b/api/tests/unit_tests/controllers/openapi/__init__.pydeleted file mode 100644index e69de29bb2d..00000000000diff --git a/api/tests/unit_tests/fields/test_dataset_fields.py b/api/tests/unit_tests/fields/test_dataset_fields.pyindex 125bcb26cf6..921e3882a96 100644--- a/api/tests/unit_tests/fields/test_dataset_fields.py+++ b/api/tests/unit_tests/fields/test_dataset_fields.py@@ -82,6 +82,14 @@ def _dump_dataset_detail(payload):return DatasetDetailResponse.model_validate(payload).model_dump(mode="json")+def test_dataset_detail_preserves_permission_keys():+ response = _dump_dataset_detail(+ _dataset_detail_payload(permission_keys=["dataset.acl.readonly", "dataset.acl.edit"])+ )++ assert response["permission_keys"] == ["dataset.acl.readonly", "dataset.acl.edit"]++def test_dataset_detail_expands_legacy_null_nested_fields():response = _dump_dataset_detail(_dataset_detail_payload(diff --git a/api/tests/unit_tests/models/test_account_models.py b/api/tests/unit_tests/models/test_account_models.pyindex 25933dd15b6..512c043b0c8 100644--- a/api/tests/unit_tests/models/test_account_models.py+++ b/api/tests/unit_tests/models/test_account_models.py@@ -12,6 +12,7 @@ This test suite covers:import base64import secretsfrom datetime import UTC, datetime+from unittest.mock import patchfrom uuid import uuid4import pytest@@ -347,7 +348,15 @@ class TestAccountRolePermissions:account.role = TenantAccountRole.ADMIN# Act & Assert- assert account.is_admin_or_owner+ with patch("models.account.dify_config.RBAC_ENABLED", False):+ assert account.is_admin_or_owner++ def test_is_admin_or_owner_with_rbac_enabled(self):+ account = Account(name="Test User", email="[email protected]")+ account.role = TenantAccountRole.NORMAL++ with patch("models.account.dify_config.RBAC_ENABLED", True):+ assert account.is_admin_or_ownerdef test_is_admin_or_owner_with_owner_role(self):"""Test is_admin_or_owner property with owner role."""@@ -383,8 +392,16 @@ class TestAccountRolePermissions:owner_account.role = TenantAccountRole.OWNER# Act & Assert- assert admin_account.is_admin- assert not owner_account.is_admin+ with patch("models.account.dify_config.RBAC_ENABLED", False):+ assert admin_account.is_admin+ assert not owner_account.is_admin++ def test_is_admin_with_rbac_enabled(self):+ account = Account(name="Test User", email="[email protected]")+ account.role = TenantAccountRole.NORMAL++ with patch("models.account.dify_config.RBAC_ENABLED", True):+ assert account.is_admindef test_has_edit_permission_with_editing_roles(self):"""Test has_edit_permission property with roles that have edit permission."""@@ -400,7 +417,15 @@ class TestAccountRolePermissions:account.role = role# Act & Assert- assert account.has_edit_permission, f"Role {role} should have edit permission"+ with patch("models.account.dify_config.RBAC_ENABLED", False):+ assert account.has_edit_permission, f"Role {role} should have edit permission"++ def test_has_edit_permission_with_rbac_enabled(self):+ account = Account(name="Test User", email="[email protected]")+ account.role = TenantAccountRole.NORMAL++ with patch("models.account.dify_config.RBAC_ENABLED", True):+ assert account.has_edit_permissiondef test_has_edit_permission_without_editing_roles(self):"""Test has_edit_permission property with roles that don't have edit permission."""@@ -415,7 +440,8 @@ class TestAccountRolePermissions:account.role = role# Act & Assert- assert not account.has_edit_permission, f"Role {role} should not have edit permission"+ with patch("models.account.dify_config.RBAC_ENABLED", False):+ assert not account.has_edit_permission, f"Role {role} should not have edit permission"def test_is_dataset_editor_property(self):"""Test is_dataset_editor property."""@@ -432,12 +458,21 @@ class TestAccountRolePermissions:account.role = role# Act & Assert- assert account.is_dataset_editor, f"Role {role} should have dataset edit permission"+ with patch("models.account.dify_config.RBAC_ENABLED", False):+ assert account.is_dataset_editor, f"Role {role} should have dataset edit permission"# Test normal role doesn't have dataset edit permissionnormal_account = Account(name="Normal User", email="[email protected]")normal_account.role = TenantAccountRole.NORMAL- assert not normal_account.is_dataset_editor+ with patch("models.account.dify_config.RBAC_ENABLED", False):+ assert not normal_account.is_dataset_editor++ def test_is_dataset_editor_with_rbac_enabled(self):+ account = Account(name="Test User", email="[email protected]")+ account.role = TenantAccountRole.NORMAL++ with patch("models.account.dify_config.RBAC_ENABLED", True):+ assert account.is_dataset_editordef test_is_dataset_operator_property(self):"""Test is_dataset_operator property."""@@ -449,8 +484,16 @@ class TestAccountRolePermissions:normal_account.role = TenantAccountRole.NORMAL# Act & Assert- assert dataset_operator.is_dataset_operator- assert not normal_account.is_dataset_operator+ with patch("models.account.dify_config.RBAC_ENABLED", False):+ assert dataset_operator.is_dataset_operator+ assert not normal_account.is_dataset_operator++ def test_is_dataset_operator_with_rbac_enabled(self):+ account = Account(name="Test User", email="[email protected]")+ account.role = TenantAccountRole.NORMAL++ with patch("models.account.dify_config.RBAC_ENABLED", True):+ assert account.is_dataset_operatordef test_current_role_property(self):"""Test current_role property."""diff --git a/api/tests/unit_tests/services/enterprise/test_rbac_service.py b/api/tests/unit_tests/services/enterprise/test_rbac_service.pynew file mode 100644index 00000000000..aa4780af0b4--- /dev/null+++ b/api/tests/unit_tests/services/enterprise/test_rbac_service.py@@ -0,0 +1,797 @@+"""Unit tests for services.enterprise.rbac_service.++The enterprise RBAC client is almost pure glue: each method turns a single+``EnterpriseRequest.send_inner_rbac_request`` call into a pydantic response+model. Rather than spinning up an HTTP server we monkeypatch that helper and+assert on the arguments it received; that catches both routing regressions+(wrong method / wrong path / wrong params) and model-shape regressions in+one place.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+from flask import Flask++from services.enterprise import rbac_service as svc++MODULE = "services.enterprise.rbac_service"+++def mock_send():+ with patch(f"{MODULE}.EnterpriseRequest.send_inner_rbac_request") as send:+ yield send+++def _call_args(send: MagicMock) -> SimpleNamespace:+ """Return the most recent (method, endpoint, kwargs) sent to the mock."""+ send.assert_called_once()+ args, kwargs = send.call_args+ return SimpleNamespace(method=args[0], endpoint=args[1], **kwargs)+++class TestCatalog:+ def test_workspace_catalog(self, mock_send: MagicMock):+ mock_send.return_value = {"groups": [{"group_key": "workspace", "group_name": "工作空间", "permissions": []}]}++ out = svc.RBACService.Catalog.workspace("tenant-1", account_id="acct-1")++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/role-permissions/catalog"+ assert call.tenant_id == "tenant-1"+ assert call.account_id == "acct-1"+ assert call.json is None+ assert call.params is None+ assert len(out.groups) == 1+ assert out.groups[0].group_key == "workspace"++ def test_app_catalog_endpoint(self, mock_send: MagicMock):+ mock_send.return_value = {"groups": []}+ svc.RBACService.Catalog.app("tenant-1")+ assert mock_send.call_args.args[1] == "/rbac/role-permissions/catalog/app"++ def test_dataset_catalog_endpoint(self, mock_send: MagicMock):+ mock_send.return_value = {"groups": []}+ svc.RBACService.Catalog.dataset("tenant-1")+ assert mock_send.call_args.args[1] == "/rbac/role-permissions/catalog/dataset"+++class TestRoles:+ def test_list_forwards_pagination_options(self, mock_send: MagicMock):+ mock_send.return_value = {+ "data": [+ {+ "id": "role-1",+ "tenant_id": "tenant-1",+ "type": "workspace",+ "category": "global_custom",+ "name": "Owner",+ "permission_keys": ["workspace.member.manage"],+ }+ ],+ "pagination": {"total_count": 1, "per_page": 20, "current_page": 1, "total_pages": 1},+ }++ out = svc.RBACService.Roles.list(+ "tenant-1",+ "acct-1",+ options=svc.ListOption(page_number=2, results_per_page=50, reverse=True),+ )++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/roles"+ assert call.params == {"page_number": 2, "results_per_page": 50, "reverse": "true"}+ assert out.pagination+ assert out.pagination.total_count == 1++ def test_list_omits_params_when_default(self, mock_send: MagicMock):+ mock_send.return_value = {"data": [], "pagination": None}+ svc.RBACService.Roles.list("tenant-1")+ assert _call_args(mock_send).params is None++ def test_list_forwards_include_owner(self, mock_send: MagicMock):+ mock_send.return_value = {"data": [], "pagination": None}++ svc.RBACService.Roles.list("tenant-1", include_owner=1)++ assert _call_args(mock_send).params == {"include_owner": 1}++ def test_list_coerces_null_permission_keys(self, mock_send: MagicMock):+ mock_send.return_value = {+ "data": [+ {+ "id": "role-1",+ "tenant_id": "tenant-1",+ "type": "workspace",+ "category": "global_custom",+ "name": "Owner",+ "permission_keys": None,+ }+ ],+ "pagination": None,+ }++ out = svc.RBACService.Roles.list("tenant-1")++ assert out.data[0].permission_keys == []++ def test_get_passes_id_query_param(self, mock_send: MagicMock):+ mock_send.return_value = {"id": "role-1", "type": "workspace", "name": "Owner"}+ svc.RBACService.Roles.get("tenant-1", "acct-1", "role-1")+ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/roles/item"+ assert call.params == {"id": "role-1"}++ def test_members_forwards_role_id_and_pagination(self, mock_send: MagicMock):+ mock_send.return_value = {+ "role_id": "role-1",+ "data": [{"account_id": "acct-2", "account_name": "Alice"}],+ "pagination": {"total_count": 1, "per_page": 20, "current_page": 1, "total_pages": 1},+ }++ out = svc.RBACService.Roles.members(+ "tenant-1",+ "acct-1",+ "role-1",+ options=svc.ListOption(page_number=1, results_per_page=20),+ )++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/roles/members"+ assert call.params == {"page_number": 1, "results_per_page": 20, "role_id": "role-1"}+ assert out.data[0].account_id == "acct-2"+ assert out.data[0].account_name == "Alice"+ assert out.pagination is not None+ assert out.pagination.total_count == 1++ def test_create_sends_body(self, mock_send: MagicMock):+ mock_send.return_value = {"id": "role-1", "type": "workspace", "name": "Owner"}+ payload = svc.RoleMutation(name="Owner", description="full access", permission_keys=["workspace.member.manage"])+ svc.RBACService.Roles.create("tenant-1", "acct-1", payload)++ call = _call_args(mock_send)+ assert call.method == "POST"+ assert call.endpoint == "/rbac/roles"+ assert call.json == {+ "name": "Owner",+ "description": "full access",+ "permission_keys": ["workspace.member.manage"],+ "type": "workspace",+ }++ def test_update_sends_id_param_and_body(self, mock_send: MagicMock):+ mock_send.return_value = {"id": "role-1", "type": "workspace", "name": "Owner"}+ payload = svc.RoleMutation(name="Owner", permission_keys=["x"])+ svc.RBACService.Roles.update("tenant-1", "acct-1", "role-1", payload)++ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/roles/item"+ assert call.params == {"id": "role-1"}+ assert call.json == {"name": "Owner", "description": "", "permission_keys": ["x"], "type": "workspace"}++ def test_delete_uses_delete_method(self, mock_send: MagicMock):+ mock_send.return_value = {"message": "success"}+ svc.RBACService.Roles.delete("tenant-1", None, "role-1")++ call = _call_args(mock_send)+ assert call.method == "DELETE"+ assert call.endpoint == "/rbac/roles/item"+ assert call.params == {"id": "role-1"}+ assert call.account_id is None++ def test_copy_sends_post_with_id_param(self, mock_send: MagicMock):+ mock_send.return_value = {"id": "role-1-copy", "type": "workspace", "name": "Owner copy"}+ svc.RBACService.Roles.copy("tenant-1", "acct-1", "role-1")++ call = _call_args(mock_send)+ assert call.method == "POST"+ assert call.endpoint == "/rbac/roles/copy"+ assert call.params == {"id": "role-1"}+ assert call.account_id == "acct-1"+++class TestAccessPolicyBindings:+ def test_lock_sends_put_with_binding_id(self, mock_send: MagicMock):+ mock_send.return_value = {"binding_id": "binding-1", "is_locked": True}++ out = svc.RBACService.AccessPolicyBindings.lock("tenant-1", "acct-1", "binding-1")++ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/access-policy-bindings/lock"+ assert call.json == {"binding_id": "binding-1"}+ assert out.binding_id == "binding-1"+ assert out.is_locked is True++ def test_unlock_sends_put_with_binding_id(self, mock_send: MagicMock):+ mock_send.return_value = {"binding_id": "binding-1", "is_locked": False}++ out = svc.RBACService.AccessPolicyBindings.unlock("tenant-1", "acct-1", "binding-1")++ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/access-policy-bindings/unlock"+ assert call.json == {"binding_id": "binding-1"}+ assert out.binding_id == "binding-1"+ assert out.is_locked is False+++class TestAccessPolicies:+ def test_list_filters_by_resource_type(self, mock_send: MagicMock):+ mock_send.return_value = {"data": [], "pagination": None}+ svc.RBACService.AccessPolicies.list(+ "tenant-1",+ "acct-1",+ resource_type=svc.RBACResourceType.APP,+ options=svc.ListOption(page_number=1),+ )+ call = _call_args(mock_send)+ assert call.endpoint == "/rbac/access-policies"+ assert call.params == {"page_number": 1, "resource_type": "app"}++ def test_copy_sends_post_with_id_param(self, mock_send: MagicMock):+ mock_send.return_value = {+ "id": "policy-1-copy",+ "resource_type": "app",+ "name": "Full access copy",+ }+ svc.RBACService.AccessPolicies.copy("tenant-1", "acct-1", "policy-1")+ call = _call_args(mock_send)+ assert call.method == "POST"+ assert call.endpoint == "/rbac/access-policies/copy"+ assert call.params == {"id": "policy-1"}++ def test_create_serialises_resource_type_enum(self, mock_send: MagicMock):+ mock_send.return_value = {"id": "policy-1", "resource_type": "dataset", "name": "KB only"}+ payload = svc.AccessPolicyCreate(+ name="KB only",+ resource_type=svc.RBACResourceType.DATASET,+ permission_keys=["dataset.acl.readonly"],+ )+ svc.RBACService.AccessPolicies.create("tenant-1", "acct-1", payload)+ call = _call_args(mock_send)+ assert call.method == "POST"+ assert call.json == {+ "name": "KB only",+ "resource_type": "dataset",+ "description": "",+ "permission_keys": ["dataset.acl.readonly"],+ }+++class TestResourceAccess:+ def test_app_whitelist_resources(self, mock_send: MagicMock):+ mock_send.return_value = {"unrestricted": True, "resource_ids": ["app-1", "app-2"]}++ out = svc.RBACService.AppAccess.whitelist_resources("tenant-1", "acct-1")++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/apps/whitelist/resources"+ assert call.params is None+ assert out.unrestricted is True+ assert out.resource_ids == ["app-1", "app-2"]++ def test_dataset_whitelist_resources(self, mock_send: MagicMock):+ mock_send.return_value = {"resource_ids": ["dataset-1"]}++ out = svc.RBACService.DatasetAccess.whitelist_resources("tenant-1", "acct-1")++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/datasets/whitelist/resources"+ assert call.params is None+ assert out.resource_ids == ["dataset-1"]++ def test_app_user_access_policies(self, mock_send: MagicMock):+ mock_send.return_value = {+ "scope": "app",+ "data": [+ {+ "account": {"account_id": "acct-1", "account_name": "Alice"},+ "roles": [+ {+ "id": "role-1",+ "type": "workspace",+ "name": "Editor",+ "permission_keys": [],+ }+ ],+ "access_policies": [+ {+ "id": "policy-1",+ "resource_type": "app",+ "name": "Can edit",+ }+ ],+ }+ ],+ }++ out = svc.RBACService.AppAccess.user_access_policies("tenant-1", "acct-1", "app-1")++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/apps/user-access-policies"+ assert call.params == {"app_id": "app-1"}+ assert out.data[0].account.account_name == "Alice"+ assert out.data[0].roles[0].id == "role-1"+ assert out.data[0].access_policies[0].id == "policy-1"++ def test_dataset_replace_user_access_policies(self, mock_send: MagicMock):+ mock_send.return_value = {+ "access_policies": [{"id": "policy-1", "resource_type": "dataset", "name": "Can edit"}]+ }+ payload = svc.ReplaceUserAccessPolicies(access_policy_ids=["policy-1"])++ out = svc.RBACService.DatasetAccess.replace_user_access_policies(+ "tenant-1", "acct-actor", "dataset-1", "acct-target", payload+ )++ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/datasets/user-access-policies"+ assert call.params == {"dataset_id": "dataset-1", "account_id": "acct-target"}+ assert call.json == {"access_policy_ids": ["policy-1"]}+ assert out.access_policies[0].id == "policy-1"++ def test_dataset_whitelist(self, mock_send: MagicMock):+ mock_send.return_value = {"account_ids": ["acct-2"]}++ out = svc.RBACService.DatasetAccess.whitelist("tenant-1", "acct-1", "dataset-1")++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/datasets/whitelist"+ assert call.params == {"dataset_id": "dataset-1"}+ assert out.account_ids == ["acct-2"]++ def test_app_matrix(self, mock_send: MagicMock):+ mock_send.return_value = {"resource_id": "app-1", "items": []}+ out = svc.RBACService.AppAccess.matrix("tenant-1", "acct-1", "app-1")+ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/apps/access-policy"+ assert call.params == {"app_id": "app-1"}+ assert out.app_id == "app-1"++ def test_dataset_matrix(self, mock_send: MagicMock):+ mock_send.return_value = {"resource_id": "dataset-1", "items": []}+ out = svc.RBACService.DatasetAccess.matrix("tenant-1", "acct-1", "dataset-1")+ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/datasets/access-policy"+ assert call.params == {"dataset_id": "dataset-1"}+ assert out.dataset_id == "dataset-1"++ def test_app_role_bindings_preserve_role_name(self, mock_send: MagicMock):+ mock_send.return_value = {+ "data": [+ {+ "id": "binding-1",+ "tenant_id": "tenant-1",+ "access_policy_id": "policy-1",+ "resource_type": "app",+ "resource_id": "app-1",+ "role_id": "role-1",+ "role_name": "Owner",+ }+ ]+ }++ out = svc.RBACService.AppAccess.list_role_bindings("tenant-1", "acct-1", "app-1", "policy-1")++ assert out.data[0].role_name == "Owner"++ def test_app_member_bindings_preserve_account_name(self, mock_send: MagicMock):+ mock_send.return_value = {+ "data": [+ {+ "id": "binding-1",+ "tenant_id": "tenant-1",+ "access_policy_id": "policy-1",+ "resource_type": "app",+ "resource_id": "app-1",+ "account_id": "acct-1",+ "account_name": "Alice",+ }+ ]+ }++ out = svc.RBACService.AppAccess.list_member_bindings("tenant-1", "acct-1", "app-1", "policy-1")++ assert out.data[0].account_name == "Alice"++ def test_app_delete_member_bindings_uses_delete_method(self, mock_send: MagicMock):+ mock_send.return_value = None+ payload = svc.DeleteMemberBindings(account_ids=["acct-2", "acct-3"])+ svc.RBACService.AppAccess.delete_member_bindings("tenant-1", "acct-1", "app-1", "policy-1", payload)+ call = _call_args(mock_send)+ assert call.method == "DELETE"+ assert call.endpoint == "/rbac/apps/access-policy/member-bindings"+ assert call.params == {"app_id": "app-1", "policy_id": "policy-1"}+ assert call.json == {"account_ids": ["acct-2", "acct-3"]}++ def test_app_replace_bindings(self, mock_send: MagicMock):+ mock_send.return_value = {"data": []}+ payload = svc.ReplaceBindings(role_ids=["workspace.owner"], account_ids=["acct-2"])+ svc.RBACService.AppAccess.replace_bindings("tenant-1", "acct-1", "app-1", "policy-1", payload)+ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/apps/access-policy/bindings"+ assert call.params == {"app_id": "app-1", "policy_id": "policy-1"}+ assert call.json == {"role_ids": ["workspace.owner"], "account_ids": ["acct-2"]}++ def test_dataset_replace_bindings(self, mock_send: MagicMock):+ mock_send.return_value = {"data": []}+ payload = svc.ReplaceBindings(role_ids=["workspace.editor"], account_ids=["acct-2"])+ svc.RBACService.DatasetAccess.replace_bindings("tenant-1", "acct-1", "ds-1", "policy-1", payload)+ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/datasets/access-policy/bindings"+ assert call.params == {"dataset_id": "ds-1", "policy_id": "policy-1"}+ assert call.json == {"role_ids": ["workspace.editor"], "account_ids": ["acct-2"]}++ def test_dataset_delete_member_bindings_uses_delete_method(self, mock_send: MagicMock):+ mock_send.return_value = None+ payload = svc.DeleteMemberBindings(account_ids=["acct-2"])+ svc.RBACService.DatasetAccess.delete_member_bindings("tenant-1", "acct-1", "ds-1", "policy-1", payload)+ call = _call_args(mock_send)+ assert call.method == "DELETE"+ assert call.endpoint == "/rbac/datasets/access-policy/member-bindings"+ assert call.params == {"dataset_id": "ds-1", "policy_id": "policy-1"}+ assert call.json == {"account_ids": ["acct-2"]}+++class TestWorkspaceAccess:+ def test_app_matrix(self, mock_send: MagicMock):+ mock_send.return_value = {+ "items": [],+ "pagination": {"total_count": 1, "per_page": 20, "current_page": 2, "total_pages": 1},+ }+ out = svc.RBACService.WorkspaceAccess.app_matrix(+ "tenant-1",+ options=svc.ListOption(page_number=2, results_per_page=20),+ )+ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/workspace/apps/access-policy"+ assert call.params == {"page_number": 2, "results_per_page": 20}+ assert out.pagination+ assert out.pagination.current_page == 2++ def test_dataset_matrix(self, mock_send: MagicMock):+ mock_send.return_value = {"items": []}+ svc.RBACService.WorkspaceAccess.dataset_matrix("tenant-1")+ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/workspace/datasets/access-policy"+ assert call.params is None++ def test_workspace_matrix_coerces_null_bindings(self, mock_send: MagicMock):+ mock_send.return_value = {+ "items": [+ {+ "policy": {+ "id": "policy-1",+ "resource_type": "app",+ "name": "Workspace App Access",+ },+ "roles": None,+ "accounts": None,+ }+ ],+ "pagination": None,+ }++ out = svc.RBACService.WorkspaceAccess.app_matrix("tenant-1")++ assert out.items[0].roles == []+ assert out.items[0].accounts == []++ def test_workspace_app_replace_bindings(self, mock_send: MagicMock):+ mock_send.return_value = {"data": []}+ payload = svc.ReplaceBindings(role_ids=["workspace.editor"], account_ids=["acct-2"])+ svc.RBACService.WorkspaceAccess.replace_app_bindings("tenant-1", "acct-1", "policy-1", payload)+ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/workspace/apps/access-policy/bindings"+ assert call.params == {"policy_id": "policy-1"}+ assert call.json == {"role_ids": ["workspace.editor"], "account_ids": ["acct-2"]}++ def test_workspace_dataset_replace_bindings(self, mock_send: MagicMock):+ mock_send.return_value = {"data": []}+ payload = svc.ReplaceBindings(role_ids=["workspace.editor"], account_ids=["acct-2"])+ svc.RBACService.WorkspaceAccess.replace_dataset_bindings("tenant-1", "acct-1", "policy-1", payload)+ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/workspace/datasets/access-policy/bindings"+ assert call.params == {"policy_id": "policy-1"}+ assert call.json == {"role_ids": ["workspace.editor"], "account_ids": ["acct-2"]}++ def test_workspace_app_matrix_forwards_language_query_param(self, mock_send: MagicMock):+ mock_send.return_value = {"items": [], "pagination": None}+ app = Flask(__name__)+ with app.test_request_context("/?language=en"):+ svc.RBACService.WorkspaceAccess.app_matrix("tenant-1")++ call = _call_args(mock_send)+ assert call.params == {"language": "en"}+++class TestMyPermissions:+ def test_resource_snapshot_maps_defaults_and_overrides(self):+ snapshot = svc.ResourcePermissionSnapshot(+ default_permission_keys=["app.acl.view_layout"],+ overrides=[+ svc.ResourcePermissionKeys(+ resource_id="app-2",+ permission_keys=["app.acl.view_layout", "app.acl.edit"],+ )+ ],+ )++ assert snapshot.permission_keys_by_resource_ids(["app-1", "app-2"]) == {+ "app-1": ["app.acl.view_layout"],+ "app-2": ["app.acl.view_layout", "app.acl.edit"],+ }++ def test_get_without_payload_uses_get(self, mock_send: MagicMock):+ mock_send.return_value = {+ "workspace": {"permission_keys": ["workspace.member.manage"]},+ "app": {"default_permission_keys": ["app.acl.view_layout", "app.acl.test_and_run"], "overrides": []},+ "dataset": {"default_permission_keys": [], "overrides": []},+ }++ with patch(f"{MODULE}.dify_config.RBAC_ENABLED", True):+ out = svc.RBACService.MyPermissions.get("tenant-1", "acct-1")++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/my-permissions"+ assert call.json is None+ assert call.params is None+ assert out.workspace.permission_keys == ["workspace.member.manage"]++ @pytest.mark.parametrize(+ ("role", "workspace_keys", "app_keys", "dataset_keys"),+ [+ (+ "owner",+ svc._LEGACY_WORKSPACE_OWNER_KEYS,+ svc._LEGACY_APP_OWNER_KEYS,+ svc._LEGACY_DATASET_OWNER_KEYS,+ ),+ (+ "admin",+ svc._LEGACY_WORKSPACE_ADMIN_KEYS,+ svc._LEGACY_APP_ADMIN_KEYS,+ svc._LEGACY_DATASET_ADMIN_KEYS,+ ),+ (+ "editor",+ svc._LEGACY_WORKSPACE_EDITOR_KEYS,+ svc._LEGACY_APP_EDITOR_KEYS,+ svc._LEGACY_DATASET_EDITOR_KEYS,+ ),+ (+ "normal",+ svc._LEGACY_WORKSPACE_NORMAL_KEYS,+ svc._LEGACY_APP_NORMAL_KEYS,+ [],+ ),+ (+ "dataset_operator",+ svc._LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS,+ [],+ svc._LEGACY_DATASET_DATASET_OPERATOR_KEYS,+ ),+ ],+ )+ def test_get_uses_legacy_role_permissions_when_rbac_disabled(+ self,+ mock_send: MagicMock,+ role: str,+ workspace_keys: list[str],+ app_keys: list[str],+ dataset_keys: list[str],+ ):+ mock_session = MagicMock()+ mock_session.__enter__.return_value = mock_session+ mock_session.scalar.return_value = role+ with (+ patch(f"{MODULE}.dify_config.RBAC_ENABLED", False),+ patch(f"{MODULE}.session_factory.create_session", return_value=mock_session),+ ):+ out = svc.RBACService.MyPermissions.get("tenant-1", "acct-1")++ mock_send.assert_not_called()+ assert out.workspace.permission_keys == workspace_keys+ assert out.app.default_permission_keys == app_keys+ assert out.dataset.default_permission_keys == dataset_keys+ assert out.app.overrides == []+ assert out.dataset.overrides == []++ def test_get_returns_empty_when_role_missing_and_rbac_disabled(self, mock_send: MagicMock):+ mock_session = MagicMock()+ mock_session.__enter__.return_value = mock_session+ mock_session.scalar.return_value = None+ with (+ patch(f"{MODULE}.dify_config.RBAC_ENABLED", False),+ patch(f"{MODULE}.session_factory.create_session", return_value=mock_session),+ ):+ out = svc.RBACService.MyPermissions.get("tenant-1", "acct-1")++ mock_send.assert_not_called()+ assert out.workspace.permission_keys == []+ assert out.app.default_permission_keys == []+ assert out.dataset.default_permission_keys == []++ def test_get_with_single_resource_filters(self, mock_send: MagicMock):+ mock_send.return_value = {+ "workspace": {"permission_keys": []},+ "app": {+ "default_permission_keys": [],+ "overrides": [{"resource_id": "app-1", "permission_keys": ["app.acl.edit"]}],+ },+ "dataset": {"default_permission_keys": [], "overrides": []},+ }++ with patch(f"{MODULE}.dify_config.RBAC_ENABLED", True):+ out = svc.RBACService.MyPermissions.get("tenant-1", "acct-1", app_id="app-1")++ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/my-permissions"+ assert call.params == {"app_id": "app-1"}+ assert out.app.overrides[0].resource_id == "app-1"+++class TestMemberRoles:+ def test_get(self, mock_send: MagicMock):+ mock_send.return_value = {+ "account_id": "acct-2",+ "roles": [+ {+ "id": "role-1",+ "type": "workspace",+ "name": "Member",+ }+ ],+ }+ out = svc.RBACService.MemberRoles.get("tenant-1", "acct-1", "acct-2")+ call = _call_args(mock_send)+ assert call.method == "GET"+ assert call.endpoint == "/rbac/members/rbac-roles"+ assert call.params == {"account_id": "acct-2"}+ assert out.account_id == "acct-2"+ assert out.roles[0].name == "Member"++ def test_replace(self, mock_send: MagicMock):+ mock_send.return_value = {"account_id": "acct-2", "roles": []}+ svc.RBACService.MemberRoles.replace(+ "tenant-1", "acct-1", "acct-2", role_ids=["workspace.owner", "workspace.editor"]+ )+ call = _call_args(mock_send)+ assert call.method == "PUT"+ assert call.endpoint == "/rbac/members/rbac-roles"+ assert call.params == {"account_id": "acct-2"}+ assert call.json == {"role_ids": ["workspace.owner", "workspace.editor"]}++ def test_batch_get(self, mock_send: MagicMock):+ mock_send.return_value = {+ "acct-2": [+ {"id": "role-1", "name": "Admin", "type": "workspace"},+ {"id": "role-2", "name": "Editor", "type": "workspace"},+ ],+ "acct-3": [],+ }++ out = svc.RBACService.MemberRoles.batch_get("tenant-1", "acct-1", ["acct-2", "acct-3"])++ call = _call_args(mock_send)+ assert call.method == "POST"+ assert call.endpoint == "/rbac/members/rbac-roles/batch"+ assert call.json == {"member_ids": ["acct-2", "acct-3"]}+ assert out[0].account_id == "acct-2"+ assert len(out[0].roles) == 2+ assert out[1].account_id == "acct-3"+ assert out[1].roles == []+++class TestResourcePermissions:+ def test_app_permissions_batch_get(self, mock_send: MagicMock):+ mock_send.return_value = {+ "data": [+ {"resource_id": "app-1", "permission_keys": ["app.acl.view_layout", "app.acl.edit"]},+ {"resource_id": "app-2", "permission_keys": []},+ ]+ }++ with patch(f"{MODULE}.dify_config.RBAC_ENABLED", True):+ out = svc.RBACService.AppPermissions.batch_get("tenant-1", "acct-1", ["app-1", "app-2"])++ call = _call_args(mock_send)+ assert call.method == "POST"+ assert call.endpoint == "/rbac/apps/permission-keys/batch"+ assert call.json == {"app_ids": ["app-1", "app-2"]}+ assert out == {+ "app-1": ["app.acl.view_layout", "app.acl.edit"],+ "app-2": [],+ }++ def test_app_permissions_batch_get_uses_legacy_role_permissions_when_rbac_disabled(self, mock_send: MagicMock):+ mock_session = MagicMock()+ mock_session.__enter__.return_value = mock_session+ mock_session.scalar.return_value = "editor"+ with (+ patch(f"{MODULE}.dify_config.RBAC_ENABLED", False),+ patch(f"{MODULE}.session_factory.create_session", return_value=mock_session),+ ):+ out = svc.RBACService.AppPermissions.batch_get("tenant-1", "acct-1", ["app-1", "app-2"])++ mock_send.assert_not_called()+ assert out == {+ "app-1": svc._LEGACY_APP_EDITOR_KEYS,+ "app-2": svc._LEGACY_APP_EDITOR_KEYS,+ }++ def test_dataset_permissions_batch_get(self, mock_send: MagicMock):+ mock_send.return_value = {+ "data": [+ {"resource_id": "ds-1", "permission_keys": ["dataset.acl.readonly"]},+ {"resource_id": "ds-2", "permission_keys": ["dataset.acl.edit"]},+ ]+ }++ with patch(f"{MODULE}.dify_config.RBAC_ENABLED", True):+ out = svc.RBACService.DatasetPermissions.batch_get("tenant-1", "acct-1", ["ds-1", "ds-2"])++ call = _call_args(mock_send)+ assert call.method == "POST"+ assert call.endpoint == "/rbac/datasets/permission-keys/batch"+ assert call.json == {"dataset_ids": ["ds-1", "ds-2"]}+ assert out == {+ "ds-1": ["dataset.acl.readonly"],+ "ds-2": ["dataset.acl.edit"],+ }++ def test_dataset_permissions_batch_get_uses_legacy_role_permissions_when_rbac_disabled(self, mock_send: MagicMock):+ mock_session = MagicMock()+ mock_session.__enter__.return_value = mock_session+ mock_session.scalar.return_value = "dataset_operator"+ with (+ patch(f"{MODULE}.dify_config.RBAC_ENABLED", False),+ patch(f"{MODULE}.session_factory.create_session", return_value=mock_session),+ ):+ out = svc.RBACService.DatasetPermissions.batch_get("tenant-1", "acct-1", ["ds-1", "ds-2"])++ mock_send.assert_not_called()+ assert out == {+ "ds-1": svc._LEGACY_DATASET_DATASET_OPERATOR_KEYS,+ "ds-2": svc._LEGACY_DATASET_DATASET_OPERATOR_KEYS,+ }+++class TestListOption:+ def test_empty_produces_empty_params(self):+ assert svc.ListOption().to_params() == {}++ def test_reverse_serialises_as_lowercase_bool(self):+ assert svc.ListOption(reverse=False).to_params()["reverse"] == "false"+ assert svc.ListOption(reverse=True).to_params()["reverse"] == "true"++ def test_extra_overrides_merge(self):+ assert svc.ListOption(page_number=1).to_params({"resource_type": "app", "skip": None}) == {+ "page_number": 1,+ "resource_type": "app",+ }diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.pyindex c98b717a105..0bfa4afb5ba 100644--- a/api/tests/unit_tests/services/test_account_service.py+++ b/api/tests/unit_tests/services/test_account_service.py@@ -1,5 +1,6 @@import jsonfrom datetime import datetime, timedelta+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytest@@ -828,8 +829,8 @@ class TestTenantService:tenant_id="tenant-456", account_id="operator-123", role="owner")- # scalar calls: permission check, ta lookup, remaining count- mock_db.session.scalar.side_effect = [mock_operator_join, mock_ta, 0]+ # scalar calls: permission check, ta lookup, owner_id lookup, remaining count+ mock_db.session.scalar.side_effect = [mock_operator_join, mock_ta, "operator-123", 0]with patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync:mock_sync.return_value = True@@ -868,8 +869,8 @@ class TestTenantService:tenant_id="tenant-456", account_id="operator-123", role="owner")- # scalar calls: permission check, ta lookup, remaining count = 1- mock_db.session.scalar.side_effect = [mock_operator_join, mock_ta, 1]+ # scalar calls: permission check, ta lookup, owner_id lookup, remaining count = 1+ mock_db.session.scalar.side_effect = [mock_operator_join, mock_ta, "operator-123", 1]with patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync:mock_sync.return_value = True@@ -899,8 +900,8 @@ class TestTenantService:tenant_id="tenant-456", account_id="operator-123", role="owner")- # scalar calls: permission check, ta lookup (no count needed for active member)- mock_db.session.scalar.side_effect = [mock_operator_join, mock_ta]+ # scalar calls: permission check, ta lookup, owner_id lookup (no count for active member)+ mock_db.session.scalar.side_effect = [mock_operator_join, mock_ta, "operator-123"]with patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync:mock_sync.return_value = True@@ -974,6 +975,43 @@ class TestTenantService:assert mock_target_join.role == "admin"self._assert_database_operations_called(mock_db)+ def test_create_owner_tenant_if_not_exist_rbac_enabled_assigns_owner_role(+ self, mock_db_dependencies, mock_external_service_dependencies+ ):+ mock_account = TestAccountAssociatedDataFactory.create_account_mock(account_id="user-rbac", name="RBAC User")+ mock_external_service_dependencies[+ "feature_service"+ ].get_system_features.return_value.is_allow_create_workspace = True+ mock_external_service_dependencies[+ "feature_service"+ ].get_system_features.return_value.license.workspaces.is_available.return_value = True++ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-rbac"+ mock_tenant.name = "RBAC User's Workspace"++ with (+ patch("services.account_service.dify_config.RBAC_ENABLED", True),+ patch("services.account_service.TenantService.create_tenant", return_value=mock_tenant),+ patch("services.account_service.TenantService.create_tenant_member"),+ patch(+ "services.account_service.AccountService._resolve_legacy_role_id",+ return_value="rbac-owner-id",+ ),+ patch("services.account_service.RBACService") as mock_rbac_service,+ patch("services.account_service.tenant_was_created.send"),+ ):+ mock_db_dependencies["db"].session.scalar.return_value = None++ TenantService.create_owner_tenant_if_not_exist(mock_account, is_setup=True)++ mock_rbac_service.MemberRoles.replace.assert_called_once_with(+ tenant_id="tenant-rbac",+ account_id="user-rbac",+ member_account_id="user-rbac",+ role_ids=["rbac-owner-id"],+ )+def test_admin_can_update_admin_member_role(self):"""Test admin can update another non-owner member, including an admin."""mock_tenant = MagicMock()@@ -1103,6 +1141,81 @@ class TestTenantService:with pytest.raises(NoPermissionError):TenantService.check_member_permission(mock_tenant, mock_operator, mock_member, "remove")+ def test_rbac_member_can_remove_non_owner_member(self):+ """Test RBAC workspace.member.manage allows removing a non-owner member."""+ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-456"+ mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")+ mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")++ mock_permissions = MagicMock()+ mock_permissions.workspace = MagicMock(permission_keys=["workspace.member.manage"])++ with (+ patch("services.account_service.dify_config.RBAC_ENABLED", True),+ patch("services.account_service.RBACService.MyPermissions.get", return_value=mock_permissions),+ patch("services.account_service.AccountService.is_rbac_workspace_owner", return_value=False),+ ):+ TenantService.check_member_permission(mock_tenant, mock_operator, mock_member, "remove")++ def test_rbac_member_cannot_remove_without_permission(self):+ """Test RBAC permission check rejects removal without workspace.member.manage."""+ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-456"+ mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")+ mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")++ mock_permissions = MagicMock()+ mock_permissions.workspace = MagicMock(permission_keys=["workspace.role.manage"])++ with (+ patch("services.account_service.dify_config.RBAC_ENABLED", True),+ patch("services.account_service.RBACService.MyPermissions.get", return_value=mock_permissions),+ ):+ with pytest.raises(NoPermissionError):+ TenantService.check_member_permission(mock_tenant, mock_operator, mock_member, "remove")++ def test_rbac_member_cannot_remove_owner_member(self):+ """Test RBAC permission check rejects removing an owner member."""+ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-456"+ mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")+ mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")++ mock_permissions = MagicMock()+ mock_permissions.workspace = MagicMock(permission_keys=["workspace.member.manage"])++ with (+ patch("services.account_service.dify_config.RBAC_ENABLED", True),+ patch("services.account_service.RBACService.MyPermissions.get", return_value=mock_permissions),+ patch("services.account_service.AccountService.is_rbac_workspace_owner", return_value=True),+ ):+ with pytest.raises(NoPermissionError):+ TenantService.check_member_permission(mock_tenant, mock_operator, mock_member, "remove")++ def test_get_rbac_workspace_owner_account_id(self):+ mock_roles = MagicMock()+ mock_roles.data = [SimpleNamespace(account_id="owner-account")]+ mock_rbac_roles = MagicMock()+ mock_rbac_roles.members.return_value = mock_roles++ with (+ patch(+ "services.account_service.AccountService._resolve_legacy_role_id",+ return_value="owner-role-id",+ ),+ patch("services.account_service.RBACService.Roles", mock_rbac_roles),+ ):+ owner_account_id = AccountService.get_rbac_workspace_owner_account_id("tenant-1", "acct-1")++ assert owner_account_id == "owner-account"+ call = mock_rbac_roles.members.call_args+ assert call.kwargs["tenant_id"] == "tenant-1"+ assert call.kwargs["account_id"] == "acct-1"+ assert call.kwargs["role_id"] == "owner-role-id"+ assert call.kwargs["options"].page_number == 1+ assert call.kwargs["options"].results_per_page == 1+class TestRegisterService:"""@@ -1891,6 +2004,185 @@ class TestRegisterService:inviter=None,)+ # ==================== RBAC Member Invitation Tests ====================++ def test_invite_new_member_rbac_enabled_new_account(+ self, mock_db_dependencies, mock_redis_dependencies, mock_task_dependencies+ ):+ """When RBAC is enabled, create the member join and replace RBAC member roles."""+ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-789"+ mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")++ with (+ patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,+ patch("services.account_service.dify_config") as mock_config,+ ):+ mock_lookup.return_value = None+ mock_config.RBAC_ENABLED = True++ mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(+ account_id="new-user-rbac", email="[email protected]", name="rbacuser", status="pending"+ )+ with (+ patch("services.account_service.RegisterService.register") as mock_register,+ patch("services.account_service.TenantService.check_member_permission"),+ patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,+ patch("services.account_service.TenantService.switch_tenant"),+ patch("services.account_service.RegisterService.generate_invite_token", return_value="rbac-token"),+ patch("services.account_service.RBACService") as mock_rbac_service,+ ):+ mock_register.return_value = mock_new_account++ result = RegisterService.invite_new_member(+ tenant=mock_tenant,+ email="[email protected]",+ language="en-US",+ role="rbac-role-id-123",+ inviter=mock_inviter,+ )++ assert result == "rbac-token"+ mock_create_member.assert_called_once_with(+ mock_tenant, mock_new_account, TenantAccountRole.NORMAL.value+ )+ mock_rbac_service.MemberRoles.replace.assert_called_once_with(+ tenant_id=str(mock_tenant.id),+ account_id=mock_inviter.id,+ member_account_id=mock_new_account.id,+ role_ids=["rbac-role-id-123"],+ )++ def test_invite_new_member_rbac_enabled_existing_account(+ self, mock_db_dependencies, mock_redis_dependencies, mock_task_dependencies+ ):+ """When RBAC is enabled and account exists, create the member join and replace RBAC member roles."""+ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-789"+ mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")+ mock_existing_account = TestAccountAssociatedDataFactory.create_account_mock(+ account_id="existing-rbac", email="[email protected]", status="pending"+ )++ mock_db_dependencies["db"].session.scalar.return_value = None++ with (+ patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,+ patch("services.account_service.dify_config") as mock_config,+ ):+ mock_lookup.return_value = mock_existing_account+ mock_config.RBAC_ENABLED = True++ with (+ patch("services.account_service.TenantService.check_member_permission"),+ patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,+ patch("services.account_service.RegisterService.generate_invite_token", return_value="rbac-token"),+ patch("services.account_service.RBACService") as mock_rbac_service,+ ):+ result = RegisterService.invite_new_member(+ tenant=mock_tenant,+ email="[email protected]",+ language="en-US",+ role="rbac-role-id-456",+ inviter=mock_inviter,+ )++ assert result == "rbac-token"+ mock_create_member.assert_called_once_with(+ mock_tenant, mock_existing_account, TenantAccountRole.NORMAL.value+ )+ mock_rbac_service.MemberRoles.replace.assert_called_once_with(+ tenant_id=str(mock_tenant.id),+ account_id=mock_inviter.id,+ member_account_id=mock_existing_account.id,+ role_ids=["rbac-role-id-456"],+ )++ def test_invite_new_member_rbac_enabled_existing_active_account_adds_role_before_signin_response(+ self, mock_db_dependencies, mock_redis_dependencies, mock_task_dependencies+ ):+ """Existing active accounts still need an RBAC membership before the API returns the signin URL."""+ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-789"+ mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")+ mock_existing_account = TestAccountAssociatedDataFactory.create_account_mock(+ account_id="existing-rbac", email="[email protected]", status=AccountStatus.ACTIVE+ )++ mock_db_dependencies["db"].session.scalar.return_value = None++ with (+ patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,+ patch("services.account_service.dify_config") as mock_config,+ ):+ mock_lookup.return_value = mock_existing_account+ mock_config.RBAC_ENABLED = True++ with (+ patch("services.account_service.TenantService.check_member_permission"),+ patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,+ patch("services.account_service.RBACService") as mock_rbac_service,+ ):+ with pytest.raises(AccountAlreadyInTenantError):+ RegisterService.invite_new_member(+ tenant=mock_tenant,+ email="[email protected]",+ language="en-US",+ role="rbac-role-id-456",+ inviter=mock_inviter,+ )++ mock_create_member.assert_called_once_with(+ mock_tenant, mock_existing_account, TenantAccountRole.NORMAL.value+ )+ mock_rbac_service.MemberRoles.replace.assert_called_once_with(+ tenant_id=str(mock_tenant.id),+ account_id=mock_inviter.id,+ member_account_id=mock_existing_account.id,+ role_ids=["rbac-role-id-456"],+ )+ mock_task_dependencies.delay.assert_not_called()++ def test_invite_new_member_rbac_disabled_uses_legacy_role(+ self, mock_db_dependencies, mock_redis_dependencies, mock_task_dependencies+ ):+ """When RBAC is disabled, create_tenant_member should be called and MemberRoles.replace should NOT."""+ mock_tenant = MagicMock()+ mock_tenant.id = "tenant-legacy"+ mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-789", name="Inviter")++ with (+ patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,+ patch("services.account_service.dify_config") as mock_config,+ ):+ mock_lookup.return_value = None+ mock_config.RBAC_ENABLED = False++ mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(+ account_id="legacy-user", email="[email protected]", name="legacyuser", status="pending"+ )+ with (+ patch("services.account_service.RegisterService.register") as mock_register,+ patch("services.account_service.TenantService.check_member_permission"),+ patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,+ patch("services.account_service.TenantService.switch_tenant"),+ patch("services.account_service.RegisterService.generate_invite_token", return_value="legacy-token"),+ patch("services.account_service.RBACService") as mock_rbac_service,+ ):+ mock_register.return_value = mock_new_account++ result = RegisterService.invite_new_member(+ tenant=mock_tenant,+ email="[email protected]",+ language="en-US",+ role="editor",+ inviter=mock_inviter,+ )++ assert result == "legacy-token"+ mock_create_member.assert_called_once_with(mock_tenant, mock_new_account, "editor")+ mock_rbac_service.MemberRoles.replace.assert_not_called()+# ==================== Token Management Tests ====================def test_generate_invite_token_success(self, mock_redis_dependencies):diff --git a/api/tests/unit_tests/services/test_dataset_service_dataset.py b/api/tests/unit_tests/services/test_dataset_service_dataset.pyindex 3d08b6fd096..46f32f93e8a 100644--- a/api/tests/unit_tests/services/test_dataset_service_dataset.py+++ b/api/tests/unit_tests/services/test_dataset_service_dataset.py@@ -15,6 +15,7 @@ from .dataset_service_test_helpers import (ProviderTokenNotInitError,RagPipelineDatasetCreateEntity,SimpleNamespace,+ TenantAccountRole,_make_knowledge_configuration,_make_retrieval_model,_make_session_context,@@ -167,6 +168,154 @@ class TestDatasetServiceValidation:DatasetService.check_is_multimodal_model("tenant-1", "provider", "embedding-model")+class TestDatasetServiceRetrievalPermissions:+ """Unit tests for dataset list permission branching."""++ def test_get_datasets_filters_by_maintainer_and_rbac_overrides(self):+ mock_db = MagicMock()+ mock_db.session.scalars.return_value.all.return_value = []+ mock_db.paginate.return_value.items = []+ mock_db.paginate.return_value.total = 0+ user = DatasetServiceUnitDataFactory.create_user_mock(role=TenantAccountRole.NORMAL)++ with (+ patch("services.dataset_service.db", mock_db),+ patch("services.dataset_service.dify_config.RBAC_ENABLED", True),+ patch(+ "services.dataset_service.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=SimpleNamespace(workspace=SimpleNamespace(permission_keys=[])),+ ),+ ):+ DatasetService.get_datasets(+ page=1,+ per_page=20,+ tenant_id="tenant-1",+ user=user,+ accessible_dataset_ids=["dataset-shared"],+ include_own_datasets=True,+ )++ select_stmt = mock_db.paginate.call_args.kwargs["select"]+ visibility_clause = str(select_stmt._where_criteria[1])+ assert "maintainer" in visibility_clause+ assert "IN" in visibility_clause++ def test_get_datasets_filters_only_by_rbac_overrides_without_manage_own_permission(self):+ mock_db = MagicMock()+ mock_db.session.scalars.return_value.all.return_value = []+ mock_db.paginate.return_value.items = []+ mock_db.paginate.return_value.total = 0+ user = DatasetServiceUnitDataFactory.create_user_mock(role=TenantAccountRole.NORMAL)++ with (+ patch("services.dataset_service.db", mock_db),+ patch("services.dataset_service.dify_config.RBAC_ENABLED", True),+ patch(+ "services.dataset_service.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=SimpleNamespace(workspace=SimpleNamespace(permission_keys=[])),+ ),+ ):+ DatasetService.get_datasets(+ page=1,+ per_page=20,+ tenant_id="tenant-1",+ user=user,+ accessible_dataset_ids=["dataset-shared"],+ )++ select_stmt = mock_db.paginate.call_args.kwargs["select"]+ visibility_clause = str(select_stmt._where_criteria[1])+ assert "maintainer" not in visibility_clause+ assert "IN" in visibility_clause++ def test_get_datasets_by_ids_applies_rbac_visibility(self):+ mock_db = MagicMock()+ mock_db.paginate.return_value.items = []+ mock_db.paginate.return_value.total = 0+ user = DatasetServiceUnitDataFactory.create_user_mock(role=TenantAccountRole.NORMAL)++ with (+ patch("services.dataset_service.db", mock_db),+ patch("services.dataset_service.dify_config.RBAC_ENABLED", True),+ ):+ DatasetService.get_datasets_by_ids(+ ["dataset-requested", "dataset-shared"],+ "tenant-1",+ user=user,+ accessible_dataset_ids=["dataset-shared", "dataset-not-requested"],+ include_own_datasets=True,+ )++ select_stmt = mock_db.paginate.call_args.kwargs["select"]+ visibility_clause = str(select_stmt._where_criteria[-1])+ assert "maintainer" in visibility_clause+ assert "IN" in visibility_clause+ visibility_params = select_stmt._where_criteria[-1].compile().params+ assert ["dataset-shared"] in visibility_params.values()+ list_params = [value for value in visibility_params.values() if isinstance(value, list)]+ assert all("dataset-not-requested" not in value for value in list_params)++ def test_get_datasets_rbac_include_all_uses_workspace_permission(self):+ mock_db = MagicMock()+ mock_db.session.scalars.return_value.all.return_value = []+ mock_db.paginate.return_value.items = []+ mock_db.paginate.return_value.total = 0++ user = DatasetServiceUnitDataFactory.create_user_mock(role=TenantAccountRole.NORMAL)+ mock_permissions = SimpleNamespace(workspace=SimpleNamespace(permission_keys=["dataset.create_and_management"]))++ with (+ patch("services.dataset_service.db", mock_db),+ patch("services.dataset_service.dify_config.RBAC_ENABLED", True),+ patch(+ "services.dataset_service.enterprise_rbac_service.RBACService.MyPermissions.get",+ return_value=mock_permissions,+ ),+ ):+ DatasetService.get_datasets(page=1, per_page=20, tenant_id="tenant-1", user=user, include_all=True)++ mock_db.session.scalars.assert_called_once()+ mock_db.paginate.assert_called_once()+ select_stmt = mock_db.paginate.call_args.kwargs["select"]+ assert len(select_stmt._where_criteria) == 1++ def test_get_datasets_rbac_without_user_returns_empty_result(self):+ mock_db = MagicMock()+ mock_db.session.scalars.return_value.all.return_value = []+ mock_db.paginate.return_value.items = []+ mock_db.paginate.return_value.total = 0++ with (+ patch("services.dataset_service.db", mock_db),+ patch("services.dataset_service.dify_config.RBAC_ENABLED", True),+ ):+ DatasetService.get_datasets(page=1, per_page=20, tenant_id="tenant-1", user=None)++ mock_db.session.scalars.assert_not_called()+ mock_db.paginate.assert_called_once()+ select_stmt = mock_db.paginate.call_args.kwargs["select"]+ assert len(select_stmt._where_criteria) == 2++ def test_get_datasets_legacy_owner_include_all_keeps_full_access(self):+ mock_db = MagicMock()+ mock_db.session.scalars.return_value.all.return_value = []+ mock_db.paginate.return_value.items = []+ mock_db.paginate.return_value.total = 0++ user = DatasetServiceUnitDataFactory.create_user_mock(role=TenantAccountRole.OWNER)++ with (+ patch("services.dataset_service.db", mock_db),+ patch("services.dataset_service.dify_config.RBAC_ENABLED", False),+ ):+ DatasetService.get_datasets(page=1, per_page=20, tenant_id="tenant-1", user=user, include_all=True)++ mock_db.session.scalars.assert_called_once()+ mock_db.paginate.assert_called_once()+ select_stmt = mock_db.paginate.call_args.kwargs["select"]+ assert len(select_stmt._where_criteria) == 1++class TestDatasetServiceCreationAndUpdate:"""Unit tests for dataset creation and update helpers."""diff --git a/e2e/support/apps.ts b/e2e/support/apps.tsindex f035b5f4a1b..3c3af547a35 100644--- a/e2e/support/apps.ts+++ b/e2e/support/apps.ts@@ -19,6 +19,6 @@ export const openBlankAppCreation = async (page: Page) => {return}- await page.getByRole('button', { name: 'Create' }).click()+ await page.getByRole('button', { name: 'Create', exact: true }).click()await page.getByRole('menuitem', { name: 'Create from Blank' }).click()}diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex 263481bc9d1..07c7c8c2a40 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -720,11 +720,6 @@"count": 1}},- "web/app/components/app/configuration/dataset-config/index.tsx": {- "ts/no-explicit-any": {- "count": 1- }- },"web/app/components/app/configuration/dataset-config/params-config/__tests__/config-content.spec.tsx": {"ts/no-explicit-any": {"count": 1@@ -965,11 +960,6 @@"count": 1}},- "web/app/components/app/overview/trigger-card.tsx": {- "ts/no-explicit-any": {- "count": 1- }- },"web/app/components/app/overview/workflow-hidden-input-fields.tsx": {"no-restricted-imports": {"count": 1@@ -1035,6 +1025,11 @@"count": 1}},+ "web/app/components/apps/new-app-card.tsx": {+ "react/set-state-in-effect": {+ "count": 3+ }+ },"web/app/components/base/action-button/index.tsx": {"erasable-syntax-only/enums": {"count": 1@@ -1921,7 +1916,7 @@},"web/app/components/base/icons/src/vender/solid/arrows/index.ts": {"no-barrel-files/no-barrel-files": {- "count": 3+ "count": 1}},"web/app/components/base/icons/src/vender/solid/communication/index.ts": {@@ -2639,11 +2634,6 @@"count": 4}},- "web/app/components/billing/billing-page/__tests__/index.spec.tsx": {- "ts/no-explicit-any": {- "count": 4- }- },"web/app/components/billing/header-billing-btn/index.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -2929,14 +2919,6 @@"count": 3}},- "web/app/components/datasets/create/step-two/index.tsx": {- "no-barrel-files/no-barrel-files": {- "count": 1- },- "react-hooks/exhaustive-deps": {- "count": 1- }- },"web/app/components/datasets/create/step-two/preview-item/index.tsx": {"erasable-syntax-only/enums": {"count": 1@@ -3006,14 +2988,6 @@"count": 1}},- "web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 2- },- "jsx-a11y/no-static-element-interactions": {- "count": 2- }- },"web/app/components/datasets/documents/components/document-list/components/index.ts": {"no-barrel-files/no-barrel-files": {"count": 2@@ -3037,14 +3011,6 @@"count": 1}},- "web/app/components/datasets/documents/components/operations.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },"web/app/components/datasets/documents/components/rename-modal.tsx": {"no-restricted-imports": {"count": 1@@ -3294,10 +3260,10 @@},"web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts": {"react-hooks-extra/no-direct-set-state-in-use-effect": {- "count": 4+ "count": 6},"react/set-state-in-effect": {- "count": 4+ "count": 6}},"web/app/components/datasets/documents/detail/metadata/index.tsx": {@@ -3409,11 +3375,6 @@"count": 1}},- "web/app/components/datasets/list/__tests__/header.spec.tsx": {- "jsx-a11y/label-has-associated-control": {- "count": 1- }- },"web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -3526,11 +3487,6 @@"count": 1}},- "web/app/components/datasets/settings/permission-selector/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },"web/app/components/datasets/settings/permission-selector/member-item.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -3568,6 +3524,14 @@"count": 2}},+ "web/app/components/develop/secret-key/secret-key-modal.tsx": {+ "jsx-a11y/click-events-have-key-events": {+ "count": 1+ },+ "jsx-a11y/no-static-element-interactions": {+ "count": 1+ }+ },"web/app/components/explore/banner/__tests__/indicator-button.spec.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -3803,11 +3767,6 @@"count": 1}},- "web/app/components/header/account-setting/model-provider-page/model-auth/add-credential-in-load-balancing.tsx": {- "ts/no-explicit-any": {- "count": 4- }- },"web/app/components/header/account-setting/model-provider-page/model-auth/add-custom-model.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 2@@ -3830,9 +3789,6 @@},"jsx-a11y/no-static-element-interactions": {"count": 1- },- "no-restricted-imports": {- "count": 1}},"web/app/components/header/account-setting/model-provider-page/model-auth/config-model.tsx": {@@ -3876,11 +3832,6 @@"count": 7}},- "web/app/components/header/account-setting/model-provider-page/model-auth/switch-credential-in-load-balancing.tsx": {- "ts/no-explicit-any": {- "count": 2- }- },"web/app/components/header/account-setting/model-provider-page/model-modal/Input.tsx": {"unicorn/prefer-number-properties": {"count": 2@@ -3981,12 +3932,7 @@"count": 2}},- "web/app/components/header/account-setting/plugin-page/utils.ts": {- "ts/no-explicit-any": {- "count": 4- }- },- "web/app/components/header/nav/index.tsx": {+ "web/app/components/header/account-setting/permission-group-list.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1},@@ -3994,8 +3940,16 @@"count": 1}},- "web/app/components/main-nav/components/web-apps-section.tsx": {- "jsx-a11y/no-autofocus": {+ "web/app/components/header/index.tsx": {+ "tailwindcss/no-duplicate-classes": {+ "count": 1+ }+ },+ "web/app/components/header/nav/index.tsx": {+ "jsx-a11y/click-events-have-key-events": {+ "count": 1+ },+ "jsx-a11y/no-static-element-interactions": {"count": 1}},@@ -4222,11 +4176,6 @@"count": 1}},- "web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx": {- "jsx-a11y/anchor-has-content": {- "count": 1- }- },"web/app/components/plugins/plugin-detail-panel/strategy-detail.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -4310,10 +4259,10 @@},"web/app/components/plugins/plugin-detail-panel/tool-selector/__tests__/index.spec.tsx": {"jsx-a11y/click-events-have-key-events": {- "count": 4+ "count": 5},"jsx-a11y/no-static-element-interactions": {- "count": 4+ "count": 5}},"web/app/components/plugins/plugin-detail-panel/tool-selector/components/index.ts": {@@ -4820,30 +4769,11 @@"count": 1}},- "web/app/components/tools/mcp/__tests__/index.spec.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 2- },- "jsx-a11y/no-static-element-interactions": {- "count": 2- }- },"web/app/components/tools/mcp/mcp-server-param-item.tsx": {"ts/no-explicit-any": {"count": 1}},- "web/app/components/tools/mcp/provider-card.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 2- },- "jsx-a11y/no-static-element-interactions": {- "count": 2- },- "ts/no-explicit-any": {- "count": 3- }- },"web/app/components/tools/provider/detail.tsx": {"jsx-a11y/anchor-has-content": {"count": 1@@ -5028,11 +4958,6 @@"count": 2}},- "web/app/components/workflow/block-selector/market-place-plugin/item.tsx": {- "erasable-syntax-only/enums": {- "count": 1- }- },"web/app/components/workflow/block-selector/market-place-plugin/list.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -5172,14 +5097,6 @@"count": 2}},- "web/app/components/workflow/header/run-and-history.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },"web/app/components/workflow/header/scroll-to-selected-node-button.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -7630,10 +7547,62 @@"count": 1}},- "web/service/access-control.ts": {- "@tanstack/query/exhaustive-deps": {+ "web/service/__tests__/use-tools.spec.tsx": {+ "no-restricted-imports": {"count": 1- },+ }+ },+ "web/service/access-control/__tests__/use-app-access-control.spec.tsx": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/__tests__/use-member-roles.spec.tsx": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/__tests__/use-permission-catalog.spec.tsx": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/__tests__/use-permission-keys.spec.tsx": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/__tests__/use-workspace-access-rules.spec.tsx": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/use-app-access-control.ts": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/use-member-roles.ts": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/use-permission-catalog.ts": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/use-permission-keys.ts": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/use-workspace-access-rules.ts": {+ "no-restricted-imports": {+ "count": 1+ }+ },+ "web/service/access-control/use-workspace-roles.ts": {"no-restricted-imports": {"count": 1}@@ -7886,9 +7855,6 @@"web/service/use-tools.ts": {"no-restricted-imports": {"count": 1- },- "ts/no-explicit-any": {- "count": 1}},"web/service/use-triggers.ts": {diff --git a/eslint.config.mjs b/eslint.config.mjsindex 1380ed67d2e..880ef4cdc56 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -7,6 +7,7 @@ import markdownPreferences from 'eslint-plugin-markdown-preferences'const GENERATED_IGNORES = ['**/storybook-static/','**/.next/',+ '**/.vinext/','web/next/','web/next-env.d.ts','**/dist/',diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.tsindex 9685823311d..64afc442406 100644--- a/packages/contracts/generated/api/console/agent/types.gen.ts+++ b/packages/contracts/generated/api/console/agent/types.gen.ts@@ -38,10 +38,12 @@ export type AgentAppDetailWithSite = {icon_type?: string | nullreadonly icon_url: string | nullid: string+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfig | nullname: string+ permission_keys?: Array<string>role?: string | nullsite?: Site | nulltags?: Array<Tag>@@ -307,10 +309,12 @@ export type AgentAppPartial = {readonly icon_url: string | nullid: stringis_starred?: boolean+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfigPartial | nullname: string+ permission_keys?: Array<string>published_reference_count?: numberpublished_references?: Array<AgentAppPublishedReferenceResponse>role?: string | null@@ -1446,10 +1450,12 @@ export type AgentAppDetailWithSiteWritable = {icon_background?: string | nullicon_type?: string | nullid: string+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfig | nullname: string+ permission_keys?: Array<string>role?: string | nullsite?: SiteWritable | nulltags?: Array<Tag>@@ -1476,10 +1482,12 @@ export type AgentAppPartialWritable = {icon_type?: string | nullid: stringis_starred?: boolean+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfigPartial | nullname: string+ permission_keys?: Array<string>published_reference_count?: numberpublished_references?: Array<AgentAppPublishedReferenceResponse>role?: string | nulldiff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.tsindex ac16494f3fe..7d6bd6f5eb2 100644--- a/packages/contracts/generated/api/console/agent/zod.gen.ts+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts@@ -618,10 +618,12 @@ export const zAgentAppPartial = z.object({icon_url: z.string().nullable(),id: z.string(),is_starred: z.boolean().optional().default(false),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfigPartial.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),published_reference_count: z.int().optional().default(0),published_references: z.array(zAgentAppPublishedReferenceResponse).optional(),role: z.string().nullish(),@@ -680,10 +682,12 @@ export const zAgentAppDetailWithSite = z.object({icon_type: z.string().nullish(),icon_url: z.string().nullable(),id: z.string(),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfig.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),role: z.string().nullish(),site: zSite.nullish(),tags: z.array(zTag).optional(),@@ -2014,10 +2018,12 @@ export const zAgentAppPartialWritable = z.object({icon_type: z.string().nullish(),id: z.string(),is_starred: z.boolean().optional().default(false),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfigPartial.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),published_reference_count: z.int().optional().default(0),published_references: z.array(zAgentAppPublishedReferenceResponse).optional(),role: z.string().nullish(),@@ -2077,10 +2083,12 @@ export const zAgentAppDetailWithSiteWritable = z.object({icon_background: z.string().nullish(),icon_type: z.string().nullish(),id: z.string(),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfig.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),role: z.string().nullish(),site: zSiteWritable.nullish(),tags: z.array(zTag).optional(),diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.tsindex 26a1b627184..904252c77eb 100644--- a/packages/contracts/generated/api/console/apps/types.gen.ts+++ b/packages/contracts/generated/api/console/apps/types.gen.ts@@ -37,10 +37,12 @@ export type AppDetailWithSite = {icon_type?: string | nullreadonly icon_url: string | nullid: string+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfig | nullname: string+ permission_keys?: Array<string>site?: Site | nulltags?: Array<Tag>tracing?: JsonValue | null@@ -69,6 +71,7 @@ export type Import = {error?: stringid: stringimported_dsl_version?: string+ permission_keys?: Array<string>status: ImportStatus}@@ -312,8 +315,10 @@ export type AppDetail = {icon?: string | nullicon_background?: string | nullid: string+ maintainer?: string | nullmode_compatible_with_agent: stringname: string+ permission_keys?: Array<string>tags?: Array<Tag>tracing?: JsonValue | nullupdated_at?: number | null@@ -413,6 +418,7 @@ export type ConvertToWorkflowPayload = {export type NewAppResponse = {new_app_id: string+ permission_keys?: Array<string>}export type CopyAppPayload = {@@ -1163,10 +1169,12 @@ export type AppPartial = {readonly icon_url: string | nullid: stringis_starred?: boolean+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfigPartial | nullname: string+ permission_keys?: Array<string>tags?: Array<Tag>updated_at?: number | nullupdated_by?: string | null@@ -1616,6 +1624,9 @@ export type AccountWithRole = {last_login_at?: number | nullname: stringrole: string+ roles?: Array<{+ [key: string]: string+ }>status: string}@@ -2592,10 +2603,12 @@ export type AppDetailWithSiteWritable = {icon_background?: string | nullicon_type?: string | nullid: string+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfig | nullname: string+ permission_keys?: Array<string>site?: SiteWritable | nulltags?: Array<Tag>tracing?: JsonValue | null@@ -2643,10 +2656,12 @@ export type AppPartialWritable = {icon_type?: string | nullid: stringis_starred?: boolean+ maintainer?: string | nullmax_active_requests?: number | nullmode: stringmodel_config?: ModelConfigPartial | nullname: string+ permission_keys?: Array<string>tags?: Array<Tag>updated_at?: number | nullupdated_by?: string | nulldiff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.tsindex 4449b5c1c70..4a6f397bcbd 100644--- a/packages/contracts/generated/api/console/apps/zod.gen.ts+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts@@ -270,6 +270,7 @@ export const zConvertToWorkflowPayload = z.object({*/export const zNewAppResponse = z.object({new_app_id: z.string(),+ permission_keys: z.array(z.string()).optional(),})/**@@ -906,6 +907,7 @@ export const zImport = z.object({error: z.string().optional().default(''),id: z.string(),imported_dsl_version: z.string().optional().default(''),+ permission_keys: z.array(z.string()).optional(),status: zImportStatus,})@@ -1485,6 +1487,7 @@ export const zAccountWithRole = z.object({last_login_at: z.int().nullish(),name: z.string(),role: z.string(),+ roles: z.array(z.record(z.string(), z.string())).optional(),status: z.string(),})@@ -1954,10 +1957,12 @@ export const zAppPartial = z.object({icon_url: z.string().nullable(),id: z.string(),is_starred: z.boolean().optional().default(false),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfigPartial.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),tags: z.array(zTag).optional(),updated_at: z.int().nullish(),updated_by: z.string().nullish(),@@ -2012,10 +2017,12 @@ export const zAppDetailWithSite = z.object({icon_type: z.string().nullish(),icon_url: z.string().nullable(),id: z.string(),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfig.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),site: zSite.nullish(),tags: z.array(zTag).optional(),tracing: zJsonValue.nullish(),@@ -2039,8 +2046,10 @@ export const zAppDetail = z.object({icon: z.string().nullish(),icon_background: z.string().nullish(),id: z.string(),+ maintainer: z.string().nullish(),mode_compatible_with_agent: z.string(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),tags: z.array(zTag).optional(),tracing: zJsonValue.nullish(),updated_at: z.int().nullish(),@@ -3481,10 +3490,12 @@ export const zAppPartialWritable = z.object({icon_type: z.string().nullish(),id: z.string(),is_starred: z.boolean().optional().default(false),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfigPartial.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),tags: z.array(zTag).optional(),updated_at: z.int().nullish(),updated_by: z.string().nullish(),@@ -3540,10 +3551,12 @@ export const zAppDetailWithSiteWritable = z.object({icon_background: z.string().nullish(),icon_type: z.string().nullish(),id: z.string(),+ maintainer: z.string().nullish(),max_active_requests: z.int().nullish(),mode: z.string(),model_config: zModelConfig.nullish(),name: z.string(),+ permission_keys: z.array(z.string()).optional(),site: zSiteWritable.nullish(),tags: z.array(zTag).optional(),tracing: zJsonValue.nullish(),diff --git a/packages/contracts/generated/api/console/datasets/types.gen.ts b/packages/contracts/generated/api/console/datasets/types.gen.tsindex 987837ab4ed..f904ea7d717 100644--- a/packages/contracts/generated/api/console/datasets/types.gen.ts+++ b/packages/contracts/generated/api/console/datasets/types.gen.ts@@ -45,8 +45,10 @@ export type DatasetDetailResponse = {indexing_technique: string | nullis_multimodal: booleanis_published: boolean+ maintainer?: string | nullname: stringpermission: string+ permission_keys?: Array<string>pipeline_id: string | nullprovider: stringretrieval_model_dict: DatasetRetrievalModelResponse@@ -120,6 +122,7 @@ export type DatasetDetail = {is_published?: booleanname?: stringpermission?: string+ permission_keys?: Array<string>pipeline_id?: stringprovider?: stringretrieval_model_dict?: DatasetRetrievalModel@@ -264,9 +267,11 @@ export type DatasetDetailWithPartialMembersResponse = {indexing_technique: string | nullis_multimodal: booleanis_published: boolean+ maintainer?: string | nullname: stringpartial_member_list?: Array<string> | nullpermission: string+ permission_keys?: Array<string>pipeline_id: string | nullprovider: stringretrieval_model_dict: DatasetRetrievalModelResponse@@ -566,9 +571,11 @@ export type DatasetListItemResponse = {indexing_technique: string | nullis_multimodal: booleanis_published: boolean+ maintainer?: string | nullname: stringpartial_member_list: Array<string>permission: string+ permission_keys?: Array<string>pipeline_id: string | nullprovider: stringretrieval_model_dict: DatasetRetrievalModelResponsediff --git a/packages/contracts/generated/api/console/datasets/zod.gen.ts b/packages/contracts/generated/api/console/datasets/zod.gen.tsindex fc6a33c3e65..10ceb11cb5d 100644--- a/packages/contracts/generated/api/console/datasets/zod.gen.ts+++ b/packages/contracts/generated/api/console/datasets/zod.gen.ts@@ -963,8 +963,10 @@ export const zDatasetDetailResponse = z.object({indexing_technique: z.string().nullable(),is_multimodal: z.boolean(),is_published: z.boolean(),+ maintainer: z.string().nullish(),name: z.string(),permission: z.string(),+ permission_keys: z.array(z.string()).optional(),pipeline_id: z.string().nullable(),provider: z.string(),retrieval_model_dict: zDatasetRetrievalModelResponse,@@ -1004,9 +1006,11 @@ export const zDatasetDetailWithPartialMembersResponse = z.object({indexing_technique: z.string().nullable(),is_multimodal: z.boolean(),is_published: z.boolean(),+ maintainer: z.string().nullish(),name: z.string(),partial_member_list: z.array(z.string()).nullish(),permission: z.string(),+ permission_keys: z.array(z.string()).optional(),pipeline_id: z.string().nullable(),provider: z.string(),retrieval_model_dict: zDatasetRetrievalModelResponse,@@ -1046,9 +1050,11 @@ export const zDatasetListItemResponse = z.object({indexing_technique: z.string().nullable(),is_multimodal: z.boolean(),is_published: z.boolean(),+ maintainer: z.string().nullish(),name: z.string(),partial_member_list: z.array(z.string()),permission: z.string(),+ permission_keys: z.array(z.string()).optional(),pipeline_id: z.string().nullable(),provider: z.string(),retrieval_model_dict: zDatasetRetrievalModelResponse,@@ -1133,6 +1139,7 @@ export const zDatasetDetail = z.object({is_published: z.boolean().optional(),name: z.string().optional(),permission: z.string().optional(),+ permission_keys: z.array(z.string()).optional(),pipeline_id: z.string().optional(),provider: z.string().optional(),retrieval_model_dict: zDatasetRetrievalModel.optional(),diff --git a/packages/contracts/generated/api/console/rag/types.gen.ts b/packages/contracts/generated/api/console/rag/types.gen.tsindex 49572f971b7..b9862a8d1e8 100644--- a/packages/contracts/generated/api/console/rag/types.gen.ts+++ b/packages/contracts/generated/api/console/rag/types.gen.ts@@ -53,8 +53,10 @@ export type DatasetDetailResponse = {indexing_technique: string | nullis_multimodal: booleanis_published: boolean+ maintainer?: string | nullname: stringpermission: string+ permission_keys?: Array<string>pipeline_id: string | nullprovider: stringretrieval_model_dict: DatasetRetrievalModelResponsediff --git a/packages/contracts/generated/api/console/rag/zod.gen.ts b/packages/contracts/generated/api/console/rag/zod.gen.tsindex 71ed29509a5..717db30baa7 100644--- a/packages/contracts/generated/api/console/rag/zod.gen.ts+++ b/packages/contracts/generated/api/console/rag/zod.gen.ts@@ -656,8 +656,10 @@ export const zDatasetDetailResponse = z.object({indexing_technique: z.string().nullable(),is_multimodal: z.boolean(),is_published: z.boolean(),+ maintainer: z.string().nullish(),name: z.string(),permission: z.string(),+ permission_keys: z.array(z.string()).optional(),pipeline_id: z.string().nullable(),provider: z.string(),retrieval_model_dict: zDatasetRetrievalModelResponse,diff --git a/packages/contracts/generated/api/console/system-features/types.gen.ts b/packages/contracts/generated/api/console/system-features/types.gen.tsindex 01c77ed076d..f1dcc7fc4b4 100644--- a/packages/contracts/generated/api/console/system-features/types.gen.ts+++ b/packages/contracts/generated/api/console/system-features/types.gen.ts@@ -23,6 +23,7 @@ export type SystemFeatureModel = {max_plugin_package_size: numberplugin_installation_permission: PluginInstallationPermissionModelplugin_manager: PluginManagerModel+ rbac_enabled: booleansso_enforced_for_signin: booleansso_enforced_for_signin_protocol: stringwebapp_auth: WebAppAuthModeldiff --git a/packages/contracts/generated/api/console/system-features/zod.gen.ts b/packages/contracts/generated/api/console/system-features/zod.gen.tsindex a7a8946ad50..80b27e7843a 100644--- a/packages/contracts/generated/api/console/system-features/zod.gen.ts+++ b/packages/contracts/generated/api/console/system-features/zod.gen.ts@@ -126,6 +126,7 @@ export const zSystemFeatureModel = z.object({restrict_to_marketplace_only: false,}),plugin_manager: zPluginManagerModel.default({ enabled: false }),+ rbac_enabled: z.boolean().default(false),sso_enforced_for_signin: z.boolean().default(false),sso_enforced_for_signin_protocol: z.string().default(''),webapp_auth: zWebAppAuthModel.default({diff --git a/packages/contracts/generated/api/console/trial-apps/types.gen.ts b/packages/contracts/generated/api/console/trial-apps/types.gen.tsindex 5021da0afdf..894da1102ee 100644--- a/packages/contracts/generated/api/console/trial-apps/types.gen.ts+++ b/packages/contracts/generated/api/console/trial-apps/types.gen.ts@@ -22,6 +22,7 @@ export type TrialAppDetailWithSite = {mode?: stringmodel_config?: TrialAppModelConfigname?: string+ permission_keys?: Array<string>site?: TrialSitetags?: Array<TrialTag>updated_at?: number@@ -269,6 +270,7 @@ export type TrialDataset = {indexing_technique?: stringname?: stringpermission?: string+ permission_keys?: Array<string>}export type JsonObject = {diff --git a/packages/contracts/generated/api/console/trial-apps/zod.gen.ts b/packages/contracts/generated/api/console/trial-apps/zod.gen.tsindex 7e6b5fbb6d4..b8768790ef9 100644--- a/packages/contracts/generated/api/console/trial-apps/zod.gen.ts+++ b/packages/contracts/generated/api/console/trial-apps/zod.gen.ts@@ -237,6 +237,7 @@ export const zTrialAppDetailWithSite = z.object({mode: z.string().optional(),model_config: zTrialAppModelConfig.optional(),name: z.string().optional(),+ permission_keys: z.array(z.string()).optional(),site: zTrialSite.optional(),tags: z.array(zTrialTag).optional(),updated_at: z.coerce@@ -286,6 +287,7 @@ export const zTrialDataset = z.object({indexing_technique: z.string().optional(),name: z.string().optional(),permission: z.string().optional(),+ permission_keys: z.array(z.string()).optional(),})export const zTrialDatasetList = z.object({diff --git a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts b/packages/contracts/generated/api/console/workspaces/orpc.gen.tsindex 630e8f6b354..7e676564999 100644--- a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts+++ b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts@@ -19,6 +19,14 @@ import {zDeleteWorkspacesCurrentModelProvidersByProviderModelsCredentialsResponse,zDeleteWorkspacesCurrentModelProvidersByProviderModelsPath,zDeleteWorkspacesCurrentModelProvidersByProviderModelsResponse,+ zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath,+ zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse,+ zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath,+ zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse,+ zDeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsPath,+ zDeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse,+ zDeleteWorkspacesCurrentRbacRolesByRoleIdPath,+ zDeleteWorkspacesCurrentRbacRolesByRoleIdResponse,zDeleteWorkspacesCurrentToolProviderBuiltinByProviderOauthCustomClientPath,zDeleteWorkspacesCurrentToolProviderBuiltinByProviderOauthCustomClientResponse,zDeleteWorkspacesCurrentToolProviderMcpBody,@@ -90,6 +98,50 @@ import {zGetWorkspacesCurrentPluginTasksByTaskIdResponse,zGetWorkspacesCurrentPluginTasksQuery,zGetWorkspacesCurrentPluginTasksResponse,+ zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath,+ zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse,+ zGetWorkspacesCurrentRbacAccessPoliciesResponse,+ zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath,+ zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse,+ zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsPath,+ zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponse,+ zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyPath,+ zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponse,+ zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesPath,+ zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponse,+ zGetWorkspacesCurrentRbacAppsByAppIdWhitelistPath,+ zGetWorkspacesCurrentRbacAppsByAppIdWhitelistResponse,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsPath,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsPath,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponse,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyPath,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponse,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesPath,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponse,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistPath,+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse,+ zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath,+ zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse,+ zGetWorkspacesCurrentRbacMyPermissionsResponse,+ zGetWorkspacesCurrentRbacRolePermissionsCatalogAppResponse,+ zGetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponse,+ zGetWorkspacesCurrentRbacRolePermissionsCatalogResponse,+ zGetWorkspacesCurrentRbacRolesByRoleIdMembersPath,+ zGetWorkspacesCurrentRbacRolesByRoleIdMembersResponse,+ zGetWorkspacesCurrentRbacRolesByRoleIdPath,+ zGetWorkspacesCurrentRbacRolesByRoleIdResponse,+ zGetWorkspacesCurrentRbacRolesResponse,+ zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsPath,+ zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponse,+ zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsPath,+ zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponse,+ zGetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponse,+ zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsPath,+ zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponse,+ zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsPath,+ zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponse,+ zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponse,zGetWorkspacesCurrentToolLabelsResponse,zGetWorkspacesCurrentToolProviderApiGetQuery,zGetWorkspacesCurrentToolProviderApiGetResponse,@@ -251,6 +303,12 @@ import {zPostWorkspacesCurrentPluginUploadGithubBody,zPostWorkspacesCurrentPluginUploadGithubResponse,zPostWorkspacesCurrentPluginUploadPkgResponse,+ zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyPath,+ zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse,+ zPostWorkspacesCurrentRbacAccessPoliciesResponse,+ zPostWorkspacesCurrentRbacRolesByRoleIdCopyPath,+ zPostWorkspacesCurrentRbacRolesByRoleIdCopyResponse,+ zPostWorkspacesCurrentRbacRolesResponse,zPostWorkspacesCurrentResponse,zPostWorkspacesCurrentToolProviderApiAddBody,zPostWorkspacesCurrentToolProviderApiAddResponse,@@ -326,6 +384,28 @@ import {zPutWorkspacesCurrentModelProvidersByProviderModelsCredentialsBody,zPutWorkspacesCurrentModelProvidersByProviderModelsCredentialsPath,zPutWorkspacesCurrentModelProvidersByProviderModelsCredentialsResponse,+ zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath,+ zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse,+ zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockPath,+ zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse,+ zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockPath,+ zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse,+ zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesPath,+ zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponse,+ zPutWorkspacesCurrentRbacAppsByAppIdWhitelistPath,+ zPutWorkspacesCurrentRbacAppsByAppIdWhitelistResponse,+ zPutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesPath,+ zPutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponse,+ zPutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistPath,+ zPutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse,+ zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath,+ zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse,+ zPutWorkspacesCurrentRbacRolesByRoleIdPath,+ zPutWorkspacesCurrentRbacRolesByRoleIdResponse,+ zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsPath,+ zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponse,+ zPutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsPath,+ zPutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponse,zPutWorkspacesCurrentToolProviderMcpBody,zPutWorkspacesCurrentToolProviderMcpResponse,} from './zod.gen'@@ -2017,7 +2097,840 @@ export const plugin2 = {byCategory,}+export const post44 = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'postWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopy',+ path: '/workspaces/current/rbac/access-policies/{policy_id}/copy',+ successStatus: 201,+ tags: ['console'],+ })+ .input(z.object({ params: zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyPath }))+ .output(zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse)++export const copy = {+ post: post44,+}++export const delete9 = oc+ .route({+ inputStructure: 'detailed',+ method: 'DELETE',+ operationId: 'deleteWorkspacesCurrentRbacAccessPoliciesByPolicyId',+ path: '/workspaces/current/rbac/access-policies/{policy_id}',+ tags: ['console'],+ })+ .input(z.object({ params: zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath }))+ .output(zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse)+export const get33 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacAccessPoliciesByPolicyId',+ path: '/workspaces/current/rbac/access-policies/{policy_id}',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath }))+ .output(zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse)++export const put4 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacAccessPoliciesByPolicyId',+ path: '/workspaces/current/rbac/access-policies/{policy_id}',+ tags: ['console'],+ })+ .input(z.object({ params: zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath }))+ .output(zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse)++export const byPolicyId = {+ delete: delete9,+ get: get33,+ put: put4,+ copy,+}++export const get34 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacAccessPolicies',+ path: '/workspaces/current/rbac/access-policies',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacAccessPoliciesResponse)++export const post45 = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'postWorkspacesCurrentRbacAccessPolicies',+ path: '/workspaces/current/rbac/access-policies',+ successStatus: 201,+ tags: ['console'],+ })+ .output(zPostWorkspacesCurrentRbacAccessPoliciesResponse)++export const accessPolicies = {+ get: get34,+ post: post45,+ byPolicyId,+}++export const put5 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLock',+ path: '/workspaces/current/rbac/access-policy-bindings/{binding_id}/lock',+ tags: ['console'],+ })+ .input(z.object({ params: zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockPath }))+ .output(zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse)++export const lock = {+ put: put5,+}++export const put6 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlock',+ path: '/workspaces/current/rbac/access-policy-bindings/{binding_id}/unlock',+ tags: ['console'],+ })+ .input(z.object({ params: zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockPath }))+ .output(zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse)++export const unlock = {+ put: put6,+}++export const byBindingId = {+ lock,+ unlock,+}++export const accessPolicyBindings = {+ byBindingId,+}++export const delete10 = oc+ .route({+ inputStructure: 'detailed',+ method: 'DELETE',+ operationId: 'deleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindings',+ path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath,+ }),+ )+ .output(zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse)++export const get35 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindings',+ path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath,+ }),+ )+ .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse)++export const memberBindings = {+ delete: delete10,+ get: get35,+}++export const get36 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindings',+ path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/role-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsPath,+ }),+ )+ .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponse)++export const roleBindings = {+ get: get36,+}++export const byPolicyId2 = {+ memberBindings,+ roleBindings,+}++export const accessPolicies2 = {+ byPolicyId: byPolicyId2,+}++export const get37 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPolicy',+ path: '/workspaces/current/rbac/apps/{app_id}/access-policy',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyPath }))+ .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponse)++export const accessPolicy = {+ get: get37,+}++export const get38 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacAppsByAppIdUserAccessPolicies',+ path: '/workspaces/current/rbac/apps/{app_id}/user-access-policies',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesPath }))+ .output(zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponse)++export const userAccessPolicies = {+ get: get38,+}++export const put7 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPolicies',+ path: '/workspaces/current/rbac/apps/{app_id}/users/{target_account_id}/access-policies',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesPath,+ }),+ )+ .output(zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponse)++export const accessPolicies3 = {+ put: put7,+}++export const byTargetAccountId = {+ accessPolicies: accessPolicies3,+}++export const users = {+ byTargetAccountId,+}++export const get39 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacAppsByAppIdWhitelist',+ path: '/workspaces/current/rbac/apps/{app_id}/whitelist',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacAppsByAppIdWhitelistPath }))+ .output(zGetWorkspacesCurrentRbacAppsByAppIdWhitelistResponse)++export const put8 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacAppsByAppIdWhitelist',+ path: '/workspaces/current/rbac/apps/{app_id}/whitelist',+ tags: ['console'],+ })+ .input(z.object({ params: zPutWorkspacesCurrentRbacAppsByAppIdWhitelistPath }))+ .output(zPutWorkspacesCurrentRbacAppsByAppIdWhitelistResponse)++export const whitelist = {+ get: get39,+ put: put8,+}++export const byAppId = {+ accessPolicies: accessPolicies2,+ accessPolicy,+ userAccessPolicies,+ users,+ whitelist,+}++export const apps = {+ byAppId,+}++export const delete11 = oc+ .route({+ inputStructure: 'detailed',+ method: 'DELETE',+ operationId:+ 'deleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindings',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/member-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params:+ zDeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsPath,+ }),+ )+ .output(+ zDeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse,+ )++export const get40 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId:+ 'getWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindings',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/member-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params:+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsPath,+ }),+ )+ .output(+ zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse,+ )++export const memberBindings2 = {+ delete: delete11,+ get: get40,+}++export const get41 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindings',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/role-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsPath,+ }),+ )+ .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponse)++export const roleBindings2 = {+ get: get41,+}++export const byPolicyId3 = {+ memberBindings: memberBindings2,+ roleBindings: roleBindings2,+}++export const accessPolicies4 = {+ byPolicyId: byPolicyId3,+}++export const get42 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicy',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/access-policy',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyPath }))+ .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponse)++export const accessPolicy2 = {+ get: get42,+}++export const get43 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPolicies',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/user-access-policies',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesPath }))+ .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponse)++export const userAccessPolicies2 = {+ get: get43,+}++export const put9 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPolicies',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/users/{target_account_id}/access-policies',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zPutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesPath,+ }),+ )+ .output(zPutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponse)++export const accessPolicies5 = {+ put: put9,+}++export const byTargetAccountId2 = {+ accessPolicies: accessPolicies5,+}++export const users2 = {+ byTargetAccountId: byTargetAccountId2,+}++export const get44 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacDatasetsByDatasetIdWhitelist',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/whitelist',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistPath }))+ .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse)++export const put10 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacDatasetsByDatasetIdWhitelist',+ path: '/workspaces/current/rbac/datasets/{dataset_id}/whitelist',+ tags: ['console'],+ })+ .input(z.object({ params: zPutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistPath }))+ .output(zPutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse)++export const whitelist2 = {+ get: get44,+ put: put10,+}++export const byDatasetId = {+ accessPolicies: accessPolicies4,+ accessPolicy: accessPolicy2,+ userAccessPolicies: userAccessPolicies2,+ users: users2,+ whitelist: whitelist2,+}++export const datasets = {+ byDatasetId,+}++export const get45 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacMembersByMemberIdRbacRoles',+ path: '/workspaces/current/rbac/members/{member_id}/rbac-roles',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath }))+ .output(zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse)++export const put11 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacMembersByMemberIdRbacRoles',+ path: '/workspaces/current/rbac/members/{member_id}/rbac-roles',+ tags: ['console'],+ })+ .input(z.object({ params: zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath }))+ .output(zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse)++export const rbacRoles = {+ get: get45,+ put: put11,+}++export const byMemberId2 = {+ rbacRoles,+}++export const members2 = {+ byMemberId: byMemberId2,+}++export const get46 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacMyPermissions',+ path: '/workspaces/current/rbac/my-permissions',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacMyPermissionsResponse)++export const myPermissions = {+ get: get46,+}++export const get47 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacRolePermissionsCatalogApp',+ path: '/workspaces/current/rbac/role-permissions/catalog/app',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacRolePermissionsCatalogAppResponse)++export const app = {+ get: get47,+}++export const get48 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacRolePermissionsCatalogDataset',+ path: '/workspaces/current/rbac/role-permissions/catalog/dataset',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponse)++export const dataset = {+ get: get48,+}++export const get49 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacRolePermissionsCatalog',+ path: '/workspaces/current/rbac/role-permissions/catalog',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacRolePermissionsCatalogResponse)++export const catalog = {+ get: get49,+ app,+ dataset,+}++export const rolePermissions = {+ catalog,+}++export const post46 = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'postWorkspacesCurrentRbacRolesByRoleIdCopy',+ path: '/workspaces/current/rbac/roles/{role_id}/copy',+ successStatus: 201,+ tags: ['console'],+ })+ .input(z.object({ params: zPostWorkspacesCurrentRbacRolesByRoleIdCopyPath }))+ .output(zPostWorkspacesCurrentRbacRolesByRoleIdCopyResponse)++export const copy2 = {+ post: post46,+}++export const get50 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacRolesByRoleIdMembers',+ path: '/workspaces/current/rbac/roles/{role_id}/members',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacRolesByRoleIdMembersPath }))+ .output(zGetWorkspacesCurrentRbacRolesByRoleIdMembersResponse)++export const members3 = {+ get: get50,+}++export const delete12 = oc+ .route({+ inputStructure: 'detailed',+ method: 'DELETE',+ operationId: 'deleteWorkspacesCurrentRbacRolesByRoleId',+ path: '/workspaces/current/rbac/roles/{role_id}',+ tags: ['console'],+ })+ .input(z.object({ params: zDeleteWorkspacesCurrentRbacRolesByRoleIdPath }))+ .output(zDeleteWorkspacesCurrentRbacRolesByRoleIdResponse)++export const get51 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacRolesByRoleId',+ path: '/workspaces/current/rbac/roles/{role_id}',+ tags: ['console'],+ })+ .input(z.object({ params: zGetWorkspacesCurrentRbacRolesByRoleIdPath }))+ .output(zGetWorkspacesCurrentRbacRolesByRoleIdResponse)++export const put12 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacRolesByRoleId',+ path: '/workspaces/current/rbac/roles/{role_id}',+ tags: ['console'],+ })+ .input(z.object({ params: zPutWorkspacesCurrentRbacRolesByRoleIdPath }))+ .output(zPutWorkspacesCurrentRbacRolesByRoleIdResponse)++export const byRoleId = {+ delete: delete12,+ get: get51,+ put: put12,+ copy: copy2,+ members: members3,+}++export const get52 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacRoles',+ path: '/workspaces/current/rbac/roles',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacRolesResponse)++export const post47 = oc+ .route({+ inputStructure: 'detailed',+ method: 'POST',+ operationId: 'postWorkspacesCurrentRbacRoles',+ path: '/workspaces/current/rbac/roles',+ successStatus: 201,+ tags: ['console'],+ })+ .output(zPostWorkspacesCurrentRbacRolesResponse)++export const roles = {+ get: get52,+ post: post47,+ byRoleId,+}++export const put13 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindings',+ path: '/workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsPath,+ }),+ )+ .output(zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponse)++export const bindings = {+ put: put13,+}++export const get53 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindings',+ path: '/workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/member-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsPath,+ }),+ )+ .output(zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponse)++export const memberBindings3 = {+ get: get53,+}++export const get54 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindings',+ path: '/workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/role-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsPath,+ }),+ )+ .output(zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponse)++export const roleBindings3 = {+ get: get54,+}++export const byPolicyId4 = {+ bindings,+ memberBindings: memberBindings3,+ roleBindings: roleBindings3,+}++export const accessPolicies6 = {+ byPolicyId: byPolicyId4,+}++export const get55 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacWorkspaceAppsAccessPolicy',+ path: '/workspaces/current/rbac/workspace/apps/access-policy',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponse)++export const accessPolicy3 = {+ get: get55,+}++export const apps2 = {+ accessPolicies: accessPolicies6,+ accessPolicy: accessPolicy3,+}++export const put14 = oc+ .route({+ inputStructure: 'detailed',+ method: 'PUT',+ operationId: 'putWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindings',+ path: '/workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zPutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsPath,+ }),+ )+ .output(zPutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponse)++export const bindings2 = {+ put: put14,+}++export const get56 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindings',+ path: '/workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/member-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsPath,+ }),+ )+ .output(zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponse)++export const memberBindings4 = {+ get: get56,+}++export const get57 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindings',+ path: '/workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/role-bindings',+ tags: ['console'],+ })+ .input(+ z.object({+ params: zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsPath,+ }),+ )+ .output(zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponse)++export const roleBindings4 = {+ get: get57,+}++export const byPolicyId5 = {+ bindings: bindings2,+ memberBindings: memberBindings4,+ roleBindings: roleBindings4,+}++export const accessPolicies7 = {+ byPolicyId: byPolicyId5,+}++export const get58 = oc+ .route({+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicy',+ path: '/workspaces/current/rbac/workspace/datasets/access-policy',+ tags: ['console'],+ })+ .output(zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponse)++export const accessPolicy4 = {+ get: get58,+}++export const datasets2 = {+ accessPolicies: accessPolicies7,+ accessPolicy: accessPolicy4,+}++export const workspace = {+ apps: apps2,+ datasets: datasets2,+}++export const rbac = {+ accessPolicies,+ accessPolicyBindings,+ apps,+ datasets,+ members: members2,+ myPermissions,+ rolePermissions,+ roles,+ workspace,+}++export const get59 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2028,10 +2941,10 @@ export const get33 = oc.output(zGetWorkspacesCurrentToolLabelsResponse)export const toolLabels = {- get: get33,+ get: get59,}-export const post44 = oc+export const post48 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2043,10 +2956,10 @@ export const post44 = oc.output(zPostWorkspacesCurrentToolProviderApiAddResponse)export const add = {- post: post44,+ post: post48,}-export const post45 = oc+export const post49 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2057,11 +2970,11 @@ export const post45 = oc.input(z.object({ body: zPostWorkspacesCurrentToolProviderApiDeleteBody })).output(zPostWorkspacesCurrentToolProviderApiDeleteResponse)-export const delete9 = {- post: post45,+export const delete13 = {+ post: post49,}-export const get34 = oc+export const get60 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2072,11 +2985,11 @@ export const get34 = oc.input(z.object({ query: zGetWorkspacesCurrentToolProviderApiGetQuery })).output(zGetWorkspacesCurrentToolProviderApiGetResponse)-export const get35 = {- get: get34,+export const get61 = {+ get: get60,}-export const get36 = oc+export const get62 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2088,10 +3001,10 @@ export const get36 = oc.output(zGetWorkspacesCurrentToolProviderApiRemoteResponse)export const remote = {- get: get36,+ get: get62,}-export const post46 = oc+export const post50 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2103,10 +3016,10 @@ export const post46 = oc.output(zPostWorkspacesCurrentToolProviderApiSchemaResponse)export const schema = {- post: post46,+ post: post50,}-export const post47 = oc+export const post51 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2118,14 +3031,14 @@ export const post47 = oc.output(zPostWorkspacesCurrentToolProviderApiTestPreResponse)export const pre = {- post: post47,+ post: post51,}export const test = {pre,}-export const get37 = oc+export const get63 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2137,10 +3050,10 @@ export const get37 = oc.output(zGetWorkspacesCurrentToolProviderApiToolsResponse)export const tools = {- get: get37,+ get: get63,}-export const post48 = oc+export const post52 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2152,13 +3065,13 @@ export const post48 = oc.output(zPostWorkspacesCurrentToolProviderApiUpdateResponse)export const update2 = {- post: post48,+ post: post52,}export const api = {add,- delete: delete9,- get: get35,+ delete: delete13,+ get: get61,remote,schema,test,@@ -2166,7 +3079,7 @@ export const api = {update: update2,}-export const post49 = oc+export const post53 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2183,10 +3096,10 @@ export const post49 = oc.output(zPostWorkspacesCurrentToolProviderBuiltinByProviderAddResponse)export const add2 = {- post: post49,+ post: post53,}-export const get38 = oc+export const get64 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2203,10 +3116,10 @@ export const get38 = oc.output(zGetWorkspacesCurrentToolProviderBuiltinByProviderCredentialInfoResponse)export const info = {- get: get38,+ get: get64,}-export const get39 = oc+export const get65 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2226,7 +3139,7 @@ export const get39 = oc)export const byCredentialType = {- get: get39,+ get: get65,}export const schema2 = {@@ -2238,7 +3151,7 @@ export const credential = {schema: schema2,}-export const get40 = oc+export const get66 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2255,10 +3168,10 @@ export const get40 = oc.output(zGetWorkspacesCurrentToolProviderBuiltinByProviderCredentialsResponse)export const credentials3 = {- get: get40,+ get: get66,}-export const post50 = oc+export const post54 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2275,10 +3188,10 @@ export const post50 = oc.output(zPostWorkspacesCurrentToolProviderBuiltinByProviderDefaultCredentialResponse)export const defaultCredential = {- post: post50,+ post: post54,}-export const post51 = oc+export const post55 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2294,11 +3207,11 @@ export const post51 = oc).output(zPostWorkspacesCurrentToolProviderBuiltinByProviderDeleteResponse)-export const delete10 = {- post: post51,+export const delete14 = {+ post: post55,}-export const get41 = oc+export const get67 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2310,10 +3223,10 @@ export const get41 = oc.output(zGetWorkspacesCurrentToolProviderBuiltinByProviderIconResponse)export const icon2 = {- get: get41,+ get: get67,}-export const get42 = oc+export const get68 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2325,10 +3238,10 @@ export const get42 = oc.output(zGetWorkspacesCurrentToolProviderBuiltinByProviderInfoResponse)export const info2 = {- get: get42,+ get: get68,}-export const get43 = oc+export const get69 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2342,10 +3255,10 @@ export const get43 = oc.output(zGetWorkspacesCurrentToolProviderBuiltinByProviderOauthClientSchemaResponse)export const clientSchema = {- get: get43,+ get: get69,}-export const delete11 = oc+export const delete15 = oc.route({inputStructure: 'detailed',method: 'DELETE',@@ -2360,7 +3273,7 @@ export const delete11 = oc).output(zDeleteWorkspacesCurrentToolProviderBuiltinByProviderOauthCustomClientResponse)-export const get44 = oc+export const get70 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2373,7 +3286,7 @@ export const get44 = oc).output(zGetWorkspacesCurrentToolProviderBuiltinByProviderOauthCustomClientResponse)-export const post52 = oc+export const post56 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2390,9 +3303,9 @@ export const post52 = oc.output(zPostWorkspacesCurrentToolProviderBuiltinByProviderOauthCustomClientResponse)export const customClient = {- delete: delete11,- get: get44,- post: post52,+ delete: delete15,+ get: get70,+ post: post56,}export const oauth = {@@ -2400,7 +3313,7 @@ export const oauth = {customClient,}-export const get45 = oc+export const get71 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2412,10 +3325,10 @@ export const get45 = oc.output(zGetWorkspacesCurrentToolProviderBuiltinByProviderToolsResponse)export const tools2 = {- get: get45,+ get: get71,}-export const post53 = oc+export const post57 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2432,7 +3345,7 @@ export const post53 = oc.output(zPostWorkspacesCurrentToolProviderBuiltinByProviderUpdateResponse)export const update3 = {- post: post53,+ post: post57,}export const byProvider2 = {@@ -2440,7 +3353,7 @@ export const byProvider2 = {credential,credentials: credentials3,defaultCredential,- delete: delete10,+ delete: delete14,icon: icon2,info: info2,oauth,@@ -2452,7 +3365,7 @@ export const builtin = {byProvider: byProvider2,}-export const post54 = oc+export const post58 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2464,10 +3377,10 @@ export const post54 = oc.output(zPostWorkspacesCurrentToolProviderMcpAuthResponse)export const auth = {- post: post54,+ post: post58,}-export const get46 = oc+export const get72 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2479,14 +3392,14 @@ export const get46 = oc.output(zGetWorkspacesCurrentToolProviderMcpToolsByProviderIdResponse)export const byProviderId = {- get: get46,+ get: get72,}export const tools3 = {byProviderId,}-export const get47 = oc+export const get73 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2498,14 +3411,14 @@ export const get47 = oc.output(zGetWorkspacesCurrentToolProviderMcpUpdateByProviderIdResponse)export const byProviderId2 = {- get: get47,+ get: get73,}export const update4 = {byProviderId: byProviderId2,}-export const delete12 = oc+export const delete16 = oc.route({inputStructure: 'detailed',method: 'DELETE',@@ -2516,7 +3429,7 @@ export const delete12 = oc.input(z.object({ body: zDeleteWorkspacesCurrentToolProviderMcpBody })).output(zDeleteWorkspacesCurrentToolProviderMcpResponse)-export const post55 = oc+export const post59 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2527,7 +3440,7 @@ export const post55 = oc.input(z.object({ body: zPostWorkspacesCurrentToolProviderMcpBody })).output(zPostWorkspacesCurrentToolProviderMcpResponse)-export const put4 = oc+export const put15 = oc.route({inputStructure: 'detailed',method: 'PUT',@@ -2539,15 +3452,15 @@ export const put4 = oc.output(zPutWorkspacesCurrentToolProviderMcpResponse)export const mcp = {- delete: delete12,- post: post55,- put: put4,+ delete: delete16,+ post: post59,+ put: put15,auth,tools: tools3,update: update4,}-export const post56 = oc+export const post60 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2559,10 +3472,10 @@ export const post56 = oc.output(zPostWorkspacesCurrentToolProviderWorkflowCreateResponse)export const create2 = {- post: post56,+ post: post60,}-export const post57 = oc+export const post61 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2573,11 +3486,11 @@ export const post57 = oc.input(z.object({ body: zPostWorkspacesCurrentToolProviderWorkflowDeleteBody })).output(zPostWorkspacesCurrentToolProviderWorkflowDeleteResponse)-export const delete13 = {- post: post57,+export const delete17 = {+ post: post61,}-export const get48 = oc+export const get74 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2588,11 +3501,11 @@ export const get48 = oc.input(z.object({ query: zGetWorkspacesCurrentToolProviderWorkflowGetQuery.optional() })).output(zGetWorkspacesCurrentToolProviderWorkflowGetResponse)-export const get49 = {- get: get48,+export const get75 = {+ get: get74,}-export const get50 = oc+export const get76 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2604,10 +3517,10 @@ export const get50 = oc.output(zGetWorkspacesCurrentToolProviderWorkflowToolsResponse)export const tools4 = {- get: get50,+ get: get76,}-export const post58 = oc+export const post62 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2619,13 +3532,13 @@ export const post58 = oc.output(zPostWorkspacesCurrentToolProviderWorkflowUpdateResponse)export const update5 = {- post: post58,+ post: post62,}export const workflow = {create: create2,- delete: delete13,- get: get49,+ delete: delete17,+ get: get75,tools: tools4,update: update5,}@@ -2637,7 +3550,7 @@ export const toolProvider = {workflow,}-export const get51 = oc+export const get77 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2649,10 +3562,10 @@ export const get51 = oc.output(zGetWorkspacesCurrentToolProvidersResponse)export const toolProviders = {- get: get51,+ get: get77,}-export const get52 = oc+export const get78 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2663,10 +3576,10 @@ export const get52 = oc.output(zGetWorkspacesCurrentToolsApiResponse)export const api2 = {- get: get52,+ get: get78,}-export const get53 = oc+export const get79 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2677,10 +3590,10 @@ export const get53 = oc.output(zGetWorkspacesCurrentToolsBuiltinResponse)export const builtin2 = {- get: get53,+ get: get79,}-export const get54 = oc+export const get80 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2691,10 +3604,10 @@ export const get54 = oc.output(zGetWorkspacesCurrentToolsMcpResponse)export const mcp2 = {- get: get54,+ get: get80,}-export const get55 = oc+export const get81 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2705,7 +3618,7 @@ export const get55 = oc.output(zGetWorkspacesCurrentToolsWorkflowResponse)export const workflow2 = {- get: get55,+ get: get81,}export const tools5 = {@@ -2715,7 +3628,7 @@ export const tools5 = {workflow: workflow2,}-export const get56 = oc+export const get82 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2727,13 +3640,13 @@ export const get56 = oc.output(zGetWorkspacesCurrentTriggerProviderByProviderIconResponse)export const icon3 = {- get: get56,+ get: get82,}/*** Get info for a trigger provider*/-export const get57 = oc+export const get83 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2746,13 +3659,13 @@ export const get57 = oc.output(zGetWorkspacesCurrentTriggerProviderByProviderInfoResponse)export const info3 = {- get: get57,+ get: get83,}/*** Remove custom OAuth client configuration*/-export const delete14 = oc+export const delete18 = oc.route({inputStructure: 'detailed',method: 'DELETE',@@ -2767,7 +3680,7 @@ export const delete14 = oc/*** Get OAuth client configuration for a provider*/-export const get58 = oc+export const get84 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2782,7 +3695,7 @@ export const get58 = oc/*** Configure custom OAuth client for a provider*/-export const post59 = oc+export const post63 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2800,9 +3713,9 @@ export const post59 = oc.output(zPostWorkspacesCurrentTriggerProviderByProviderOauthClientResponse)export const client = {- delete: delete14,- get: get58,- post: post59,+ delete: delete18,+ get: get84,+ post: post63,}export const oauth2 = {@@ -2812,7 +3725,7 @@ export const oauth2 = {/*** Build a subscription instance for a trigger provider*/-export const post60 = oc+export const post64 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2834,7 +3747,7 @@ export const post60 = oc)export const bySubscriptionBuilderId = {- post: post60,+ post: post64,}export const build = {@@ -2844,7 +3757,7 @@ export const build = {/*** Add a new subscription instance for a trigger provider*/-export const post61 = oc+export const post65 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2862,13 +3775,13 @@ export const post61 = oc.output(zPostWorkspacesCurrentTriggerProviderByProviderSubscriptionsBuilderCreateResponse)export const create3 = {- post: post61,+ post: post65,}/*** Get the request logs for a subscription instance for a trigger provider*/-export const get59 = oc+export const get85 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2889,7 +3802,7 @@ export const get59 = oc)export const bySubscriptionBuilderId2 = {- get: get59,+ get: get85,}export const logs = {@@ -2899,7 +3812,7 @@ export const logs = {/*** Update a subscription instance for a trigger provider*/-export const post62 = oc+export const post66 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2921,7 +3834,7 @@ export const post62 = oc)export const bySubscriptionBuilderId3 = {- post: post62,+ post: post66,}export const update6 = {@@ -2931,7 +3844,7 @@ export const update6 = {/*** Verify and update a subscription instance for a trigger provider*/-export const post63 = oc+export const post67 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2953,7 +3866,7 @@ export const post63 = oc)export const bySubscriptionBuilderId4 = {- post: post63,+ post: post67,}export const verifyAndUpdate = {@@ -2963,7 +3876,7 @@ export const verifyAndUpdate = {/*** Get a subscription instance for a trigger provider*/-export const get60 = oc+export const get86 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -2984,7 +3897,7 @@ export const get60 = oc)export const bySubscriptionBuilderId5 = {- get: get60,+ get: get86,}export const builder = {@@ -2999,7 +3912,7 @@ export const builder = {/*** List all trigger subscriptions for the current tenant's provider*/-export const get61 = oc+export const get87 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -3012,13 +3925,13 @@ export const get61 = oc.output(zGetWorkspacesCurrentTriggerProviderByProviderSubscriptionsListResponse)export const list4 = {- get: get61,+ get: get87,}/*** Initiate OAuth authorization flow for a trigger provider*/-export const get62 = oc+export const get88 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -3035,7 +3948,7 @@ export const get62 = oc.output(zGetWorkspacesCurrentTriggerProviderByProviderSubscriptionsOauthAuthorizeResponse)export const authorize = {- get: get62,+ get: get88,}export const oauth3 = {@@ -3045,7 +3958,7 @@ export const oauth3 = {/*** Verify credentials for an existing subscription (edit mode only)*/-export const post64 = oc+export const post68 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3067,7 +3980,7 @@ export const post64 = oc)export const bySubscriptionId = {- post: post64,+ post: post68,}export const verify = {@@ -3091,7 +4004,7 @@ export const byProvider3 = {/*** Delete a subscription instance*/-export const post65 = oc+export const post69 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3107,14 +4020,14 @@ export const post65 = oc).output(zPostWorkspacesCurrentTriggerProviderBySubscriptionIdSubscriptionsDeleteResponse)-export const delete15 = {- post: post65,+export const delete19 = {+ post: post69,}/*** Update a subscription instance*/-export const post66 = oc+export const post70 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3132,11 +4045,11 @@ export const post66 = oc.output(zPostWorkspacesCurrentTriggerProviderBySubscriptionIdSubscriptionsUpdateResponse)export const update7 = {- post: post66,+ post: post70,}export const subscriptions2 = {- delete: delete15,+ delete: delete19,update: update7,}@@ -3152,7 +4065,7 @@ export const triggerProvider = {/*** List all trigger providers for the current tenant*/-export const get63 = oc+export const get89 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -3164,10 +4077,10 @@ export const get63 = oc.output(zGetWorkspacesCurrentTriggersResponse)export const triggers = {- get: get63,+ get: get89,}-export const post67 = oc+export const post71 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3178,7 +4091,7 @@ export const post67 = oc.output(zPostWorkspacesCurrentResponse)export const current = {- post: post67,+ post: post71,agentProvider,agentProviders,customizedSnippets,@@ -3190,6 +4103,7 @@ export const current = {models: models2,permission,plugin: plugin2,+ rbac,toolLabels,toolProvider,toolProviders,@@ -3198,7 +4112,7 @@ export const current = {triggers,}-export const post68 = oc+export const post72 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3210,14 +4124,14 @@ export const post68 = oc.output(zPostWorkspacesCustomConfigWebappLogoUploadResponse)export const upload2 = {- post: post68,+ post: post72,}export const webappLogo = {upload: upload2,}-export const post69 = oc+export const post73 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3229,11 +4143,11 @@ export const post69 = oc.output(zPostWorkspacesCustomConfigResponse)export const customConfig = {- post: post69,+ post: post73,webappLogo,}-export const post70 = oc+export const post74 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3245,10 +4159,10 @@ export const post70 = oc.output(zPostWorkspacesInfoResponse)export const info4 = {- post: post70,+ post: post74,}-export const post71 = oc+export const post75 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3260,10 +4174,10 @@ export const post71 = oc.output(zPostWorkspacesSwitchResponse)export const switch3 = {- post: post71,+ post: post75,}-export const get64 = oc+export const get90 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -3275,7 +4189,7 @@ export const get64 = oc.output(zGetWorkspacesByTenantIdModelProvidersByProviderByIconTypeByLangResponse)export const byLang = {- get: get64,+ get: get90,}export const byIconType = {@@ -3294,7 +4208,7 @@ export const byTenantId = {modelProviders: modelProviders2,}-export const get65 = oc+export const get91 = oc.route({inputStructure: 'detailed',method: 'GET',@@ -3305,7 +4219,7 @@ export const get65 = oc.output(zGetWorkspacesResponse)export const workspaces = {- get: get65,+ get: get91,current,customConfig,info: info4,diff --git a/packages/contracts/generated/api/console/workspaces/types.gen.ts b/packages/contracts/generated/api/console/workspaces/types.gen.tsindex 59ee3242e75..29f23567e95 100644--- a/packages/contracts/generated/api/console/workspaces/types.gen.ts+++ b/packages/contracts/generated/api/console/workspaces/types.gen.ts@@ -182,7 +182,7 @@ export type EndpointUpdatePayload = {export type MemberInvitePayload = {emails?: Array<string>language?: string | null- role: TenantAccountRole+ role: string}export type MemberInviteResponse = {@@ -506,6 +506,109 @@ export type PluginCategoryListResponse = {plugins: Array<PluginCategoryInstalledPluginResponse>}+export type AccessPolicyList = {+ data?: Array<AccessPolicy>+ pagination?: Pagination | null+}++export type AccessPolicy = {+ category?: string+ created_at?: number+ description?: string+ id: string+ is_builtin?: boolean+ name: string+ permission_keys?: Array<string>+ policy_key?: string+ resource_type: string+ tenant_id?: string+ updated_at?: number+}++export type AccessPolicyBindingState = {+ binding_id: string+ is_locked?: boolean+}++export type MemberBindingsResponse = {+ data?: Array<AccessPolicyMemberBinding>+}++export type RoleBindingsResponse = {+ data?: Array<AccessPolicyRoleBinding>+}++export type AppAccessMatrix = {+ app_id?: string+ items?: Array<AccessMatrixItem>+}++export type ResourceUserAccessPoliciesResponse = {+ data?: Array<ResourceUserAccessPolicies>+ scope: string+}++export type ReplaceUserAccessPoliciesResponse = {+ access_policies?: Array<AccessPolicy>+}++export type ResourceWhitelist = {+ account_ids?: Array<string>+}++export type DatasetAccessMatrix = {+ dataset_id?: string+ items?: Array<AccessMatrixItem>+}++export type MemberRolesResponse = {+ account_id: string+ roles?: Array<RbacRole>+}++export type MyPermissionsResponse = {+ app?: ResourcePermissionSnapshot+ dataset?: ResourcePermissionSnapshot+ workspace?: WorkspacePermissionSnapshot+}++export type PermissionCatalogResponse = {+ groups?: Array<PermissionCatalogGroup>+}++export type RbacRoleList = {+ data?: Array<RbacRole>+ pagination?: Pagination | null+}++export type RbacRole = {+ category?: string+ description?: string+ id: string+ is_builtin?: boolean+ name: string+ permission_keys?: Array<string>+ role_tag?: string+ tenant_id?: string | null+ type: string+}++export type MembersInRoleList = {+ data?: Array<MembersInRole>+ pagination?: Pagination | null+}++export type AccessMatrixItem = {+ accounts?: Array<AccessPolicyAccount>+ policy?: AccessPolicy | null+ roles?: Array<AccessPolicyRole>+}++export type WorkspaceAccessMatrix = {+ items?: Array<AccessMatrixItem>+ pagination?: Pagination | null+}+export type ToolProviderOpaqueResponse = unknownexport type ApiToolProviderAddPayload = {@@ -827,6 +930,9 @@ export type AccountWithRole = {last_login_at?: number | nullname: stringrole: string+ roles?: Array<{+ [key: string]: string+ }>status: string}@@ -842,8 +948,6 @@ export type Inner = {provider?: string | null}-export type TenantAccountRole = 'admin' | 'dataset_operator' | 'editor' | 'normal' | 'owner'-export type MemberInviteResultResponse = {email: stringmessage?: string | null@@ -1009,6 +1113,79 @@ export type PluginCategoryInstalledPluginResponse = {version: string}+export type Pagination = {+ current_page?: number+ per_page?: number+ total_count?: number+ total_pages?: number+}++export type AccessPolicyMemberBinding = {+ access_policy_id: string+ account_id: string+ account_name?: string+ created_at?: number+ id: string+ resource_id?: string+ resource_type: string+ tenant_id?: string+}++export type AccessPolicyRoleBinding = {+ access_policy_id: string+ created_at?: number+ id: string+ resource_id?: string+ resource_type: string+ role_id: string+ role_name?: string+ tenant_id?: string+}++export type ResourceUserAccessPolicies = {+ access_policies?: Array<AccessPolicy>+ account: RbacRoleAccount+ roles?: Array<RbacRole>+}++export type ResourcePermissionSnapshot = {+ default_permission_keys?: Array<string>+ overrides?: Array<ResourcePermissionKeys>+}++export type WorkspacePermissionSnapshot = {+ permission_keys?: Array<string>+}++export type PermissionCatalogGroup = {+ description?: string+ group_key: string+ group_name: string+ permissions?: Array<PermissionCatalogItem>+}++export type MembersInRole = {+ account_id?: string+ account_name?: string+}++export type AccessPolicyAccount = {+ account_id: string+ account_name: string+ avatar?: string+ binding_id: string+ email?: string+ is_locked?: boolean+}++export type AccessPolicyRole = {+ binding_id: string+ is_locked?: boolean+ role_id: string+ role_name: string+ role_tag?: string+}+export type ApiProviderSchemaType = 'openai_actions' | 'openai_plugin' | 'openapi' | 'swagger'export type CredentialType = 'api-key' | 'oauth2' | 'unauthorized'@@ -1208,6 +1385,24 @@ export type PluginDeclarationResponse = {export type PluginInstallationSource = 'github' | 'marketplace' | 'package' | 'remote'+export type RbacRoleAccount = {+ account_id: string+ account_name?: string+ avatar?: string+ email?: string+}++export type ResourcePermissionKeys = {+ permission_keys?: Array<string>+ resource_id: string+}++export type PermissionCatalogItem = {+ description?: string+ key: string+ name: string+}+export type ToolParameterForm = 'form' | 'llm' | 'schema'export type AiModelEntityResponse = {@@ -2791,6 +2986,723 @@ export type GetWorkspacesCurrentPluginByCategoryListResponses = {export type GetWorkspacesCurrentPluginByCategoryListResponse= GetWorkspacesCurrentPluginByCategoryListResponses[keyof GetWorkspacesCurrentPluginByCategoryListResponses]+export type GetWorkspacesCurrentRbacAccessPoliciesData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/access-policies'+}++export type GetWorkspacesCurrentRbacAccessPoliciesResponses = {+ 200: AccessPolicyList+}++export type GetWorkspacesCurrentRbacAccessPoliciesResponse+ = GetWorkspacesCurrentRbacAccessPoliciesResponses[keyof GetWorkspacesCurrentRbacAccessPoliciesResponses]++export type PostWorkspacesCurrentRbacAccessPoliciesData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/access-policies'+}++export type PostWorkspacesCurrentRbacAccessPoliciesResponses = {+ 201: AccessPolicy+}++export type PostWorkspacesCurrentRbacAccessPoliciesResponse+ = PostWorkspacesCurrentRbacAccessPoliciesResponses[keyof PostWorkspacesCurrentRbacAccessPoliciesResponses]++export type DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/access-policies/{policy_id}'+}++export type DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses = {+ 200: AccessPolicy+}++export type DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse+ = DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses[keyof DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses]++export type GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/access-policies/{policy_id}'+}++export type GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses = {+ 200: AccessPolicy+}++export type GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse+ = GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses[keyof GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses]++export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/access-policies/{policy_id}'+}++export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses = {+ 200: AccessPolicy+}++export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse+ = PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses[keyof PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses]++export type PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/access-policies/{policy_id}/copy'+}++export type PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponses = {+ 201: AccessPolicy+}++export type PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse+ = PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponses[keyof PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponses]++export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockData = {+ body?: never+ path: {+ binding_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/access-policy-bindings/{binding_id}/lock'+}++export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponses = {+ 200: AccessPolicyBindingState+}++export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse+ = PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponses[keyof PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponses]++export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockData = {+ body?: never+ path: {+ binding_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/access-policy-bindings/{binding_id}/unlock'+}++export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponses = {+ 200: AccessPolicyBindingState+}++export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse+ = PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponses[keyof PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponses]++export type DeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsData = {+ body?: never+ path: {+ app_id: string+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings'+}++export type DeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponses+ = {+ 200: MemberBindingsResponse+ }++export type DeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = DeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponses[keyof DeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponses]++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsData = {+ body?: never+ path: {+ app_id: string+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings'+}++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponses = {+ 200: MemberBindingsResponse+}++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponses[keyof GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponses]++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsData = {+ body?: never+ path: {+ app_id: string+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/role-bindings'+}++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponses = {+ 200: RoleBindingsResponse+}++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponse+ = GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponses[keyof GetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponses]++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPolicyData = {+ body?: never+ path: {+ app_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/access-policy'+}++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponses = {+ 200: AppAccessMatrix+}++export type GetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponse+ = GetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponses[keyof GetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponses]++export type GetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesData = {+ body?: never+ path: {+ app_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/user-access-policies'+}++export type GetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponses = {+ 200: ResourceUserAccessPoliciesResponse+}++export type GetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponse+ = GetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponses[keyof GetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponses]++export type PutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesData = {+ body?: never+ path: {+ app_id: string+ target_account_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/users/{target_account_id}/access-policies'+}++export type PutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponses = {+ 200: ReplaceUserAccessPoliciesResponse+}++export type PutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponse+ = PutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponses[keyof PutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponses]++export type GetWorkspacesCurrentRbacAppsByAppIdWhitelistData = {+ body?: never+ path: {+ app_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/whitelist'+}++export type GetWorkspacesCurrentRbacAppsByAppIdWhitelistResponses = {+ 200: ResourceWhitelist+}++export type GetWorkspacesCurrentRbacAppsByAppIdWhitelistResponse+ = GetWorkspacesCurrentRbacAppsByAppIdWhitelistResponses[keyof GetWorkspacesCurrentRbacAppsByAppIdWhitelistResponses]++export type PutWorkspacesCurrentRbacAppsByAppIdWhitelistData = {+ body?: never+ path: {+ app_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/apps/{app_id}/whitelist'+}++export type PutWorkspacesCurrentRbacAppsByAppIdWhitelistResponses = {+ 200: ResourceWhitelist+}++export type PutWorkspacesCurrentRbacAppsByAppIdWhitelistResponse+ = PutWorkspacesCurrentRbacAppsByAppIdWhitelistResponses[keyof PutWorkspacesCurrentRbacAppsByAppIdWhitelistResponses]++export type DeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsData+ = {+ body?: never+ path: {+ dataset_id: string+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/member-bindings'+ }++export type DeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponses+ = {+ 200: MemberBindingsResponse+ }++export type DeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = DeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponses[keyof DeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponses]++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsData+ = {+ body?: never+ path: {+ dataset_id: string+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/member-bindings'+ }++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponses+ = {+ 200: MemberBindingsResponse+ }++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponses[keyof GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponses]++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsData = {+ body?: never+ path: {+ dataset_id: string+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/role-bindings'+}++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponses+ = {+ 200: RoleBindingsResponse+ }++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponse+ = GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponses[keyof GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponses]++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyData = {+ body?: never+ path: {+ dataset_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/access-policy'+}++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponses = {+ 200: DatasetAccessMatrix+}++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponse+ = GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponses[keyof GetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponses]++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesData = {+ body?: never+ path: {+ dataset_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/user-access-policies'+}++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponses = {+ 200: ResourceUserAccessPoliciesResponse+}++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponse+ = GetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponses[keyof GetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponses]++export type PutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesData = {+ body?: never+ path: {+ dataset_id: string+ target_account_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/users/{target_account_id}/access-policies'+}++export type PutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponses+ = {+ 200: ReplaceUserAccessPoliciesResponse+ }++export type PutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponse+ = PutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponses[keyof PutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponses]++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistData = {+ body?: never+ path: {+ dataset_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/whitelist'+}++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponses = {+ 200: ResourceWhitelist+}++export type GetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse+ = GetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponses[keyof GetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponses]++export type PutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistData = {+ body?: never+ path: {+ dataset_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/datasets/{dataset_id}/whitelist'+}++export type PutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponses = {+ 200: ResourceWhitelist+}++export type PutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse+ = PutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponses[keyof PutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponses]++export type GetWorkspacesCurrentRbacMembersByMemberIdRbacRolesData = {+ body?: never+ path: {+ member_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/members/{member_id}/rbac-roles'+}++export type GetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponses = {+ 200: MemberRolesResponse+}++export type GetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse+ = GetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponses[keyof GetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponses]++export type PutWorkspacesCurrentRbacMembersByMemberIdRbacRolesData = {+ body?: never+ path: {+ member_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/members/{member_id}/rbac-roles'+}++export type PutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponses = {+ 200: MemberRolesResponse+}++export type PutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse+ = PutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponses[keyof PutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponses]++export type GetWorkspacesCurrentRbacMyPermissionsData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/my-permissions'+}++export type GetWorkspacesCurrentRbacMyPermissionsResponses = {+ 200: MyPermissionsResponse+}++export type GetWorkspacesCurrentRbacMyPermissionsResponse+ = GetWorkspacesCurrentRbacMyPermissionsResponses[keyof GetWorkspacesCurrentRbacMyPermissionsResponses]++export type GetWorkspacesCurrentRbacRolePermissionsCatalogData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/role-permissions/catalog'+}++export type GetWorkspacesCurrentRbacRolePermissionsCatalogResponses = {+ 200: PermissionCatalogResponse+}++export type GetWorkspacesCurrentRbacRolePermissionsCatalogResponse+ = GetWorkspacesCurrentRbacRolePermissionsCatalogResponses[keyof GetWorkspacesCurrentRbacRolePermissionsCatalogResponses]++export type GetWorkspacesCurrentRbacRolePermissionsCatalogAppData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/role-permissions/catalog/app'+}++export type GetWorkspacesCurrentRbacRolePermissionsCatalogAppResponses = {+ 200: PermissionCatalogResponse+}++export type GetWorkspacesCurrentRbacRolePermissionsCatalogAppResponse+ = GetWorkspacesCurrentRbacRolePermissionsCatalogAppResponses[keyof GetWorkspacesCurrentRbacRolePermissionsCatalogAppResponses]++export type GetWorkspacesCurrentRbacRolePermissionsCatalogDatasetData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/role-permissions/catalog/dataset'+}++export type GetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponses = {+ 200: PermissionCatalogResponse+}++export type GetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponse+ = GetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponses[keyof GetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponses]++export type GetWorkspacesCurrentRbacRolesData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/roles'+}++export type GetWorkspacesCurrentRbacRolesResponses = {+ 200: RbacRoleList+}++export type GetWorkspacesCurrentRbacRolesResponse+ = GetWorkspacesCurrentRbacRolesResponses[keyof GetWorkspacesCurrentRbacRolesResponses]++export type PostWorkspacesCurrentRbacRolesData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/roles'+}++export type PostWorkspacesCurrentRbacRolesResponses = {+ 201: RbacRole+}++export type PostWorkspacesCurrentRbacRolesResponse+ = PostWorkspacesCurrentRbacRolesResponses[keyof PostWorkspacesCurrentRbacRolesResponses]++export type DeleteWorkspacesCurrentRbacRolesByRoleIdData = {+ body?: never+ path: {+ role_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/roles/{role_id}'+}++export type DeleteWorkspacesCurrentRbacRolesByRoleIdResponses = {+ 200: RbacRole+}++export type DeleteWorkspacesCurrentRbacRolesByRoleIdResponse+ = DeleteWorkspacesCurrentRbacRolesByRoleIdResponses[keyof DeleteWorkspacesCurrentRbacRolesByRoleIdResponses]++export type GetWorkspacesCurrentRbacRolesByRoleIdData = {+ body?: never+ path: {+ role_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/roles/{role_id}'+}++export type GetWorkspacesCurrentRbacRolesByRoleIdResponses = {+ 200: RbacRole+}++export type GetWorkspacesCurrentRbacRolesByRoleIdResponse+ = GetWorkspacesCurrentRbacRolesByRoleIdResponses[keyof GetWorkspacesCurrentRbacRolesByRoleIdResponses]++export type PutWorkspacesCurrentRbacRolesByRoleIdData = {+ body?: never+ path: {+ role_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/roles/{role_id}'+}++export type PutWorkspacesCurrentRbacRolesByRoleIdResponses = {+ 200: RbacRole+}++export type PutWorkspacesCurrentRbacRolesByRoleIdResponse+ = PutWorkspacesCurrentRbacRolesByRoleIdResponses[keyof PutWorkspacesCurrentRbacRolesByRoleIdResponses]++export type PostWorkspacesCurrentRbacRolesByRoleIdCopyData = {+ body?: never+ path: {+ role_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/roles/{role_id}/copy'+}++export type PostWorkspacesCurrentRbacRolesByRoleIdCopyResponses = {+ 201: RbacRole+}++export type PostWorkspacesCurrentRbacRolesByRoleIdCopyResponse+ = PostWorkspacesCurrentRbacRolesByRoleIdCopyResponses[keyof PostWorkspacesCurrentRbacRolesByRoleIdCopyResponses]++export type GetWorkspacesCurrentRbacRolesByRoleIdMembersData = {+ body?: never+ path: {+ role_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/roles/{role_id}/members'+}++export type GetWorkspacesCurrentRbacRolesByRoleIdMembersResponses = {+ 200: MembersInRoleList+}++export type GetWorkspacesCurrentRbacRolesByRoleIdMembersResponse+ = GetWorkspacesCurrentRbacRolesByRoleIdMembersResponses[keyof GetWorkspacesCurrentRbacRolesByRoleIdMembersResponses]++export type PutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/bindings'+}++export type PutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponses = {+ 200: AccessMatrixItem+}++export type PutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponse+ = PutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponses[keyof PutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponses]++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/member-bindings'+}++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponses = {+ 200: MemberBindingsResponse+}++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponse+ = GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponses[keyof GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponses]++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/role-bindings'+}++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponses = {+ 200: RoleBindingsResponse+}++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponse+ = GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponses[keyof GetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponses]++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/workspace/apps/access-policy'+}++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponses = {+ 200: WorkspaceAccessMatrix+}++export type GetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponse+ = GetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponses[keyof GetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponses]++export type PutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/bindings'+}++export type PutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponses = {+ 200: AccessMatrixItem+}++export type PutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponse+ = PutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponses[keyof PutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponses]++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/member-bindings'+}++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponses+ = {+ 200: MemberBindingsResponse+ }++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponse+ = GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponses[keyof GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponses]++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsData = {+ body?: never+ path: {+ policy_id: string+ }+ query?: never+ url: '/workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/role-bindings'+}++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponses+ = {+ 200: RoleBindingsResponse+ }++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponse+ = GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponses[keyof GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponses]++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyData = {+ body?: never+ path?: never+ query?: never+ url: '/workspaces/current/rbac/workspace/datasets/access-policy'+}++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponses = {+ 200: WorkspaceAccessMatrix+}++export type GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponse+ = GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponses[keyof GetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponses]+export type GetWorkspacesCurrentToolLabelsData = {body?: neverpath?: neverdiff --git a/packages/contracts/generated/api/console/workspaces/zod.gen.ts b/packages/contracts/generated/api/console/workspaces/zod.gen.tsindex 8c430ddec8b..fb6f643d7a9 100644--- a/packages/contracts/generated/api/console/workspaces/zod.gen.ts+++ b/packages/contracts/generated/api/console/workspaces/zod.gen.ts@@ -138,6 +138,15 @@ export const zEndpointUpdatePayload = z.object({settings: z.record(z.string(), z.unknown()),})+/**+ * MemberInvitePayload+ */+export const zMemberInvitePayload = z.object({+ emails: z.array(z.string()).optional(),+ language: z.string().nullish(),+ role: z.string(),+})+/*** OwnerTransferCheckPayload*/@@ -446,6 +455,68 @@ export const zParserGithubUpload = z.object({version: z.string(),})+/**+ * AccessPolicy+ */+export const zAccessPolicy = z.object({+ category: z.string().optional().default(''),+ created_at: z.int().optional().default(0),+ description: z.string().optional().default(''),+ id: z.string(),+ is_builtin: z.boolean().optional().default(false),+ name: z.string(),+ permission_keys: z.array(z.string()).optional(),+ policy_key: z.string().optional().default(''),+ resource_type: z.string(),+ tenant_id: z.string().optional().default(''),+ updated_at: z.int().optional().default(0),+})++/**+ * AccessPolicyBindingState+ */+export const zAccessPolicyBindingState = z.object({+ binding_id: z.string(),+ is_locked: z.boolean().optional().default(false),+})++/**+ * ReplaceUserAccessPoliciesResponse+ */+export const zReplaceUserAccessPoliciesResponse = z.object({+ access_policies: z.array(zAccessPolicy).optional(),+})++/**+ * ResourceWhitelist+ */+export const zResourceWhitelist = z.object({+ account_ids: z.array(z.string()).optional(),+})++/**+ * RBACRole+ */+export const zRbacRole = z.object({+ category: z.string().optional().default(''),+ description: z.string().optional().default(''),+ id: z.string(),+ is_builtin: z.boolean().optional().default(false),+ name: z.string(),+ permission_keys: z.array(z.string()).optional(),+ role_tag: z.string().optional().default(''),+ tenant_id: z.string().nullish(),+ type: z.string(),+})++/**+ * MemberRolesResponse+ */+export const zMemberRolesResponse = z.object({+ account_id: z.string(),+ roles: z.array(zRbacRole).optional(),+})+/*** ToolProviderOpaqueResponse*/@@ -829,6 +900,7 @@ export const zAccountWithRole = z.object({last_login_at: z.int().nullish(),name: z.string(),role: z.string(),+ roles: z.array(z.record(z.string(), z.string())).optional(),status: z.string(),})@@ -839,20 +911,6 @@ export const zAccountWithRoleList = z.object({accounts: z.array(zAccountWithRole),})-/**- * TenantAccountRole- */-export const zTenantAccountRole = z.enum(['admin', 'dataset_operator', 'editor', 'normal', 'owner'])--/**- * MemberInvitePayload- */-export const zMemberInvitePayload = z.object({- emails: z.array(z.string()).optional(),- language: z.string().nullish(),- role: zTenantAccountRole,-})-/*** MemberInviteResultResponse*/@@ -1061,6 +1119,153 @@ export const zPluginPermissionResponse = z.object({install_permission: zInstallPermission,})+/**+ * Pagination+ */+export const zPagination = z.object({+ current_page: z.int().optional().default(0),+ per_page: z.int().optional().default(0),+ total_count: z.int().optional().default(0),+ total_pages: z.int().optional().default(0),+})++/**+ * _AccessPolicyList+ */+export const zAccessPolicyList = z.object({+ data: z.array(zAccessPolicy).optional(),+ pagination: zPagination.nullish(),+})++/**+ * _RBACRoleList+ */+export const zRbacRoleList = z.object({+ data: z.array(zRbacRole).optional(),+ pagination: zPagination.nullish(),+})++/**+ * AccessPolicyMemberBinding+ */+export const zAccessPolicyMemberBinding = z.object({+ access_policy_id: z.string(),+ account_id: z.string(),+ account_name: z.string().optional().default(''),+ created_at: z.int().optional().default(0),+ id: z.string(),+ resource_id: z.string().optional().default(''),+ resource_type: z.string(),+ tenant_id: z.string().optional().default(''),+})++/**+ * MemberBindingsResponse+ */+export const zMemberBindingsResponse = z.object({+ data: z.array(zAccessPolicyMemberBinding).optional(),+})++/**+ * AccessPolicyRoleBinding+ */+export const zAccessPolicyRoleBinding = z.object({+ access_policy_id: z.string(),+ created_at: z.int().optional().default(0),+ id: z.string(),+ resource_id: z.string().optional().default(''),+ resource_type: z.string(),+ role_id: z.string(),+ role_name: z.string().optional().default(''),+ tenant_id: z.string().optional().default(''),+})++/**+ * RoleBindingsResponse+ */+export const zRoleBindingsResponse = z.object({+ data: z.array(zAccessPolicyRoleBinding).optional(),+})++/**+ * WorkspacePermissionSnapshot+ */+export const zWorkspacePermissionSnapshot = z.object({+ permission_keys: z.array(z.string()).optional(),+})++/**+ * MembersInRole+ */+export const zMembersInRole = z.object({+ account_id: z.string().optional().default(''),+ account_name: z.string().optional().default(''),+})++/**+ * _MembersInRoleList+ */+export const zMembersInRoleList = z.object({+ data: z.array(zMembersInRole).optional(),+ pagination: zPagination.nullish(),+})++/**+ * AccessPolicyAccount+ */+export const zAccessPolicyAccount = z.object({+ account_id: z.string(),+ account_name: z.string(),+ avatar: z.string().optional().default(''),+ binding_id: z.string(),+ email: z.string().optional().default(''),+ is_locked: z.boolean().optional().default(false),+})++/**+ * AccessPolicyRole+ */+export const zAccessPolicyRole = z.object({+ binding_id: z.string(),+ is_locked: z.boolean().optional().default(false),+ role_id: z.string(),+ role_name: z.string(),+ role_tag: z.string().optional().default(''),+})++/**+ * AccessMatrixItem+ */+export const zAccessMatrixItem = z.object({+ accounts: z.array(zAccessPolicyAccount).optional(),+ policy: zAccessPolicy.nullish(),+ roles: z.array(zAccessPolicyRole).optional(),+})++/**+ * AppAccessMatrix+ */+export const zAppAccessMatrix = z.object({+ app_id: z.string().optional().default(''),+ items: z.array(zAccessMatrixItem).optional(),+})++/**+ * DatasetAccessMatrix+ */+export const zDatasetAccessMatrix = z.object({+ dataset_id: z.string().optional().default(''),+ items: z.array(zAccessMatrixItem).optional(),+})++/**+ * WorkspaceAccessMatrix+ */+export const zWorkspaceAccessMatrix = z.object({+ items: z.array(zAccessMatrixItem).optional(),+ pagination: zPagination.nullish(),+})+/*** ApiProviderSchemaType*@@ -1465,6 +1670,84 @@ export const zPluginCategoryBuiltinToolProviderResponse = z.object({*/export const zPluginInstallationSource = z.enum(['github', 'marketplace', 'package', 'remote'])+/**+ * RBACRoleAccount+ */+export const zRbacRoleAccount = z.object({+ account_id: z.string(),+ account_name: z.string().optional().default(''),+ avatar: z.string().optional().default(''),+ email: z.string().optional().default(''),+})++/**+ * ResourceUserAccessPolicies+ */+export const zResourceUserAccessPolicies = z.object({+ access_policies: z.array(zAccessPolicy).optional(),+ account: zRbacRoleAccount,+ roles: z.array(zRbacRole).optional(),+})++/**+ * ResourceUserAccessPoliciesResponse+ */+export const zResourceUserAccessPoliciesResponse = z.object({+ data: z.array(zResourceUserAccessPolicies).optional(),+ scope: z.string(),+})++/**+ * ResourcePermissionKeys+ */+export const zResourcePermissionKeys = z.object({+ permission_keys: z.array(z.string()).optional(),+ resource_id: z.string(),+})++/**+ * ResourcePermissionSnapshot+ */+export const zResourcePermissionSnapshot = z.object({+ default_permission_keys: z.array(z.string()).optional(),+ overrides: z.array(zResourcePermissionKeys).optional(),+})++/**+ * MyPermissionsResponse+ */+export const zMyPermissionsResponse = z.object({+ app: zResourcePermissionSnapshot.optional(),+ dataset: zResourcePermissionSnapshot.optional(),+ workspace: zWorkspacePermissionSnapshot.optional(),+})++/**+ * PermissionCatalogItem+ */+export const zPermissionCatalogItem = z.object({+ description: z.string().optional().default(''),+ key: z.string(),+ name: z.string(),+})++/**+ * PermissionCatalogGroup+ */+export const zPermissionCatalogGroup = z.object({+ description: z.string().optional().default(''),+ group_key: z.string(),+ group_name: z.string(),+ permissions: z.array(zPermissionCatalogItem).optional(),+})++/**+ * PermissionCatalogResponse+ */+export const zPermissionCatalogResponse = z.object({+ groups: z.array(zPermissionCatalogGroup).optional(),+})+/*** ToolParameterForm*/@@ -2711,6 +2994,411 @@ export const zGetWorkspacesCurrentPluginByCategoryListQuery = z.object({*/export const zGetWorkspacesCurrentPluginByCategoryListResponse = zPluginCategoryListResponse+/**+ * Success+ */+export const zGetWorkspacesCurrentRbacAccessPoliciesResponse = zAccessPolicyList++/**+ * Policy created+ */+export const zPostWorkspacesCurrentRbacAccessPoliciesResponse = zAccessPolicy++export const zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({+ policy_id: z.uuid(),+})++/**+ * Success+ */+export const zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = zAccessPolicy++export const zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({+ policy_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = zAccessPolicy++export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({+ policy_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = zAccessPolicy++export const zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyPath = z.object({+ policy_id: z.uuid(),+})++/**+ * Policy copied+ */+export const zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse = zAccessPolicy++export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockPath = z.object({+ binding_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse+ = zAccessPolicyBindingState++export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockPath = z.object({+ binding_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse+ = zAccessPolicyBindingState++export const zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath+ = z.object({+ app_id: z.uuid(),+ policy_id: z.string(),+ })++/**+ * Success+ */+export const zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = zMemberBindingsResponse++export const zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath+ = z.object({+ app_id: z.uuid(),+ policy_id: z.string(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = zMemberBindingsResponse++export const zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsPath+ = z.object({+ app_id: z.uuid(),+ policy_id: z.uuid(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponse+ = zRoleBindingsResponse++export const zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyPath = z.object({+ app_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponse = zAppAccessMatrix++export const zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesPath = z.object({+ app_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponse+ = zResourceUserAccessPoliciesResponse++export const zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesPath+ = z.object({+ app_id: z.uuid(),+ target_account_id: z.uuid(),+ })++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponse+ = zReplaceUserAccessPoliciesResponse++export const zGetWorkspacesCurrentRbacAppsByAppIdWhitelistPath = z.object({+ app_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacAppsByAppIdWhitelistResponse = zResourceWhitelist++export const zPutWorkspacesCurrentRbacAppsByAppIdWhitelistPath = z.object({+ app_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacAppsByAppIdWhitelistResponse = zResourceWhitelist++export const zDeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsPath+ = z.object({+ dataset_id: z.uuid(),+ policy_id: z.string(),+ })++/**+ * Success+ */+export const zDeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = zMemberBindingsResponse++export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsPath+ = z.object({+ dataset_id: z.uuid(),+ policy_id: z.string(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse+ = zMemberBindingsResponse++export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsPath+ = z.object({+ dataset_id: z.uuid(),+ policy_id: z.uuid(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponse+ = zRoleBindingsResponse++export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyPath = z.object({+ dataset_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponse = zDatasetAccessMatrix++export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesPath = z.object({+ dataset_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponse+ = zResourceUserAccessPoliciesResponse++export const zPutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesPath+ = z.object({+ dataset_id: z.uuid(),+ target_account_id: z.uuid(),+ })++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponse+ = zReplaceUserAccessPoliciesResponse++export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistPath = z.object({+ dataset_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse = zResourceWhitelist++export const zPutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistPath = z.object({+ dataset_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse = zResourceWhitelist++export const zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath = z.object({+ member_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse = zMemberRolesResponse++export const zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath = z.object({+ member_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse = zMemberRolesResponse++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacMyPermissionsResponse = zMyPermissionsResponse++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacRolePermissionsCatalogResponse = zPermissionCatalogResponse++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacRolePermissionsCatalogAppResponse = zPermissionCatalogResponse++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponse+ = zPermissionCatalogResponse++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacRolesResponse = zRbacRoleList++/**+ * Role created+ */+export const zPostWorkspacesCurrentRbacRolesResponse = zRbacRole++export const zDeleteWorkspacesCurrentRbacRolesByRoleIdPath = z.object({+ role_id: z.uuid(),+})++/**+ * Success+ */+export const zDeleteWorkspacesCurrentRbacRolesByRoleIdResponse = zRbacRole++export const zGetWorkspacesCurrentRbacRolesByRoleIdPath = z.object({+ role_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacRolesByRoleIdResponse = zRbacRole++export const zPutWorkspacesCurrentRbacRolesByRoleIdPath = z.object({+ role_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacRolesByRoleIdResponse = zRbacRole++export const zPostWorkspacesCurrentRbacRolesByRoleIdCopyPath = z.object({+ role_id: z.uuid(),+})++/**+ * Role copied+ */+export const zPostWorkspacesCurrentRbacRolesByRoleIdCopyResponse = zRbacRole++export const zGetWorkspacesCurrentRbacRolesByRoleIdMembersPath = z.object({+ role_id: z.uuid(),+})++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacRolesByRoleIdMembersResponse = zMembersInRoleList++export const zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsPath = z.object({+ policy_id: z.uuid(),+})++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponse+ = zAccessMatrixItem++export const zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsPath+ = z.object({+ policy_id: z.uuid(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponse+ = zMemberBindingsResponse++export const zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsPath+ = z.object({+ policy_id: z.uuid(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponse+ = zRoleBindingsResponse++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponse = zWorkspaceAccessMatrix++export const zPutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsPath+ = z.object({+ policy_id: z.uuid(),+ })++/**+ * Success+ */+export const zPutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponse+ = zAccessMatrixItem++export const zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsPath+ = z.object({+ policy_id: z.uuid(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponse+ = zMemberBindingsResponse++export const zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsPath+ = z.object({+ policy_id: z.uuid(),+ })++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponse+ = zRoleBindingsResponse++/**+ * Success+ */+export const zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponse = zWorkspaceAccessMatrix+/*** Success*/diff --git a/packages/contracts/generated/api/openapi/types.gen.ts b/packages/contracts/generated/api/openapi/types.gen.tsindex 244ce92417c..e1217f3f6d7 100644--- a/packages/contracts/generated/api/openapi/types.gen.ts+++ b/packages/contracts/generated/api/openapi/types.gen.ts@@ -257,6 +257,7 @@ export type Import = {error?: stringid: stringimported_dsl_version?: string+ permission_keys?: Array<string>status: ImportStatus}diff --git a/packages/contracts/generated/api/openapi/zod.gen.ts b/packages/contracts/generated/api/openapi/zod.gen.tsindex df0d82117a0..51a3cb8f480 100644--- a/packages/contracts/generated/api/openapi/zod.gen.ts+++ b/packages/contracts/generated/api/openapi/zod.gen.ts@@ -263,6 +263,7 @@ export const zImport = z.object({error: z.string().optional().default(''),id: z.string(),imported_dsl_version: z.string().optional().default(''),+ permission_keys: z.array(z.string()).optional(),status: zImportStatus,})diff --git a/packages/contracts/generated/api/service/types.gen.ts b/packages/contracts/generated/api/service/types.gen.tsindex 687fc29f1db..97921643514 100644--- a/packages/contracts/generated/api/service/types.gen.ts+++ b/packages/contracts/generated/api/service/types.gen.ts@@ -352,8 +352,10 @@ export type DatasetDetailResponse = {indexing_technique: string | nullis_multimodal: booleanis_published: boolean+ maintainer?: string | nullname: stringpermission: string+ permission_keys?: Array<string>pipeline_id: string | nullprovider: stringretrieval_model_dict: DatasetRetrievalModelResponse@@ -390,9 +392,11 @@ export type DatasetDetailWithPartialMembersResponse = {indexing_technique: string | nullis_multimodal: booleanis_published: boolean+ maintainer?: string | nullname: stringpartial_member_list?: Array<string> | nullpermission: string+ permission_keys?: Array<string>pipeline_id: string | nullprovider: stringretrieval_model_dict: DatasetRetrievalModelResponsediff --git a/packages/contracts/generated/api/service/zod.gen.ts b/packages/contracts/generated/api/service/zod.gen.tsindex 5dcac8cf9db..6ccc5671cb2 100644--- a/packages/contracts/generated/api/service/zod.gen.ts+++ b/packages/contracts/generated/api/service/zod.gen.ts@@ -602,8 +602,10 @@ export const zDatasetDetailResponse = z.object({indexing_technique: z.string().nullable(),is_multimodal: z.boolean(),is_published: z.boolean(),+ maintainer: z.string().nullish(),name: z.string(),permission: z.string(),+ permission_keys: z.array(z.string()).optional(),pipeline_id: z.string().nullable(),provider: z.string(),retrieval_model_dict: zDatasetRetrievalModelResponse,@@ -643,9 +645,11 @@ export const zDatasetDetailWithPartialMembersResponse = z.object({indexing_technique: z.string().nullable(),is_multimodal: z.boolean(),is_published: z.boolean(),+ maintainer: z.string().nullish(),name: z.string(),partial_member_list: z.array(z.string()).nullish(),permission: z.string(),+ permission_keys: z.array(z.string()).optional(),pipeline_id: z.string().nullable(),provider: z.string(),retrieval_model_dict: zDatasetRetrievalModelResponse,diff --git a/packages/contracts/generated/api/web/types.gen.ts b/packages/contracts/generated/api/web/types.gen.tsindex a1f03e0b3c3..61c9cf103be 100644--- a/packages/contracts/generated/api/web/types.gen.ts+++ b/packages/contracts/generated/api/web/types.gen.ts@@ -566,6 +566,7 @@ export type SystemFeatureModel = {max_plugin_package_size: numberplugin_installation_permission: PluginInstallationPermissionModelplugin_manager: PluginManagerModel+ rbac_enabled: booleansso_enforced_for_signin: booleansso_enforced_for_signin_protocol: stringwebapp_auth: WebAppAuthModeldiff --git a/packages/contracts/generated/api/web/zod.gen.ts b/packages/contracts/generated/api/web/zod.gen.tsindex 8c35ac0ca54..8045ad341e3 100644--- a/packages/contracts/generated/api/web/zod.gen.ts+++ b/packages/contracts/generated/api/web/zod.gen.ts@@ -861,6 +861,7 @@ export const zSystemFeatureModel = z.object({restrict_to_marketplace_only: false,}),plugin_manager: zPluginManagerModel.default({ enabled: false }),+ rbac_enabled: z.boolean().default(false),sso_enforced_for_signin: z.boolean().default(false),sso_enforced_for_signin_protocol: z.string().default(''),webapp_auth: zWebAppAuthModel.default({diff --git a/packages/contracts/generated/enterprise/types.gen.ts b/packages/contracts/generated/enterprise/types.gen.tsindex 0c990967a3c..600f8975678 100644--- a/packages/contracts/generated/enterprise/types.gen.ts+++ b/packages/contracts/generated/enterprise/types.gen.ts@@ -1290,6 +1290,11 @@ export type GetMfaInfoReply = {globalEnabled?: boolean}+export type GetMemberRbacRolesReply = {+ accountId?: string+ roles?: Array<RbacRole>+}+export type GetMemberReply = {account?: AccountDetail}@@ -1660,6 +1665,16 @@ export type PluginInstallationSettingsReply = {restrictToMarketplaceOnly?: boolean}+export type RbacRole = {+ id?: string+ type?: string+ name?: string+ description?: string+ isBuiltin?: boolean+ category?: string+ permissionKeys?: Array<string>+}+export type ResetMemberPasswordReply = {id?: stringpassword?: string@@ -1939,6 +1954,16 @@ export type UpdateMfaStatusRes = {message?: string}+export type UpdateMemberRbacRolesReply = {+ accountId?: string+ roles?: Array<RbacRole>+}++export type UpdateMemberRbacRolesReq = {+ id?: string+ roleIds?: Array<string>+}+export type UpdateMemberReply = {account?: Account}diff --git a/packages/contracts/generated/enterprise/zod.gen.ts b/packages/contracts/generated/enterprise/zod.gen.tsindex 8e4251b2095..d7a42b35d4c 100644--- a/packages/contracts/generated/enterprise/zod.gen.ts+++ b/packages/contracts/generated/enterprise/zod.gen.ts@@ -1492,6 +1492,21 @@ export const zPluginInstallationSettingsReply = z.object({restrictToMarketplaceOnly: z.boolean().optional(),})+export const zRbacRole = z.object({+ id: z.string().optional(),+ type: z.string().optional(),+ name: z.string().optional(),+ description: z.string().optional(),+ isBuiltin: z.boolean().optional(),+ category: z.string().optional(),+ permissionKeys: z.array(z.string()).optional(),+})++export const zGetMemberRbacRolesReply = z.object({+ accountId: z.string().optional(),+ roles: z.array(zRbacRole).optional(),+})+export const zResetMemberPasswordReply = z.object({id: z.string().optional(),password: z.string().optional(),@@ -1944,6 +1959,16 @@ export const zUpdateMfaStatusRes = z.object({message: z.string().optional(),})+export const zUpdateMemberRbacRolesReply = z.object({+ accountId: z.string().optional(),+ roles: z.array(zRbacRole).optional(),+})++export const zUpdateMemberRbacRolesReq = z.object({+ id: z.string().optional(),+ roleIds: z.array(z.string()).optional(),+})+export const zUpdateMemberReply = z.object({account: zAccount.optional(),})diff --git a/packages/contracts/openapi-ts.api.config.ts b/packages/contracts/openapi-ts.api.config.tsindex 26c9e4cef40..8fce8a25bd3 100644--- a/packages/contracts/openapi-ts.api.config.ts+++ b/packages/contracts/openapi-ts.api.config.ts@@ -183,7 +183,17 @@ const addOperationIds = (document: SwaggerDocument) => {}const hasSuccessResponse = (operation: SwaggerOperation) => {- return Object.keys(operation.responses ?? {}).some(status => /^2\d\d$/.test(status))+ return Object.entries(operation.responses ?? {}).some(([status, response]) => {+ if (!/^2\d\d$/.test(status))+ return false+ if (!isObject(response))+ return false+ const content = (response as JsonObject).content+ // 204 No Content is a valid success response without a body+ if (!isObject(content) || Object.keys(content).length === 0)+ return status === '204'+ return true+ })}const filterContractOperations = (document: SwaggerDocument) => {diff --git a/web/__tests__/app-sidebar/dataset-info-flow.test.tsx b/web/__tests__/app-sidebar/dataset-info-flow.test.tsxindex 3093b2809dc..bff6f5a29c5 100644--- a/web/__tests__/app-sidebar/dataset-info-flow.test.tsx+++ b/web/__tests__/app-sidebar/dataset-info-flow.test.tsx@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import DatasetInfo from '@/app/components/app-sidebar/dataset-info'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'import { RETRIEVE_METHOD } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'const mockReplace = vi.fn()const mockInvalidDatasetList = vi.fn()@@ -33,11 +34,6 @@ vi.mock('@/context/dataset-detail', () => ({}),}))-vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: { isCurrentWorkspaceDatasetOperator: boolean }) => unknown) =>- selector({ isCurrentWorkspaceDatasetOperator: false }),-}))-vi.mock('@/hooks/use-knowledge', () => ({useKnowledge: () => ({formatIndexingTechniqueAndMethod: () => 'indexing-technique',@@ -153,6 +149,11 @@ const createDataset = (overrides: Partial<DataSet> = {}): DataSet => ({enable_api: false,is_multimodal: false,is_published: true,+ permission_keys: [+ DatasetACLPermission.Edit,+ DatasetACLPermission.Delete,+ DatasetACLPermission.ImportExportDSL,+ ],...overrides,})diff --git a/web/__tests__/app/app-access-control-flow.test.tsx b/web/__tests__/app/app-access-control-flow.test.tsxindex 415b48c5cad..3ab3587f258 100644--- a/web/__tests__/app/app-access-control-flow.test.tsx+++ b/web/__tests__/app/app-access-control-flow.test.tsx@@ -56,7 +56,7 @@ vi.mock('@/hooks/use-async-window-open', () => ({useAsyncWindowOpen: () => vi.fn(),}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useGetUserCanAccessApp: () => ({data: { result: true },isLoading: false,@@ -127,7 +127,8 @@ describe('App Access Control Flow', () => {})it('refreshes app detail after confirming access control updates', async () => {- renderWithQueryClient(<AppPublisher publishedAt={1700000000} />)+ const { queryClient } = renderWithQueryClient(<AppPublisher publishedAt={1700000000} />)+ const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue()fireEvent.click(screen.getByRole('button', { name: 'workflow.common.publish' }))fireEvent.click(screen.getByText('app.accessControlDialog.accessItems.specific'))@@ -137,11 +138,7 @@ describe('App Access Control Flow', () => {fireEvent.click(screen.getByRole('button', { name: 'confirm-access-control' }))await waitFor(() => {- expect(mockFetchAppDetailDirect).toHaveBeenCalledWith({ url: '/apps', id: 'app-1' })- expect(mockSetAppDetail).toHaveBeenCalledWith(expect.objectContaining({- id: 'app-1',- access_mode: AccessMode.PUBLIC,- }))+ expect(invalidateQueriesSpy).toHaveBeenCalledWith({ queryKey: ['apps', 'detail', 'app-1'] })})await waitFor(() => {diff --git a/web/__tests__/app/app-publisher-flow.test.tsx b/web/__tests__/app/app-publisher-flow.test.tsxindex 593211ce9dd..37019fba17e 100644--- a/web/__tests__/app/app-publisher-flow.test.tsx+++ b/web/__tests__/app/app-publisher-flow.test.tsx@@ -59,7 +59,7 @@ vi.mock('@/hooks/use-async-window-open', () => ({useAsyncWindowOpen: () => mockOpenAsyncWindow,}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useGetUserCanAccessApp: () => ({data: { result: true },isLoading: false,diff --git a/web/__tests__/apps/app-card-operations-flow.test.tsx b/web/__tests__/apps/app-card-operations-flow.test.tsxindex 67bd892b4ec..1c8624ddde9 100644--- a/web/__tests__/apps/app-card-operations-flow.test.tsx+++ b/web/__tests__/apps/app-card-operations-flow.test.tsx@@ -17,6 +17,7 @@ import { AppCard } from '@/app/components/apps/app-card'import { AccessMode } from '@/models/access-control'import { exportAppConfig, updateAppInfo } from '@/service/apps'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'let mockIsCurrentWorkspaceEditor = truelet mockSystemFeatures = {@@ -82,6 +83,17 @@ vi.mock('@/next/dynamic', () => ({vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: mockIsCurrentWorkspaceEditor ? ['app.create_and_management'] : [],+ }),+ useSelector: <T,>(selector: (state: {+ isCurrentWorkspaceEditor: boolean+ userProfile: { id: string }+ workspacePermissionKeys: string[]+ }) => T): T => selector({+ isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: mockIsCurrentWorkspaceEditor ? ['app.create_and_management'] : [],}),}))@@ -121,7 +133,7 @@ vi.mock('@/service/workflow', () => ({fetchWorkflowDraft: vi.fn().mockResolvedValue({ environment_variables: [] }),}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useGetUserCanAccessApp: () => ({ data: { result: true }, isLoading: false }),}))@@ -234,6 +246,14 @@ const createMockApp = (overrides: Partial<App> = {}): App => ({tags: overrides.tags ?? [],access_mode: overrides.access_mode ?? AccessMode.PUBLIC,max_active_requests: overrides.max_active_requests ?? null,+ created_by: overrides.created_by ?? 'user-1',+ permission_keys: overrides.permission_keys ?? [+ AppACLPermission.Edit,+ AppACLPermission.ImportExportDSL,+ AppACLPermission.Delete,+ AppACLPermission.ReleaseAndVersion,+ AppACLPermission.AccessConfig,+ ],})const mockOnRefresh = vi.fn()@@ -350,12 +370,11 @@ describe('App Card Operations Flow', () => {// -- Access mode display --describe('Access Mode Display', () => {- it('should not render operations menu for non-editor users', () => {+ it('should not render operations menu when user has no app permissions', () => {mockIsCurrentWorkspaceEditor = false- renderAppCard({ name: 'Readonly App' })+ renderAppCard({ name: 'Readonly App', created_by: 'another-user', permission_keys: [] })- expect(screen.queryByText('app.editApp')).not.toBeInTheDocument()- expect(screen.queryByText('common.operation.delete')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'common.operation.more' })).not.toBeInTheDocument()})})diff --git a/web/__tests__/apps/app-list-browsing-flow.test.tsx b/web/__tests__/apps/app-list-browsing-flow.test.tsxindex 39d9219be66..555702a66f9 100644--- a/web/__tests__/apps/app-list-browsing-flow.test.tsx+++ b/web/__tests__/apps/app-list-browsing-flow.test.tsx@@ -20,6 +20,7 @@ import { AppModeEnum } from '@/types/app'let mockIsCurrentWorkspaceEditor = truelet mockIsCurrentWorkspaceDatasetOperator = falselet mockIsLoadingCurrentWorkspace = false+let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']let mockSystemFeatures = {branding: { enabled: false },@@ -65,6 +66,12 @@ vi.mock('@/context/app-context', () => ({isCurrentWorkspaceDatasetOperator: mockIsCurrentWorkspaceDatasetOperator,isLoadingCurrentWorkspace: mockIsLoadingCurrentWorkspace,userProfile: { id: 'member-1' },+ isLoadingWorkspacePermissionKeys: mockIsLoadingCurrentWorkspace,+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -215,6 +222,7 @@ describe('App List Browsing Flow', () => {mockIsCurrentWorkspaceEditor = truemockIsCurrentWorkspaceDatasetOperator = falsemockIsLoadingCurrentWorkspace = false+ mockWorkspacePermissionKeys = ['app.create_and_management']mockSystemFeatures = {branding: { enabled: false },webapp_auth: { enabled: false },@@ -303,8 +311,9 @@ describe('App List Browsing Flow', () => {expect(screen.getByRole('button', { name: 'common.operation.create' })).toBeInTheDocument()})- it('should hide the create menu when user is not a workspace editor', () => {+ it('should hide the create menu when user lacks app creation permission', () => {mockIsCurrentWorkspaceEditor = false+ mockWorkspacePermissionKeys = []mockPages = [createPage([createMockApp({ name: 'Test App' }),])]@@ -312,6 +321,9 @@ describe('App List Browsing Flow', () => {renderList()expect(screen.queryByRole('button', { name: 'common.operation.create' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'app.newApp.startFromBlank' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'app.newApp.startFromTemplate' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'app.importDSL' })).not.toBeInTheDocument()})})@@ -346,8 +358,9 @@ describe('App List Browsing Flow', () => {expect(screen.getByText('app.newApp.dropDSLToCreateApp')).toBeInTheDocument()})- it('should hide drag-drop hint for non-editors', () => {+ it('should hide drag-drop hint without app creation permission', () => {mockIsCurrentWorkspaceEditor = false+ mockWorkspacePermissionKeys = []mockPages = [createPage([createMockApp()])]renderList()diff --git a/web/__tests__/apps/create-app-flow.test.tsx b/web/__tests__/apps/create-app-flow.test.tsxindex 1fcc22c4d28..237dec91230 100644--- a/web/__tests__/apps/create-app-flow.test.tsx+++ b/web/__tests__/apps/create-app-flow.test.tsx@@ -21,6 +21,7 @@ import { AppModeEnum } from '@/types/app'let mockIsCurrentWorkspaceEditor = truelet mockIsCurrentWorkspaceDatasetOperator = falselet mockIsLoadingCurrentWorkspace = false+let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']let mockSystemFeatures = {branding: { enabled: false },webapp_auth: { enabled: false },@@ -51,6 +52,12 @@ vi.mock('@/context/app-context', () => ({isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,isCurrentWorkspaceDatasetOperator: mockIsCurrentWorkspaceDatasetOperator,isLoadingCurrentWorkspace: mockIsLoadingCurrentWorkspace,+ isLoadingWorkspacePermissionKeys: mockIsLoadingCurrentWorkspace,+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -261,6 +268,7 @@ describe('Create App Flow', () => {mockIsCurrentWorkspaceEditor = truemockIsCurrentWorkspaceDatasetOperator = falsemockIsLoadingCurrentWorkspace = false+ mockWorkspacePermissionKeys = ['app.create_and_management']mockSystemFeatures = {branding: { enabled: false },webapp_auth: { enabled: false },@@ -282,8 +290,9 @@ describe('Create App Flow', () => {expect(screen.getByText('app.importDSL')).toBeInTheDocument()})- it('should not render the create menu when user is not an editor', () => {+ it('should render disabled the create menu when user lacks app creation permission', () => {mockIsCurrentWorkspaceEditor = false+ mockWorkspacePermissionKeys = []renderList()expect(screen.queryByRole('button', { name: 'common.operation.create' })).not.toBeInTheDocument()diff --git a/web/__tests__/billing/billing-integration.test.tsx b/web/__tests__/billing/billing-integration.test.tsxindex 57f6faddcc7..2fde9b506f4 100644--- a/web/__tests__/billing/billing-integration.test.tsx+++ b/web/__tests__/billing/billing-integration.test.tsx@@ -127,6 +127,11 @@ const setupProviderContext = (planOverrides: PlanOverrides = {}, extra: Record<sconst setupAppContext = (overrides: Record<string, unknown> = {}) => {mockAppCtx = {isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [+ 'billing.view',+ 'billing.manage',+ 'billing.subscription.manage',+ ],userProfile: { email: '[email protected]' },langGeniusVersionInfo: { current_version: '1.0.0' },...overrides,@@ -228,9 +233,12 @@ describe('Billing Page + Plan Integration', () => {// Verify billing URL button visibility and behaviordescribe('Billing URL button', () => {- it('should show billing button when enableBilling and isCurrentWorkspaceManager', () => {+ it('should show billing button when subscription management permission is granted', () => {setupProviderContext({ type: Plan.sandbox })- setupAppContext({ isCurrentWorkspaceManager: true })+ setupAppContext({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.subscription.manage'],+ })render(<Billing />)@@ -238,9 +246,12 @@ describe('Billing Page + Plan Integration', () => {expect(screen.getByText(/viewBillingAction/i)).toBeInTheDocument()})- it('should hide billing button when user is not workspace manager', () => {+ it('should hide billing button when subscription management permission is missing', () => {setupProviderContext({ type: Plan.sandbox })- setupAppContext({ isCurrentWorkspaceManager: false })+ setupAppContext({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['billing.view', 'billing.manage'],+ })render(<Billing />)@@ -254,6 +265,17 @@ describe('Billing Page + Plan Integration', () => {expect(screen.queryByText(/viewBillingTitle/i)).not.toBeInTheDocument()})++ it('should hide billing button when no billing permissions are granted', () => {+ setupProviderContext({ type: Plan.sandbox })+ setupAppContext({+ workspacePermissionKeys: [],+ })++ render(<Billing />)++ expect(screen.queryByText(/viewBillingTitle/i)).not.toBeInTheDocument()+ })})})diff --git a/web/__tests__/billing/cloud-plan-payment-flow.test.tsx b/web/__tests__/billing/cloud-plan-payment-flow.test.tsxindex 7682de5f884..5a80f8cd456 100644--- a/web/__tests__/billing/cloud-plan-payment-flow.test.tsx+++ b/web/__tests__/billing/cloud-plan-payment-flow.test.tsx@@ -60,6 +60,11 @@ vi.mock('@/next/navigation', () => ({const setupAppContext = (overrides: Record<string, unknown> = {}) => {mockAppCtx = {isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [+ 'billing.view',+ 'billing.manage',+ 'billing.subscription.manage',+ ],...overrides,}}@@ -276,8 +281,27 @@ describe('Cloud Plan Payment Flow', () => {// ─── 5. Permission Check ────────────────────────────────────────────────describe('Permission check', () => {- it('should show error toast when non-manager clicks upgrade button', async () => {- setupAppContext({ isCurrentWorkspaceManager: false })+ it('should change plans when billing manage permission is granted without manager role', async () => {+ setupAppContext({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.manage'],+ })+ const user = userEvent.setup()+ renderCloudPlanItem({ currentPlan: Plan.sandbox, plan: Plan.professional })++ const button = getPlanButton('billing.plansCommon.startBuilding')+ await user.click(button)++ await waitFor(() => {+ expect(mockFetchSubscriptionUrls).toHaveBeenCalledWith(Plan.professional, 'month')+ })+ })++ it('should show error toast when billing manage permission is missing for plan changes', async () => {+ setupAppContext({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.view', 'billing.subscription.manage'],+ })const user = userEvent.setup()renderCloudPlanItem({ currentPlan: Plan.sandbox, plan: Plan.professional })@@ -287,8 +311,41 @@ describe('Cloud Plan Payment Flow', () => {await waitFor(() => {expect(screen.getByText('billing.buyPermissionDeniedTip')).toBeInTheDocument()})- // Should not proceed with paymentexpect(mockFetchSubscriptionUrls).not.toHaveBeenCalled()})++ it('should open billing portal when subscription management permission is granted without manager role', async () => {+ setupAppContext({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.subscription.manage'],+ })+ const user = userEvent.setup()+ renderCloudPlanItem({ currentPlan: Plan.professional, plan: Plan.professional })++ const button = getPlanButton('billing.plansCommon.currentPlan')+ await user.click(button)++ await waitFor(() => {+ expect(mockOpenAsyncWindow).toHaveBeenCalled()+ })+ expect(mockFetchSubscriptionUrls).not.toHaveBeenCalled()+ })++ it('should show error toast when subscription management permission is missing for current paid plan', async () => {+ setupAppContext({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.view', 'billing.manage'],+ })+ const user = userEvent.setup()+ renderCloudPlanItem({ currentPlan: Plan.professional, plan: Plan.professional })++ const button = getPlanButton('billing.plansCommon.currentPlan')+ await user.click(button)++ await waitFor(() => {+ expect(screen.getByText('billing.buyPermissionDeniedTip')).toBeInTheDocument()+ })+ expect(mockOpenAsyncWindow).not.toHaveBeenCalled()+ })})})diff --git a/web/__tests__/billing/education-verification-flow.test.tsx b/web/__tests__/billing/education-verification-flow.test.tsxindex 6098d446348..42131506208 100644--- a/web/__tests__/billing/education-verification-flow.test.tsx+++ b/web/__tests__/billing/education-verification-flow.test.tsx@@ -143,6 +143,11 @@ const setupContexts = (}mockAppCtx = {isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [+ 'billing.view',+ 'billing.manage',+ 'billing.subscription.manage',+ ],userProfile: { email: '[email protected]' },langGeniusVersionInfo: { current_version: '1.0.0' },...appOverrides,diff --git a/web/__tests__/billing/pricing-modal-flow.test.tsx b/web/__tests__/billing/pricing-modal-flow.test.tsxindex 2ec72986181..c06f56772d0 100644--- a/web/__tests__/billing/pricing-modal-flow.test.tsx+++ b/web/__tests__/billing/pricing-modal-flow.test.tsx@@ -112,6 +112,11 @@ const setupContexts = (planOverrides: Record<string, unknown> = {}, appOverrides}mockAppCtx = {isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [+ 'billing.view',+ 'billing.manage',+ 'billing.subscription.manage',+ ],userProfile: { email: '[email protected]' },langGeniusVersionInfo: { current_version: '1.0.0' },...appOverrides,diff --git a/web/__tests__/billing/self-hosted-plan-flow.test.tsx b/web/__tests__/billing/self-hosted-plan-flow.test.tsxindex f2b5cd3531c..08a3d0fed54 100644--- a/web/__tests__/billing/self-hosted-plan-flow.test.tsx+++ b/web/__tests__/billing/self-hosted-plan-flow.test.tsx@@ -49,6 +49,7 @@ vi.mock('@/app/components/billing/pricing/plans/self-hosted-plan-item/list', ()const setupAppContext = (overrides: Record<string, unknown> = {}) => {mockAppCtx = {isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['billing.manage'],...overrides,}}@@ -179,8 +180,22 @@ describe('Self-Hosted Plan Flow', () => {// ─── 3. Permission Check ────────────────────────────────────────────────describe('Permission check', () => {- it('should show error toast when non-manager clicks community button', async () => {- setupAppContext({ isCurrentWorkspaceManager: false })+ it('should redirect when billing manage permission is granted without manager role', async () => {+ setupAppContext({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.manage'],+ })+ const user = userEvent.setup()+ renderSelfHostedPlanItem(SelfHostedPlan.community)++ const button = screen.getByRole('button')+ await user.click(button)++ expect(assignedHref).toBe(getStartedWithCommunityUrl)+ })++ it('should show error toast when billing manage permission is missing for community button', async () => {+ setupAppContext({ workspacePermissionKeys: [] })const user = userEvent.setup()renderSelfHostedPlanItem(SelfHostedPlan.community)@@ -194,8 +209,8 @@ describe('Self-Hosted Plan Flow', () => {expect(assignedHref).toBe('')})- it('should show error toast when non-manager clicks premium button', async () => {- setupAppContext({ isCurrentWorkspaceManager: false })+ it('should show error toast when billing manage permission is missing for premium button', async () => {+ setupAppContext({ workspacePermissionKeys: [] })const user = userEvent.setup()renderSelfHostedPlanItem(SelfHostedPlan.premium)@@ -208,8 +223,8 @@ describe('Self-Hosted Plan Flow', () => {expect(assignedHref).toBe('')})- it('should show error toast when non-manager clicks enterprise button', async () => {- setupAppContext({ isCurrentWorkspaceManager: false })+ it('should show error toast when billing manage permission is missing for enterprise button', async () => {+ setupAppContext({ workspacePermissionKeys: [] })const user = userEvent.setup()renderSelfHostedPlanItem(SelfHostedPlan.enterprise)diff --git a/web/__tests__/custom/custom-page-flow.test.tsx b/web/__tests__/custom/custom-page-flow.test.tsxindex 66158ec5062..5650f0893c5 100644--- a/web/__tests__/custom/custom-page-flow.test.tsx+++ b/web/__tests__/custom/custom-page-flow.test.tsx@@ -51,7 +51,7 @@ const createBrandState = (overrides: Partial<ReturnType<typeof useWebAppBrand>>webappBrandRemoved: false,uploadDisabled: false,workspaceLogo: 'https://example.com/workspace-logo.png',- isCurrentWorkspaceManager: true,+ canManageCustomBrand: true,isSandbox: false,handleApply: vi.fn(),handleCancel: vi.fn(),diff --git a/web/__tests__/datasets/dataset-settings-flow.test.tsx b/web/__tests__/datasets/dataset-settings-flow.test.tsxindex eaafcafe626..1c07128eb67 100644--- a/web/__tests__/datasets/dataset-settings-flow.test.tsx+++ b/web/__tests__/datasets/dataset-settings-flow.test.tsx@@ -16,6 +16,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'import { IndexingType } from '@/app/components/datasets/create/step-two'import { ChunkingMode, DatasetPermission, DataSourceType, WeightedScoreEnum } from '@/models/datasets'import { RETRIEVE_METHOD } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'// --- Mocks ---@@ -28,7 +29,13 @@ const mockInvalidDatasetList = vi.fn()const mockUpdateDatasetSetting = vi.fn().mockResolvedValue({})vi.mock('@/context/app-context', () => ({- useSelector: () => false,+ useSelector: <T,>(selector: (state: {+ userProfile: { id: string }+ workspacePermissionKeys: string[]+ }) => T): T => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: ['dataset.create_and_management'],+ }),}))vi.mock('@/service/datasets', () => ({@@ -128,6 +135,7 @@ const createMockDataset = (overrides?: Partial<DataSet>): DataSet => ({runtime_mode: 'general',enable_api: true,is_multimodal: false,+ permission_keys: [DatasetACLPermission.Edit],...overrides,} as DataSet)diff --git a/web/__tests__/develop/api-key-management-flow.test.tsx b/web/__tests__/develop/api-key-management-flow.test.tsxindex 233e152f8fa..0267fdd45e1 100644--- a/web/__tests__/develop/api-key-management-flow.test.tsx+++ b/web/__tests__/develop/api-key-management-flow.test.tsx@@ -86,13 +86,13 @@ describe('API Key management flow', () => {expect(screen.getByText('https://api.dify.ai/v1')).toBeInTheDocument()expect(screen.getByText('appApi.ok')).toBeInTheDocument()- expect(screen.getByText('appApi.apiKey')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'appApi.apiKey' })).toBeDisabled()})it('clicking API Key button opens SecretKeyModal with real modal content', async () => {const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })- render(<ApiServer apiBaseUrl="https://api.dify.ai/v1" appId="app-1" />)+ render(<ApiServer apiBaseUrl="https://api.dify.ai/v1" appId="app-1" canManageApiKey />)// Click API Key button (rendered by SecretKeyButton)await act(async () => {@@ -112,7 +112,7 @@ describe('API Key management flow', () => {const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })mockIsLoading.mockReturnValue(true)- render(<ApiServer apiBaseUrl="https://api.dify.ai/v1" appId="app-1" />)+ render(<ApiServer apiBaseUrl="https://api.dify.ai/v1" appId="app-1" canManageApiKey />)await act(async () => {await user.click(screen.getByText('appApi.apiKey'))@@ -130,7 +130,7 @@ describe('API Key management flow', () => {it('modal can be closed by clicking X icon', async () => {const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })- render(<ApiServer apiBaseUrl="https://api.dify.ai/v1" appId="app-1" />)+ render(<ApiServer apiBaseUrl="https://api.dify.ai/v1" appId="app-1" canManageApiKey />)// Open modalawait act(async () => {@@ -143,7 +143,7 @@ describe('API Key management flow', () => {})// Click X icon to close- const closeIcon = document.body.querySelector('svg.cursor-pointer')+ const closeIcon = document.body.querySelector('.i-heroicons-x-mark-20-solid.cursor-pointer')expect(closeIcon).toBeInTheDocument()await act(async () => {@@ -161,7 +161,7 @@ describe('API Key management flow', () => {const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })const { rerender } = render(- <ApiServer apiBaseUrl="http://localhost:5001/v1" appId="app-dev" />,+ <ApiServer apiBaseUrl="http://localhost:5001/v1" appId="app-dev" canManageApiKey />,)expect(screen.getByText('http://localhost:5001/v1')).toBeInTheDocument()@@ -177,14 +177,14 @@ describe('API Key management flow', () => {})// Close modal, update URL and re-verify- const xIcon = document.body.querySelector('svg.cursor-pointer')+ const xIcon = document.body.querySelector('.i-heroicons-x-mark-20-solid.cursor-pointer')await act(async () => {await user.click(xIcon!)})await flushUI()rerender(- <ApiServer apiBaseUrl="https://api.production.com/v1" appId="app-prod" />,+ <ApiServer apiBaseUrl="https://api.production.com/v1" appId="app-prod" canManageApiKey />,)expect(screen.getByText('https://api.production.com/v1')).toBeInTheDocument()diff --git a/web/__tests__/develop/develop-page-flow.test.tsx b/web/__tests__/develop/develop-page-flow.test.tsxindex 703f7362f1f..4c4bcd0f064 100644--- a/web/__tests__/develop/develop-page-flow.test.tsx+++ b/web/__tests__/develop/develop-page-flow.test.tsx@@ -56,6 +56,8 @@ vi.mock('@/context/app-context', () => ({isCurrentWorkspaceManager: true,isCurrentWorkspaceEditor: true,}),+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) =>+ selector({ userProfile: { id: 'user-1' }, workspacePermissionKeys: ['app.create_and_management'] }),}))vi.mock('@/hooks/use-timestamp', () => ({@@ -108,6 +110,7 @@ describe('DevelopMain page flow', () => {name: 'Test App',api_base_url: 'https://api.test.com/v1',mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.edit'],}render(<DevelopMain appId="app-1" />)@@ -128,6 +131,7 @@ describe('DevelopMain page flow', () => {name: 'Chat App',api_base_url: 'https://api.test.com/v1',mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.edit'],}const { container } = render(<DevelopMain appId="app-1" />)@@ -150,6 +154,7 @@ describe('DevelopMain page flow', () => {name: 'My App',api_base_url: 'https://api.example.com/v1',mode: AppModeEnum.COMPLETION,+ permission_keys: ['app.acl.edit'],}rerender(<DevelopMain appId="app-1" />)@@ -166,6 +171,7 @@ describe('DevelopMain page flow', () => {name: 'Test App',api_base_url: 'https://api.test.com/v1',mode: AppModeEnum.WORKFLOW,+ permission_keys: ['app.acl.edit'],}render(<DevelopMain appId="app-1" />)@@ -196,6 +202,7 @@ describe('DevelopMain page flow', () => {name: `${mode} App`,api_base_url: 'https://api.test.com/v1',mode,+ permission_keys: ['app.acl.edit'],}const { container, unmount } = render(<DevelopMain appId="app-1" />)@@ -216,6 +223,7 @@ describe('DevelopMain page flow', () => {name: 'Test App',api_base_url: 'https://api.test.com/v1',mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.edit'],}render(<DevelopMain appId="app-1" />)diff --git a/web/__tests__/embedded-user-id-store.test.tsx b/web/__tests__/embedded-user-id-store.test.tsxindex 7e9eec644bc..7adb33b7ffd 100644--- a/web/__tests__/embedded-user-id-store.test.tsx+++ b/web/__tests__/embedded-user-id-store.test.tsx@@ -1,23 +1,25 @@import { screen, waitFor } from '@testing-library/react'import * as React from 'react'-import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'+import { renderToString } from 'react-dom/server'+import { createSystemFeaturesWrapper, renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'import WebAppStoreProvider, { useWebAppStore } from '@/context/web-app-context'import { AccessMode } from '@/models/access-control'-vi.mock('@/next/navigation', () => ({+const navigationMocks = vi.hoisted(() => ({usePathname: vi.fn(() => '/chatbot/sample-app'),- useSearchParams: vi.fn(() => {- const params = new URLSearchParams()- return params- }),+ useSearchParams: vi.fn(() => new URLSearchParams()),+}))++const useGetWebAppAccessModeByCodeMock = vi.hoisted(() => vi.fn())++vi.mock('@/next/navigation', () => ({+ usePathname: navigationMocks.usePathname,+ useSearchParams: navigationMocks.useSearchParams,}))vi.mock('@/service/use-share', () => ({- useGetWebAppAccessModeByCode: vi.fn(() => ({- isLoading: false,- data: { accessMode: AccessMode.PUBLIC },- })),+ useGetWebAppAccessModeByCode: (...args: unknown[]) => useGetWebAppAccessModeByCodeMock(...args),}))const mockGetProcessedSystemVariablesFromUrlParams = vi.fn()@@ -61,10 +63,50 @@ const initialWebAppStore = (() => {beforeEach(() => {mockGetProcessedSystemVariablesFromUrlParams.mockReset()+ navigationMocks.usePathname.mockReset()+ navigationMocks.usePathname.mockReturnValue('/chatbot/sample-app')+ navigationMocks.useSearchParams.mockReset()+ navigationMocks.useSearchParams.mockReturnValue(new URLSearchParams())+ useGetWebAppAccessModeByCodeMock.mockReset()+ useGetWebAppAccessModeByCodeMock.mockReturnValue({+ isLoading: false,+ data: { accessMode: AccessMode.PUBLIC },+ })useWebAppStore.setState(initialWebAppStore, true)})describe('WebAppStoreProvider embedded user id handling', () => {+ it('parses share code from redirect_url during server render without window', () => {+ const params = new URLSearchParams()+ params.set('redirect_url', encodeURIComponent('/chatbot/redirected-app'))+ navigationMocks.usePathname.mockReturnValue('/webapp-signin')+ navigationMocks.useSearchParams.mockReturnValue(params)+ const originalWindow = globalThis.window+ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: undefined,+ })+ const { wrapper: Wrapper } = createSystemFeaturesWrapper()++ try {+ expect(() => renderToString(+ <Wrapper>+ <WebAppStoreProvider>+ <div />+ </WebAppStoreProvider>+ </Wrapper>,+ )).not.toThrow()+ }+ finally {+ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: originalWindow,+ })+ }++ expect(useGetWebAppAccessModeByCodeMock).toHaveBeenCalledWith('redirected-app')+ })+it('hydrates embedded user and conversation ids from system variables', async () => {mockGetProcessedSystemVariablesFromUrlParams.mockResolvedValue({user_id: 'iframe-user-123',diff --git a/web/__tests__/explore/explore-app-list-flow.test.tsx b/web/__tests__/explore/explore-app-list-flow.test.tsxindex f93353443c2..786fef89486 100644--- a/web/__tests__/explore/explore-app-list-flow.test.tsx+++ b/web/__tests__/explore/explore-app-list-flow.test.tsx@@ -15,6 +15,13 @@ import { fetchAppDetail, fetchAppList, fetchBanners } from '@/service/explore'import { useMembers } from '@/service/use-common'import { AppModeEnum } from '@/types/app'+type MockAppContext = {+ userProfile: { id: string }+ workspacePermissionKeys: string[]+}++const mockUseAppContext = vi.hoisted(() => vi.fn<() => MockAppContext>())+const allCategoriesEn = 'explore.apps.allCategories:{"lng":"en"}'let mockTabValue = allCategoriesEnconst mockSetTab = vi.fn()@@ -109,7 +116,8 @@ vi.mock('@/service/client', () => ({}))vi.mock('@/context/app-context', () => ({- useAppContext: vi.fn(),+ useAppContext: mockUseAppContext,+ useSelector: <T,>(selector: (state: MockAppContext) => T): T => selector(mockUseAppContext()),}))vi.mock('@/service/use-common', () => ({@@ -188,6 +196,7 @@ const createApp = (overrides: Partial<App> = {}): App => ({const mockMemberRole = (hasEditPermission: boolean) => {;(useAppContext as Mock).mockReturnValue({userProfile: { id: 'user-1' },+ workspacePermissionKeys: hasEditPermission ? ['app.create_and_management'] : [],});(useMembers as Mock).mockReturnValue({data: {diff --git a/web/__tests__/explore/installed-app-flow.test.tsx b/web/__tests__/explore/installed-app-flow.test.tsxindex 66d88cdf926..b37e69bce92 100644--- a/web/__tests__/explore/installed-app-flow.test.tsx+++ b/web/__tests__/explore/installed-app-flow.test.tsx@@ -11,7 +11,7 @@ import { render, screen, waitFor } from '@testing-library/react'import InstalledApp from '@/app/components/explore/installed-app'import { useWebAppStore } from '@/context/web-app-context'import { AccessMode } from '@/models/access-control'-import { useGetUserCanAccessApp } from '@/service/access-control'+import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'import { useGetInstalledAppAccessModeByAppId, useGetInstalledAppMeta, useGetInstalledAppParams, useGetInstalledApps } from '@/service/use-explore'import { AppModeEnum } from '@/types/app'@@ -19,7 +19,7 @@ vi.mock('@/context/web-app-context', () => ({useWebAppStore: vi.fn(),}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useGetUserCanAccessApp: vi.fn(),}))diff --git a/web/__tests__/header/nav-flow.test.tsx b/web/__tests__/header/nav-flow.test.tsxindex dba7b4bf4af..33927f19da4 100644--- a/web/__tests__/header/nav-flow.test.tsx+++ b/web/__tests__/header/nav-flow.test.tsx@@ -43,6 +43,7 @@ vi.mock('@/app/components/app/store', () => ({vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,+ workspacePermissionKeys: mockIsCurrentWorkspaceEditor ? ['app.create_and_management'] : [],}),}))diff --git a/web/__tests__/plugins/plugin-auth-flow.test.tsx b/web/__tests__/plugins/plugin-auth-flow.test.tsxindex c4d28e3f34b..cc42d5204ba 100644--- a/web/__tests__/plugins/plugin-auth-flow.test.tsx+++ b/web/__tests__/plugins/plugin-auth-flow.test.tsx@@ -90,7 +90,6 @@ describe('Plugin Authentication Flow Integration', () => {canOAuth: false,canApiKey: true,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -108,7 +107,6 @@ describe('Plugin Authentication Flow Integration', () => {canOAuth: true,canApiKey: true,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -125,7 +123,6 @@ describe('Plugin Authentication Flow Integration', () => {canOAuth: false,canApiKey: true,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -147,7 +144,6 @@ describe('Plugin Authentication Flow Integration', () => {credentials: [{ id: 'cred-1', name: 'My API Key', is_default: true },],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -165,7 +161,6 @@ describe('Plugin Authentication Flow Integration', () => {canOAuth: false,canApiKey: true,credentials: [{ id: 'cred-1', name: 'Key', is_default: true }],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -187,7 +182,6 @@ describe('Plugin Authentication Flow Integration', () => {canOAuth: false,canApiKey: true,credentials: [{ id: 'cred-1', name: 'Key', is_default: true }],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -207,7 +201,6 @@ describe('Plugin Authentication Flow Integration', () => {canOAuth: false,canApiKey: true,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -229,7 +222,6 @@ describe('Plugin Authentication Flow Integration', () => {canOAuth: true,canApiKey: false,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -258,7 +250,6 @@ describe('Plugin Authentication Flow Integration', () => {{ id: 'cred-2', name: 'API Key 2', is_default: false },{ id: 'cred-3', name: 'OAuth Token', is_default: false, credential_type: CredentialTypeEnum.OAUTH2 },],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})diff --git a/web/__tests__/plugins/plugin-page-shell-flow.test.tsx b/web/__tests__/plugins/plugin-page-shell-flow.test.tsxindex 421d805d072..ac090ec577b 100644--- a/web/__tests__/plugins/plugin-page-shell-flow.test.tsx+++ b/web/__tests__/plugins/plugin-page-shell-flow.test.tsx@@ -34,6 +34,14 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: {+ current_version: '1.0.0',+ },+ workspacePermissionKeys: [+ 'plugin.install',+ 'plugin.manage',+ 'plugin.plugin_preferences',+ ],}),}))diff --git a/web/__tests__/tools/provider-list-shell-flow.test.tsx b/web/__tests__/tools/provider-list-shell-flow.test.tsxindex 346834c642c..dcf88dda46e 100644--- a/web/__tests__/tools/provider-list-shell-flow.test.tsx+++ b/web/__tests__/tools/provider-list-shell-flow.test.tsx@@ -20,6 +20,18 @@ vi.mock('@/app/components/plugins/hooks', () => ({}),}))+vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ userProfile: { id: 'user-1', timezone: 'UTC' },+ workspacePermissionKeys: ['tool.manage', 'mcp.manage', 'plugin.install', 'plugin.manage', 'plugin.plugin_preferences'],+ langGeniusVersionInfo: { current_version: '1.0.0' },+ }),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ workspacePermissionKeys: ['tool.manage', 'mcp.manage', 'plugin.install', 'plugin.manage', 'plugin.plugin_preferences'],+ }),+}))+vi.mock('@/service/use-tools', () => ({useAllToolProviders: () => ({data: [@@ -69,6 +81,8 @@ vi.mock('@/service/use-plugins', () => ({: null,}),useInvalidateInstalledPluginList: () => mockInvalidateInstalledPluginList,+ useMutationPluginPermissionSettings: () => ({ mutate: vi.fn(), isPending: false }),+ usePluginPermissionSettings: () => ({ data: undefined, isLoading: false, isFetching: false, error: null }),}))vi.mock('@/app/components/tools/labels/filter', () => ({@@ -152,6 +166,10 @@ vi.mock('@/app/components/tools/mcp', () => ({default: ({ searchText }: { searchText: string }) => <div data-testid="mcp-list">{searchText}</div>,}))+vi.mock('@/app/components/header/account-setting/update-setting-dialog', () => ({+ default: () => null,+}))+const renderProviderList = (searchParams = '') => {const { wrapper: SysWrapper } = createSystemFeaturesWrapper({systemFeatures: { enable_marketplace: true },diff --git a/web/__tests__/tools/tool-browsing-and-filtering.test.tsx b/web/__tests__/tools/tool-browsing-and-filtering.test.tsxindex d470326805e..be00661f710 100644--- a/web/__tests__/tools/tool-browsing-and-filtering.test.tsx+++ b/web/__tests__/tools/tool-browsing-and-filtering.test.tsx@@ -43,9 +43,23 @@ vi.mock('@/app/components/plugins/hooks', () => ({}),}))+vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ userProfile: { id: 'user-1', timezone: 'UTC' },+ workspacePermissionKeys: ['tool.manage', 'mcp.manage', 'plugin.install', 'plugin.manage', 'plugin.plugin_preferences'],+ langGeniusVersionInfo: { current_version: '1.0.0' },+ }),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ workspacePermissionKeys: ['tool.manage', 'mcp.manage', 'plugin.install', 'plugin.manage', 'plugin.plugin_preferences'],+ }),+}))+vi.mock('@/service/use-plugins', () => ({useCheckInstalled: () => ({ data: null }),useInvalidateInstalledPluginList: () => vi.fn(),+ useMutationPluginPermissionSettings: () => ({ mutate: vi.fn(), isPending: false }),+ usePluginPermissionSettings: () => ({ data: undefined, isLoading: false, isFetching: false, error: null }),}))const mockCollections: Collection[] = [@@ -198,6 +212,10 @@ vi.mock('@/app/components/tools/mcp', () => ({default: () => <div data-testid="mcp-list">MCP List</div>,}))+vi.mock('@/app/components/header/account-setting/update-setting-dialog', () => ({+ default: () => null,+}))+vi.mock('@langgenius/dify-ui/cn', () => ({cn: (...args: unknown[]) => args.filter(Boolean).join(' '),}))diff --git a/web/__tests__/tools/tool-provider-detail-flow.test.tsx b/web/__tests__/tools/tool-provider-detail-flow.test.tsxindex 7b873601d48..e99e7ac24c2 100644--- a/web/__tests__/tools/tool-provider-detail-flow.test.tsx+++ b/web/__tests__/tools/tool-provider-detail-flow.test.tsx@@ -48,6 +48,9 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: true,}),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: ['tool.manage', 'credential.manage', 'credential.use'],+ }),}))const mockSetShowModelModal = vi.fn()diff --git a/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsx b/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsxindex 761d8c1c8bf..8fa969fa899 100644--- a/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsx+++ b/web/app/(commonLayout)/__tests__/role-route-guard.spec.tsx@@ -47,14 +47,14 @@ vi.mock('@/service/client', () => ({const mockUseQuery = vi.mocked(useQuery)-function renderGuard(children: ReactNode, systemFeatures: { enable_app_deploy?: boolean } = {}) {+function renderGuard(children: ReactNode) {return renderWithSystemFeatures(<RoleRouteGuard>{children}</RoleRouteGuard>,{systemFeatures: {- enable_app_deploy: systemFeatures.enable_app_deploy ?? true,+ enable_app_deploy: true,},},)@@ -70,86 +70,37 @@ const setCurrentWorkspaceQuery = (overrides: { role?: string, isPending?: booleadescribe('RoleRouteGuard', () => {beforeEach(() => {vi.clearAllMocks()- mockPathname = '/apps'+ mockPathname = '/app/app-1'setCurrentWorkspaceQuery()})- it('should render loading while workspace is loading', () => {- setCurrentWorkspaceQuery({ isPending: true })-- renderGuard(<div>content</div>)-- expect(screen.getByRole('status')).toBeInTheDocument()- expect(screen.queryByText('content')).not.toBeInTheDocument()- expect(mocks.redirect).not.toHaveBeenCalled()- expect(mocks.currentWorkspaceQueryOptions).toHaveBeenCalledWith({- select: expect.any(Function),- })- })-- it('should redirect dataset operator on guarded routes', () => {- setCurrentWorkspaceQuery({ role: 'dataset_operator' })-- expect(() => renderGuard(<div>content</div>)).toThrow('NEXT_REDIRECT:/datasets')-- expect(mocks.redirect).toHaveBeenCalledWith('/datasets')- })-- it('should allow dataset operator on routes outside the guarded list', () => {- mockPathname = '/new-route'- setCurrentWorkspaceQuery({ role: 'dataset_operator' })+ it.each(['/', '/apps', '/app/app-1', '/deployments/create', '/snippets', '/explore/apps', '/tools', '/integrations', '/datasets'])('should allow %s without workspace role checks', (pathname) => {+ mockPathname = pathnamerenderGuard(<div>content</div>)expect(screen.getByText('content')).toBeInTheDocument()expect(mocks.redirect).not.toHaveBeenCalled()+ expect(mockUseQuery).not.toHaveBeenCalled()+ expect(mocks.currentWorkspaceQueryOptions).not.toHaveBeenCalled()})- it('should redirect dataset operator on deployments routes', () => {- mockPathname = '/deployments/create'- setCurrentWorkspaceQuery({ role: 'dataset_operator' })-- expect(() => renderGuard(<div>content</div>)).toThrow('NEXT_REDIRECT:/datasets')-- expect(mocks.redirect).toHaveBeenCalledWith('/datasets')- })-- it('should prefer app deploy redirect when app deploy is disabled', () => {- mockPathname = '/deployments/create'- setCurrentWorkspaceQuery({ role: 'dataset_operator' })-- expect(() => renderGuard(<div>content</div>, { enable_app_deploy: false })).toThrow('NEXT_REDIRECT:/')-- expect(mocks.redirect).toHaveBeenCalledWith('/')- })-- it('should redirect app deploy routes when app deploy is disabled', () => {+ it('should redirect deployments route when app deploy is disabled', () => {mockPathname = '/deployments/create'- setCurrentWorkspaceQuery({ role: 'editor' })-- expect(() => renderGuard(<div>content</div>, { enable_app_deploy: false })).toThrow('NEXT_REDIRECT:/')-- expect(mocks.redirect).toHaveBeenCalledWith('/')- })-- it('should allow dataset operator on non-guarded routes', () => {- mockPathname = '/plugins'- setCurrentWorkspaceQuery({ role: 'dataset_operator' })-- renderGuard(<div>content</div>)-- expect(screen.getByText('content')).toBeInTheDocument()- expect(mocks.redirect).not.toHaveBeenCalled()- })- it('should not block non-guarded routes while workspace is loading', () => {- mockPathname = '/plugins'- setCurrentWorkspaceQuery({ isPending: true })-- renderGuard(<div>content</div>)+ expect(() => renderWithSystemFeatures(+ <RoleRouteGuard>+ <div>content</div>+ </RoleRouteGuard>,+ {+ systemFeatures: {+ enable_app_deploy: false,+ },+ },+ )).toThrow('NEXT_REDIRECT:/apps')- expect(screen.getByText('content')).toBeInTheDocument()- expect(screen.queryByRole('status')).not.toBeInTheDocument()- expect(mocks.redirect).not.toHaveBeenCalled()+ expect(mocks.redirect).toHaveBeenCalledWith('/apps')+ expect(mockUseQuery).not.toHaveBeenCalled()+ expect(mocks.currentWorkspaceQueryOptions).not.toHaveBeenCalled()})})diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsxindex f1e12b34c70..f9742f35e13 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx@@ -4,11 +4,12 @@ import { useStore } from '@/app/components/app/store'import { usePathname, useRouter } from '@/next/navigation'import { fetchAppDetailDirect } from '@/service/apps'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import AppDetailLayout from '../layout-main'const mockReplace = vi.fn()let mockPathname = '/app/app-1/workflow'-let mockIsCurrentWorkspaceEditor = true+let mockIsLoadingWorkspacePermissionKeys = falsevi.mock('@/next/navigation', () => ({usePathname: vi.fn(),@@ -22,8 +23,10 @@ vi.mock('@/service/apps', () => ({vi.mock('@/context/app-context', () => ({useAppContext: () => ({currentWorkspace: { id: 'workspace-1' },- isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,isLoadingCurrentWorkspace: false,+ isLoadingWorkspacePermissionKeys: mockIsLoadingWorkspacePermissionKeys,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],}),}))@@ -39,6 +42,7 @@ const createAppDetail = (overrides: Partial<App> = {}) => ({id: 'app-1',name: 'Demo App',mode: AppModeEnum.WORKFLOW,+ permission_keys: [AppACLPermission.ViewLayout, AppACLPermission.Monitor],...overrides,}) as App@@ -52,7 +56,7 @@ describe('AppDetailLayout', () => {beforeEach(() => {vi.clearAllMocks()mockPathname = '/app/app-1/workflow'- mockIsCurrentWorkspaceEditor = true+ mockIsLoadingWorkspacePermissionKeys = falsemockUsePathname.mockImplementation(() => mockPathname)mockUseRouter.mockReturnValue({back: vi.fn(),@@ -99,8 +103,171 @@ describe('AppDetailLayout', () => {})it('should redirect restricted app pages before exposing app detail content', async () => {- mockIsCurrentWorkspaceEditor = falsemockPathname = '/app/app-1/logs'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [AppACLPermission.ViewLayout] }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/app/app-1/workflow')+ })+ expect(screen.queryByText('App page content')).not.toBeInTheDocument()+ expect(useStore.getState().appDetail).toBeUndefined()+ })++ it('should allow users with monitor access to open logs directly', async () => {+ mockPathname = '/app/app-1/logs'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [AppACLPermission.Monitor] }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitForAppContent()++ expect(mockReplace).not.toHaveBeenCalledWith('/app/app-1/overview')+ expect(useStore.getState().appDetail?.id).toBe('app-1')+ })++ it('should allow users with layout access to open workflow pages directly', async () => {+ mockPathname = '/app/app-1/workflow'++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitForAppContent()++ expect(mockReplace).not.toHaveBeenCalledWith('/app/app-1/overview')+ expect(useStore.getState().appDetail?.id).toBe('app-1')+ })++ it('should redirect workflow pages when layout access is missing', async () => {+ mockPathname = '/app/app-1/workflow'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [] }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/app/app-1/develop')+ })+ expect(screen.queryByText('App page content')).not.toBeInTheDocument()+ expect(useStore.getState().appDetail).toBeUndefined()+ })++ it('should redirect overview pages when monitor access is missing', async () => {+ mockPathname = '/app/app-1/overview'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [AppACLPermission.ViewLayout] }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/app/app-1/workflow')+ })+ expect(screen.queryByText('App page content')).not.toBeInTheDocument()+ expect(useStore.getState().appDetail).toBeUndefined()+ })++ it('should wait for workspace permission keys before redirecting restricted pages', async () => {+ mockIsLoadingWorkspacePermissionKeys = true+ mockPathname = '/app/app-1/overview'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [AppACLPermission.ViewLayout] }))++ const { rerender } = render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitFor(() => {+ expect(mockFetchAppDetailDirect).toHaveBeenCalledTimes(1)+ })+ expect(mockReplace).not.toHaveBeenCalled()+ expect(screen.queryByText('App page content')).not.toBeInTheDocument()++ mockIsLoadingWorkspacePermissionKeys = false+ rerender(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/app/app-1/workflow')+ })+ })++ it('should allow users with monitor access to open overview directly', async () => {+ mockPathname = '/app/app-1/overview'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [AppACLPermission.Monitor] }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitForAppContent()++ expect(mockReplace).not.toHaveBeenCalled()+ expect(useStore.getState().appDetail?.id).toBe('app-1')+ })++ it('should redirect access config pages when access config access is missing', async () => {+ mockPathname = '/app/app-1/access-config'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [AppACLPermission.ViewLayout] }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/app/app-1/workflow')+ })+ expect(screen.queryByText('App page content')).not.toBeInTheDocument()+ expect(useStore.getState().appDetail).toBeUndefined()+ })++ it('should allow users with access config access to open access config directly', async () => {+ mockPathname = '/app/app-1/access-config'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({ permission_keys: [AppACLPermission.AccessConfig] }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitForAppContent()++ expect(mockReplace).not.toHaveBeenCalled()+ expect(useStore.getState().appDetail?.id).toBe('app-1')+ })++ it('should redirect annotation pages when edit access is missing', async () => {+ mockPathname = '/app/app-1/annotations'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({+ mode: AppModeEnum.CHAT,+ permission_keys: [AppACLPermission.Monitor],+ }))render(<AppDetailLayout appId="app-1">@@ -114,4 +281,23 @@ describe('AppDetailLayout', () => {expect(screen.queryByText('App page content')).not.toBeInTheDocument()expect(useStore.getState().appDetail).toBeUndefined()})++ it('should allow users with edit access to open annotations directly', async () => {+ mockPathname = '/app/app-1/annotations'+ mockFetchAppDetailDirect.mockResolvedValue(createAppDetail({+ mode: AppModeEnum.CHAT,+ permission_keys: [AppACLPermission.Edit],+ }))++ render(+ <AppDetailLayout appId="app-1">+ <div>App page content</div>+ </AppDetailLayout>,+ )++ await waitForAppContent()++ expect(mockReplace).not.toHaveBeenCalled()+ expect(useStore.getState().appDetail?.id).toBe('app-1')+ })})diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/access-config/__tests__/page.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/access-config/__tests__/page.spec.tsxnew file mode 100644index 00000000000..1aa69c277b4--- /dev/null+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/access-config/__tests__/page.spec.tsx@@ -0,0 +1,24 @@+import { render, screen } from '@testing-library/react'+import AccessConfig from '../page'++vi.mock('@/app/components/app/access-config', () => ({+ default: ({ appId }: { appId: string }) => (+ <div data-testid="app-access-config" data-app-id={appId}>+ app access config+ {appId}+ </div>+ ),+}))++describe('App access config route', () => {+ // Route rendering resolves the async app id params for the client page.+ describe('Rendering', () => {+ it('should pass app id from route params', async () => {+ render(await AccessConfig({+ params: Promise.resolve({ locale: 'en-US', appId: 'app-route-id' }),+ }))++ expect(screen.getByTestId('app-access-config')).toHaveAttribute('data-app-id', 'app-route-id')+ })+ })+})diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/access-config/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/access-config/page.tsxnew file mode 100644index 00000000000..85ce85bc398--- /dev/null+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/access-config/page.tsx@@ -0,0 +1,16 @@+import type { Locale } from '@/i18n-config'+import AppAccessConfigPage from '@/app/components/app/access-config'++export type AccessConfigPageProps = {+ params: Promise<{ locale: Locale, appId: string }>+}++const AccessConfig = async (props: AccessConfigPageProps) => {+ const params = await props.params++ const { appId } = params++ return <AppAccessConfigPage appId={appId} />+}++export default AccessConfigdiff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsxindex 8eb6a9bd0e3..dcbcba4116d 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx@@ -13,6 +13,8 @@ import useDocumentTitle from '@/hooks/use-document-title'import { usePathname, useRouter } from '@/next/navigation'import { fetchAppDetailDirect } from '@/service/apps'import { AppModeEnum } from '@/types/app'+import { getRedirectionPath } from '@/utils/app-redirection'+import { getAppACLCapabilities } from '@/utils/permission'type IAppDetailLayoutProps = {children: React.ReactNode@@ -34,7 +36,7 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {const { t } = useTranslation()const router = useRouter()const pathname = usePathname()- const { isCurrentWorkspaceEditor, isLoadingCurrentWorkspace, currentWorkspace } = useAppContext()+ const { isLoadingCurrentWorkspace, isLoadingWorkspacePermissionKeys, currentWorkspace, userProfile, workspacePermissionKeys } = useAppContext()const { appDetail, setAppDetail } = useStore(useShallow(state => ({appDetail: state.appDetail,setAppDetail: state.setAppDetail,@@ -84,15 +86,33 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {}, [appId, router, setAppDetail])useEffect(() => {- if (!routeAppDetail || !currentWorkspace.id || isLoadingCurrentWorkspace || isLoadingAppDetail)+ if (!routeAppDetail || !currentWorkspace.id || isLoadingCurrentWorkspace || isLoadingWorkspacePermissionKeys || isLoadingAppDetail)returnif (routeAppDetail.id !== appId)return- // redirection- const canIEditApp = isCurrentWorkspaceEditor- if (!canIEditApp && (pathname.endsWith('configuration') || pathname.endsWith('workflow') || pathname.endsWith('logs') || pathname.endsWith('annotations'))) {- router.replace(`/app/${appId}/overview`)+ const appACLCapabilities = getAppACLCapabilities(routeAppDetail.permission_keys, {+ currentUserId: userProfile?.id,+ resourceMaintainer: routeAppDetail.maintainer,+ workspacePermissionKeys,+ })+ const isLayoutPath = pathname.endsWith('configuration') || pathname.endsWith('workflow')+ const isLogsPath = pathname.endsWith('logs')+ const isAnnotationsPath = pathname.endsWith('annotations')+ const isOverviewPath = pathname.endsWith('overview')+ const isAccessConfigPath = pathname.endsWith('access-config')+ if (+ (isLayoutPath && !appACLCapabilities.canAccessLayout)+ || (isLogsPath && !appACLCapabilities.canMonitor)+ || (isAnnotationsPath && !appACLCapabilities.canEdit)+ || (isOverviewPath && !appACLCapabilities.canMonitor)+ || (isAccessConfigPath && !appACLCapabilities.canAccessConfig)+ ) {+ router.replace(getRedirectionPath(routeAppDetail, {+ currentUserId: userProfile?.id,+ resourceMaintainer: routeAppDetail.maintainer,+ workspacePermissionKeys,+ }))return}if ((routeAppDetail.mode === AppModeEnum.WORKFLOW || routeAppDetail.mode === AppModeEnum.ADVANCED_CHAT) && (pathname).endsWith('configuration')) {@@ -105,7 +125,7 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {if (appDetailRes && appDetail?.id !== appDetailRes.id)setAppDetail({ ...appDetailRes, enable_sso: false })- }, [appDetail?.id, appDetailRes, appId, currentWorkspace.id, isCurrentWorkspaceEditor, isLoadingAppDetail, isLoadingCurrentWorkspace, pathname, routeAppDetail, router, setAppDetail])+ }, [appDetail?.id, appDetailRes, appId, currentWorkspace.id, isLoadingAppDetail, isLoadingCurrentWorkspace, isLoadingWorkspacePermissionKeys, pathname, routeAppDetail, router, setAppDetail, userProfile?.id, workspacePermissionKeys])if (!appDetail) {return (diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/card-view.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/card-view.spec.tsxnew file mode 100644index 00000000000..4099e1fce56--- /dev/null+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/card-view.spec.tsx@@ -0,0 +1,159 @@+import type { App } from '@/types/app'+import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import CardView from '../card-view'++const mockAppState = vi.hoisted(() => ({+ appDetail: {+ id: 'app-1',+ mode: 'chat',+ permission_keys: [] as string[],+ },+ setAppDetail: vi.fn(),+}))++const mockUpdateAppSiteStatus = vi.hoisted(() => vi.fn())+const mockUpdateAppSiteConfig = vi.hoisted(() => vi.fn())+const mockUpdateAppSiteAccessToken = vi.hoisted(() => vi.fn())+const mockInvalidateQueries = vi.hoisted(() => vi.fn())++vi.mock('@/app/components/app/store', () => ({+ useStore: <T,>(selector: (state: typeof mockAppState) => T): T => selector(mockAppState),+}))++vi.mock('@/service/use-workflow', () => ({+ useAppWorkflow: () => ({ data: undefined }),+}))++vi.mock('@/service/apps', () => ({+ updateAppSiteStatus: (...args: unknown[]) => mockUpdateAppSiteStatus(...args),+ updateAppSiteConfig: (...args: unknown[]) => mockUpdateAppSiteConfig(...args),+ updateAppSiteAccessToken: (...args: unknown[]) => mockUpdateAppSiteAccessToken(...args),+}))++vi.mock('@tanstack/react-query', () => ({+ useQueryClient: () => ({+ invalidateQueries: mockInvalidateQueries,+ }),+}))++vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', () => ({+ collaborationManager: {+ onAppStateUpdate: vi.fn(() => vi.fn()),+ },+}))++vi.mock('@/app/components/workflow/collaboration/core/websocket-manager', () => ({+ webSocketClient: {+ getSocket: vi.fn(() => null),+ },+}))++vi.mock('@/app/components/app/overview/app-card', () => ({+ default: ({+ cardType,+ onChangeStatus,+ onGenerateCode,+ onSaveSiteConfig,+ }: {+ cardType: string+ onChangeStatus?: (value: boolean) => void+ onGenerateCode?: () => void+ onSaveSiteConfig?: (params: Record<string, unknown>) => void+ }) => (+ <div>+ <button type="button" onClick={() => onChangeStatus?.(true)}>+ toggle+ {' '}+ {cardType}+ </button>+ {onGenerateCode && (+ <button type="button" onClick={() => onGenerateCode()}>+ generate+ {' '}+ {cardType}+ </button>+ )}+ {onSaveSiteConfig && (+ <button type="button" onClick={() => onSaveSiteConfig({ title: 'Site title' })}>+ save+ {' '}+ {cardType}+ </button>+ )}+ </div>+ ),+}))++vi.mock('@/app/components/app/overview/trigger-card', () => ({+ default: () => <div>trigger card</div>,+}))++vi.mock('@/app/components/tools/mcp/mcp-service-card', () => ({+ default: () => <div>mcp card</div>,+}))++describe('CardView ACL edit guards', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockAppState.appDetail = {+ id: 'app-1',+ mode: 'chat',+ permission_keys: [],+ }+ mockUpdateAppSiteStatus.mockResolvedValue(mockAppState.appDetail as App)+ mockUpdateAppSiteConfig.mockResolvedValue(mockAppState.appDetail as App)+ mockUpdateAppSiteAccessToken.mockResolvedValue({ code: 'token' })+ mockInvalidateQueries.mockResolvedValue(undefined)+ })++ // User-facing card actions should not mutate app settings without app ACL edit permission.+ describe('Permissions', () => {+ it('should not call write APIs when app ACL edit permission is missing', async () => {+ const user = userEvent.setup()++ render(<CardView appId="app-1" />)++ await user.click(screen.getByRole('button', { name: /toggle webapp/ }))+ await user.click(screen.getByRole('button', { name: /save webapp/ }))+ await user.click(screen.getByRole('button', { name: /generate webapp/ }))+ await user.click(screen.getByRole('button', { name: /toggle api/ }))++ expect(mockUpdateAppSiteStatus).not.toHaveBeenCalled()+ expect(mockUpdateAppSiteConfig).not.toHaveBeenCalled()+ expect(mockUpdateAppSiteAccessToken).not.toHaveBeenCalled()+ })++ it('should call write APIs when app ACL edit permission is present', async () => {+ const user = userEvent.setup()+ mockAppState.appDetail.permission_keys = ['app.acl.edit']++ render(<CardView appId="app-1" />)++ await user.click(screen.getByRole('button', { name: /toggle webapp/ }))+ await user.click(screen.getByRole('button', { name: /save webapp/ }))+ await user.click(screen.getByRole('button', { name: /generate webapp/ }))+ await user.click(screen.getByRole('button', { name: /toggle api/ }))++ await waitFor(() => {+ expect(mockUpdateAppSiteStatus).toHaveBeenCalledTimes(2)+ })+ expect(mockUpdateAppSiteStatus).toHaveBeenCalledWith({+ url: '/apps/app-1/site-enable',+ body: { enable_site: true },+ })+ expect(mockUpdateAppSiteStatus).toHaveBeenCalledWith({+ url: '/apps/app-1/api-enable',+ body: { enable_api: true },+ })+ expect(mockUpdateAppSiteConfig).toHaveBeenCalledWith({+ url: '/apps/app-1/site',+ body: { title: 'Site title' },+ })+ expect(mockUpdateAppSiteAccessToken).toHaveBeenCalledWith({+ url: '/apps/app-1/site/access-token-reset',+ })+ expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['apps', 'detail', 'app-1'] })+ })+ })+})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.tsxnew file mode 100644index 00000000000..75516435b66--- /dev/null+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx@@ -0,0 +1,127 @@+import { render, screen } from '@testing-library/react'+import { AppACLPermission } from '@/utils/permission'+import ChartView from '../chart-view'++const testState = vi.hoisted(() => ({+ appDetail: {+ id: 'app-1',+ mode: 'chat',+ maintainer: 'maintainer-1',+ permission_keys: [] as string[],+ },+ currentUserId: 'user-1',+ workspacePermissionKeys: [] as string[],+ chartRenderSpy: vi.fn(),+}))++vi.mock('@/app/components/app/store', () => ({+ useStore: <T,>(selector: (state: { appDetail: typeof testState.appDetail }) => T): T => selector({+ appDetail: testState.appDetail,+ }),+}))++vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn((selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: testState.currentUserId },+ workspacePermissionKeys: testState.workspacePermissionKeys,+ })),+}))++vi.mock('@/context/i18n', () => ({+ useDocLink: () => (path: string) => path,+}))++vi.mock('@/app/components/app/overview/app-chart', () => ({+ AvgResponseTime: () => {+ testState.chartRenderSpy('avg-response-time')+ return <div>avg response time chart</div>+ },+ AvgSessionInteractions: () => {+ testState.chartRenderSpy('avg-session-interactions')+ return <div>avg session interactions chart</div>+ },+ AvgUserInteractions: () => {+ testState.chartRenderSpy('avg-user-interactions')+ return <div>avg user interactions chart</div>+ },+ ConversationsChart: () => {+ testState.chartRenderSpy('conversations')+ return <div>conversations chart</div>+ },+ CostChart: () => {+ testState.chartRenderSpy('cost')+ return <div>cost chart</div>+ },+ EndUsersChart: () => {+ testState.chartRenderSpy('end-users')+ return <div>end users chart</div>+ },+ MessagesChart: () => {+ testState.chartRenderSpy('messages')+ return <div>messages chart</div>+ },+ TokenPerSecond: () => {+ testState.chartRenderSpy('token-per-second')+ return <div>token per second chart</div>+ },+ UserSatisfactionRate: () => {+ testState.chartRenderSpy('user-satisfaction-rate')+ return <div>user satisfaction rate chart</div>+ },+ WorkflowCostChart: () => {+ testState.chartRenderSpy('workflow-cost')+ return <div>workflow cost chart</div>+ },+ WorkflowDailyTerminalsChart: () => {+ testState.chartRenderSpy('workflow-daily-terminals')+ return <div>workflow daily terminals chart</div>+ },+ WorkflowMessagesChart: () => {+ testState.chartRenderSpy('workflow-messages')+ return <div>workflow messages chart</div>+ },+}))++vi.mock('../long-time-range-picker', () => ({+ default: () => <button type="button">long time range</button>,+}))++vi.mock('../time-range-picker', () => ({+ default: () => <button type="button">time range</button>,+}))++describe('ChartView monitor permission', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ testState.appDetail = {+ id: 'app-1',+ mode: 'chat',+ maintainer: 'maintainer-1',+ permission_keys: [],+ }+ testState.currentUserId = 'user-1'+ testState.workspacePermissionKeys = []+ })++ // Monitoring charts are part of the app monitor permission surface.+ describe('Permissions', () => {+ it('should not render monitoring charts when app monitor permission is missing', () => {+ render(<ChartView appId="app-1" headerRight={<button type="button">header action</button>} />)++ expect(screen.queryByRole('heading', { name: 'common.appMenus.overview' })).not.toBeInTheDocument()+ expect(screen.queryByText('header action')).not.toBeInTheDocument()+ expect(testState.chartRenderSpy).not.toHaveBeenCalled()+ })++ it('should render monitoring charts when app monitor permission is granted', () => {+ testState.appDetail.permission_keys = [AppACLPermission.Monitor]++ render(<ChartView appId="app-1" headerRight={<button type="button">header action</button>} />)++ expect(screen.getByRole('heading', { name: 'common.appMenus.overview' })).toBeInTheDocument()+ expect(screen.getByText('header action')).toBeInTheDocument()+ expect(screen.getByText('conversations chart')).toBeInTheDocument()+ expect(testState.chartRenderSpy).toHaveBeenCalledWith('conversations')+ })+ })+})diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/view.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/view.spec.tsxnew file mode 100644index 00000000000..5ac607fc301--- /dev/null+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/view.spec.tsx@@ -0,0 +1,82 @@+import type { ReactNode } from 'react'+import { render, screen } from '@testing-library/react'+import { AppACLPermission } from '@/utils/permission'+import OverviewView from '../view'++const testState = vi.hoisted(() => ({+ appDetail: {+ id: 'app-1',+ mode: 'chat',+ maintainer: 'maintainer-1',+ permission_keys: [] as string[],+ },+ currentUserId: 'user-1',+ workspacePermissionKeys: [] as string[],+}))++vi.mock('@/app/components/app/store', () => ({+ useStore: <T,>(selector: (state: { appDetail: typeof testState.appDetail }) => T): T => selector({+ appDetail: testState.appDetail,+ }),+}))++vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn((selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: testState.currentUserId },+ workspacePermissionKeys: testState.workspacePermissionKeys,+ })),+}))++vi.mock('@/app/components/app/overview/apikey-info-panel', () => ({+ default: () => <div>api key info panel</div>,+}))++vi.mock('../chart-view', () => ({+ default: ({ appId, headerRight }: { appId: string, headerRight: ReactNode }) => (+ <div>+ chart view+ {' '}+ {appId}+ {headerRight}+ </div>+ ),+}))++vi.mock('../tracing/panel', () => ({+ default: () => <button type="button">tracing</button>,+}))++describe('OverviewView monitor permission', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ testState.appDetail = {+ id: 'app-1',+ mode: 'chat',+ maintainer: 'maintainer-1',+ permission_keys: [],+ }+ testState.currentUserId = 'user-1'+ testState.workspacePermissionKeys = []+ })++ // The overview page should be controlled as one monitor-permission surface.+ describe('Permissions', () => {+ it('should not render overview page content when app monitor permission is missing', () => {+ render(<OverviewView appId="app-1" />)++ expect(screen.queryByText('api key info panel')).not.toBeInTheDocument()+ expect(screen.queryByText(/chart view app-1/)).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'tracing' })).not.toBeInTheDocument()+ })++ it('should render overview page content when app monitor permission is granted', () => {+ testState.appDetail.permission_keys = [AppACLPermission.Monitor]++ render(<OverviewView appId="app-1" />)++ expect(screen.getByText('api key info panel')).toBeInTheDocument()+ expect(screen.getByText(/chart view app-1/)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'tracing' })).toBeInTheDocument()+ })+ })+})diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsxindex 06465e3551a..fd7a35c86da 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsx@@ -6,8 +6,8 @@ import type { UpdateAppSiteCodeResponse } from '@/models/app'import type { App } from '@/types/app'import type { I18nKeysByPrefix } from '@/types/i18n'import { toast } from '@langgenius/dify-ui/toast'+import { useQueryClient } from '@tanstack/react-query'import { useSetLocalStorage } from 'foxact/use-local-storage'-import * as React from 'react'import { useCallback, useEffect, useMemo } from 'react'import { useTranslation } from 'react-i18next'import AppCard from '@/app/components/app/overview/app-card'@@ -19,15 +19,17 @@ import { collaborationManager } from '@/app/components/workflow/collaboration/coimport { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'import { isTriggerNode } from '@/app/components/workflow/types'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import {- fetchAppDetail,updateAppSiteAccessToken,updateAppSiteConfig,updateAppSiteStatus,} from '@/service/apps'+import { appDetailQueryKeyPrefix } from '@/service/use-apps'import { useAppWorkflow } from '@/service/use-workflow'import { AppModeEnum } from '@/types/app'import { asyncRunSafe } from '@/utils'+import { getAppACLCapabilities } from '@/utils/permission'type ICardViewProps = {appId: string@@ -37,8 +39,15 @@ type ICardViewProps = {const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {const { t } = useTranslation()+ const queryClient = useQueryClient()const appDetail = useAppStore(state => state.appDetail)- const setAppDetail = useAppStore(state => state.setAppDetail)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canEditApp = useMemo(() => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }).canEdit, [appDetail?.maintainer, appDetail?.permission_keys, currentUserId, workspacePermissionKeys])const isWorkflowApp = appDetail?.mode === AppModeEnum.WORKFLOWconst showMCPCard = isInPanel@@ -80,13 +89,12 @@ const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {const updateAppDetail = useCallback(async () => {try {- const res = await fetchAppDetail({ url: '/apps', id: appId })- setAppDetail({ ...res })+ await queryClient.invalidateQueries({ queryKey: [...appDetailQueryKeyPrefix, appId] })}catch (error) {console.error(error)}- }, [appId, setAppDetail])+ }, [appId, queryClient])const handleCallbackResult = (err: Error | null, message?: I18nKeysByPrefix<'common', 'actionMsg.'>) => {const type = err ? 'error' : 'success'@@ -129,6 +137,9 @@ const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {}, [appId, updateAppDetail])const onChangeSiteStatus = async (value: boolean) => {+ if (!canEditApp)+ return+const [err] = await asyncRunSafe<App>(updateAppSiteStatus({url: `/apps/${appId}/site-enable`,@@ -140,6 +151,9 @@ const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {}const onChangeApiStatus = async (value: boolean) => {+ if (!canEditApp)+ return+const [err] = await asyncRunSafe<App>(updateAppSiteStatus({url: `/apps/${appId}/api-enable`,@@ -151,6 +165,9 @@ const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {}const onSaveSiteConfig: IAppCardProps['onSaveSiteConfig'] = async (params) => {+ if (!canEditApp)+ return+const [err] = await asyncRunSafe<App>(updateAppSiteConfig({url: `/apps/${appId}/site`,@@ -164,6 +181,9 @@ const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {}const onGenerateCode = async () => {+ if (!canEditApp)+ return+const [err] = await asyncRunSafe<UpdateAppSiteCodeResponse>(updateAppSiteAccessToken({url: `/apps/${appId}/site/access-token-reset`,diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsxindex e935fee8f37..a4ee7d06a92 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx@@ -10,7 +10,9 @@ import { TIME_PERIOD_MAPPING as LONG_TIME_PERIOD_MAPPING } from '@/app/componentimport { AvgResponseTime, AvgSessionInteractions, AvgUserInteractions, ConversationsChart, CostChart, EndUsersChart, MessagesChart, TokenPerSecond, UserSatisfactionRate, WorkflowCostChart, WorkflowDailyTerminalsChart, WorkflowMessagesChart } from '@/app/components/app/overview/app-chart'import { useStore as useAppStore } from '@/app/components/app/store'import { IS_CLOUD_EDITION } from '@/config'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDocLink } from '@/context/i18n'+import { getAppACLCapabilities } from '@/utils/permission'import LongTimeRangePicker from './long-time-range-picker'import TimeRangePicker from './time-range-picker'@@ -37,6 +39,13 @@ export default function ChartView({ appId, headerRight }: IChartViewProps) {const { t } = useTranslation()const docLink = useDocLink()const appDetail = useAppStore(state => state.appDetail)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canMonitor = React.useMemo(() => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }).canMonitor, [appDetail?.maintainer, appDetail?.permission_keys, currentUserId, workspacePermissionKeys])const isChatApp = appDetail?.mode !== 'completion' && appDetail?.mode !== 'workflow'const isWorkflow = appDetail?.mode === 'workflow'const [period, setPeriod] = useState<PeriodParams>(IS_CLOUD_EDITION@@ -44,7 +53,7 @@ export default function ChartView({ appId, headerRight }: IChartViewProps) {: { name: t('filter.period.last7days', { ns: 'appLog' }), query: { start: today.subtract(7, 'day').startOf('day').format(queryDateFormat), end: today.endOf('day').format(queryDateFormat) } },)- if (!appDetail)+ if (!appDetail || !canMonitor)return nullreturn (diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsxindex 92ec0d59ec3..7b84d311fc9 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx@@ -1,7 +1,5 @@import * as React from 'react'-import ApikeyInfoPanel from '@/app/components/app/overview/apikey-info-panel'-import ChartView from './chart-view'-import TracingPanel from './tracing/panel'+import OverviewView from './view'export type IDevelopProps = {params: Promise<{ appId: string }>@@ -15,15 +13,7 @@ const Overview = async (props: IDevelopProps) => {} = paramsreturn (- <div className="flex h-full min-h-0 flex-col">- <ApikeyInfoPanel />- <div className="min-h-0 flex-1">- <ChartView- appId={appId}- headerRight={<TracingPanel />}- />- </div>- </div>+ <OverviewView appId={appId} />)}diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/panel.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/panel.spec.tsxnew file mode 100644index 00000000000..dc2970513a0--- /dev/null+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/panel.spec.tsx@@ -0,0 +1,137 @@+import type { ComponentProps, ReactNode } from 'react'+import { render, screen, waitFor } from '@testing-library/react'+import { fetchTracingConfig, fetchTracingStatus, updateTracingStatus } from '@/service/apps'+import { AppACLPermission } from '@/utils/permission'+import Panel from '../panel'++const testState = vi.hoisted(() => ({+ appPermissionKeys: [] as string[],+ workspacePermissionKeys: [] as string[],+ configButtonProps: [] as Array<{+ readOnly: boolean+ hasConfigured: boolean+ }>,+}))++vi.mock('@/next/navigation', () => ({+ usePathname: () => '/app/app-1/overview',+}))++vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn((selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: testState.workspacePermissionKeys,+ })),+}))++vi.mock('@/app/components/app/store', () => ({+ useStore: vi.fn((selector: (state: { appDetail: { permission_keys: string[] } }) => unknown) => selector({+ appDetail: {+ permission_keys: testState.appPermissionKeys,+ },+ })),+}))++vi.mock('@/service/apps', () => ({+ fetchTracingStatus: vi.fn(),+ fetchTracingConfig: vi.fn(),+ updateTracingStatus: vi.fn(),+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: vi.fn(),+}))++vi.mock('@langgenius/dify-ui/status-dot', () => ({+ StatusDot: ({ status }: { status: string }) => <span data-testid="status-dot">{status}</span>,+}))++vi.mock('@/app/components/base/icons/src/public/tracing', () => ({+ AliyunIcon: () => <span data-testid="aliyun-icon" />,+ ArizeIcon: () => <span data-testid="arize-icon" />,+ DatabricksIcon: () => <span data-testid="databricks-icon" />,+ LangfuseIcon: () => <span data-testid="langfuse-icon" />,+ LangsmithIcon: () => <span data-testid="langsmith-icon" />,+ MlflowIcon: () => <span data-testid="mlflow-icon" />,+ OpikIcon: () => <span data-testid="opik-icon" />,+ PhoenixIcon: () => <span data-testid="phoenix-icon" />,+ TencentIcon: () => <span data-testid="tencent-icon" />,+ TracingIcon: () => <span data-testid="tracing-icon" />,+ WeaveIcon: () => <span data-testid="weave-icon" />,+}))++vi.mock('../config-button', () => ({+ default: ({ children, ...props }: ComponentProps<'div'> & { readOnly: boolean, hasConfigured: boolean, children?: ReactNode }) => {+ testState.configButtonProps.push({+ readOnly: props.readOnly,+ hasConfigured: props.hasConfigured,+ })++ return (+ <div+ data-testid="config-button"+ data-read-only={String(props.readOnly)}+ data-has-configured={String(props.hasConfigured)}+ >+ {children}+ </div>+ )+ },+}))++const mockedFetchTracingStatus = vi.mocked(fetchTracingStatus)+const mockedFetchTracingConfig = vi.mocked(fetchTracingConfig)+const mockedUpdateTracingStatus = vi.mocked(updateTracingStatus)++const renderPanel = async () => {+ render(<Panel />)++ await screen.findAllByTestId('config-button')+}++describe('Tracing overview panel permissions', () => {+ beforeEach(() => {+ testState.appPermissionKeys = []+ testState.workspacePermissionKeys = []+ testState.configButtonProps = []+ mockedFetchTracingStatus.mockResolvedValue({+ enabled: false,+ tracing_provider: null,+ })+ mockedFetchTracingConfig.mockResolvedValue({+ tracing_provider: 'langfuse',+ tracing_config: {},+ has_not_configured: true,+ } as Awaited<ReturnType<typeof fetchTracingConfig>>)+ mockedUpdateTracingStatus.mockResolvedValue({+ result: 'success',+ })+ })++ afterEach(() => {+ vi.clearAllMocks()+ })++ it('marks tracing config as read-only without app monitor or workspace tracking permissions', async () => {+ await renderPanel()++ await waitFor(() => {+ expect(testState.configButtonProps[0]).toMatchObject({+ readOnly: true,+ hasConfigured: false,+ })+ })+ })++ it('allows tracing config when app ACL includes monitor permission', async () => {+ testState.appPermissionKeys = [AppACLPermission.Monitor]++ await renderPanel()++ await waitFor(() => {+ expect(testState.configButtonProps[0]).toMatchObject({+ readOnly: false,+ hasConfigured: false,+ })+ })+ })+})diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsxindex a12a28a7018..7c0de99e0f5 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx@@ -5,20 +5,29 @@ import type { TracingStatus } from '@/models/app'import { cn } from '@langgenius/dify-ui/cn'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { toast } from '@langgenius/dify-ui/toast'-import {- RiArrowDownDoubleLine,- RiEqualizer2Line,-} from '@remixicon/react'import { useBoolean } from 'ahooks'import * as React from 'react'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useStore as useAppStore } from '@/app/components/app/store'import Divider from '@/app/components/base/divider'-import { AliyunIcon, ArizeIcon, DatabricksIcon, LangfuseIcon, LangsmithIcon, MlflowIcon, OpikIcon, PhoenixIcon, TencentIcon, WeaveIcon } from '@/app/components/base/icons/src/public/tracing'+import {+ AliyunIcon,+ ArizeIcon,+ DatabricksIcon,+ LangfuseIcon,+ LangsmithIcon,+ MlflowIcon,+ OpikIcon,+ PhoenixIcon,+ TencentIcon,+ WeaveIcon,+} from '@/app/components/base/icons/src/public/tracing'import Loading from '@/app/components/base/loading'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { usePathname } from '@/next/navigation'import { fetchTracingConfig as doFetchTracingConfig, fetchTracingStatus, updateTracingStatus } from '@/service/apps'+import { getAppACLCapabilities } from '@/utils/permission'import ConfigButton from './config-button'import TracingIcon from './tracing-icon'import { TracingProvider } from './type'@@ -30,8 +39,16 @@ const Panel: FC = () => {const pathname = usePathname()const matched = /\/app\/([^/]+)/.exec(pathname)const appId = (matched?.length && matched[1]) ? matched[1] : ''- const { isCurrentWorkspaceEditor } = useAppContext()- const readOnly = !isCurrentWorkspaceEditor+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const appDetail = useAppStore(s => s.appDetail)+ const appACLCapabilities = React.useMemo(() => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }), [appDetail?.maintainer, appDetail?.permission_keys, currentUserId, workspacePermissionKeys])+ const canConfigTracing = appACLCapabilities.canMonitor+ const readOnly = !canConfigTracingconst [isLoaded, {setTrue: setLoaded,@@ -253,11 +270,11 @@ const Panel: FC = () => {<TracingIcon size="md" /><div className="mx-2 system-sm-semibold text-text-secondary">{t(`${I18N_PREFIX}.title`, { ns: 'app' })}</div><div className="rounded-md p-1">- <RiEqualizer2Line className="size-4 text-text-tertiary" />+ <span className="i-ri-equalizer-2-line size-4 text-text-tertiary" /></div><Divider type="vertical" className="h-3.5" /><div className="rounded-md p-1">- <RiArrowDownDoubleLine className="size-4 text-text-tertiary" />+ <span className="i-ri-arrow-down-double-line size-4 text-text-tertiary" /></div></div></ConfigButton>@@ -297,7 +314,7 @@ const Panel: FC = () => {</div>{InUseProviderIcon && <InUseProviderIcon className="ml-1 h-4" />}<div className="ml-2 rounded-md p-1">- <RiEqualizer2Line className="size-4 text-text-tertiary" />+ <span className="i-ri-equalizer-2-line size-4 text-text-tertiary" /></div><Divider type="vertical" className="h-3.5" /></div>diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/view.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/view.tsxnew file mode 100644index 00000000000..7f27286a657--- /dev/null+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/view.tsx@@ -0,0 +1,41 @@+'use client'++import * as React from 'react'+import ApikeyInfoPanel from '@/app/components/app/overview/apikey-info-panel'+import { useStore as useAppStore } from '@/app/components/app/store'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { getAppACLCapabilities } from '@/utils/permission'+import ChartView from './chart-view'+import TracingPanel from './tracing/panel'++type OverviewViewProps = {+ appId: string+}++const OverviewView = ({ appId }: OverviewViewProps) => {+ const appDetail = useAppStore(state => state.appDetail)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canMonitor = React.useMemo(() => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }).canMonitor, [appDetail?.maintainer, appDetail?.permission_keys, currentUserId, workspacePermissionKeys])++ if (!appDetail || !canMonitor)+ return null++ return (+ <div className="flex h-full min-h-0 flex-col">+ <ApikeyInfoPanel />+ <div className="min-h-0 flex-1">+ <ChartView+ appId={appId}+ headerRight={<TracingPanel />}+ />+ </div>+ </div>+ )+}++export default OverviewViewdiff --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 ae1fedf8312..23a9672a220 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@@ -1,6 +1,7 @@import { render, screen, waitFor } from '@testing-library/react'import { usePathname, useRouter } from '@/next/navigation'import { useDatasetDetail } from '@/service/knowledge/use-dataset'+import { DatasetACLPermission } from '@/utils/permission'import DatasetDetailLayout from '../layout-main'const mockReplace = vi.fn()@@ -17,6 +18,10 @@ vi.mock('@/service/knowledge/use-dataset', () => ({vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceDatasetOperator: false,+ isLoadingCurrentWorkspace: false,+ isLoadingWorkspacePermissionKeys: false,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],}),}))@@ -198,4 +203,94 @@ describe('DatasetDetailLayout', () => {expect(screen.getByText('Create from pipeline content').parentElement).not.toHaveClass('rounded-lg')})})++ describe('Permission Route Guards', () => {+ it('should redirect from hit testing when retrieval recall permission is missing', async () => {+ // Arrange+ mockUsePathname.mockReturnValue('/datasets/dataset-1/hitTesting')+ mockUseDatasetDetail.mockReturnValue({+ data: {+ id: 'dataset-1',+ name: 'Dataset 1',+ provider: 'external',+ runtime_mode: 'general',+ is_published: true,+ permission_keys: [],+ },+ error: null,+ refetch: vi.fn(),+ } as unknown as ReturnType<typeof useDatasetDetail>)++ // Act+ render(+ <DatasetDetailLayout datasetId="dataset-1">+ <div>Hit testing content</div>+ </DatasetDetailLayout>,+ )++ // Assert+ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/datasets/dataset-1/settings')+ })+ expect(screen.queryByText('Hit testing content')).not.toBeInTheDocument()+ })++ it('should redirect from access config when access config permission is missing', async () => {+ // Arrange+ mockUsePathname.mockReturnValue('/datasets/dataset-1/access-config')+ mockUseDatasetDetail.mockReturnValue({+ data: {+ id: 'dataset-1',+ name: 'Dataset 1',+ provider: 'vendor',+ runtime_mode: 'general',+ is_published: true,+ permission_keys: [],+ },+ error: null,+ refetch: vi.fn(),+ } as unknown as ReturnType<typeof useDatasetDetail>)++ // Act+ render(+ <DatasetDetailLayout datasetId="dataset-1">+ <div>Access config content</div>+ </DatasetDetailLayout>,+ )++ // Assert+ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/datasets/dataset-1/documents')+ })+ expect(screen.queryByText('Access config content')).not.toBeInTheDocument()+ })++ it('should render access config when access config permission is granted', () => {+ // Arrange+ mockUsePathname.mockReturnValue('/datasets/dataset-1/access-config')+ mockUseDatasetDetail.mockReturnValue({+ data: {+ id: 'dataset-1',+ name: 'Dataset 1',+ provider: 'vendor',+ runtime_mode: 'general',+ is_published: true,+ permission_keys: [DatasetACLPermission.AccessConfig],+ },+ error: null,+ refetch: vi.fn(),+ } as unknown as ReturnType<typeof useDatasetDetail>)++ // Act+ render(+ <DatasetDetailLayout datasetId="dataset-1">+ <div>Access config content</div>+ </DatasetDetailLayout>,+ )++ // Assert+ expect(screen.getByText('Access config content')).toBeInTheDocument()+ expect(mockReplace).not.toHaveBeenCalled()+ })+ })})diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/access-config/__tests__/page.spec.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/access-config/__tests__/page.spec.tsxnew file mode 100644index 00000000000..b1eec08101f--- /dev/null+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/access-config/__tests__/page.spec.tsx@@ -0,0 +1,24 @@+import { render, screen } from '@testing-library/react'+import AccessConfig from '../page'++vi.mock('@/app/components/datasets/access-config', () => ({+ default: ({ datasetId }: { datasetId: string }) => (+ <div data-testid="dataset-access-config" data-dataset-id={datasetId}>+ dataset access config+ {datasetId}+ </div>+ ),+}))++describe('Dataset access config route', () => {+ // Route rendering resolves the async dataset id params for the client page.+ describe('Rendering', () => {+ it('should pass dataset id from route params', async () => {+ render(await AccessConfig({+ params: Promise.resolve({ datasetId: 'dataset-route-id' }),+ }))++ expect(screen.getByTestId('dataset-access-config')).toHaveAttribute('data-dataset-id', 'dataset-route-id')+ })+ })+})diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/access-config/page.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/access-config/page.tsxnew file mode 100644index 00000000000..66a809a795d--- /dev/null+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/access-config/page.tsx@@ -0,0 +1,15 @@+import DatasetAccessConfigPage from '@/app/components/datasets/access-config'++type Props = {+ params: Promise<{ datasetId: string }>+}++const AccessConfig = async (props: Props) => {+ const params = await props.params++ const { datasetId } = params++ return <DatasetAccessConfigPage datasetId={datasetId} />+}++export default AccessConfigdiff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsxindex dd08e312545..3791009061d 100644--- a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx@@ -1,14 +1,17 @@'use client'import type { FC } from 'react'+import type { DataSet } from '@/models/datasets'import { cn } from '@langgenius/dify-ui/cn'import * as React from 'react'import { useEffect } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'+import { useAppContext } from '@/context/app-context'import DatasetDetailContext from '@/context/dataset-detail'import useDocumentTitle from '@/hooks/use-document-title'import { usePathname, useRouter } from '@/next/navigation'import { useDatasetDetail } from '@/service/knowledge/use-dataset'+import { getDatasetACLCapabilities } from '@/utils/permission'type IAppDetailLayoutProps = {children: React.ReactNode@@ -28,6 +31,23 @@ const shouldRedirectToDatasetList = (error: unknown) => {return status === 403 || status === 404}+const getDatasetRedirectionPath = (+ dataset: DataSet,+ datasetACLCapabilities: ReturnType<typeof getDatasetACLCapabilities>,+) => {+ if (dataset.provider === 'external') {+ if (datasetACLCapabilities.canRetrievalRecall)+ return `/datasets/${dataset.id}/hitTesting`++ return `/datasets/${dataset.id}/settings`+ }++ if (dataset.runtime_mode === 'rag_pipeline' && !dataset.is_published)+ return `/datasets/${dataset.id}/pipeline`++ return `/datasets/${dataset.id}/documents`+}+const DatasetDetailLayout: FC<IAppDetailLayoutProps> = (props) => {const {children,@@ -36,9 +56,32 @@ const DatasetDetailLayout: FC<IAppDetailLayoutProps> = (props) => {const { t } = useTranslation()const router = useRouter()const pathname = usePathname()+ const {+ isLoadingCurrentWorkspace,+ isLoadingWorkspacePermissionKeys,+ userProfile,+ workspacePermissionKeys,+ } = useAppContext()const { data: datasetRes, error, refetch: mutateDatasetRes } = useDatasetDetail(datasetId)const shouldRedirect = shouldRedirectToDatasetList(error)+ const datasetACLCapabilities = React.useMemo(() => getDatasetACLCapabilities(datasetRes?.permission_keys, {+ currentUserId: userProfile?.id,+ resourceMaintainer: datasetRes?.maintainer,+ workspacePermissionKeys,+ }), [datasetRes?.maintainer, datasetRes?.permission_keys, userProfile?.id, workspacePermissionKeys])+ const isAccessConfigPath = pathname.endsWith('/access-config')+ const isHitTestingPath = pathname.endsWith('/hitTesting')+ const isPermissionControlledPath = isAccessConfigPath || isHitTestingPath+ const isCheckingRouteAccess = !!datasetRes+ && isPermissionControlledPath+ && (isLoadingCurrentWorkspace || !!isLoadingWorkspacePermissionKeys)+ const shouldRedirectUnauthorizedRoute = !!datasetRes+ && !isCheckingRouteAccess+ && (+ (isAccessConfigPath && !datasetACLCapabilities.canAccessConfig)+ || (isHitTestingPath && !datasetACLCapabilities.canRetrievalRecall)+ )useDocumentTitle(datasetRes?.name || t('menus.datasets', { ns: 'common' }))@@ -47,12 +90,22 @@ const DatasetDetailLayout: FC<IAppDetailLayoutProps> = (props) => {router.replace('/datasets')}, [router, shouldRedirect])+ useEffect(() => {+ if (!datasetRes || !shouldRedirectUnauthorizedRoute)+ return++ router.replace(getDatasetRedirectionPath(datasetRes, datasetACLCapabilities))+ }, [datasetACLCapabilities, datasetRes, router, shouldRedirectUnauthorizedRoute])+if (!datasetRes && !error)return <Loading type="app" />if (shouldRedirect)return <Loading type="app" />+ if (isCheckingRouteAccess || shouldRedirectUnauthorizedRoute)+ return <Loading type="app" />+const isPipelinePage = pathname.endsWith('/pipeline') || pathname.includes('/create-from-pipeline')return (diff --git a/web/app/(commonLayout)/datasets/layout.spec.tsx b/web/app/(commonLayout)/datasets/layout.spec.tsxindex 7abc2253ce2..4db962ff301 100644--- a/web/app/(commonLayout)/datasets/layout.spec.tsx+++ b/web/app/(commonLayout)/datasets/layout.spec.tsx@@ -5,15 +5,19 @@ import DatasetsLayout from './layout'const mockReplace = vi.fn()const mockUseAppContext = vi.fn()+let mockPathname = '/datasets'+let mockExternalKnowledgeApiProviderEnabled: boolean | undefinedvi.mock('@/next/navigation', () => ({useRouter: () => ({replace: mockReplace,}),+ usePathname: () => mockPathname,}))vi.mock('@/context/app-context', () => ({useAppContext: () => mockUseAppContext(),+ useSelector: (selector: (state: AppContextMock) => unknown) => selector(mockUseAppContext()),}))vi.mock('@/context/external-api-panel-context', () => ({@@ -21,13 +25,18 @@ vi.mock('@/context/external-api-panel-context', () => ({}))vi.mock('@/context/external-knowledge-api-context', () => ({- ExternalKnowledgeApiProvider: ({ children }: { children: ReactNode }) => <>{children}</>,+ ExternalKnowledgeApiProvider: ({ children, enabled }: { children: ReactNode, enabled?: boolean }) => {+ mockExternalKnowledgeApiProviderEnabled = enabled+ return <>{children}</>+ },}))type AppContextMock = {isCurrentWorkspaceEditor: booleanisCurrentWorkspaceDatasetOperator: booleanisLoadingCurrentWorkspace: boolean+ isLoadingWorkspacePermissionKeys: boolean+ workspacePermissionKeys: string[]currentWorkspace: {id: string}@@ -37,6 +46,8 @@ const baseContext: AppContextMock = {isCurrentWorkspaceEditor: true,isCurrentWorkspaceDatasetOperator: false,isLoadingCurrentWorkspace: false,+ isLoadingWorkspacePermissionKeys: false,+ workspacePermissionKeys: [],currentWorkspace: {id: 'workspace-1',},@@ -52,6 +63,8 @@ const setAppContext = (overrides: Partial<AppContextMock> = {}) => {describe('DatasetsLayout', () => {beforeEach(() => {vi.clearAllMocks()+ mockPathname = '/datasets'+ mockExternalKnowledgeApiProviderEnabled = undefinedsetAppContext()})@@ -72,10 +85,64 @@ describe('DatasetsLayout', () => {expect(mockReplace).not.toHaveBeenCalled()})- it('should redirect non-editor and non-dataset-operator users to /apps', async () => {+ it('should render loading while workspace permission keys are loading', () => {+ setAppContext({+ isLoadingWorkspacePermissionKeys: true,+ workspacePermissionKeys: [],+ })++ render((+ <DatasetsLayout>+ <div>datasets</div>+ </DatasetsLayout>+ ))++ expect(screen.getByRole('status')).toBeInTheDocument()+ expect(screen.queryByText('datasets')).not.toBeInTheDocument()+ expect(mockReplace).not.toHaveBeenCalled()+ })++ it('should render children without a page-level dataset permission', () => {+ setAppContext({+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceDatasetOperator: true,+ workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'],+ })++ render((+ <DatasetsLayout>+ <div>datasets</div>+ </DatasetsLayout>+ ))++ expect(screen.getByText('datasets')).toBeInTheDocument()+ expect(mockReplace).not.toHaveBeenCalled()+ })++ it('should render children on the dataset list route without dataset permissions', () => {setAppContext({isCurrentWorkspaceEditor: false,isCurrentWorkspaceDatasetOperator: false,+ workspacePermissionKeys: [],+ })++ render((+ <DatasetsLayout>+ <div>datasets</div>+ </DatasetsLayout>+ ))++ expect(screen.getByText('datasets')).toBeInTheDocument()+ expect(mockReplace).not.toHaveBeenCalled()+ })++ it.each([+ '/datasets/create',+ '/datasets/create-from-pipeline',+ ])('should redirect direct dataset creation route to /datasets without dataset.create_and_management: %s', async (pathname) => {+ mockPathname = pathname+ setAppContext({+ workspacePermissionKeys: [],})render((@@ -86,14 +153,14 @@ describe('DatasetsLayout', () => {expect(screen.queryByText('datasets')).not.toBeInTheDocument()await waitFor(() => {- expect(mockReplace).toHaveBeenCalledWith('/apps')+ expect(mockReplace).toHaveBeenCalledWith('/datasets')})})- it('should render children for dataset operators', () => {+ it('should render direct dataset creation route when workspace has dataset.create_and_management', () => {+ mockPathname = '/datasets/create'setAppContext({- isCurrentWorkspaceEditor: false,- isCurrentWorkspaceDatasetOperator: true,+ workspacePermissionKeys: ['dataset.create_and_management'],})render((@@ -105,4 +172,66 @@ describe('DatasetsLayout', () => {expect(screen.getByText('datasets')).toBeInTheDocument()expect(mockReplace).not.toHaveBeenCalled()})++ it('should redirect direct external dataset connection route to /datasets without dataset.external.connect', async () => {+ mockPathname = '/datasets/connect'+ setAppContext({+ workspacePermissionKeys: [],+ })++ render((+ <DatasetsLayout>+ <div>datasets</div>+ </DatasetsLayout>+ ))++ expect(screen.queryByText('datasets')).not.toBeInTheDocument()+ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/datasets')+ })+ })++ it('should render direct external dataset connection route when workspace has dataset.external.connect', () => {+ mockPathname = '/datasets/connect'+ setAppContext({+ workspacePermissionKeys: ['dataset.external.connect'],+ })++ render((+ <DatasetsLayout>+ <div>datasets</div>+ </DatasetsLayout>+ ))++ expect(screen.getByText('datasets')).toBeInTheDocument()+ expect(mockReplace).not.toHaveBeenCalled()+ })++ it('should disable external knowledge API queries without dataset.external.connect', () => {+ setAppContext({+ workspacePermissionKeys: [],+ })++ render((+ <DatasetsLayout>+ <div>datasets</div>+ </DatasetsLayout>+ ))++ expect(mockExternalKnowledgeApiProviderEnabled).toBe(false)+ })++ it('should enable external knowledge API queries with dataset.external.connect', () => {+ setAppContext({+ workspacePermissionKeys: ['dataset.external.connect'],+ })++ render((+ <DatasetsLayout>+ <div>datasets</div>+ </DatasetsLayout>+ ))++ expect(mockExternalKnowledgeApiProviderEnabled).toBe(true)+ })})diff --git a/web/app/(commonLayout)/datasets/layout.tsx b/web/app/(commonLayout)/datasets/layout.tsxindex a465f8222b0..8f6777dedfb 100644--- a/web/app/(commonLayout)/datasets/layout.tsx+++ b/web/app/(commonLayout)/datasets/layout.tsx@@ -2,32 +2,53 @@import { useEffect } from 'react'import Loading from '@/app/components/base/loading'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextSelector } from '@/context/app-context'import { ExternalApiPanelProvider } from '@/context/external-api-panel-context'import { ExternalKnowledgeApiProvider } from '@/context/external-knowledge-api-context'-import { useRouter } from '@/next/navigation'+import { usePathname, useRouter } from '@/next/navigation'+import { hasPermission } from '@/utils/permission'++const isDatasetCreatePath = (pathname: string) => {+ return pathname === '/datasets/create'+ || pathname.startsWith('/datasets/create/')+ || pathname === '/datasets/create-from-pipeline'+ || pathname.startsWith('/datasets/create-from-pipeline/')+}++const isDatasetExternalConnectPath = (pathname: string) => {+ return pathname === '/datasets/connect'+ || pathname.startsWith('/datasets/connect/')+}export default function DatasetsLayout({ children }: { children: React.ReactNode }) {- const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator, currentWorkspace, isLoadingCurrentWorkspace } = useAppContext()+ const currentWorkspaceId = useAppContextSelector(state => state.currentWorkspace.id)+ const isLoadingCurrentWorkspace = useAppContextSelector(state => state.isLoadingCurrentWorkspace)+ const isLoadingWorkspacePermissionKeys = useAppContextSelector(state => state.isLoadingWorkspacePermissionKeys)+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)const router = useRouter()- const shouldRedirect = !isLoadingCurrentWorkspace- && currentWorkspace.id- && !(isCurrentWorkspaceEditor || isCurrentWorkspaceDatasetOperator)+ const pathname = usePathname()+ const isLoadingAccess = isLoadingCurrentWorkspace || !!isLoadingWorkspacePermissionKeys+ const canCreateDataset = hasPermission(workspacePermissionKeys, 'dataset.create_and_management')+ const canConnectExternalDataset = hasPermission(workspacePermissionKeys, 'dataset.external.connect')+ const shouldRedirectToDatasets = !isLoadingAccess+ && !!currentWorkspaceId+ && ((isDatasetCreatePath(pathname) && !canCreateDataset)+ || (isDatasetExternalConnectPath(pathname) && !canConnectExternalDataset))useEffect(() => {- if (shouldRedirect)- router.replace('/apps')- }, [shouldRedirect, router])+ if (shouldRedirectToDatasets)+ router.replace('/datasets')+ }, [shouldRedirectToDatasets, router])- if (isLoadingCurrentWorkspace || !currentWorkspace.id)+ if (isLoadingAccess || !currentWorkspaceId)return <Loading type="app" />- if (shouldRedirect) {+ if (shouldRedirectToDatasets) {return null}return (- <ExternalKnowledgeApiProvider>+ <ExternalKnowledgeApiProvider enabled={canConnectExternalDataset}><ExternalApiPanelProvider>{children}</ExternalApiPanelProvider>diff --git a/web/app/(commonLayout)/marketplace/__tests__/page.spec.tsx b/web/app/(commonLayout)/marketplace/__tests__/page.spec.tsxindex ea33cc0ddf1..f0d3eecda30 100644--- a/web/app/(commonLayout)/marketplace/__tests__/page.spec.tsx+++ b/web/app/(commonLayout)/marketplace/__tests__/page.spec.tsx@@ -1,13 +1,18 @@+import type { ReactNode } from 'react'import { render, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import MarketplacePage from '../page'vi.mock('@/app/components/plugins/marketplace', () => ({default: ({ showInstallButton }: { showInstallButton?: boolean }) => (- <div data-show-install={String(showInstallButton ?? true)}>Marketplace</div>+ <div data-show-install={String(!!showInstallButton)}>Marketplace</div>),}))+vi.mock('@/app/components/plugins/marketplace/marketplace-install-permission-provider', () => ({+ default: ({ children }: { children: ReactNode }) => <>{children}</>,+}))+describe('MarketplacePage', () => {beforeEach(() => {vi.clearAllMocks()diff --git a/web/app/(commonLayout)/marketplace/page.tsx b/web/app/(commonLayout)/marketplace/page.tsxindex 0d0232ae939..b87761b2bfa 100644--- a/web/app/(commonLayout)/marketplace/page.tsx+++ b/web/app/(commonLayout)/marketplace/page.tsx@@ -1,5 +1,6 @@import type { SearchParams } from 'nuqs'import Marketplace from '@/app/components/plugins/marketplace'+import MarketplaceInstallPermissionProvider from '@/app/components/plugins/marketplace/marketplace-install-permission-provider'type MarketplacePageProps = {searchParams?: Promise<SearchParams>@@ -10,10 +11,13 @@ const MarketplacePage = ({}: MarketplacePageProps) => {return (<div id="marketplace-container" className="flex h-full min-h-0 flex-col overflow-y-auto bg-background-default-subtle pr-1">- <Marketplace- searchParams={searchParams}- isMarketplacePlatform- />+ <MarketplaceInstallPermissionProvider>+ <Marketplace+ searchParams={searchParams}+ isMarketplacePlatform+ showInstallButton+ />+ </MarketplaceInstallPermissionProvider></div>)}diff --git a/web/app/(commonLayout)/plugins/page.tsx b/web/app/(commonLayout)/plugins/page.tsxindex f62512295b1..55dd57b7ea2 100644--- a/web/app/(commonLayout)/plugins/page.tsx+++ b/web/app/(commonLayout)/plugins/page.tsx@@ -20,7 +20,7 @@ const PluginList = async ({return (<PluginPageplugins={<PluginsPanel />}- marketplace={<Marketplace pluginTypeSwitchClassName="top-[60px]" />}+ marketplace={<Marketplace showInstallButton pluginTypeSwitchClassName="top-[60px]" />}/>)}diff --git a/web/app/(commonLayout)/role-route-guard.tsx b/web/app/(commonLayout)/role-route-guard.tsxindex fc81c091716..90526cbb3ca 100644--- a/web/app/(commonLayout)/role-route-guard.tsx+++ b/web/app/(commonLayout)/role-route-guard.tsx@@ -1,39 +1,21 @@'use client'import type { ReactNode } from 'react'-import { useQuery, useSuspenseQuery } from '@tanstack/react-query'-import Loading from '@/app/components/base/loading'+import { useSuspenseQuery } from '@tanstack/react-query'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { redirect, usePathname } from '@/next/navigation'-import { consoleQuery } from '@/service/client'--const datasetOperatorRedirectRoutes = ['/', '/apps', '/app', '/deployments', '/snippets', '/roster', '/explore', '/tools', '/integrations'] as constfunction isPathUnderRoute(pathname: string, route: string) {return pathname === route || pathname.startsWith(`${route}/`)}export function RoleRouteGuard({ children }: { children: ReactNode }) {- const currentWorkspaceRoleQuery = useQuery(consoleQuery.workspaces.current.post.queryOptions({- select: workspace => workspace.role,- }))const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const pathname = usePathname()- const shouldGuardRoute = datasetOperatorRedirectRoutes.some(route => isPathUnderRoute(pathname, route))- const shouldRedirectDatasetOperator = shouldGuardRoute- && !currentWorkspaceRoleQuery.isPending- && currentWorkspaceRoleQuery.data === 'dataset_operator'const shouldRedirectAppDeploy = isPathUnderRoute(pathname, '/deployments') && !systemFeatures.enable_app_deploy- // Block rendering only for guarded routes to avoid permission flicker.- if (shouldGuardRoute && currentWorkspaceRoleQuery.isPending)- return <Loading type="app" />-if (shouldRedirectAppDeploy)- redirect('/')-- if (shouldRedirectDatasetOperator)- redirect('/datasets')+ redirect('/apps')return <>{children}</>}diff --git a/web/app/(shareLayout)/components/__tests__/authenticated-layout.spec.tsx b/web/app/(shareLayout)/components/__tests__/authenticated-layout.spec.tsxindex 26abb993847..9768daf58be 100644--- a/web/app/(shareLayout)/components/__tests__/authenticated-layout.spec.tsx+++ b/web/app/(shareLayout)/components/__tests__/authenticated-layout.spec.tsx@@ -84,7 +84,7 @@ vi.mock('@/service/use-share', () => ({useGetWebAppMeta: () => appMetaQueryState,}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useGetUserCanAccessApp: () => userCanAccessAppQueryState,}))diff --git a/web/app/(shareLayout)/components/authenticated-layout.tsx b/web/app/(shareLayout)/components/authenticated-layout.tsxindex 9cc7ea76012..ae2466146c3 100644--- a/web/app/(shareLayout)/components/authenticated-layout.tsx+++ b/web/app/(shareLayout)/components/authenticated-layout.tsx@@ -7,7 +7,7 @@ import AppUnavailable from '@/app/components/base/app-unavailable'import Loading from '@/app/components/base/loading'import { useWebAppStore } from '@/context/web-app-context'import { usePathname, useRouter, useSearchParams } from '@/next/navigation'-import { useGetUserCanAccessApp } from '@/service/access-control'+import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'import { useGetWebAppInfo, useGetWebAppMeta, useGetWebAppParams } from '@/service/use-share'import { webAppLogout } from '@/service/webapp-auth'diff --git a/web/app/components/access-rules-editor/__tests__/index.spec.tsx b/web/app/components/access-rules-editor/__tests__/index.spec.tsxnew file mode 100644index 00000000000..abb6508afa1--- /dev/null+++ b/web/app/components/access-rules-editor/__tests__/index.spec.tsx@@ -0,0 +1,290 @@+import type { AccessPolicyWithBindings, ResourceUserAccessSetting } from '@/models/access-control'+import type { Member } from '@/models/common'+import { fireEvent, render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import AccessRulesEditor from '../index'++const mockMembers = vi.hoisted(() => ({+ accounts: [] as Member[] | null,+ isLoading: false,+}))++vi.mock('@/service/use-common', () => ({+ useMembers: vi.fn(() => ({+ data: { accounts: mockMembers.accounts },+ isLoading: mockMembers.isLoading,+ })),+}))++const createRule = (resourceType: 'app' | 'dataset'): AccessPolicyWithBindings => ({+ policy: {+ id: `${resourceType}-policy-id`,+ tenant_id: 'tenant-id',+ resource_type: resourceType,+ policy_key: `${resourceType}-policy-key`,+ name: `${resourceType} policy`,+ description: `${resourceType} policy description`,+ permission_keys: [],+ is_builtin: false,+ category: 'global_custom',+ created_at: '2026-05-22T00:00:00Z',+ updated_at: '2026-05-22T00:00:00Z',+ },+ roles: [],+ accounts: [],+})++const createUserAccessSetting = (): ResourceUserAccessSetting => ({+ account: {+ account_id: 'account-1',+ account_name: 'Evan',+ email: '[email protected]',+ },+ roles: [{+ id: 'role-1',+ type: 'app',+ category: 'global_custom',+ name: 'Maintainer',+ is_builtin: false,+ permission_keys: [],+ }],+ access_policies: [{+ id: 'app-policy-id',+ tenant_id: 'tenant-id',+ resource_type: 'app',+ policy_key: 'app-policy-key',+ name: 'Manage',+ description: 'Can manage this app',+ permission_keys: [],+ is_builtin: false,+ category: 'global_custom',+ }],+})++const createDefaultUserAccessSetting = (): ResourceUserAccessSetting => ({+ ...createUserAccessSetting(),+ access_policies: [],+})++const createMember = (overrides: Partial<Member> = {}): Member => ({+ id: 'account-2',+ name: 'Mia',+ email: '[email protected]',+ avatar: '',+ avatar_url: '',+ status: 'active',+ role: 'normal',+ roles: [],+ ...overrides,+} as Member)++describe('AccessRulesEditor', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockMembers.accounts = []+ mockMembers.isLoading = false+ })++ it('should render loading state before empty or row content', () => {+ render(+ <AccessRulesEditor+ rules={[]}+ userAccessSettings={[]}+ isLoadingRules+ isLoadingUserAccessSettings={false}+ openScope="specific"+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ />,+ )++ expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()+ expect(screen.queryByText('permission.accessRule.noUserAccessSettings')).not.toBeInTheDocument()+ })++ it('should render empty state when there are no user access settings', () => {+ render(+ <AccessRulesEditor+ rules={[]}+ userAccessSettings={[]}+ isLoadingRules={false}+ isLoadingUserAccessSettings={false}+ openScope="specific"+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ />,+ )++ expect(screen.getByText('permission.accessRule.noUserAccessSettings')).toBeInTheDocument()+ })++ it('should disable resource access controls before open scope is available', () => {+ render(+ <AccessRulesEditor+ rules={[]}+ userAccessSettings={[]}+ isLoadingRules={false}+ isLoadingUserAccessSettings={false}+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ />,+ )++ expect(screen.getByText('permission.accessRule.resourceOpenScope')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'permission.accessRule.resourceOpenScopeDescription' })).toBeInTheDocument()++ const allMembersButton = screen.getByRole('button', { name: /permission\.accessRule\.allPermittedMembers/ })+ const specificMembersButton = screen.getByRole('button', { name: /permission\.accessRule\.specificMembersOnly/ })+ expect(allMembersButton).toBeDisabled()+ expect(specificMembersButton).toBeDisabled()+ expect(allMembersButton).toHaveAttribute('aria-pressed', 'false')+ expect(specificMembersButton).toHaveAttribute('aria-pressed', 'false')+ })++ it('should render resource access controls and update account exceptions', () => {+ const onOpenScopeChange = vi.fn()+ const onUserAccessPoliciesChange = vi.fn()+ const onRemoveAccessPolicyMemberBinding = vi.fn()++ render(+ <AccessRulesEditor+ rules={[createRule('app')]}+ userAccessSettings={[createUserAccessSetting()]}+ isLoadingRules={false}+ isLoadingUserAccessSettings={false}+ openScope="specific"+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ onOpenScopeChange={onOpenScopeChange}+ onUserAccessPoliciesChange={onUserAccessPoliciesChange}+ onRemoveAccessPolicyMemberBinding={onRemoveAccessPolicyMemberBinding}+ />,+ )++ expect(screen.getByText('permission.accessRule.resourceOpenScope')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /permission\.accessRule\.specificMembersOnly/ })).toHaveAttribute('aria-pressed', 'true')+ expect(screen.getByText('permission.accessRule.individualPermissionSettings')).toBeInTheDocument()+ expect(screen.getByText('Evan')).toBeInTheDocument()+ expect(screen.getByText('[email protected]')).toBeInTheDocument()+ expect(screen.queryByText('Maintainer')).not.toBeInTheDocument()+ expect(screen.getAllByText('Manage').length).toBeGreaterThan(0)++ fireEvent.click(screen.getByRole('button', { name: /permission\.accessRule\.allPermittedMembers/ }))+ expect(onOpenScopeChange).not.toHaveBeenCalled()+ expect(screen.getByText('permission.accessRule.changeOpenScopeTitle')).toBeInTheDocument()+ expect(screen.getByText('permission.accessRule.changeOpenScopeDescription')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'common.operation.change' }))+ expect(onOpenScopeChange).toHaveBeenCalledWith('all')++ fireEvent.click(screen.getByRole('button', { name: 'common.operation.remove' }))+ expect(onRemoveAccessPolicyMemberBinding).toHaveBeenCalledWith('account-1', 'app-policy-id')+ })++ it('should render the fixed default option when an account has no exception policy', () => {+ render(+ <AccessRulesEditor+ rules={[createRule('app')]}+ userAccessSettings={[createDefaultUserAccessSetting()]}+ isLoadingRules={false}+ isLoadingUserAccessSettings={false}+ openScope="specific"+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ />,+ )++ expect(screen.getByText('permission.accessRule.defaultPermission')).toBeInTheDocument()+ })++ it('should mark maintainer rows and prevent editing them', () => {+ const onUserAccessPoliciesChange = vi.fn()+ const onRemoveAccessPolicyMemberBinding = vi.fn()++ render(+ <AccessRulesEditor+ rules={[createRule('app')]}+ userAccessSettings={[createUserAccessSetting()]}+ isLoadingRules={false}+ isLoadingUserAccessSettings={false}+ openScope="specific"+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ maintainerId="account-1"+ onUserAccessPoliciesChange={onUserAccessPoliciesChange}+ onRemoveAccessPolicyMemberBinding={onRemoveAccessPolicyMemberBinding}+ />,+ )++ expect(screen.getByText('permission.accessRule.maintainer')).toBeInTheDocument()+ expect(screen.getByLabelText(/permission\.accessRule\.exceptionPermissionFor/)).toBeDisabled()++ const removeButton = screen.getByRole('button', { name: 'common.operation.remove' })+ expect(removeButton).toBeDisabled()++ fireEvent.click(removeButton)+ expect(onUserAccessPoliciesChange).not.toHaveBeenCalled()+ expect(onRemoveAccessPolicyMemberBinding).not.toHaveBeenCalled()+ })++ it('should keep open scope unchanged when the confirmation is cancelled', () => {+ const onOpenScopeChange = vi.fn()++ render(+ <AccessRulesEditor+ rules={[]}+ userAccessSettings={[]}+ isLoadingRules={false}+ isLoadingUserAccessSettings={false}+ openScope="specific"+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ onOpenScopeChange={onOpenScopeChange}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /permission\.accessRule\.allPermittedMembers/ }))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))++ expect(onOpenScopeChange).not.toHaveBeenCalled()+ })++ it('should add unassigned members with default permission', async () => {+ const user = userEvent.setup()+ const onAddAccessSubject = vi.fn()+ mockMembers.accounts = [+ createMember({+ id: 'account-1',+ name: 'Evan',+ email: '[email protected]',+ }),+ createMember(),+ ]++ render(+ <AccessRulesEditor+ rules={[]}+ userAccessSettings={[createUserAccessSetting()]}+ isLoadingRules={false}+ isLoadingUserAccessSettings={false}+ openScope="specific"+ isUpdatingOpenScope={false}+ updatingAccountId={null}+ onAddAccessSubject={onAddAccessSubject}+ />,+ )++ await user.click(screen.getByRole('button', { name: 'common.operation.add' }))++ const dialog = screen.getByRole('dialog', { name: 'permission.accessRule.addMembersTitle' })+ expect(within(dialog).getByText('Evan')).toBeInTheDocument()+ expect(within(dialog).getByRole('button', { name: 'common.operation.added' })).toBeDisabled()+ expect(within(dialog).queryByRole('button', { name: 'permission.accessRule.addMemberAria:{"name":"Evan"}' })).not.toBeInTheDocument()+ expect(within(dialog).getByText('Mia')).toBeInTheDocument()+ expect(within(dialog).queryByRole('tablist')).not.toBeInTheDocument()++ await user.click(within(dialog).getByRole('button', { name: 'permission.accessRule.addMemberAria:{"name":"Mia"}' }))++ expect(onAddAccessSubject).toHaveBeenCalledWith('account-2', ['default'])+ })+})diff --git a/web/app/components/access-rules-editor/add-access-subject-popover.tsx b/web/app/components/access-rules-editor/add-access-subject-popover.tsxnew file mode 100644index 00000000000..68e26f4b8f2--- /dev/null+++ b/web/app/components/access-rules-editor/add-access-subject-popover.tsx@@ -0,0 +1,181 @@+'use client'++import type { ResourceUserAccessSetting } from '@/models/access-control'+import type { Member } from '@/models/common'+import { Avatar } from '@langgenius/dify-ui/avatar'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@langgenius/dify-ui/popover'+import { memo, useCallback, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import { useMembers } from '@/service/use-common'+import { DEFAULT_ACCESS_POLICY_ID } from './constants'++type AddAccessSubjectPopoverProps = {+ userAccessSettings: ResourceUserAccessSetting[]+ updatingAccountId: string | null+ onAddAccessSubject: (accountId: string, accessPolicyIds: string[]) => void+}++function AddAccessSubjectPopover({+ userAccessSettings,+ updatingAccountId,+ onAddAccessSubject,+}: AddAccessSubjectPopoverProps) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [searchValue, setSearchValue] = useState('')+ const { data: membersData, isLoading } = useMembers()+ const existingAccountIds = useMemo(() => {+ return new Set(userAccessSettings.map(setting => setting.account.account_id))+ }, [userAccessSettings])+ const availableMembers = useMemo(() => {+ const normalizedSearchValue = searchValue.trim().toLowerCase()++ return (membersData?.accounts ?? []).filter((member) => {+ if (!normalizedSearchValue)+ return true++ const name = member.name || ''+ const email = member.email || ''+ return name.toLowerCase().includes(normalizedSearchValue)+ || email.toLowerCase().includes(normalizedSearchValue)+ })+ }, [membersData?.accounts, searchValue])++ const handleAddMember = useCallback((member: Member) => {+ onAddAccessSubject(member.id, [DEFAULT_ACCESS_POLICY_ID])+ }, [onAddAccessSubject])++ const handleOpenChange = useCallback((nextOpen: boolean) => {+ if (!nextOpen)+ setSearchValue('')++ setOpen(nextOpen)+ }, [])++ const addLabel = t('operation.add', { ns: 'common' })+ const addedLabel = t('operation.added', { ns: 'common' })++ return (+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger+ render={(+ <Button+ variant="primary"+ size="medium"+ >+ <span className="i-ri-add-line size-3.5" aria-hidden />+ <span>{addLabel}</span>+ </Button>+ )}+ />+ <PopoverContent+ placement="bottom-end"+ sideOffset={8}+ popupClassName="w-[344px] max-w-[calc(100vw-32px)] overflow-hidden bg-components-panel-bg-blur p-0 shadow-lg backdrop-blur-[5px]"+ popupProps={{+ 'role': 'dialog',+ 'aria-label': t('accessRule.addMembersTitle', { ns: 'permission' }),+ }}+ >+ <div className="p-2 pb-1">+ <div className="relative">+ <span className="pointer-events-none absolute top-1/2 left-2 i-ri-search-line size-4 -translate-y-1/2 text-components-input-text-placeholder" aria-hidden="true" />+ <Input+ type="search"+ aria-label={t('operation.search', { ns: 'common' })}+ value={searchValue}+ placeholder={t('placeholder.search', { ns: 'common' })}+ className="h-8 ps-7 [&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"+ onValueChange={setSearchValue}+ autoComplete="off"+ enterKeyHint="search"+ />+ </div>+ </div>+ {isLoading+ ? (+ <div className="flex h-20 items-center justify-center p-1">+ <Loading type="app" />+ </div>+ )+ : availableMembers.length === 0+ ? (+ <div className="px-3 py-6 text-center system-xs-regular text-text-tertiary">+ {t('accessRule.noAvailableMembers', { ns: 'permission' })}+ </div>+ )+ : (+ <ul className="max-h-80 overflow-y-auto p-1">+ {availableMembers.map((member) => {+ const isAdded = existingAccountIds.has(member.id)+ const isUpdating = updatingAccountId === member.id+ const memberName = member.name || member.email++ return (+ <li+ key={member.id}+ className={cn(+ 'flex min-h-10 items-center gap-2 rounded-lg py-1 pr-3 pl-2',+ !isAdded && 'hover:bg-state-base-hover',+ )}+ >+ <Avatar+ avatar={member.avatar_url ?? member.avatar ?? null}+ name={memberName}+ size="sm"+ className={cn('bg-components-icon-bg-blue-solid', isAdded && 'opacity-50')}+ />+ <div className={cn('min-w-0 flex-1', isAdded && 'opacity-50')}>+ <div className="truncate system-sm-medium text-text-secondary">+ {memberName}+ </div>+ <div className="truncate system-xs-regular text-text-tertiary">+ {member.email}+ </div>+ </div>+ {isAdded+ ? (+ <button+ type="button"+ disabled+ className="shrink-0 cursor-not-allowed border-0 bg-transparent p-0 system-xs-regular text-text-tertiary disabled:opacity-100"+ >+ {addedLabel}+ </button>+ )+ : (+ <button+ type="button"+ disabled={isUpdating}+ aria-label={t('accessRule.addMemberAria', { ns: 'permission', name: memberName })}+ className={cn(+ 'flex h-6 shrink-0 items-center rounded-md px-1 system-xs-medium text-text-accent outline-hidden',+ 'hover:bg-state-accent-hover focus-visible:bg-state-accent-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid',+ 'disabled:cursor-not-allowed disabled:text-text-disabled disabled:hover:bg-transparent',+ )}+ onClick={() => handleAddMember(member)}+ >+ {isUpdating+ ? <span className="i-ri-loader-2-line size-3.5 animate-spin" aria-hidden />+ : `+ ${addLabel}`}+ </button>+ )}+ </li>+ )+ })}+ </ul>+ )}+ </PopoverContent>+ </Popover>+ )+}++export default memo(AddAccessSubjectPopover)diff --git a/web/app/components/access-rules-editor/constants.ts b/web/app/components/access-rules-editor/constants.tsnew file mode 100644index 00000000000..2e5fe085136--- /dev/null+++ b/web/app/components/access-rules-editor/constants.ts@@ -0,0 +1,2 @@+export const ACCESS_RULE_TABLE_GRID = 'grid-cols-[minmax(0,0.72fr)_minmax(0,1fr)_72px]'+export const DEFAULT_ACCESS_POLICY_ID = 'default'diff --git a/web/app/components/access-rules-editor/index.tsx b/web/app/components/access-rules-editor/index.tsxnew file mode 100644index 00000000000..4029780a721--- /dev/null+++ b/web/app/components/access-rules-editor/index.tsx@@ -0,0 +1,130 @@+'use client'++import type {+ AccessPolicyWithBindings,+ ResourceOpenScope,+ ResourceUserAccessSetting,+} from '@/models/access-control'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import AddAccessSubjectPopover from './add-access-subject-popover'+import { ACCESS_RULE_TABLE_GRID } from './constants'+import ResourceOpenScopeSection from './open-scope-section'+import TitleInfotip from './title-infotip'+import UserAccessPolicyRow from './user-access-policy-row'++export type AccessRulesEditorProps = {+ rules: AccessPolicyWithBindings[]+ userAccessSettings: ResourceUserAccessSetting[]+ isLoadingRules: boolean+ isLoadingUserAccessSettings: boolean+ openScope?: ResourceOpenScope+ isUpdatingOpenScope: boolean+ updatingAccountId: string | null+ maintainerId?: string | null+ className?: string+ onOpenScopeChange?: (openScope: ResourceOpenScope) => void+ onUserAccessPoliciesChange?: (accountId: string, accessPolicyIds: string[]) => void+ onRemoveAccessPolicyMemberBinding?: (accountId: string, accessPolicyId: string) => void+ onAddAccessSubject?: (accountId: string, accessPolicyIds: string[]) => void+}++export default function AccessRulesEditor({+ rules,+ userAccessSettings,+ isLoadingRules,+ isLoadingUserAccessSettings,+ openScope,+ isUpdatingOpenScope,+ updatingAccountId,+ maintainerId,+ className,+ onOpenScopeChange,+ onUserAccessPoliciesChange,+ onRemoveAccessPolicyMemberBinding,+ onAddAccessSubject,+}: AccessRulesEditorProps) {+ const { t } = useTranslation()+ const isLoading = isLoadingRules || isLoadingUserAccessSettings+ const individualPermissionSettingsTip = t('accessRule.individualPermissionSettingsTip', { ns: 'permission' })+ const policyOptions = useMemo(() => {+ return rules.map(rule => ({+ id: rule.policy.id,+ name: rule.policy.name,+ }))+ }, [rules])++ return (+ <div className={cn('flex flex-col gap-4', className)}>+ <ResourceOpenScopeSection+ value={openScope}+ disabled={isUpdatingOpenScope || !openScope}+ onChange={onOpenScopeChange}+ />+ <div className="flex min-h-8 items-center gap-2">+ <div className="flex min-w-0 flex-1 items-center gap-1">+ <h2 className="system-sm-semibold text-text-secondary">+ {t('accessRule.individualPermissionSettings', { ns: 'permission' })}+ </h2>+ <TitleInfotip content={individualPermissionSettingsTip} />+ </div>+ {onAddAccessSubject+ ? (+ <AddAccessSubjectPopover+ userAccessSettings={userAccessSettings}+ updatingAccountId={updatingAccountId}+ onAddAccessSubject={onAddAccessSubject}+ />+ )+ : (+ <Button+ variant="primary"+ size="medium"+ disabled+ >+ <span className="i-ri-add-line size-3.5" aria-hidden />+ <span>{t('operation.add', { ns: 'common' })}</span>+ </Button>+ )}+ </div>+ <section className="overflow-hidden rounded-xl border border-components-panel-border bg-components-panel-bg">+ <div className={cn('grid items-center gap-4 border-b border-divider-deep px-10 py-4 system-sm-semibold text-text-tertiary', ACCESS_RULE_TABLE_GRID)}>+ <div>{t('accessRule.member', { ns: 'permission' })}</div>+ <div>{t('accessRule.permission', { ns: 'permission' })}</div>+ <div>{t('accessRule.actions', { ns: 'permission' })}</div>+ </div>+ {isLoading+ ? (+ <div className="px-4 py-8 text-center">+ <Loading type="app" />+ </div>+ )+ : userAccessSettings.length === 0+ ? (+ <div className="px-4 py-8 text-center system-sm-regular text-text-tertiary">+ {t('accessRule.noUserAccessSettings', { ns: 'permission' })}+ </div>+ )+ : (+ <div className="px-4">+ {userAccessSettings.map((setting, index) => (+ <UserAccessPolicyRow+ key={setting.account.account_id}+ setting={setting}+ policyOptions={policyOptions}+ disabled={updatingAccountId === setting.account.account_id}+ isMaintainer={maintainerId === setting.account.account_id}+ className={cn(index > 0 && 'border-t border-divider-subtle')}+ onChange={onUserAccessPoliciesChange}+ onRemove={onRemoveAccessPolicyMemberBinding}+ />+ ))}+ </div>+ )}+ </section>+ </div>+ )+}diff --git a/web/app/components/access-rules-editor/open-scope-confirm-dialog.tsx b/web/app/components/access-rules-editor/open-scope-confirm-dialog.tsxnew file mode 100644index 00000000000..bfdb9a9e12f--- /dev/null+++ b/web/app/components/access-rules-editor/open-scope-confirm-dialog.tsx@@ -0,0 +1,59 @@+'use client'++import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { memo, useCallback } from 'react'+import { useTranslation } from 'react-i18next'++type OpenScopeConfirmDialogProps = {+ open: boolean+ onCancel: () => void+ onConfirm: () => void+}++function OpenScopeConfirmDialog({+ open,+ onCancel,+ onConfirm,+}: OpenScopeConfirmDialogProps) {+ const { t } = useTranslation()+ const handleOpenChange = useCallback((nextOpen: boolean) => {+ if (!nextOpen)+ onCancel()+ }, [onCancel])++ return (+ <AlertDialog+ open={open}+ onOpenChange={handleOpenChange}+ >+ <AlertDialogContent className="w-120 overflow-hidden! rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0! text-left align-middle shadow-lg">+ <div className="flex flex-col items-start gap-2 self-stretch p-6 pb-4">+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('accessRule.changeOpenScopeTitle', { ns: 'permission' })}+ </AlertDialogTitle>+ <AlertDialogDescription render={<div />} className="system-md-regular text-text-secondary">+ {t('accessRule.changeOpenScopeDescription', { ns: 'permission' })}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions className="gap-2 p-6">+ <AlertDialogCancelButton variant="secondary">+ {t('operation.cancel', { ns: 'common' })}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton onClick={onConfirm}>+ {t('operation.change', { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )+}++export default memo(OpenScopeConfirmDialog)diff --git a/web/app/components/access-rules-editor/open-scope-option.tsx b/web/app/components/access-rules-editor/open-scope-option.tsxnew file mode 100644index 00000000000..fb2fc20943e--- /dev/null+++ b/web/app/components/access-rules-editor/open-scope-option.tsx@@ -0,0 +1,45 @@+'use client'++import type { ResourceOpenScope } from '@/models/access-control'+import { cn } from '@langgenius/dify-ui/cn'+import { memo } from 'react'++type OpenScopeOptionProps = {+ value: ResourceOpenScope+ selected: boolean+ disabled: boolean+ title: string+ description: string+ onChange?: (openScope: ResourceOpenScope) => void+}++function OpenScopeOption({+ value,+ selected,+ disabled,+ title,+ description,+ onChange,+}: OpenScopeOptionProps) {+ return (+ <button+ type="button"+ aria-pressed={selected}+ disabled={disabled || !onChange}+ className={cn(+ 'flex min-h-19 flex-col items-start rounded-xl border bg-components-panel-bg px-7 py-3 text-left shadow-xs outline-hidden transition-colors',+ 'focus-visible:ring-2 focus-visible:ring-state-accent-solid',+ selected+ ? 'border-[1.5px] border-state-accent-solid'+ : 'border-components-panel-border hover:border-divider-deep',+ (disabled || !onChange) && 'cursor-not-allowed opacity-70',+ )}+ onClick={() => onChange?.(value)}+ >+ <div className="system-sm-semibold text-text-secondary">{title}</div>+ <p className="mt-0.5 system-xs-regular text-text-tertiary">{description}</p>+ </button>+ )+}++export default memo(OpenScopeOption)diff --git a/web/app/components/access-rules-editor/open-scope-section.tsx b/web/app/components/access-rules-editor/open-scope-section.tsxnew file mode 100644index 00000000000..62cabc40ccb--- /dev/null+++ b/web/app/components/access-rules-editor/open-scope-section.tsx@@ -0,0 +1,79 @@+'use client'++import type { ResourceOpenScope } from '@/models/access-control'+import { memo, useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import OpenScopeConfirmDialog from './open-scope-confirm-dialog'+import OpenScopeOption from './open-scope-option'+import TitleInfotip from './title-infotip'++type ResourceOpenScopeSectionProps = {+ value?: ResourceOpenScope+ disabled: boolean+ onChange?: (openScope: ResourceOpenScope) => void+}++function ResourceOpenScopeSection({+ value,+ disabled,+ onChange,+}: ResourceOpenScopeSectionProps) {+ const { t } = useTranslation()+ const [pendingOpenScope, setPendingOpenScope] = useState<ResourceOpenScope | null>(null)+ const resourceOpenScopeDescription = t('accessRule.resourceOpenScopeDescription', { ns: 'permission' })++ const handleRequestChange = useCallback((nextOpenScope: ResourceOpenScope) => {+ if (nextOpenScope === value)+ return++ setPendingOpenScope(nextOpenScope)+ }, [value])++ const handleCancelChange = useCallback(() => {+ setPendingOpenScope(null)+ }, [])++ const handleConfirmChange = useCallback(() => {+ if (!pendingOpenScope)+ return++ onChange?.(pendingOpenScope)+ setPendingOpenScope(null)+ }, [onChange, pendingOpenScope])++ return (+ <section className="flex flex-col gap-2">+ <div className="flex min-w-0 items-center gap-1">+ <h2 className="system-sm-semibold text-text-secondary">+ {t('accessRule.resourceOpenScope', { ns: 'permission' })}+ </h2>+ <TitleInfotip content={resourceOpenScopeDescription} />+ </div>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ <OpenScopeOption+ value="all"+ selected={value === 'all'}+ disabled={disabled || !onChange}+ title={t('accessRule.allPermittedMembers', { ns: 'permission' })}+ description={t('accessRule.allPermittedMembersDescription', { ns: 'permission' })}+ onChange={onChange ? handleRequestChange : undefined}+ />+ <OpenScopeOption+ value="specific"+ selected={value === 'specific'}+ disabled={disabled || !onChange}+ title={t('accessRule.specificMembersOnly', { ns: 'permission' })}+ description={t('accessRule.specificMembersOnlyDescription', { ns: 'permission' })}+ onChange={onChange ? handleRequestChange : undefined}+ />+ </div>+ <OpenScopeConfirmDialog+ open={!!pendingOpenScope}+ onCancel={handleCancelChange}+ onConfirm={handleConfirmChange}+ />+ </section>+ )+}++export default memo(ResourceOpenScopeSection)diff --git a/web/app/components/access-rules-editor/title-infotip.tsx b/web/app/components/access-rules-editor/title-infotip.tsxnew file mode 100644index 00000000000..d0b150c2dc6--- /dev/null+++ b/web/app/components/access-rules-editor/title-infotip.tsx@@ -0,0 +1,14 @@+'use client'++import { Infotip } from '@/app/components/base/infotip'++export default function TitleInfotip({ content }: { content: string }) {+ return (+ <Infotip+ aria-label={content}+ popupClassName="max-w-64 text-left wrap-break-word text-text-secondary"+ >+ {content}+ </Infotip>+ )+}diff --git a/web/app/components/access-rules-editor/user-access-policy-row.tsx b/web/app/components/access-rules-editor/user-access-policy-row.tsxnew file mode 100644index 00000000000..4c3e9d7100c--- /dev/null+++ b/web/app/components/access-rules-editor/user-access-policy-row.tsx@@ -0,0 +1,133 @@+'use client'++import type { ResourceUserAccessSetting } from '@/models/access-control'+import { Avatar } from '@langgenius/dify-ui/avatar'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectTrigger,+ SelectValue,+} from '@langgenius/dify-ui/select'+import { memo, useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import { ACCESS_RULE_TABLE_GRID, DEFAULT_ACCESS_POLICY_ID } from './constants'++type PolicyOption = {+ id: string+ name: string+}++type UserAccessPolicyRowProps = {+ setting: ResourceUserAccessSetting+ policyOptions: PolicyOption[]+ disabled: boolean+ isMaintainer?: boolean+ className?: string+ onChange?: (accountId: string, accessPolicyIds: string[]) => void+ onRemove?: (accountId: string, accessPolicyId: string) => void+}++function UserAccessPolicyRow({+ setting,+ policyOptions,+ disabled,+ isMaintainer = false,+ className,+ onChange,+ onRemove,+}: UserAccessPolicyRowProps) {+ const { t } = useTranslation()+ const accountId = setting.account.account_id+ const selectedPolicy = setting.access_policies[0]+ const selectedAccessPolicyId = selectedPolicy?.id+ const selectedPolicyId = selectedAccessPolicyId ?? DEFAULT_ACCESS_POLICY_ID+ const isPolicySelectDisabled = disabled || isMaintainer || !onChange+ const isRemoveDisabled = disabled || isMaintainer || !onRemove || !selectedAccessPolicyId+ const defaultAccessPolicyName = t('accessRule.defaultPermission', { ns: 'permission' })+ const accountEmail = setting.account.email || setting.account.account_name++ const handlePolicyChange = useCallback((nextPolicyId: string | null) => {+ if (isPolicySelectDisabled || !nextPolicyId || nextPolicyId === selectedPolicyId)+ return++ onChange?.(accountId, [nextPolicyId])+ }, [accountId, isPolicySelectDisabled, onChange, selectedPolicyId])++ const handleRemove = useCallback(() => {+ if (isRemoveDisabled || !selectedAccessPolicyId)+ return++ onRemove?.(accountId, selectedAccessPolicyId)+ }, [accountId, isRemoveDisabled, onRemove, selectedAccessPolicyId])++ return (+ <div className={cn('grid min-h-19 items-center gap-4 px-6 py-4', ACCESS_RULE_TABLE_GRID, className)}>+ <div className="flex min-w-0 items-center gap-3">+ <Avatar+ avatar={setting.account.avatar ?? null}+ name={setting.account.account_name}+ size="md"+ className="bg-components-icon-bg-blue-solid"+ />+ <div className="min-w-0">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate system-md-medium text-text-secondary">+ {setting.account.account_name}+ </span>+ {isMaintainer && (+ <span className="max-w-24 shrink-0 truncate rounded-[5px] border border-text-accent-secondary px-1 py-0.5 system-2xs-medium-uppercase text-text-accent-secondary">+ {t('accessRule.maintainer', { ns: 'permission' })}+ </span>+ )}+ </div>+ <p className="truncate system-xs-regular text-text-tertiary">+ {accountEmail}+ </p>+ </div>+ </div>+ <Select+ value={selectedPolicyId}+ onValueChange={handlePolicyChange}+ >+ <SelectTrigger+ aria-label={t('accessRule.exceptionPermissionFor', { ns: 'permission', name: setting.account.account_name })}+ size="small"+ disabled={isPolicySelectDisabled}+ className="w-36"+ >+ <SelectValue>+ {selectedPolicyId === DEFAULT_ACCESS_POLICY_ID+ ? defaultAccessPolicyName+ : setting.access_policies[0]?.name}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={DEFAULT_ACCESS_POLICY_ID}>+ <SelectItemText>{defaultAccessPolicyName}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ {policyOptions.map(policy => (+ <SelectItem key={policy.id} value={policy.id}>+ <SelectItemText>{policy.name}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <button+ type="button"+ disabled={isRemoveDisabled}+ className="w-fit rounded-md border-none bg-transparent p-0 text-left system-xs-medium text-text-destructive outline-hidden hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid disabled:cursor-not-allowed disabled:text-text-disabled disabled:hover:no-underline"+ onClick={handleRemove}+ >+ {t('operation.remove', { ns: 'common' })}+ </button>+ </div>+ )+}++export default memo(UserAccessPolicyRow)diff --git a/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx b/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsxindex 19d7dd5a436..6dc9f5dfb19 100644--- a/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx+++ b/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx@@ -1,10 +1,11 @@import { render, screen } from '@testing-library/react'+import { AppACLPermission } from '@/utils/permission'import AppDetailSection from '../app-detail-section'import { useAppInfoActions } from '../app-info/use-app-info-actions'let mockAppMode = 'chat'-let mockIsCurrentWorkspaceEditor = truelet mockPathname = '/app/app-1/logs'+let mockAppPermissionKeys: string[] = []vi.mock('@/app/components/app/store', () => ({useStore: (selector: (state: Record<string, unknown>) => unknown) => selector({@@ -15,13 +16,15 @@ vi.mock('@/app/components/app/store', () => ({icon: '🤖',icon_type: 'emoji',icon_background: '#fff',+ permission_keys: mockAppPermissionKeys,},}),}))vi.mock('@/context/app-context', () => ({useAppContext: () => ({- isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],}),}))@@ -51,13 +54,13 @@ describe('AppDetailSection', () => {beforeEach(() => {vi.clearAllMocks()mockAppMode = 'chat'- mockIsCurrentWorkspaceEditor = truemockPathname = '/app/app-1/logs'+ mockAppPermissionKeys = [AppACLPermission.Monitor]})// Rendering behavior for app detail navigation entries.describe('Rendering', () => {- it('should split logs and annotations into separate navigation links for chat apps', () => {+ it('should render logs and overview for chat apps with app monitor permission', () => {// ArrangemockAppMode = 'chat'@@ -66,13 +69,28 @@ describe('AppDetailSection', () => {// Assertexpect(screen.getByRole('link', { name: 'common.appMenus.logs' })).toHaveAttribute('href', '/app/app-1/logs')+ expect(screen.getByRole('link', { name: 'common.appMenus.overview' })).toHaveAttribute('href', '/app/app-1/overview')+ expect(screen.queryByRole('link', { name: 'common.appMenus.annotations' })).not.toBeInTheDocument()+ })++ it('should render annotations for chat apps with app edit permission', () => {+ // Arrange+ mockAppMode = 'chat'+ mockAppPermissionKeys = [AppACLPermission.Edit]++ // Act+ render(<AppDetailSection />)++ // Assertexpect(screen.getByRole('link', { name: 'common.appMenus.annotations' })).toHaveAttribute('href', '/app/app-1/annotations')expect(screen.getByRole('link', { name: 'common.appMenus.annotations' })).toHaveAttribute('data-icon', 'Annotations')+ expect(screen.queryByRole('link', { name: 'common.appMenus.overview' })).not.toBeInTheDocument()})it('should render dividers before logs and after annotations for chat apps', () => {// ArrangemockAppMode = 'chat'+ mockAppPermissionKeys = [AppACLPermission.Monitor, AppACLPermission.Edit]// Actrender(<AppDetailSection />)@@ -116,9 +134,9 @@ describe('AppDetailSection', () => {expect(screen.queryByRole('link', { name: 'common.appMenus.annotations' })).not.toBeInTheDocument()})- it('should not render log group dividers for non-editor users', () => {+ it('should not render monitor group dividers without monitor or edit permission', () => {// Arrange- mockIsCurrentWorkspaceEditor = false+ mockAppPermissionKeys = []// Actrender(<AppDetailSection />)@@ -127,6 +145,62 @@ describe('AppDetailSection', () => {expect(screen.queryAllByRole('separator')).toHaveLength(0)expect(screen.queryByRole('link', { name: 'common.appMenus.logs' })).not.toBeInTheDocument()expect(screen.queryByRole('link', { name: 'common.appMenus.annotations' })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: 'common.appMenus.overview' })).not.toBeInTheDocument()+ })++ it('should render logs for users with app monitor permission', () => {+ // Arrange+ mockAppPermissionKeys = [AppACLPermission.Monitor]++ // Act+ render(<AppDetailSection />)++ // Assert+ expect(screen.getByRole('link', { name: 'common.appMenus.logs' })).toHaveAttribute('href', '/app/app-1/logs')+ expect(screen.queryByRole('link', { name: 'common.appMenus.annotations' })).not.toBeInTheDocument()+ expect(screen.getAllByRole('separator')).toHaveLength(2)+ })++ it('should render the layout navigation for users with view layout permission', () => {+ // Arrange+ mockAppPermissionKeys = [AppACLPermission.ViewLayout]++ // Act+ render(<AppDetailSection />)++ // Assert+ expect(screen.getByRole('link', { name: 'common.appMenus.promptEng' })).toHaveAttribute('href', '/app/app-1/configuration')+ expect(screen.queryByRole('link', { name: 'common.appMenus.logs' })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: 'common.appMenus.annotations' })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: 'common.appMenus.overview' })).not.toBeInTheDocument()+ })++ it('should hide the layout navigation when layout access is missing', () => {+ // Act+ render(<AppDetailSection />)++ // Assert+ expect(screen.queryByRole('link', { name: 'common.appMenus.promptEng' })).not.toBeInTheDocument()+ })++ it('should render resource access navigation when app access config permission is granted', () => {+ // Arrange+ mockAppPermissionKeys = [AppACLPermission.AccessConfig]++ // Act+ render(<AppDetailSection />)++ // Assert+ expect(screen.getByRole('link', { name: 'common.settings.resourceAccess' })).toHaveAttribute('href', '/app/app-1/access-config')+ expect(screen.queryByRole('link', { name: 'common.appMenus.overview' })).not.toBeInTheDocument()+ })++ it('should hide resource access navigation when app access config permission is missing', () => {+ // Act+ render(<AppDetailSection />)++ // Assert+ expect(screen.queryByRole('link', { name: 'common.settings.resourceAccess' })).not.toBeInTheDocument()})it('should pass collapsed mode to app info and navigation links when collapsed', () => {diff --git a/web/app/components/app-sidebar/__tests__/app-sidebar-dropdown.spec.tsx b/web/app/components/app-sidebar/__tests__/app-sidebar-dropdown.spec.tsxindex 5557118c784..98f4d7b672c 100644--- a/web/app/components/app-sidebar/__tests__/app-sidebar-dropdown.spec.tsx+++ b/web/app/components/app-sidebar/__tests__/app-sidebar-dropdown.spec.tsx@@ -13,12 +13,6 @@ vi.mock('@/app/components/app/store', () => ({}),}))-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceEditor: true,- }),-}))-vi.mock('@langgenius/dify-ui/dropdown-menu', () => {const DropdownMenuContext = React.createContext<{ isOpen: boolean, setOpen: (open: boolean) => void } | null>(null)@@ -175,9 +169,9 @@ describe('AppSidebarDropdown', () => {render(<AppSidebarDropdown navigation={navigation} />)const appName = screen.getByText('Test App')- const appInfoArea = appName.closest('[class*="cursor-pointer"]')- if (appInfoArea)- await user.click(appInfoArea)+ await user.click(appName)++ expect(screen.getByTestId('app-info')).toHaveAttribute('data-open', 'true')})it('should display workflow mode label', () => {diff --git a/web/app/components/app-sidebar/__tests__/dataset-detail-section.spec.tsx b/web/app/components/app-sidebar/__tests__/dataset-detail-section.spec.tsxindex ac02bb1f4e8..25763fb11ae 100644--- a/web/app/components/app-sidebar/__tests__/dataset-detail-section.spec.tsx+++ b/web/app/components/app-sidebar/__tests__/dataset-detail-section.spec.tsx@@ -1,9 +1,9 @@import type { DataSet, RelatedAppResponse } from '@/models/datasets'import { render, screen } from '@testing-library/react'+import { DatasetACLPermission } from '@/utils/permission'import DatasetDetailSection from '../dataset-detail-section'let mockPathname = '/datasets/dataset-1/documents'-let mockIsDatasetOperator = falselet mockDataset: DataSet | undefinedlet mockRelatedApps: RelatedAppResponse | undefined@@ -13,7 +13,8 @@ vi.mock('@/next/navigation', () => ({vi.mock('@/context/app-context', () => ({useAppContext: () => ({- isCurrentWorkspaceDatasetOperator: mockIsDatasetOperator,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],}),}))@@ -27,7 +28,12 @@ vi.mock('../dataset-info', () => ({}))vi.mock('../nav-link', () => ({- default: ({ name, href }: { name: string, href: string }) => <a href={href}>{name}</a>,+ default: ({ name, href, disabled }: { name: string, href: string, disabled?: boolean }) => {+ if (disabled)+ return <button disabled>{name}</button>++ return <a href={href}>{name}</a>+ },}))vi.mock('../../datasets/extra-info', () => ({@@ -63,6 +69,7 @@ const createDataset = (overrides: Partial<DataSet> = {}): DataSet => ({score_threshold: 0,},enable_api: true,+ permission_keys: [DatasetACLPermission.Edit],...overrides,} as DataSet)@@ -70,7 +77,6 @@ describe('DatasetDetailSection', () => {beforeEach(() => {vi.clearAllMocks()mockPathname = '/datasets/dataset-1/documents'- mockIsDatasetOperator = falsemockDataset = createDataset()mockRelatedApps = {data: [],@@ -87,4 +93,47 @@ describe('DatasetDetailSection', () => {expect(extraInfo).toHaveAttribute('data-document-count', '120')expect(extraInfo.parentElement).toHaveClass('mt-auto', 'shrink-0')})++ it('should hide dataset stats and API access when dataset edit permission is missing', () => {+ mockDataset = createDataset({+ permission_keys: [DatasetACLPermission.Readonly],+ })++ render(<DatasetDetailSection expand />)++ expect(screen.queryByTestId('extra-info')).not.toBeInTheDocument()+ })++ it('should render resource access navigation when dataset access config permission is granted', () => {+ mockDataset = createDataset({+ permission_keys: [DatasetACLPermission.AccessConfig],+ })++ render(<DatasetDetailSection expand />)++ expect(screen.getByRole('link', { name: 'common.settings.resourceAccess' })).toHaveAttribute('href', '/datasets/dataset-1/access-config')+ })++ it('should hide resource access navigation when dataset access config permission is missing', () => {+ render(<DatasetDetailSection expand />)++ expect(screen.queryByRole('link', { name: 'common.settings.resourceAccess' })).not.toBeInTheDocument()+ })++ it('should render hit testing navigation as a link when retrieval recall permission is granted', () => {+ mockDataset = createDataset({+ permission_keys: [DatasetACLPermission.RetrievalRecall],+ })++ render(<DatasetDetailSection expand />)++ expect(screen.getByRole('link', { name: 'common.datasetMenus.hitTesting' })).toHaveAttribute('href', '/datasets/dataset-1/hitTesting')+ })++ it('should disable hit testing navigation when retrieval recall permission is missing', () => {+ render(<DatasetDetailSection expand />)++ expect(screen.getByRole('button', { name: 'common.datasetMenus.hitTesting' })).toBeDisabled()+ expect(screen.queryByRole('link', { name: 'common.datasetMenus.hitTesting' })).not.toBeInTheDocument()+ })})diff --git a/web/app/components/app-sidebar/__tests__/index.spec.tsx b/web/app/components/app-sidebar/__tests__/index.spec.tsxindex 6aefcca8c33..cf3537a1464 100644--- a/web/app/components/app-sidebar/__tests__/index.spec.tsx+++ b/web/app/components/app-sidebar/__tests__/index.spec.tsx@@ -110,7 +110,7 @@ describe('AppDetailNav', () => {it('should apply expanded width class', () => {const { container } = render(<AppDetailNav navigation={navigation} />)const sidebar = container.firstElementChild as HTMLElement- expect(sidebar).toHaveClass('w-[216px]')+ expect(sidebar).toHaveClass('w-55')})it('should apply collapsed width class', () => {diff --git a/web/app/components/app-sidebar/app-detail-section.tsx b/web/app/components/app-sidebar/app-detail-section.tsxindex 9d77e17df76..5df0a4ef573 100644--- a/web/app/components/app-sidebar/app-detail-section.tsx+++ b/web/app/components/app-sidebar/app-detail-section.tsx@@ -8,6 +8,8 @@ import {RiDashboard2Line,RiFileList3Fill,RiFileList3Line,+ RiLock2Fill,+ RiLock2Line,RiTerminalBoxFill,RiTerminalBoxLine,RiTerminalWindowFill,@@ -21,6 +23,7 @@ import Annotations from '@/app/components/base/icons/src/vender/Annotations'import { useAppContext } from '@/context/app-context'import { usePathname } from '@/next/navigation'import { AppModeEnum } from '@/types/app'+import { getAppACLCapabilities } from '@/utils/permission'import { AppInfoView } from './app-info'import { useAppInfoActions } from './app-info/use-app-info-actions'import NavLink from './nav-link'@@ -68,7 +71,7 @@ const AppDetailSection = ({}: AppDetailSectionProps) => {const { t } = useTranslation()const pathname = usePathname()- const { isCurrentWorkspaceEditor } = useAppContext()+ const { userProfile, workspacePermissionKeys } = useAppContext()const appDetail = useStore(state => state.appDetail)const appInfoActions = useAppInfoActions({resetKey: appDetail?.id,@@ -81,9 +84,14 @@ const AppDetailSection = ({const appId = appDetail.idconst isWorkflowApp = appDetail.mode === AppModeEnum.WORKFLOW || appDetail.mode === AppModeEnum.ADVANCED_CHATconst supportsAnnotations = appDetail.mode !== AppModeEnum.WORKFLOW && appDetail.mode !== AppModeEnum.COMPLETION+ const appACLCapabilities = getAppACLCapabilities(appDetail.permission_keys, {+ currentUserId: userProfile?.id,+ resourceMaintainer: appDetail.maintainer,+ workspacePermissionKeys,+ })return [- ...(isCurrentWorkspaceEditor+ ...(appACLCapabilities.canAccessLayout? [{name: t('appMenus.promptEng', { ns: 'common' }),href: `/app/${appId}/${isWorkflowApp ? 'workflow' : 'configuration'}`,@@ -98,34 +106,49 @@ const AppDetailSection = ({icon: RiTerminalBoxLine,selectedIcon: RiTerminalBoxFill,},- ...(isCurrentWorkspaceEditor+ ...(appACLCapabilities.canMonitor? [{name: t('appMenus.logs', { ns: 'common' }),href: `/app/${appId}/logs`,icon: RiFileList3Line,selectedIcon: RiFileList3Fill,- }, ...(supportsAnnotations- ? [{- name: t('appMenus.annotations', { ns: 'common' }),- href: `/app/${appId}/annotations`,- icon: AnnotationNavIcon,- selectedIcon: AnnotationNavIcon,- }]- : [])]+ }]+ : []+ ),+ ...(appACLCapabilities.canEdit && supportsAnnotations+ ? [{+ name: t('appMenus.annotations', { ns: 'common' }),+ href: `/app/${appId}/annotations`,+ icon: AnnotationNavIcon,+ selectedIcon: AnnotationNavIcon,+ }]+ : []+ ),+ ...(appACLCapabilities.canMonitor+ ? [{+ name: t('appMenus.overview', { ns: 'common' }),+ href: `/app/${appId}/overview`,+ icon: RiDashboard2Line,+ selectedIcon: RiDashboard2Fill,+ }]+ : []+ ),+ ...(appACLCapabilities.canAccessConfig+ ? [{+ name: t('settings.resourceAccess', { ns: 'common' }),+ href: `/app/${appId}/access-config`,+ icon: RiLock2Line,+ selectedIcon: RiLock2Fill,+ }]: []),- {- name: t('appMenus.overview', { ns: 'common' }),- href: `/app/${appId}/overview`,- icon: RiDashboard2Line,- selectedIcon: RiDashboard2Fill,- },]- }, [appDetail, isCurrentWorkspaceEditor, t])+ }, [appDetail, t, userProfile?.id, workspacePermissionKeys])if (!appDetail)return null+ const hasLogsNavigation = navigation.some(isLogsNavItem)const hasAnnotationsNavigation = navigation.some(isAnnotationsNavItem)return (@@ -147,7 +170,7 @@ const AppDetailSection = ({</div><nav className={cn('flex flex-col gap-y-0.5 py-1', expand ? 'px-1' : 'px-3')}>{navigation.map((item) => {- const shouldRenderDividerBefore = isLogsNavItem(item)+ const shouldRenderDividerBefore = isLogsNavItem(item) || (!hasLogsNavigation && isAnnotationsNavItem(item))const shouldRenderDividerAfter = hasAnnotationsNavigation ? isAnnotationsNavItem(item) : isLogsNavItem(item)return (diff --git a/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx b/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsxindex 8017201e6e2..78137d42c13 100644--- a/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx+++ b/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx@@ -3,8 +3,19 @@ import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import AppInfoDetailPanel from '../app-info-detail-panel'+const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['app.create_and_management'] as string[],+}))++vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))+vi.mock('../../../base/app-icon', () => ({default: ({ size, icon }: { size: string, icon: string }) => (<div data-testid="app-icon" data-size={size} data-icon={icon} />@@ -66,6 +77,12 @@ vi.mock('../app-operations', () => ({),}))+const defaultAppPermissionKeys = [+ AppACLPermission.Edit,+ AppACLPermission.ImportExportDSL,+ AppACLPermission.Delete,+]+const createAppDetail = (overrides: Partial<App> = {}): App & Partial<AppSSO> => ({id: 'app-1',name: 'Test App',@@ -76,6 +93,7 @@ const createAppDetail = (overrides: Partial<App> = {}): App & Partial<AppSSO> =>icon_url: '',description: 'A test description',use_icon_as_answer_icon: false,+ permission_keys: defaultAppPermissionKeys,...overrides,} as App & Partial<AppSSO>)@@ -90,6 +108,7 @@ describe('AppInfoDetailPanel', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys.value = ['app.create_and_management']})describe('Rendering', () => {@@ -167,6 +186,14 @@ describe('AppInfoDetailPanel', () => {expect(defaultProps.openModal).toHaveBeenCalledWith('duplicate')})+ it('should hide duplicate operation when app.create_and_management permission is missing', () => {+ mockWorkspacePermissionKeys.value = []++ render(<AppInfoDetailPanel {...defaultProps} />)++ expect(screen.queryByTestId('op-duplicate')).not.toBeInTheDocument()+ })+it('should call exportCheck when export is clicked', async () => {const user = userEvent.setup()render(<AppInfoDetailPanel {...defaultProps} />)@@ -217,6 +244,19 @@ describe('AppInfoDetailPanel', () => {expect(screen.queryByTestId('op-import')).not.toBeInTheDocument()})+ it('should not show import DSL when import/export DSL permission is missing', () => {+ render(+ <AppInfoDetailPanel+ {...defaultProps}+ appDetail={createAppDetail({+ mode: AppModeEnum.WORKFLOW,+ permission_keys: [AppACLPermission.Edit],+ })}+ />,+ )+ expect(screen.queryByTestId('op-import')).not.toBeInTheDocument()+ })+it('should call openModal with importDSL when import is clicked', async () => {const user = userEvent.setup()render(diff --git a/web/app/components/app-sidebar/app-info/__tests__/index.spec.tsx b/web/app/components/app-sidebar/app-info/__tests__/index.spec.tsxindex ea0f117dede..573cdf02334 100644--- a/web/app/components/app-sidebar/app-info/__tests__/index.spec.tsx+++ b/web/app/components/app-sidebar/app-info/__tests__/index.spec.tsx@@ -8,12 +8,16 @@ import AppInfo from '..'const mockDetailPanel = vi.hoisted(() => vi.fn())const mockModals = vi.hoisted(() => vi.fn())-let mockIsCurrentWorkspaceEditor = true+let mockAppPermissionKeys = ['app.acl.view_layout']const mockSetPanelOpen = vi.fn()vi.mock('@/context/app-context', () => ({useAppContext: () => ({- isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,+ workspacePermissionKeys: ['app.create_and_management'],+ }),+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: ['app.create_and_management'],}),}))@@ -53,6 +57,7 @@ const mockAppDetail: App & Partial<AppSSO> = {icon_url: '',description: '',use_icon_as_answer_icon: false,+ permission_keys: mockAppPermissionKeys,} as App & Partial<AppSSO>const mockUseAppInfoActions = {@@ -80,8 +85,9 @@ vi.mock('../use-app-info-actions', () => ({describe('AppInfo', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCurrentWorkspaceEditor = true+ mockAppPermissionKeys = ['app.acl.view_layout']mockUseAppInfoActions.appDetail = mockAppDetail+ mockUseAppInfoActions.appDetail.permission_keys = mockAppPermissionKeysmockUseAppInfoActions.panelOpen = falsemockUseAppInfoActions.activeModal = null})@@ -130,9 +136,10 @@ describe('AppInfo', () => {expect(updater(true)).toBe(false)})- it('should not toggle panel when trigger is clicked and user is not editor', async () => {+ it('should not toggle panel when app ACL does not allow layout access', async () => {const user = userEvent.setup()- mockIsCurrentWorkspaceEditor = false+ mockAppPermissionKeys = []+ mockUseAppInfoActions.appDetail.permission_keys = mockAppPermissionKeysrender(<AppInfo expand />)await user.click(screen.getByTestId('trigger'))diff --git a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.tsindex fe5fa03f679..e5f060bced1 100644--- a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts+++ b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts@@ -25,6 +25,7 @@ const mockFetchWorkflowDraft = vi.fn()const mockDownloadBlob = vi.fn()const mockGetSocket = vi.fn()const mockOnAppMetaUpdate = vi.fn()+const mockSetQueryData = vi.fn()let mockAppDetail: Record<string, unknown> | undefined = {id: 'app-1',@@ -63,9 +64,16 @@ vi.mock('@langgenius/dify-ui/toast', () => ({}))vi.mock('@/service/use-apps', () => ({+ appDetailQueryKeyPrefix: ['apps', 'detail'],useInvalidateAppList: () => mockInvalidateAppList,}))+vi.mock('@tanstack/react-query', () => ({+ useQueryClient: () => ({+ setQueryData: mockSetQueryData,+ }),+}))+vi.mock('@/service/apps', () => ({updateAppInfo: (...args: unknown[]) => mockUpdateAppInfo(...args),copyApp: (...args: unknown[]) => mockCopyApp(...args),@@ -107,6 +115,7 @@ describe('useAppInfoActions', () => {vi.clearAllMocks()mockOnAppMetaUpdate.mockReturnValue(() => {})mockGetSocket.mockReturnValue(null)+ mockSetQueryData.mockReset()mockAppDetail = {id: 'app-1',name: 'Test App',diff --git a/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsx b/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsxindex 13a55f8984d..cb796157232 100644--- a/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsx+++ b/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsx@@ -14,7 +14,9 @@ import * as React from 'react'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import CardView from '@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { AppModeEnum } from '@/types/app'+import { getAppACLCapabilities, hasPermission } from '@/utils/permission'import AppIcon from '../../base/app-icon'import { AppInfoDetailDrawer } from './app-info-detail-drawer'import { getAppModeLabel } from './app-mode-labels'@@ -36,53 +38,73 @@ const AppInfoDetailPanel = ({exportCheck,}: AppInfoDetailPanelProps) => {const { t } = useTranslation()+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(appDetail.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail.maintainer,+ workspacePermissionKeys,+ }), [appDetail.maintainer, appDetail.permission_keys, currentUserId, workspacePermissionKeys])+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const primaryOperations = useMemo<Operation[]>(() => [- {- id: 'edit',- title: t('editApp', { ns: 'app' }),- icon: <RiEditLine />,- onClick: () => openModal('edit'),- },- {- id: 'duplicate',- title: t('duplicate', { ns: 'app' }),- icon: <RiFileCopy2Line />,- onClick: () => openModal('duplicate'),- },- {- id: 'export',- title: t('export', { ns: 'app' }),- icon: <RiFileDownloadLine />,- onClick: exportCheck,- },- ], [t, openModal, exportCheck])+ ...(appACLCapabilities.canEdit+ ? [{+ id: 'edit',+ title: t('editApp', { ns: 'app' }),+ icon: <RiEditLine />,+ onClick: () => openModal('edit'),+ }]+ : []),+ ...(canCreateApp+ ? [{+ id: 'duplicate',+ title: t('duplicate', { ns: 'app' }),+ icon: <RiFileCopy2Line />,+ onClick: () => openModal('duplicate'),+ }]+ : []),+ ...(appACLCapabilities.canImportExportDSL+ ? [{+ id: 'export',+ title: t('export', { ns: 'app' }),+ icon: <RiFileDownloadLine />,+ onClick: exportCheck,+ }]+ : []),+ ], [appACLCapabilities, canCreateApp, t, openModal, exportCheck])const secondaryOperations = useMemo<Operation[]>(() => [- ...(appDetail.mode === AppModeEnum.ADVANCED_CHAT || appDetail.mode === AppModeEnum.WORKFLOW)+ ...(appACLCapabilities.canImportExportDSL && (appDetail.mode === AppModeEnum.ADVANCED_CHAT || appDetail.mode === AppModeEnum.WORKFLOW)? [{id: 'import',title: t('common.importDSL', { ns: 'workflow' }),icon: <RiFileUploadLine />,onClick: () => openModal('importDSL'),}]- : [],- {- id: 'divider-1',- title: '',- icon: <></>,- onClick: () => {},- type: 'divider' as const,- },- {- id: 'delete',- title: t('operation.delete', { ns: 'common' }),- icon: <RiDeleteBinLine />,- onClick: () => openModal('delete'),- },- ], [appDetail.mode, t, openModal])+ : []),+ ...(appACLCapabilities.canDelete+ ? [+ {+ id: 'divider-1',+ title: '',+ icon: <></>,+ onClick: () => {},+ type: 'divider' as const,+ },+ {+ id: 'delete',+ title: t('operation.delete', { ns: 'common' }),+ icon: <RiDeleteBinLine />,+ onClick: () => openModal('delete'),+ },+ ]+ : []),+ ], [appACLCapabilities, appDetail.mode, t, openModal])const switchOperation = useMemo(() => {+ if (!appACLCapabilities.canEdit)+ return nullif (appDetail.mode !== AppModeEnum.COMPLETION && appDetail.mode !== AppModeEnum.CHAT)return nullreturn {@@ -91,7 +113,7 @@ const AppInfoDetailPanel = ({icon: <RiExchange2Line />,onClick: () => openModal('switch'),}- }, [appDetail.mode, t, openModal])+ }, [appACLCapabilities.canEdit, appDetail.mode, t, openModal])return (<AppInfoDetailDrawerdiff --git a/web/app/components/app-sidebar/app-info/index.tsx b/web/app/components/app-sidebar/app-info/index.tsxindex c2bde1ddb10..f08c1f12ed8 100644--- a/web/app/components/app-sidebar/app-info/index.tsx+++ b/web/app/components/app-sidebar/app-info/index.tsx@@ -1,6 +1,7 @@import type { AppInfoActions } from './use-app-info-actions'import * as React from 'react'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { getAppACLCapabilities } from '@/utils/permission'import AppInfoDetailPanel from './app-info-detail-panel'import AppInfoModals from './app-info-modals'import AppInfoTrigger from './app-info-trigger'@@ -79,7 +80,6 @@ export const AppInfoView = ({actions,renderDetail = true,}: AppInfoViewProps) => {- const { isCurrentWorkspaceEditor } = useAppContext()const {appDetail,panelOpen,@@ -87,6 +87,13 @@ export const AppInfoView = ({activeModal,secretEnvList,} = actions+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const appACLCapabilities = getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ })if (!appDetail)return null@@ -101,7 +108,7 @@ export const AppInfoView = ({appDetail={appDetail}expand={expand}onClick={() => {- if (isCurrentWorkspaceEditor)+ if (appACLCapabilities.canAccessLayout)setPanelOpen(v => !v)}}/>diff --git a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts b/web/app/components/app-sidebar/app-info/use-app-info-actions.tsindex 6162869e1e7..463a23cddf5 100644--- a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts+++ b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts@@ -3,6 +3,7 @@ import type { DuplicateAppModalProps } from '@/app/components/app/duplicate-modaimport type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'import type { EnvironmentVariable } from '@/app/components/workflow/types'import { toast } from '@langgenius/dify-ui/toast'+import { useQueryClient } from '@tanstack/react-query'import { useSetLocalStorage } from 'foxact/use-local-storage'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -11,7 +12,7 @@ import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { useProviderContext } from '@/context/provider-context'import { useRouter } from '@/next/navigation'import { copyApp, deleteApp, exportAppConfig, fetchAppDetail, updateAppInfo } from '@/service/apps'-import { useInvalidateAppList } from '@/service/use-apps'+import { appDetailQueryKeyPrefix, useInvalidateAppList } from '@/service/use-apps'import { fetchWorkflowDraft } from '@/service/workflow'import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'@@ -53,6 +54,7 @@ const getCurrentUiState = (state: AppInfoUiState, resetKey?: string) => {export function useAppInfoActions({ onDetailExpand, resetKey }: UseAppInfoActionsParams) {const { t } = useTranslation()const { replace } = useRouter()+ const queryClient = useQueryClient()const { onPlanInfoChanged } = useProviderContext()const appDetail = useAppStore(state => state.appDetail)const setAppDetail = useAppStore(state => state.setAppDetail)@@ -145,6 +147,7 @@ export function useAppInfoActions({ onDetailExpand, resetKey }: UseAppInfoActionconst res = await fetchAppDetail({ url: '/apps', id: appDetail.id })if (disposed)return+ queryClient.setQueryData([...appDetailQueryKeyPrefix, appDetail.id], res)setAppDetail({ ...res })}catch (error) {@@ -158,7 +161,7 @@ export function useAppInfoActions({ onDetailExpand, resetKey }: UseAppInfoActiondisposed = trueunsubscribe?.()}- }, [appDetail?.id, setAppDetail])+ }, [appDetail?.id, queryClient, setAppDetail])const onEdit: CreateAppModalProps['onConfirm'] = useCallback(async ({name,@@ -184,13 +187,14 @@ export function useAppInfoActions({ onDetailExpand, resetKey }: UseAppInfoAction})closeModal()toast(t('editDone', { ns: 'app' }), { type: 'success' })+ queryClient.setQueryData([...appDetailQueryKeyPrefix, app.id], app)setAppDetail(app)emitAppMetaUpdate()}catch {toast(t('editFailed', { ns: 'app' }), { type: 'error' })}- }, [appDetail, closeModal, setAppDetail, t, emitAppMetaUpdate])+ }, [appDetail, closeModal, queryClient, setAppDetail, t, emitAppMetaUpdate])const onCopy: DuplicateAppModalProps['onConfirm'] = useCallback(async ({name,@@ -213,12 +217,12 @@ export function useAppInfoActions({ onDetailExpand, resetKey }: UseAppInfoActiontoast(t('newApp.appCreated', { ns: 'app' }), { type: 'success' })setNeedRefresh('1')onPlanInfoChanged()- getRedirection(true, newApp, replace)+ getRedirection(newApp, replace)}catch {toast(t('newApp.appCreateFailed', { ns: 'app' }), { type: 'error' })}- }, [appDetail, closeModal, onPlanInfoChanged, replace, t])+ }, [appDetail, closeModal, onPlanInfoChanged, replace, setNeedRefresh, t])const onExport = useCallback(async (include = false) => {if (!appDetail)diff --git a/web/app/components/app-sidebar/app-sidebar-dropdown.tsx b/web/app/components/app-sidebar/app-sidebar-dropdown.tsxindex 2b41e80a19d..3292c34cf5e 100644--- a/web/app/components/app-sidebar/app-sidebar-dropdown.tsx+++ b/web/app/components/app-sidebar/app-sidebar-dropdown.tsx@@ -6,15 +6,9 @@ import {DropdownMenuContent,DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'-import {- RiEqualizer2Line,- RiMenuLine,-} from '@remixicon/react'-import * as React from 'react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { useStore as useAppStore } from '@/app/components/app/store'-import { useAppContext } from '@/context/app-context'import AppIcon from '../base/app-icon'import Divider from '../base/divider'import AppInfo from './app-info'@@ -33,7 +27,6 @@ type Props = Readonly<{const AppSidebarDropdown = ({ navigation, appInfoActions }: Props) => {const { t } = useTranslation()- const { isCurrentWorkspaceEditor } = useAppContext()const appDetail = useAppStore(state => state.appDetail)const [detailExpand, setDetailExpand] = useState(false)const [open, setOpen] = useState(false)@@ -59,7 +52,7 @@ const AppSidebarDropdown = ({ navigation, appInfoActions }: Props) => {background={appDetail.icon_background}imageUrl={appDetail.icon_url}/>- <RiMenuLine className="size-4 text-text-tertiary" />+ <span className="i-ri-menu-line size-4 text-text-tertiary" /></DropdownMenuTrigger><DropdownMenuContentplacement="bottom-start"@@ -69,7 +62,7 @@ const AppSidebarDropdown = ({ navigation, appInfoActions }: Props) => {<div className={cn('w-[305px] rounded-xl border-[0.5px] border-components-panel-border bg-background-default-subtle shadow-lg')}><div className="p-2"><div- className={cn('flex flex-col gap-2 rounded-lg p-2 pb-2.5', isCurrentWorkspaceEditor && 'cursor-pointer hover:bg-state-base-hover')}+ className="flex cursor-pointer flex-col gap-2 rounded-lg p-2 pb-2.5 hover:bg-state-base-hover"onClick={() => {if (appInfoActions)appInfoActions.setPanelOpen(true)@@ -88,7 +81,7 @@ const AppSidebarDropdown = ({ navigation, appInfoActions }: Props) => {/><div className="flex items-center justify-center rounded-md p-0.5"><div className="flex size-5 items-center justify-center">- <RiEqualizer2Line className="size-4 text-text-tertiary" />+ <span className="i-ri-equalizer-2-line size-4 text-text-tertiary" /></div></div></div>diff --git a/web/app/components/app-sidebar/dataset-detail-section.tsx b/web/app/components/app-sidebar/dataset-detail-section.tsxindex 824712155a1..f337c6b15aa 100644--- a/web/app/components/app-sidebar/dataset-detail-section.tsx+++ b/web/app/components/app-sidebar/dataset-detail-section.tsx@@ -9,6 +9,8 @@ import {RiFileTextLine,RiFocus2Fill,RiFocus2Line,+ RiLock2Fill,+ RiLock2Line,} from '@remixicon/react'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'@@ -19,6 +21,7 @@ import { useAppContext } from '@/context/app-context'import DatasetDetailContext from '@/context/dataset-detail'import { usePathname } from '@/next/navigation'import { useDatasetDetail, useDatasetRelatedApps } from '@/service/knowledge/use-dataset'+import { getDatasetACLCapabilities } from '@/utils/permission'import DatasetInfo from './dataset-info'import NavLink from './nav-link'@@ -37,9 +40,14 @@ const DatasetDetailSection = ({const { t } = useTranslation()const pathname = usePathname()const datasetId = getDatasetIdFromPathname(pathname)- const { isCurrentWorkspaceDatasetOperator } = useAppContext()+ const { userProfile, workspacePermissionKeys } = useAppContext()const { data: datasetRes, refetch: mutateDatasetRes } = useDatasetDetail(datasetId ?? '')const { data: relatedApps } = useDatasetRelatedApps(datasetId ?? '', { enabled: !!datasetId && !!datasetRes })+ const datasetACLCapabilities = useMemo(() => getDatasetACLCapabilities(datasetRes?.permission_keys, {+ currentUserId: userProfile?.id,+ resourceMaintainer: datasetRes?.maintainer,+ workspacePermissionKeys,+ }), [datasetRes?.maintainer, datasetRes?.permission_keys, userProfile?.id, workspacePermissionKeys])const isButtonDisabledWithPipeline = useMemo(() => {if (!datasetRes)@@ -61,7 +69,7 @@ const DatasetDetailSection = ({href: `/datasets/${datasetId}/hitTesting`,icon: RiFocus2Line,selectedIcon: RiFocus2Fill,- disabled: isButtonDisabledWithPipeline,+ disabled: isButtonDisabledWithPipeline || !datasetACLCapabilities.canRetrievalRecall,},{name: t('datasetMenus.settings', { ns: 'common' }),@@ -70,6 +78,16 @@ const DatasetDetailSection = ({selectedIcon: RiEqualizer2Fill,disabled: false,},+ ...(datasetACLCapabilities.canAccessConfig+ ? [{+ name: t('settings.resourceAccess', { ns: 'common' }),+ href: `/datasets/${datasetId}/access-config`,+ icon: RiLock2Line,+ selectedIcon: RiLock2Fill,+ disabled: false,+ }]+ : []+ ),]if (datasetRes?.provider !== 'external') {@@ -90,7 +108,7 @@ const DatasetDetailSection = ({}return baseNavigation- }, [t, datasetId, isButtonDisabledWithPipeline, datasetRes?.provider])+ }, [t, datasetId, isButtonDisabledWithPipeline, datasetRes?.provider, datasetACLCapabilities])if (!datasetRes)return null@@ -128,7 +146,7 @@ const DatasetDetailSection = ({/>))}</nav>- {!isCurrentWorkspaceDatasetOperator && (+ {datasetACLCapabilities.canEdit && (<div className="mt-auto shrink-0"><ExtraInforelatedApps={relatedApps}diff --git a/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx b/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsxindex 05a06f2f77d..e1bfb008a71 100644--- a/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx+++ b/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx@@ -8,10 +8,10 @@ import {DataSourceType,} from '@/models/datasets'import { RETRIEVE_METHOD } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'import Dropdown from '../dropdown'let mockDataset: DataSet-let mockIsDatasetOperator = falseconst mockReplace = vi.fn()const mockInvalidDatasetList = vi.fn()const mockInvalidDatasetDetail = vi.fn()@@ -78,6 +78,11 @@ const createDataset = (overrides: Partial<DataSet> = {}): DataSet => ({runtime_mode: 'rag_pipeline',enable_api: false,is_multimodal: false,+ permission_keys: [+ DatasetACLPermission.Edit,+ DatasetACLPermission.Delete,+ DatasetACLPermission.ImportExportDSL,+ ],...overrides,})@@ -89,11 +94,6 @@ vi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: (selector: (state: { dataset?: DataSet }) => unknown) => selector({ dataset: mockDataset }),}))-vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: { isCurrentWorkspaceDatasetOperator: boolean }) => unknown) =>- selector({ isCurrentWorkspaceDatasetOperator: mockIsDatasetOperator }),-}))-vi.mock('@/service/knowledge/use-dataset', () => ({datasetDetailQueryKeyPrefix: ['dataset', 'detail'],useInvalidDatasetList: () => mockInvalidDatasetList,@@ -143,7 +143,6 @@ describe('Dropdown callback coverage', () => {beforeEach(() => {vi.clearAllMocks()mockDataset = createDataset({ pipeline_id: 'pipeline-1', runtime_mode: 'rag_pipeline' })- mockIsDatasetOperator = falsemockExportPipeline.mockResolvedValue({ data: 'pipeline-content' })mockCheckIsUsedInApp.mockResolvedValue({ is_using: false })mockDeleteDataset.mockResolvedValue({})diff --git a/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx b/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsxindex e1c4aa7b2b7..63e05435c99 100644--- a/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx+++ b/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx@@ -8,13 +8,14 @@ import {DataSourceType,} from '@/models/datasets'import { RETRIEVE_METHOD } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'import DatasetInfo from '..'import Dropdown from '../dropdown'import Menu from '../menu'import MenuItem from '../menu-item'let mockDataset: DataSet-let mockIsDatasetOperator = false+const mockPush = vi.fn()const mockReplace = vi.fn()const mockInvalidDatasetList = vi.fn()const mockInvalidDatasetDetail = vi.fn()@@ -87,11 +88,17 @@ const createDataset = (overrides: Partial<DataSet> = {}): DataSet => ({runtime_mode: 'rag_pipeline',enable_api: false,is_multimodal: false,+ permission_keys: [+ DatasetACLPermission.Edit,+ DatasetACLPermission.Delete,+ DatasetACLPermission.ImportExportDSL,+ ],...overrides,})vi.mock('@/next/navigation', () => ({useRouter: () => ({+ push: mockPush,replace: mockReplace,}),}))@@ -100,11 +107,6 @@ vi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: (selector: (state: { dataset?: DataSet }) => unknown) => selector({ dataset: mockDataset }),}))-vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: { isCurrentWorkspaceDatasetOperator: boolean }) => unknown) =>- selector({ isCurrentWorkspaceDatasetOperator: mockIsDatasetOperator }),-}))-vi.mock('@/service/knowledge/use-dataset', () => ({datasetDetailQueryKeyPrefix: ['dataset', 'detail'],useInvalidDatasetList: () => mockInvalidDatasetList,@@ -161,7 +163,6 @@ describe('DatasetInfo', () => {beforeEach(() => {vi.clearAllMocks()mockDataset = createDataset()- mockIsDatasetOperator = false})// Rendering of dataset summary details based on expand and dataset state.@@ -273,6 +274,21 @@ describe('Menu', () => {expect(screen.getByText('common.operation.delete')).toBeInTheDocument()})+ it('should show resource access option when enabled', () => {+ render(+ <Menu+ showDelete={false}+ showAccessConfig+ openRenameModal={vi.fn()}+ handleExportPipeline={vi.fn()}+ detectIsUsedByApp={vi.fn()}+ openAccessConfig={vi.fn()}+ />,+ )++ expect(screen.getByText('common.settings.resourceAccess')).toBeInTheDocument()+ })+it('should hide export and delete options when not rag pipeline and not deletable', () => {// ArrangemockDataset = createDataset({ runtime_mode: 'general' })@@ -331,6 +347,26 @@ describe('Menu', () => {expect(handleExportPipeline).toHaveBeenCalledTimes(1)expect(detectIsUsedByApp).toHaveBeenCalledTimes(1)})++ it('should invoke access config callback from its menu item', async () => {+ const user = userEvent.setup()+ const openAccessConfig = vi.fn()++ render(+ <Menu+ showDelete={false}+ showAccessConfig+ openRenameModal={vi.fn()}+ handleExportPipeline={vi.fn()}+ detectIsUsedByApp={vi.fn()}+ openAccessConfig={openAccessConfig}+ />,+ )++ await user.click(screen.getByText('common.settings.resourceAccess'))++ expect(openAccessConfig).toHaveBeenCalledTimes(1)+ })})})@@ -338,7 +374,6 @@ describe('Dropdown', () => {beforeEach(() => {vi.clearAllMocks()mockDataset = createDataset({ pipeline_id: 'pipeline-1', runtime_mode: 'rag_pipeline' })- mockIsDatasetOperator = falsemockExportPipeline.mockResolvedValue({ data: 'pipeline-content' })mockCheckIsUsedInApp.mockResolvedValue({ is_using: false })mockDeleteDataset.mockResolvedValue({})@@ -356,12 +391,19 @@ describe('Dropdown', () => {}})- // Rendering behavior based on workspace role.+ // Rendering behavior based on dataset ACL permission keys.describe('Rendering', () => {- it('should hide delete option when user is dataset operator', async () => {+ it('should hide delete option when dataset lacks delete ACL permission', async () => {const user = userEvent.setup()// Arrange- mockIsDatasetOperator = true+ mockDataset = createDataset({+ pipeline_id: 'pipeline-1',+ runtime_mode: 'rag_pipeline',+ permission_keys: [+ DatasetACLPermission.Edit,+ DatasetACLPermission.ImportExportDSL,+ ],+ })render(<Dropdown expand />)// Act@@ -370,6 +412,24 @@ describe('Dropdown', () => {// Assertexpect(screen.queryByText('common.operation.delete')).not.toBeInTheDocument()})++ it('should show resource access option when dataset only has access config ACL permission', async () => {+ const user = userEvent.setup()+ // Arrange+ mockDataset = createDataset({+ runtime_mode: 'general',+ permission_keys: [DatasetACLPermission.AccessConfig],+ })+ render(<Dropdown expand />)++ // Act+ await openMenu(user)++ // Assert+ expect(screen.getByText('common.settings.resourceAccess')).toBeInTheDocument()+ expect(screen.queryByText('common.operation.edit')).not.toBeInTheDocument()+ expect(screen.queryByText('common.operation.delete')).not.toBeInTheDocument()+ })})// User interactions that trigger modals and exports.@@ -441,5 +501,22 @@ describe('Dropdown', () => {expect(mockInvalidDatasetList).toHaveBeenCalledTimes(1)expect(mockReplace).toHaveBeenCalledWith('/datasets')})++ it('should navigate to dataset access config when resource access is clicked', async () => {+ const user = userEvent.setup()+ // Arrange+ mockDataset = createDataset({+ runtime_mode: 'general',+ permission_keys: [DatasetACLPermission.AccessConfig],+ })+ render(<Dropdown expand />)++ // Act+ await openMenu(user)+ await user.click(screen.getByText('common.settings.resourceAccess'))++ // Assert+ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-1/access-config')+ })})})diff --git a/web/app/components/app-sidebar/dataset-info/dropdown.tsx b/web/app/components/app-sidebar/dataset-info/dropdown.tsxindex 8d37fadb656..6539e6e1715 100644--- a/web/app/components/app-sidebar/dataset-info/dropdown.tsx+++ b/web/app/components/app-sidebar/dataset-info/dropdown.tsx@@ -26,6 +26,7 @@ import { datasetDetailQueryKeyPrefix, useInvalidDatasetList } from '@/service/knimport { useInvalid } from '@/service/use-base'import { useExportPipelineDSL } from '@/service/use-pipeline'import { downloadBlob } from '@/utils/download'+import { getDatasetACLCapabilities } from '@/utils/permission'import ActionButton from '../../base/action-button'import RenameDatasetModal from '../../datasets/rename-modal'import Menu from './menu'@@ -59,14 +60,24 @@ const DropDown = ({triggerClassName,}: DropDownProps) => {const { t } = useTranslation()- const { replace } = useRouter()+ const { push, replace } = useRouter()const [open, setOpen] = useState(false)const [showRenameModal, setShowRenameModal] = useState(false)const [confirmMessage, setConfirmMessage] = useState<string>('')const [showConfirmDelete, setShowConfirmDelete] = useState(false)- const isCurrentWorkspaceDatasetOperator = useAppContextWithSelector(state => state.isCurrentWorkspaceDatasetOperator)const dataset = useDatasetDetailContextWithSelector(state => state.dataset) as DataSet+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const datasetACLCapabilities = React.useMemo(() => getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }), [dataset?.maintainer, dataset?.permission_keys, currentUserId, workspacePermissionKeys])+ const canShowOperations = datasetACLCapabilities.canEdit+ || datasetACLCapabilities.canImportExportDSL+ || datasetACLCapabilities.canAccessConfig+ || datasetACLCapabilities.canDeleteconst invalidDatasetList = useInvalidDatasetList()const invalidDatasetDetail = useInvalid([...datasetDetailQueryKeyPrefix, dataset.id])@@ -115,6 +126,11 @@ const DropDown = ({}}, [dataset.id, t])+ const openAccessConfig = useCallback(() => {+ setOpen(false)+ push(`/datasets/${dataset.id}/access-config`)+ }, [dataset.id, push])+const onConfirmDelete = useCallback(async () => {try {await deleteDataset(dataset.id)@@ -127,6 +143,9 @@ const DropDown = ({}}, [dataset.id, replace, invalidDatasetList, t])+ if (!canShowOperations)+ return null+return (<DropdownMenuopen={open}@@ -149,10 +168,14 @@ const DropDown = ({popupClassName="border-0 bg-transparent p-0 shadow-none backdrop-blur-none"><Menu- showDelete={!isCurrentWorkspaceDatasetOperator}+ showEdit={datasetACLCapabilities.canEdit}+ showDelete={datasetACLCapabilities.canDelete}+ showExportPipeline={datasetACLCapabilities.canImportExportDSL}+ showAccessConfig={datasetACLCapabilities.canAccessConfig}openRenameModal={openRenameModal}handleExportPipeline={handleExportPipeline}detectIsUsedByApp={detectIsUsedByApp}+ openAccessConfig={openAccessConfig}/></DropdownMenuContent>{showRenameModal && (diff --git a/web/app/components/app-sidebar/dataset-info/menu.tsx b/web/app/components/app-sidebar/dataset-info/menu.tsxindex 8192bbda42c..ae8bd2ec270 100644--- a/web/app/components/app-sidebar/dataset-info/menu.tsx+++ b/web/app/components/app-sidebar/dataset-info/menu.tsx@@ -1,4 +1,9 @@-import { RiDeleteBinLine, RiEditLine, RiFileDownloadLine } from '@remixicon/react'+import {+ RiDeleteBinLine,+ RiEditLine,+ RiFileDownloadLine,+ RiLock2Line,+} from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'@@ -6,17 +11,25 @@ import Divider from '../../base/divider'import MenuItem from './menu-item'type MenuProps = {+ showEdit?: booleanshowDelete: boolean+ showExportPipeline?: boolean+ showAccessConfig?: booleanopenRenameModal: () => voidhandleExportPipeline: () => voiddetectIsUsedByApp: () => void+ openAccessConfig?: () => void}const Menu = ({+ showEdit = true,showDelete,+ showExportPipeline = true,+ showAccessConfig = false,openRenameModal,handleExportPipeline,detectIsUsedByApp,+ openAccessConfig,}: MenuProps) => {const { t } = useTranslation()const runtimeMode = useDatasetDetailContextWithSelector(state => state.dataset?.runtime_mode)@@ -24,18 +37,27 @@ const Menu = ({return (<div className="flex w-[200px] flex-col rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]"><div className="flex flex-col p-1">- <MenuItem- Icon={RiEditLine}- name={t('operation.edit', { ns: 'common' })}- handleClick={openRenameModal}- />- {runtimeMode === 'rag_pipeline' && (+ {showEdit && (+ <MenuItem+ Icon={RiEditLine}+ name={t('operation.edit', { ns: 'common' })}+ handleClick={openRenameModal}+ />+ )}+ {showExportPipeline && runtimeMode === 'rag_pipeline' && (<MenuItemIcon={RiFileDownloadLine}name={t('operations.exportPipeline', { ns: 'datasetPipeline' })}handleClick={handleExportPipeline}/>)}+ {showAccessConfig && (+ <MenuItem+ Icon={RiLock2Line}+ name={t('settings.resourceAccess', { ns: 'common' })}+ handleClick={openAccessConfig}+ />+ )}</div>{showDelete && (<>diff --git a/web/app/components/app-sidebar/index.tsx b/web/app/components/app-sidebar/index.tsxindex 22ae25ddb0a..3e4fb51ee21 100644--- a/web/app/components/app-sidebar/index.tsx+++ b/web/app/components/app-sidebar/index.tsx@@ -71,7 +71,7 @@ const AppDetailNav = ({ref={sidebarRef}className={cn('flex shrink-0 flex-col border-r border-divider-burn bg-background-default-subtle transition-all',- expand ? 'w-[216px]' : 'w-14',+ expand ? 'w-55' : 'w-14',)}><divdiff --git a/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsx b/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsxindex 51f1f0c341b..f72100e9a8f 100644--- a/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsx+++ b/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsx@@ -12,9 +12,16 @@ const mockToastError = vi.fn()const mockUpdateMutate = vi.fn()const mockExportMutateAsync = vi.fn()const mockDeleteMutate = vi.fn()+let mockWorkspacePermissionKeys: string[] = ['snippets.create_and_modify', 'snippets.management']let mockDropdownOpen = falselet mockDropdownOnOpenChange: ((open: boolean) => void) | undefined+vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+vi.mock('@/next/navigation', () => ({useRouter: () => ({replace: mockReplace,@@ -156,6 +163,7 @@ const mockSnippet: SnippetDetail = {describe('SnippetInfoDropdown', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys = ['snippets.create_and_modify', 'snippets.management']mockDropdownOpen = falsemockDropdownOnOpenChange = undefined})@@ -167,6 +175,35 @@ describe('SnippetInfoDropdown', () => {expect(screen.getByRole('button')).toBeInTheDocument()})++ it('should render nothing without snippet create or management permission', () => {+ mockWorkspacePermissionKeys = []++ render(<SnippetInfoDropdown snippet={mockSnippet} />)++ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('should split edit from export and delete actions by snippet permission', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys = ['snippets.create_and_modify']++ const { unmount } = render(<SnippetInfoDropdown snippet={mockSnippet} />)+ await user.click(screen.getByRole('button'))++ expect(screen.getByText('snippet.menu.editInfo')).toBeInTheDocument()+ expect(screen.queryByText('snippet.menu.exportSnippet')).not.toBeInTheDocument()+ expect(screen.queryByText('snippet.menu.deleteSnippet')).not.toBeInTheDocument()++ unmount()+ mockWorkspacePermissionKeys = ['snippets.management']+ render(<SnippetInfoDropdown snippet={mockSnippet} />)+ await user.click(screen.getByRole('button'))++ expect(screen.queryByText('snippet.menu.editInfo')).not.toBeInTheDocument()+ expect(screen.getByText('snippet.menu.exportSnippet')).toBeInTheDocument()+ expect(screen.getByText('snippet.menu.deleteSnippet')).toBeInTheDocument()+ })})// Edit flow should seed the dialog with current snippet info and submit updates.@@ -207,6 +244,7 @@ describe('SnippetInfoDropdown', () => {describe('Export Snippet', () => {it('should export and download the snippet yaml', async () => {const user = userEvent.setup()+ mockWorkspacePermissionKeys = ['snippets.management']mockExportMutateAsync.mockResolvedValue('yaml: content')render(<SnippetInfoDropdown snippet={mockSnippet} />)@@ -226,6 +264,7 @@ describe('SnippetInfoDropdown', () => {it('should show an error toast when export fails', async () => {const user = userEvent.setup()+ mockWorkspacePermissionKeys = ['snippets.management']mockExportMutateAsync.mockRejectedValue(new Error('export failed'))render(<SnippetInfoDropdown snippet={mockSnippet} />)diff --git a/web/app/components/app-sidebar/snippet-info/dropdown.tsx b/web/app/components/app-sidebar/snippet-info/dropdown.tsxindex eb108fd2005..00400019f92 100644--- a/web/app/components/app-sidebar/snippet-info/dropdown.tsx+++ b/web/app/components/app-sidebar/snippet-info/dropdown.tsx@@ -22,6 +22,8 @@ import { toast } from '@langgenius/dify-ui/toast'import * as React from 'react'import { useTranslation } from 'react-i18next'import CreateSnippetDialog from '@/app/components/snippets/create-snippet-dialog'+import { canCreateAndModifySnippets, canManageSnippets } from '@/app/components/snippets/utils/permission'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useRouter } from '@/next/navigation'import { useDeleteSnippetMutation, useExportSnippetMutation, useUpdateSnippetMutation } from '@/service/use-snippets'@@ -34,12 +36,16 @@ type SnippetInfoDropdownProps = {const SnippetInfoDropdown = ({ snippet }: SnippetInfoDropdownProps) => {const { t } = useTranslation('snippet')const { replace } = useRouter()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const [open, setOpen] = React.useState(false)const [isEditDialogOpen, setIsEditDialogOpen] = React.useState(false)const [isDeleteDialogOpen, setIsDeleteDialogOpen] = React.useState(false)const updateSnippetMutation = useUpdateSnippetMutation()const exportSnippetMutation = useExportSnippetMutation()const deleteSnippetMutation = useDeleteSnippetMutation()+ const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)+ const canManageSnippet = canManageSnippets(workspacePermissionKeys)+ const canShowOperations = canCreateAndModifySnippet || canManageSnippetconst initialValue = React.useMemo(() => ({name: snippet.name,@@ -52,6 +58,9 @@ const SnippetInfoDropdown = ({ snippet }: SnippetInfoDropdownProps) => {}, [])const handleExportSnippet = React.useCallback(async () => {+ if (!canManageSnippet)+ return+setOpen(false)try {const data = await exportSnippetMutation.mutateAsync({ snippetId: snippet.id })@@ -61,7 +70,7 @@ const SnippetInfoDropdown = ({ snippet }: SnippetInfoDropdownProps) => {catch {toast.error(t('exportFailed'))}- }, [exportSnippetMutation, snippet.id, snippet.name, t])+ }, [canManageSnippet, exportSnippetMutation, snippet.id, snippet.name, t])const handleEditSnippet = React.useCallback(async ({ name, description }: {name: string@@ -99,6 +108,9 @@ const SnippetInfoDropdown = ({ snippet }: SnippetInfoDropdownProps) => {})}, [deleteSnippetMutation, replace, snippet.id, t])+ if (!canShowOperations)+ return null+return (<><DropdownMenu open={open} onOpenChange={setOpen}>@@ -112,26 +124,32 @@ const SnippetInfoDropdown = ({ snippet }: SnippetInfoDropdownProps) => {sideOffset={4}popupClassName="w-[180px] p-1">- <DropdownMenuItem className="mx-0 gap-2" onClick={handleOpenEditDialog}>- <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />- <span className="grow">{t('menu.editInfo')}</span>- </DropdownMenuItem>- <DropdownMenuItem className="mx-0 gap-2" onClick={handleExportSnippet}>- <span aria-hidden className="i-ri-download-2-line size-4 shrink-0 text-text-tertiary" />- <span className="grow">{t('menu.exportSnippet')}</span>- </DropdownMenuItem>- <DropdownMenuSeparator className="my-1! bg-divider-subtle" />- <DropdownMenuItem- className="mx-0 gap-2"- variant="destructive"- onClick={() => {- setOpen(false)- setIsDeleteDialogOpen(true)- }}- >- <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />- <span className="grow">{t('menu.deleteSnippet')}</span>- </DropdownMenuItem>+ {canCreateAndModifySnippet && (+ <DropdownMenuItem className="mx-0 gap-2" onClick={handleOpenEditDialog}>+ <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />+ <span className="grow">{t('menu.editInfo')}</span>+ </DropdownMenuItem>+ )}+ {canManageSnippet && (+ <>+ <DropdownMenuItem className="mx-0 gap-2" onClick={handleExportSnippet}>+ <span aria-hidden className="i-ri-download-2-line size-4 shrink-0 text-text-tertiary" />+ <span className="grow">{t('menu.exportSnippet')}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator className="my-1! bg-divider-subtle" />+ <DropdownMenuItem+ className="mx-0 gap-2"+ variant="destructive"+ onClick={() => {+ setOpen(false)+ setIsDeleteDialogOpen(true)+ }}+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />+ <span className="grow">{t('menu.deleteSnippet')}</span>+ </DropdownMenuItem>+ </>+ )}</DropdownMenuContent></DropdownMenu>diff --git a/web/app/components/app/access-config/__tests__/index.spec.tsx b/web/app/components/app/access-config/__tests__/index.spec.tsxnew file mode 100644index 00000000000..49e8c86825d--- /dev/null+++ b/web/app/components/app/access-config/__tests__/index.spec.tsx@@ -0,0 +1,214 @@+import type { AccessRulesEditorProps } from '@/app/components/access-rules-editor'+import { render, screen } from '@testing-library/react'+import { useStore } from '@/app/components/app/store'+import {+ useAppAccessRules,+ useAppUserAccessSettings,+} from '@/service/access-control/use-app-access-config'+import { AppACLPermission } from '@/utils/permission'+import AppAccessConfigPage from '../index'++const mockAppContext = vi.hoisted(() => ({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [] as string[],+}))++const mockAppAccessRules = vi.hoisted(() => ({+ items: [] as AccessRulesEditorProps['rules'],+ isLoading: false,+}))++const mockAppUserAccessSettings = vi.hoisted(() => ({+ data: [] as NonNullable<AccessRulesEditorProps['userAccessSettings']>,+ scope: 'specific' as AccessRulesEditorProps['openScope'],+ isLoading: false,+}))++const mockAccessRulesEditor = vi.hoisted(() => ({+ props: null as AccessRulesEditorProps | null,+}))++const mockMutations = vi.hoisted(() => ({+ updateOpenScope: vi.fn(),+ updateUserAccessSettings: vi.fn(),+ removeMemberBindings: vi.fn(),+}))++vi.mock('@/context/app-context', () => ({+ useAppContext: () => mockAppContext,+}))++vi.mock('@/service/access-control/use-app-access-config', () => ({+ useAppAccessRules: vi.fn(() => ({+ data: { items: mockAppAccessRules.items },+ isLoading: mockAppAccessRules.isLoading,+ })),+ useAppUserAccessSettings: vi.fn(() => ({+ data: mockAppUserAccessSettings.scope+ ? { data: mockAppUserAccessSettings.data, scope: mockAppUserAccessSettings.scope }+ : undefined,+ isLoading: mockAppUserAccessSettings.isLoading,+ })),+ useUpdateAppOpenScope: vi.fn(() => ({+ mutate: mockMutations.updateOpenScope,+ isPending: false,+ })),+ useUpdateAppUserAccessSettings: vi.fn(() => ({+ mutate: mockMutations.updateUserAccessSettings,+ })),+ useRemoveAppAccessPolicyMemberBindings: vi.fn(() => ({+ mutate: mockMutations.removeMemberBindings,+ })),+}))++vi.mock('@/app/components/access-rules-editor', () => ({+ default: (props: AccessRulesEditorProps) => {+ mockAccessRulesEditor.props = props+ return (+ <div data-testid="access-rules-editor" />+ )+ },+}))++describe('AppAccessConfigPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockAppContext.userProfile = { id: 'user-1' }+ mockAppContext.workspacePermissionKeys = []+ mockAppAccessRules.items = []+ mockAppAccessRules.isLoading = false+ mockAppUserAccessSettings.data = []+ mockAppUserAccessSettings.scope = 'specific'+ mockAppUserAccessSettings.isLoading = false+ mockAccessRulesEditor.props = null+ useStore.setState({+ appDetail: {+ id: 'app-1',+ maintainer: 'account-1',+ permission_keys: [AppACLPermission.AccessConfig],+ } as NonNullable<ReturnType<typeof useStore.getState>['appDetail']>,+ })+ })++ // Rendering wires the app access rules into the shared editor.+ describe('Rendering', () => {+ it('should render access config title and pass app rules to the editor', () => {+ render(<AppAccessConfigPage appId="app-1" />)++ expect(screen.getByRole('heading', { name: 'common.settings.resourceAccess' })).toBeInTheDocument()+ expect(screen.getByText('permission.accessRule.appDescription')).toBeInTheDocument()+ expect(screen.getByTestId('access-rules-editor')).toBeInTheDocument()+ expect(mockAccessRulesEditor.props?.className).toBe('w-full max-w-200')+ expect(mockAccessRulesEditor.props?.rules).toEqual([])+ expect(mockAccessRulesEditor.props?.userAccessSettings).toEqual([])+ expect(mockAccessRulesEditor.props?.openScope).toBe('specific')+ })++ it('should not pass open scope before user access settings finish loading', () => {+ mockAppUserAccessSettings.scope = undefined+ mockAppUserAccessSettings.isLoading = true++ render(<AppAccessConfigPage appId="app-1" />)++ expect(mockAccessRulesEditor.props?.openScope).toBeUndefined()+ })++ it('should pass the user access settings open scope to the editor', () => {+ mockAppUserAccessSettings.scope = 'all'++ render(<AppAccessConfigPage appId="app-1" />)++ expect(mockAccessRulesEditor.props?.openScope).toBe('all')+ })++ it('should pass access rule loading state to the editor', () => {+ mockAppAccessRules.isLoading = true+ mockAppUserAccessSettings.isLoading = true++ render(<AppAccessConfigPage appId="app-1" />)++ expect(mockAccessRulesEditor.props?.isLoadingRules).toBe(true)+ expect(mockAccessRulesEditor.props?.isLoadingUserAccessSettings).toBe(true)+ expect(mockAccessRulesEditor.props?.isUpdatingOpenScope).toBe(true)+ })++ it('should pass the app maintainer id from app detail to the editor', () => {+ useStore.setState({+ appDetail: {+ id: 'app-1',+ maintainer: 'account-1',+ permission_keys: [AppACLPermission.AccessConfig],+ } as NonNullable<ReturnType<typeof useStore.getState>['appDetail']>,+ })++ render(<AppAccessConfigPage appId="app-1" />)++ expect(mockAccessRulesEditor.props?.maintainerId).toBe('account-1')+ })++ it('should wire open scope and user policy updates', () => {+ render(<AppAccessConfigPage appId="app-1" />)++ mockAccessRulesEditor.props?.onOpenScopeChange?.('all')+ expect(mockMutations.updateOpenScope).toHaveBeenCalledWith('all', expect.objectContaining({+ onError: expect.any(Function),+ }))++ mockAccessRulesEditor.props?.onUserAccessPoliciesChange?.('account-1', ['policy-1'])+ expect(mockMutations.updateUserAccessSettings).toHaveBeenCalledWith({+ accountId: 'account-1',+ accessPolicyIds: ['policy-1'],+ }, expect.objectContaining({+ onSettled: expect.any(Function),+ }))++ mockAccessRulesEditor.props?.onAddAccessSubject?.('account-2', ['default'])+ expect(mockMutations.updateUserAccessSettings).toHaveBeenCalledWith({+ accountId: 'account-2',+ accessPolicyIds: ['default'],+ }, expect.objectContaining({+ onSettled: expect.any(Function),+ }))++ mockAccessRulesEditor.props?.onRemoveAccessPolicyMemberBinding?.('account-3', 'policy-3')+ expect(mockMutations.removeMemberBindings).toHaveBeenCalledWith({+ accessPolicyId: 'policy-3',+ accountIds: ['account-3'],+ }, expect.objectContaining({+ onSettled: expect.any(Function),+ }))+ })++ it('should not mount access config data hooks when access config permission is missing', () => {+ useStore.setState({+ appDetail: {+ id: 'app-1',+ maintainer: 'account-1',+ permission_keys: [AppACLPermission.ViewLayout],+ } as NonNullable<ReturnType<typeof useStore.getState>['appDetail']>,+ })++ render(<AppAccessConfigPage appId="app-1" />)++ expect(screen.queryByTestId('access-rules-editor')).not.toBeInTheDocument()+ expect(useAppAccessRules).not.toHaveBeenCalled()+ expect(useAppUserAccessSettings).not.toHaveBeenCalled()+ })++ it('should allow the app maintainer with app management workspace permission', () => {+ mockAppContext.userProfile = { id: 'account-1' }+ mockAppContext.workspacePermissionKeys = ['app.create_and_management']+ useStore.setState({+ appDetail: {+ id: 'app-1',+ maintainer: 'account-1',+ permission_keys: [] as string[],+ } as NonNullable<ReturnType<typeof useStore.getState>['appDetail']>,+ })++ render(<AppAccessConfigPage appId="app-1" />)++ expect(screen.getByTestId('access-rules-editor')).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/app/access-config/index.tsx b/web/app/components/app/access-config/index.tsxnew file mode 100644index 00000000000..9704540bbd7--- /dev/null+++ b/web/app/components/app/access-config/index.tsx@@ -0,0 +1,120 @@+'use client'++import type { ResourceOpenScope } from '@/models/access-control'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useCallback, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import AccessRulesEditor from '@/app/components/access-rules-editor'+import { useStore } from '@/app/components/app/store'+import { useAppContext } from '@/context/app-context'+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import {+ useAppAccessRules,+ useAppUserAccessSettings,+ useRemoveAppAccessPolicyMemberBindings,+ useUpdateAppOpenScope,+ useUpdateAppUserAccessSettings,+} from '@/service/access-control/use-app-access-config'+import { getAppACLCapabilities } from '@/utils/permission'++type AppAccessConfigPageProps = {+ appId: string+}++type AppAccessConfigContentProps = {+ appId: string+ maintainerId?: string | null+}++const AppAccessConfigContent = ({ appId, maintainerId }: AppAccessConfigContentProps) => {+ const { t } = useTranslation()+ const locale = useLocale()+ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])+ const { data: appAccessRulesResponse, isLoading: isLoadingAppAccessRules } = useAppAccessRules(appId, language)+ const { data: appUserAccessSettingsResponse, isLoading: isLoadingAppUserAccessSettings } = useAppUserAccessSettings(appId, language)+ const { mutate: updateAppOpenScope, isPending: isUpdatingAppOpenScope } = useUpdateAppOpenScope(appId)+ const { mutate: updateAppUserAccessSettings } = useUpdateAppUserAccessSettings(appId)+ const { mutate: removeAppAccessPolicyMemberBindings } = useRemoveAppAccessPolicyMemberBindings(appId)+ const [optimisticOpenScope, setOptimisticOpenScope] = useState<ResourceOpenScope | null>(null)+ const [updatingAccountId, setUpdatingAccountId] = useState<string | null>(null)++ const appAccessRules = appAccessRulesResponse?.items || []+ const appUserAccessSettings = appUserAccessSettingsResponse?.data || []+ const openScope = optimisticOpenScope || appUserAccessSettingsResponse?.scope++ const handleOpenScopeChange = useCallback((nextOpenScope: ResourceOpenScope) => {+ if (nextOpenScope === openScope)+ return++ const previousOptimisticOpenScope = optimisticOpenScope+ setOptimisticOpenScope(nextOpenScope)+ updateAppOpenScope(nextOpenScope, {+ onError: () => setOptimisticOpenScope(previousOptimisticOpenScope),+ })+ }, [openScope, optimisticOpenScope, updateAppOpenScope])++ const handleUserAccessPoliciesChange = useCallback((accountId: string, accessPolicyIds: string[]) => {+ setUpdatingAccountId(accountId)+ updateAppUserAccessSettings(+ { accountId, accessPolicyIds },+ { onSettled: () => setUpdatingAccountId(null) },+ )+ }, [updateAppUserAccessSettings])++ const handleRemoveAccessPolicyMemberBinding = useCallback((accountId: string, accessPolicyId: string) => {+ setUpdatingAccountId(accountId)+ removeAppAccessPolicyMemberBindings(+ { accessPolicyId, accountIds: [accountId] },+ { onSettled: () => setUpdatingAccountId(null) },+ )+ }, [removeAppAccessPolicyMemberBindings])++ return (+ <ScrollArea+ className="h-full bg-background-default-subtle"+ slotClassNames={{ viewport: 'overscroll-contain' }}+ >+ <header className="flex min-h-15.5 flex-col justify-center px-6 py-3">+ <h1 className="system-xl-semibold text-text-primary">{t('settings.resourceAccess', { ns: 'common' })}</h1>+ <p className="mt-0.5 system-sm-regular text-text-tertiary">+ {t('accessRule.appDescription', { ns: 'permission' })}+ </p>+ </header>+ <main className="w-full px-6 pt-8 pb-10">+ <AccessRulesEditor+ className="w-full max-w-200"+ rules={appAccessRules}+ userAccessSettings={appUserAccessSettings}+ isLoadingRules={isLoadingAppAccessRules}+ isLoadingUserAccessSettings={isLoadingAppUserAccessSettings}+ openScope={openScope}+ isUpdatingOpenScope={isLoadingAppUserAccessSettings || isUpdatingAppOpenScope}+ updatingAccountId={updatingAccountId}+ maintainerId={maintainerId}+ onOpenScopeChange={handleOpenScopeChange}+ onUserAccessPoliciesChange={handleUserAccessPoliciesChange}+ onRemoveAccessPolicyMemberBinding={handleRemoveAccessPolicyMemberBinding}+ onAddAccessSubject={handleUserAccessPoliciesChange}+ />+ </main>+ </ScrollArea>+ )+}++const AppAccessConfigPage = ({ appId }: AppAccessConfigPageProps) => {+ const { userProfile, workspacePermissionKeys } = useAppContext()+ const appDetail = useStore(state => state.appDetail)+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId: userProfile?.id,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }), [appDetail?.maintainer, appDetail?.permission_keys, userProfile?.id, workspacePermissionKeys])++ if (!appDetail || appDetail.id !== appId || !appACLCapabilities.canAccessConfig)+ return null++ return <AppAccessConfigContent appId={appId} maintainerId={appDetail.maintainer} />+}++export default AppAccessConfigPagediff --git a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsxindex 1a8a181f68c..c8bce5401e6 100644--- a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx@@ -35,7 +35,7 @@ vi.mock('@/context/app-context', () => ({}),}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useAppWhiteListSubjects: (...args: unknown[]) => mockUseAppWhiteListSubjects(...args),useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),}))diff --git a/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx b/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsxindex b447e9c381b..11ba79e1851 100644--- a/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx@@ -18,7 +18,7 @@ vi.mock('@/context/app-context', () => ({}),}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),}))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 f3cb47f16b8..dd5e2f4f22f 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@@ -22,7 +22,7 @@ const mockUseMutation = vi.hoisted(() => vi.fn())const mockUseAppWhiteListSubjects = vi.fn()const mockUseSearchForWhiteListCandidates = vi.fn()-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useAppWhiteListSubjects: (...args: unknown[]) => mockUseAppWhiteListSubjects(...args),useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),}))diff --git a/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsx b/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsxindex 044e5aa3d60..5e8ec42be8a 100644--- a/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/specific-groups-or-members.spec.tsx@@ -10,6 +10,10 @@ vi.mock('@/service/access-control', () => ({useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),}))+vi.mock('@/service/access-control/use-app-access-control', () => ({+ useSearchForWhiteListCandidates: (...args: unknown[]) => mockUseSearchForWhiteListCandidates(...args),+}))+const createGroup = (overrides: Partial<AccessControlGroup> = {}): AccessControlGroup => ({id: 'group-1',name: 'Group One',diff --git a/web/app/components/app/app-access-control/access-subject-selector/add-button.tsx b/web/app/components/app/app-access-control/access-subject-selector/add-button.tsxindex 43da1de6a70..42fc822e866 100644--- a/web/app/components/app/app-access-control/access-subject-selector/add-button.tsx+++ b/web/app/components/app/app-access-control/access-subject-selector/add-button.tsx@@ -21,7 +21,7 @@ import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'import { SkeletonRectangle } from '@/app/components/base/skeleton'-import { useSearchForWhiteListCandidates } from '@/service/access-control'+import { useSearchForWhiteListCandidates } from '@/service/access-control/use-app-access-control'import { SelectedGroupsBreadCrumb, SubjectItem } from './subject-options'import {getSubjectLabel,diff --git a/web/app/components/app/app-access-control/index.tsx b/web/app/components/app/app-access-control/index.tsxindex d07e6b1b7d7..18c28d12757 100644--- a/web/app/components/app/app-access-control/index.tsx+++ b/web/app/components/app/app-access-control/index.tsx@@ -7,7 +7,7 @@ import { useMutation, useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AccessMode } from '@/models/access-control'-import { useAppWhiteListSubjects } from '@/service/access-control'+import { useAppWhiteListSubjects } from '@/service/access-control/use-app-access-control'import { consoleQuery } from '@/service/client'import { AccessControlDialog } from './access-control-dialog'import { AccessControlDialogContent } from './access-control-dialog-content'diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsxindex f918b28a898..f5b800ee40b 100644--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx@@ -34,6 +34,7 @@ const hotkeyMocks = vi.hoisted(() => ({}))let mockAppDetail: Record<string, any> | null = null+let mockWorkspacePermissionKeys: string[] = ['tool.manage']vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -65,7 +66,7 @@ vi.mock('@/hooks/use-async-window-open', () => ({useAsyncWindowOpen: () => mockOpenAsyncWindow,}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useGetUserCanAccessApp: (params: unknown) => {mockUseGetUserCanAccessApp(params)return {@@ -108,6 +109,9 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: true,}),+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),}))vi.mock('@langgenius/dify-ui/toast', () => ({@@ -190,6 +194,7 @@ describe('AppPublisher', () => {sectionProps.summary = nullsectionProps.access = nullsectionProps.actions = null+ mockWorkspacePermissionKeys = ['tool.manage']mockAppDetail = {id: 'app-1',name: 'Demo App',@@ -362,6 +367,26 @@ describe('AppPublisher', () => {expect(screen.getByTestId('workflow-tool-drawer')).toBeInTheDocument()})+ it('should not open workflow tool drawer without tool.manage', () => {+ mockWorkspacePermissionKeys = []+ mockAppDetail = {+ ...mockAppDetail,+ mode: AppModeEnum.WORKFLOW,+ }++ render(+ <AppPublisher+ publishedAt={Date.now()}+ />,+ )++ fireEvent.click(screen.getByText('common.publish'))+ fireEvent.click(screen.getByText('publisher-workflow-tool'))++ expect(screen.queryByTestId('workflow-tool-drawer')).not.toBeInTheDocument()+ expect(sectionProps.actions?.workflowToolAvailable).toBe(false)+ })+it('should close embedded and access control panels through child callbacks', async () => {render(<AppPublisher@@ -382,11 +407,12 @@ describe('AppPublisher', () => {})it('should refresh app detail after access control confirmation', async () => {- render(+ const { queryClient } = render(<AppPublisherpublishedAt={Date.now()}/>,)+ const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue()fireEvent.click(screen.getByText('common.publish'))fireEvent.click(screen.getByText('publisher-access-control'))@@ -396,11 +422,7 @@ describe('AppPublisher', () => {fireEvent.click(screen.getByText('confirm-access-control'))await waitFor(() => {- expect(mockFetchAppDetailDirect).toHaveBeenCalledWith({ url: '/apps', id: 'app-1' })- expect(mockSetAppDetail).toHaveBeenCalledWith({- id: 'app-1',- access_mode: AccessMode.PUBLIC,- })+ expect(invalidateQueriesSpy).toHaveBeenCalledWith({ queryKey: ['apps', 'detail', 'app-1'] })})})diff --git a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx b/web/app/components/app/app-publisher/__tests__/sections.spec.tsxindex 1572f3d4e07..6675dd49f39 100644--- a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx@@ -243,7 +243,6 @@ describe('app-publisher sections', () => {workflowToolAvailable={false}workflowToolIsLoading={false}workflowToolOutdated={false}- workflowToolIsCurrentWorkspaceManagerworkflowToolMessage="workflow-disabled"onConfigureWorkflowTool={vi.fn()}/>,@@ -282,7 +281,6 @@ describe('app-publisher sections', () => {workflowToolAvailableworkflowToolIsLoading={false}workflowToolOutdated={false}- workflowToolIsCurrentWorkspaceManageronConfigureWorkflowTool={vi.fn()}/>,)@@ -309,7 +307,6 @@ describe('app-publisher sections', () => {workflowToolAvailableworkflowToolIsLoading={false}workflowToolOutdated={false}- workflowToolIsCurrentWorkspaceManageronConfigureWorkflowTool={vi.fn()}/>,)diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsxindex 961c33cf72f..f3e65682a8f 100644--- a/web/app/components/app/app-publisher/index.tsx+++ b/web/app/components/app/app-publisher/index.tsx@@ -8,7 +8,7 @@ import { Button } from '@langgenius/dify-ui/button'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { toast } from '@langgenius/dify-ui/toast'import { useHotkey } from '@tanstack/react-hotkeys'-import { useSuspenseQuery } from '@tanstack/react-query'+import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import {use,useEffect,@@ -26,6 +26,7 @@ import EmbeddedModal from '@/app/components/app/overview/embedded'import { useStore as useAppStore } from '@/app/components/app/store'import { trackEvent } from '@/app/components/base/amplitude'import { buildInstalledAppPath } from '@/app/components/explore/installed-app/routes'+import { useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import { WorkflowToolDrawer } from '@/app/components/tools/workflow-tool'import { useConfigureButton } from '@/app/components/tools/workflow-tool/hooks/use-configure-button'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'@@ -36,9 +37,10 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'import { AccessMode } from '@/models/access-control'-import { useAppWhiteListSubjects, useGetUserCanAccessApp } from '@/service/access-control'-import { fetchAppDetailDirect, publishToCreatorsPlatform } from '@/service/apps'+import { useAppWhiteListSubjects, useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'+import { publishToCreatorsPlatform } from '@/service/apps'import { fetchInstalledAppList } from '@/service/explore'+import { appDetailQueryKeyPrefix } from '@/service/use-apps'import { useInvalidateAppWorkflow } from '@/service/use-workflow'import { fetchPublishedWorkflow } from '@/service/workflow'import { AppModeEnum } from '@/types/app'@@ -80,7 +82,7 @@ export type AppPublisherProps = {hasHumanInputNode?: boolean}-const PUBLISH_SHORTCUT = ['Mod', 'Shift', 'P']+const PUBLISH_SHORTCUT = ['ctrl', '⇧', 'P']export type AppPublisherPublishParams = ModelAndParameter | PublishWorkflowParams@@ -126,7 +128,8 @@ export function AppPublisher({const workflowStore = use(WorkflowContext)const appDetail = useAppStore(state => state.appDetail)- const setAppDetail = useAppStore(s => s.setAppDetail)+ const canManageTools = useCanManageTools()+ const queryClient = useQueryClient()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const { formatTimeFromNow } = useFormatTimeFromNow()const { app_base_url: appBaseURL = '', access_token: accessToken = '' } = appDetail?.site ?? {}@@ -237,8 +240,7 @@ export function AppPublisher({if (!appDetail)returntry {- const res = await fetchAppDetailDirect({ url: '/apps', id: appDetail.id })- setAppDetail(res)+ await queryClient.invalidateQueries({ queryKey: [...appDetailQueryKeyPrefix, appDetail.id] })}finally {setShowAppAccessControl(false)@@ -319,10 +321,11 @@ export function AppPublisher({}, [appDetail?.id, invalidateAppWorkflow, workflowStore])const hasPublishedVersion = !!publishedAt+ const workflowToolVisible = appDetail?.mode === AppModeEnum.WORKFLOW && !hasHumanInputNode && !hasTriggerNode+ const workflowToolAvailableForUser = workflowToolAvailable && canManageToolsconst workflowToolMessage = !hasPublishedVersion || !workflowToolAvailable? t('common.workflowAsToolDisabledHint', { ns: 'workflow' }): undefined- const workflowToolVisible = appDetail?.mode === AppModeEnum.WORKFLOW && !hasHumanInputNode && !hasTriggerNodeconst workflowToolPublished = !!toolPublishedfunction closeWorkflowToolDrawer() {setWorkflowToolDrawerOpen(false)@@ -332,7 +335,7 @@ export function AppPublisher({background: (appDetail?.icon_type === 'image' ? appDefaultIconBackground : appDetail?.icon_background) || appDefaultIconBackground,}const workflowTool = useConfigureButton({- enabled: workflowToolVisible,+ enabled: workflowToolVisible && canManageTools,published: workflowToolPublished,detailNeedUpdate: workflowToolPublished && published,workflowAppId: appDetail?.id ?? '',@@ -346,6 +349,9 @@ export function AppPublisher({onConfigured: closeWorkflowToolDrawer,})function openWorkflowToolDrawer() {+ if (!canManageTools)+ return+handleOpenChange(false)setWorkflowToolDrawerOpen(true)}@@ -429,10 +435,9 @@ export function AppPublisher({showBatchRunConfig={hiddenLaunchVariables.length > 0 && (appDetail?.mode === AppModeEnum.WORKFLOW || appDetail?.mode === AppModeEnum.COMPLETION)}showRunConfig={hiddenLaunchVariables.length > 0}toolPublished={toolPublished}- workflowToolAvailable={workflowToolAvailable}+ workflowToolAvailable={workflowToolAvailableForUser}workflowToolIsLoading={workflowTool.isLoading}workflowToolOutdated={workflowTool.outdated}- workflowToolIsCurrentWorkspaceManager={workflowTool.isCurrentWorkspaceManager}workflowToolMessage={workflowToolMessage}onConfigureWorkflowTool={openWorkflowToolDrawer}/>@@ -471,7 +476,7 @@ export function AppPublisher({onSubmit={handleWorkflowLaunchConfirm}/></Popover>- {workflowToolDrawerOpen && (+ {workflowToolDrawerOpen && canManageTools && (<WorkflowToolDrawerisAdd={!workflowToolPublished}payload={workflowTool.payload}diff --git a/web/app/components/app/app-publisher/sections.tsx b/web/app/components/app/app-publisher/sections.tsxindex b3fd7dc14ba..abb2deb2e86 100644--- a/web/app/components/app/app-publisher/sections.tsx+++ b/web/app/components/app/app-publisher/sections.tsx@@ -9,7 +9,6 @@ import {TooltipContent,TooltipTrigger,} from '@langgenius/dify-ui/tooltip'-import { RiSettings2Line } from '@remixicon/react'import { formatForDisplay } from '@tanstack/react-hotkeys'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'@@ -71,7 +70,6 @@ type ActionsSectionProps = Pick<AppPublisherProps, | 'hasHumanInputNode'showRunConfig?: booleanworkflowToolIsLoading: booleanworkflowToolOutdated: boolean- workflowToolIsCurrentWorkspaceManager: booleanworkflowToolMessage?: stringonConfigureWorkflowTool: () => void}@@ -275,7 +273,6 @@ export const PublisherActionsSection = ({workflowToolAvailable = true,workflowToolIsLoading,workflowToolOutdated,- workflowToolIsCurrentWorkspaceManager,workflowToolMessage,onConfigureWorkflowTool,}: ActionsSectionProps) => {@@ -297,7 +294,7 @@ export const PublisherActionsSection = ({actionButton={showRunConfig? {ariaLabel: t('operation.config', { ns: 'common' }),- icon: <RiSettings2Line className="size-4" />,+ icon: <span className="i-ri-settings-2-line size-4" />,onClick: () => handleOpenRunConfig?.(appURL),}: undefined}@@ -316,7 +313,7 @@ export const PublisherActionsSection = ({actionButton={showBatchRunConfig? {ariaLabel: t('operation.config', { ns: 'common' }),- icon: <RiSettings2Line className="size-4" />,+ icon: <span className="i-ri-settings-2-line size-4" />,onClick: () => handleOpenRunConfig?.(`${appURL}${appURL.includes('?') ? '&' : '?'}mode=batch`),}: undefined}@@ -366,7 +363,6 @@ export const PublisherActionsSection = ({published={!!toolPublished}isLoading={workflowToolIsLoading}outdated={workflowToolOutdated}- isCurrentWorkspaceManager={workflowToolIsCurrentWorkspaceManager}onConfigure={onConfigureWorkflowTool}disabledReason={workflowToolMessage}/>diff --git a/web/app/components/app/configuration/config/agent-setting-button.tsx b/web/app/components/app/configuration/config/agent-setting-button.tsxindex 68a3f8cef16..ff95d4c8c9d 100644--- a/web/app/components/app/configuration/config/agent-setting-button.tsx+++ b/web/app/components/app/configuration/config/agent-setting-button.tsx@@ -2,7 +2,6 @@import type { FC } from 'react'import type { AgentConfig } from '@/models/debug'import { Button } from '@langgenius/dify-ui/button'-import { RiSettings2Line } from '@remixicon/react'import * as React from 'react'import { useState } from 'react'import { useTranslation } from 'react-i18next'@@ -12,6 +11,7 @@ type Props = Readonly<{isFunctionCall: booleanisChatModel: booleanagentConfig?: AgentConfig+ disabled?: booleanonAgentSettingChange: (payload: AgentConfig) => void}>@@ -20,14 +20,15 @@ const AgentSettingButton: FC<Props> = ({isFunctionCall,isChatModel,agentConfig,+ disabled = false,}) => {const { t } = useTranslation()const [isShowAgentSetting, setIsShowAgentSetting] = useState(false)return (<>- <Button onClick={() => setIsShowAgentSetting(true)} className="mr-2 shrink-0">- <RiSettings2Line className="mr-1 size-4 text-text-tertiary" />+ <Button onClick={() => setIsShowAgentSetting(true)} className="mr-2 shrink-0" disabled={disabled}>+ <span className="mr-1 i-ri-settings-2-line size-4 text-text-tertiary" />{t('agent.setting.name', { ns: 'appDebug' })}</Button>{isShowAgentSetting && (diff --git a/web/app/components/app/configuration/configuration-view.tsx b/web/app/components/app/configuration/configuration-view.tsxindex a33280bb06c..90f2d429720 100644--- a/web/app/components/app/configuration/configuration-view.tsx+++ b/web/app/components/app/configuration/configuration-view.tsx@@ -109,6 +109,7 @@ const ConfigurationView: FC<ConfigurationViewModel> = ({isChatModel={contextValue.modelModeType === ModelModeType.chat}agentConfig={modelConfig.agentConfig}isFunctionCall={contextValue.isFunctionCall}+ disabled={contextValue.readonly}onAgentSettingChange={onAgentSettingChange}/>)}@@ -119,6 +120,7 @@ const ConfigurationView: FC<ConfigurationViewModel> = ({provider={modelConfig.provider}completionParams={contextValue.completionParams}modelId={modelConfig.model_id}+ readonly={contextValue.readonly}setModel={onModelChange}onCompletionParamsChange={onCompletionParamsChange}debugWithMultipleModel={debugWithMultipleModel}@@ -245,7 +247,7 @@ const ConfigurationView: FC<ConfigurationViewModel> = ({inWorkflow={false}showFileUpload={false}isChatMode={contextValue.mode !== AppModeEnum.COMPLETION}- disabled={false}+ disabled={!!contextValue.readonly}onChange={onFeaturesChange}onClose={onCloseFeaturePanel}promptVariables={promptVariables}diff --git a/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsxindex 25e38b48552..56dac4e06e9 100644--- a/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx@@ -8,7 +8,7 @@ import { ComparisonOperator, LogicalOperator } from '@/app/components/workflow/nimport { getSelectedDatasetsMode } from '@/app/components/workflow/nodes/knowledge-retrieval/utils'import { DatasetPermission, DataSourceType } from '@/models/datasets'import { AppModeEnum, ModelModeType, RETRIEVE_TYPE } from '@/types/app'-import { hasEditPermissionForDataset } from '@/utils/permission'+import { DatasetACLPermission, getDatasetACLCapabilities, hasEditPermissionForDataset } from '@/utils/permission'import DatasetConfig from '../index'// Mock external dependencies@@ -42,10 +42,29 @@ vi.mock('@/context/app-context', () => ({userProfile: {id: 'user-123',},+ workspacePermissionKeys: [],})),}))vi.mock('@/utils/permission', () => ({+ DatasetACLPermission: {+ Readonly: 'dataset.acl.readonly',+ Edit: 'dataset.acl.edit',+ Use: 'dataset.acl.use',+ },+ getDatasetACLCapabilities: vi.fn(() => ({+ canReadonly: false,+ canEdit: true,+ canImportExportDSL: false,+ canPipelineTest: false,+ canDocumentDownload: false,+ canRetrievalRecall: false,+ canUse: true,+ canDeleteFile: false,+ canPipelineRelease: false,+ canDelete: false,+ canAccessConfig: false,+ })),hasEditPermissionForDataset: vi.fn(() => true),}))@@ -234,6 +253,7 @@ const createMockDataset = (overrides: Partial<DataSet> = {}): DataSet => {indexing_technique: 'high_quality' as any,author_name: 'Test Author',created_by: 'user-123',+ maintainer: 'user-123',updated_by: 'user-123',updated_at: Date.now(),app_count: 0,@@ -306,6 +326,19 @@ const renderDatasetConfig = (contextOverrides: Partial<typeof mockConfigContext>describe('DatasetConfig', () => {beforeEach(() => {vi.clearAllMocks()+ vi.mocked(getDatasetACLCapabilities).mockReturnValue({+ canReadonly: false,+ canEdit: true,+ canImportExportDSL: false,+ canPipelineTest: false,+ canDocumentDownload: false,+ canRetrievalRecall: false,+ canUse: true,+ canDeleteFile: false,+ canPipelineRelease: false,+ canDelete: false,+ canAccessConfig: false,+ })mockConfigContext.dataSets = []mockConfigContext.setDataSets = vi.fn()mockConfigContext.setModelConfig = vi.fn()@@ -438,6 +471,38 @@ describe('DatasetConfig', () => {expect(screen.getByTestId(`card-item-${dataset.id}`))!.toBeInTheDocument()})++ it('should disable dataset editing when ACL does not grant edit even if legacy dataset permission allows it', () => {+ const dataset = createMockDataset({+ permission: DatasetPermission.allTeamMembers,+ permission_keys: [DatasetACLPermission.Use],+ })+ vi.mocked(hasEditPermissionForDataset).mockReturnValue(true)+ vi.mocked(getDatasetACLCapabilities).mockReturnValue({+ canReadonly: false,+ canEdit: false,+ canImportExportDSL: false,+ canPipelineTest: false,+ canDocumentDownload: false,+ canRetrievalRecall: false,+ canUse: true,+ canDeleteFile: false,+ canPipelineRelease: false,+ canDelete: false,+ canAccessConfig: false,+ })++ renderDatasetConfig({+ dataSets: [dataset],+ })++ expect(screen.getByTestId(`card-item-${dataset.id}`))!.toBeInTheDocument()+ expect(screen.queryByText('Edit')).not.toBeInTheDocument()+ expect(getDatasetACLCapabilities).toHaveBeenCalledWith(dataset.permission_keys, expect.objectContaining({+ currentUserId: 'user-123',+ resourceMaintainer: dataset.maintainer,+ }))+ })})describe('Context Variables', () => {diff --git a/web/app/components/app/configuration/dataset-config/index.tsx b/web/app/components/app/configuration/dataset-config/index.tsxindex 6ea2a638396..aa5624099aa 100644--- a/web/app/components/app/configuration/dataset-config/index.tsx+++ b/web/app/components/app/configuration/dataset-config/index.tsx@@ -31,7 +31,7 @@ import {import { useSelector as useAppContextSelector } from '@/context/app-context'import ConfigContext from '@/context/debug-configuration'import { AppModeEnum } from '@/types/app'-import { hasEditPermissionForDataset } from '@/utils/permission'+import { getDatasetACLCapabilities } from '@/utils/permission'import FeaturePanel from '../base/feature-panel'import OperationBtn from '../base/operation-btn'import { useFormattingChangedDispatcher } from '../debug/hooks'@@ -45,7 +45,8 @@ type Props = Readonly<{}>const DatasetConfig: FC<Props> = ({ readonly, hideMetadataFilter }) => {const { t } = useTranslation()- const userProfile = useAppContextSelector(s => s.userProfile)+ const currentUserId = useAppContextSelector(s => s.userProfile?.id)+ const workspacePermissionKeys = useAppContextSelector(s => s.workspacePermissionKeys)const {mode,dataSets: dataSet,@@ -155,17 +156,17 @@ const DatasetConfig: FC<Props> = ({ readonly, hideMetadataFilter }) => {const formattedDataset = useMemo(() => {return dataSet.map((item) => {- const datasetConfig = {- createdBy: item.created_by,- partialMemberList: item.partial_member_list || [],- permission: item.permission,- }+ const datasetACLCapabilities = getDatasetACLCapabilities(item.permission_keys, {+ currentUserId,+ resourceMaintainer: item.maintainer,+ workspacePermissionKeys,+ })return {...item,- editable: hasEditPermissionForDataset(userProfile?.id || '', datasetConfig),+ editable: datasetACLCapabilities.canEdit,}})- }, [dataSet, userProfile?.id])+ }, [currentUserId, dataSet, workspacePermissionKeys])const metadataList = useMemo(() => {return intersectionBy(...formattedDataset.filter((dataset) => {@@ -249,7 +250,7 @@ const DatasetConfig: FC<Props> = ({ readonly, hideMetadataFilter }) => {setDatasetConfigs(newInputs)}, [setDatasetConfigs, datasetConfigsRef])- const handleMetadataCompletionParamsChange = useCallback((newParams: Record<string, any>) => {+ const handleMetadataCompletionParamsChange = useCallback((newParams: Record<string, unknown>) => {const newInputs = produce(datasetConfigsRef.current!, (draft) => {draft.metadata_model_config = {...draft.metadata_model_config!,diff --git a/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsxindex fe475cf8711..46dac5351ce 100644--- a/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx@@ -33,6 +33,13 @@ vi.mock('@/service/knowledge/use-dataset', () => ({useInfiniteDatasets: (...args: any[]) => mockUseInfiniteDatasets(...args),}))+let mockWorkspacePermissionKeys = ['dataset.create_and_management']+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+vi.mock('@/hooks/use-knowledge', () => ({useKnowledge: () => ({formatIndexingTechniqueAndMethod: (tech: string, method: string) => `${tech}:${method}`,@@ -78,6 +85,7 @@ const makeDataset = (overrides: Partial<DataSet>): DataSet => ({describe('SelectDataSet', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys = ['dataset.create_and_management']})it('renders dataset entries, allows selection, and fires onSelect', async () => {@@ -139,6 +147,25 @@ describe('SelectDataSet', () => {expect(screen.getByRole('button', { name: 'common.operation.add' })).toBeDisabled()})+ it('should hide the create dataset link when dataset.create_and_management is unavailable', async () => {+ mockWorkspacePermissionKeys = []+ mockUseInfiniteDatasets.mockReturnValue({+ data: { pages: [{ data: [] }] },+ isLoading: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ })++ await act(async () => {+ render(<SelectDataSet {...baseProps} onSelect={vi.fn()} selectedIds={[]} />)+ })++ expect(screen.getByText('appDebug.feature.dataSet.noDataSet')).toBeInTheDocument()+ expect(screen.queryByRole('link', { name: 'appDebug.feature.dataSet.toCreate' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.operation.add' })).toBeDisabled()+ })+it('uses selectedIds as the initial modal selection', async () => {const datasetOne = makeDataset({id: 'set-1',diff --git a/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx b/web/app/components/app/configuration/dataset-config/select-dataset/index.tsxindex 8b1d7b106f8..60c4d79a1a6 100644--- a/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx+++ b/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx@@ -13,9 +13,11 @@ import Badge from '@/app/components/base/badge'import Loading from '@/app/components/base/loading'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import FeatureIcon from '@/app/components/header/account-setting/model-provider-page/model-selector/feature-icon'+import { useSelector as useAppContextSelector } from '@/context/app-context'import { useKnowledge } from '@/hooks/use-knowledge'import Link from '@/next/link'import { useInfiniteDatasets } from '@/service/knowledge/use-dataset'+import { hasPermission } from '@/utils/permission'type ISelectDataSetProps = {isShow: boolean@@ -36,6 +38,8 @@ const SelectDataSet: FC<ISelectDataSetProps> = ({const [selectedIdsInModal, setSelectedIdsInModal] = useState(() => selectedIds)const canSelectMulti = trueconst { formatIndexingTechniqueAndMethod } = useKnowledge()+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)+ const canCreateDataset = hasPermission(workspacePermissionKeys, 'dataset.create_and_management')const { data, isLoading, isFetchingNextPage, fetchNextPage, hasNextPage } = useInfiniteDatasets({ page: 1 },{ enabled: isShow, staleTime: 0, refetchOnMount: 'always' },@@ -107,7 +111,9 @@ const SelectDataSet: FC<ISelectDataSetProps> = ({{hasNoData && (<div className="mt-6 flex h-32 items-center justify-center space-x-1 rounded-lg border border-divider-subtle bg-components-panel-on-panel-item-bg text-[13px]"><span className="text-text-tertiary">{t('feature.dataSet.noDataSet', { ns: 'appDebug' })}</span>- <Link href="/datasets/create" className="font-normal text-text-accent">{t('feature.dataSet.toCreate', { ns: 'appDebug' })}</Link>+ {canCreateDataset && (+ <Link href="/datasets/create" className="font-normal text-text-accent">{t('feature.dataSet.toCreate', { ns: 'appDebug' })}</Link>+ )}</div>)}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 cc7f574208d..092ad6d7ec2 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@@ -1,15 +1,19 @@import type { MockedFunction } from 'vitest'import type { DataSet } from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'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, DataSourceType, RerankingModeEnum } from '@/models/datasets'import { updateDatasetSetting } from '@/service/datasets'import { useMembers } from '@/service/use-common'import { RETRIEVE_METHOD } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'import SettingsModal from '../index'const toastMocks = vi.hoisted(() => ({@@ -33,7 +37,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({const mockOnCancel = vi.fn()const mockOnSave = vi.fn()const mockSetShowAccountSettingModal = vi.fn()-let mockIsWorkspaceDatasetOperator = falseconst mockUseModelList = vi.fn()const mockUseModelListAndDefaultModel = vi.fn()@@ -65,14 +68,20 @@ vi.mock('@/service/use-common', async () => ({}))vi.mock('@/context/app-context', () => ({- useAppContext: () => ({ isCurrentWorkspaceDatasetOperator: mockIsWorkspaceDatasetOperator }),- useSelector: <T,>(selector: (value: { userProfile: { id: string, name: string, email: string, avatar_url: string } }) => T) => selector({+ useAppContext: () => {+ throw new Error('legacy workspace dataset_operator state should not be used by SettingsModal')+ },+ useSelector: <T,>(selector: (value: {+ userProfile: { id: string, name: string, email: string, avatar_url: string }+ workspacePermissionKeys: string[]+ }) => T) => selector({userProfile: {id: 'user-1',name: 'User One',email: '[email protected]',avatar_url: 'avatar.png',},+ workspacePermissionKeys: [],}),}))@@ -185,6 +194,7 @@ const createDataset = (overrides: Partial<DataSet> = {}, retrievalOverrides: Parruntime_mode: 'general',enable_api: true,is_multimodal: false,+ permission_keys: [DatasetACLPermission.Edit],...overrides,retrieval_model_dict: {...retrievalConfig,@@ -198,12 +208,19 @@ const createDataset = (overrides: Partial<DataSet> = {}, retrievalOverrides: Par}const renderWithProviders = (dataset: DataSet) => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ queryClient.setQueryData(systemFeaturesQueryOptions().queryKey, defaultSystemFeatures)+return render(- <SettingsModal- currentDataset={dataset}- onCancel={mockOnCancel}- onSave={mockOnSave}- />,+ <QueryClientProvider client={queryClient}>+ <SettingsModal+ currentDataset={dataset}+ onCancel={mockOnCancel}+ onSave={mockOnSave}+ />+ </QueryClientProvider>,)}@@ -220,7 +237,6 @@ const renderSettingsModal = async (dataset: DataSet) => {describe('SettingsModal', () => {beforeEach(() => {vi.clearAllMocks()- mockIsWorkspaceDatasetOperator = falsemockUseMembers.mockReturnValue({data: {accounts: [@@ -379,6 +395,18 @@ describe('SettingsModal', () => {})})+ // Dataset ACL permissions control whether the legacy dataset permission selector is editable.+ describe('Permission Handling', () => {+ it('should disable permission selector when dataset lacks edit ACL permission', async () => {+ const dataset = createDataset({ permission_keys: [DatasetACLPermission.Readonly] })++ const { container } = renderWithProviders(dataset)+ await waitFor(() => expect(mockUseMembers).toHaveBeenCalled())++ expect(container.querySelector('[class*="cursor-not-allowed"]')).toBeInTheDocument()+ })+ })+// Validation guardrails before saving.describe('Validation', () => {it('should block save when dataset name is empty', async () => {diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsxindex 5350bb04474..2a832586dfd 100644--- a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx+++ b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx@@ -21,7 +21,6 @@ import { ModelTypeEnum } from '@/app/components/header/account-setting/model-proimport { useModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'import { useIntegrationsSetting } from '@/app/components/header/account-setting/use-integrations-setting'-import { useAppContext } from '@/context/app-context'import { useDocLink } from '@/context/i18n'import { DatasetPermission } from '@/models/datasets'import { updateDatasetSetting } from '@/service/datasets'@@ -57,7 +56,6 @@ const SettingsModal: FC<SettingsModalProps> = ({const isExternal = currentDataset.provider === 'external'const openIntegrationsSetting = useIntegrationsSetting()const [loading, setLoading] = useState(false)- const { isCurrentWorkspaceDatasetOperator } = useAppContext()const [localeCurrentDataset, setLocaleCurrentDataset] = useState({ ...currentDataset })const [topK, setTopK] = useState(localeCurrentDataset?.external_retrieval_model.top_k ?? 2)const [scoreThreshold, setScoreThreshold] = useState(localeCurrentDataset?.external_retrieval_model.score_threshold ?? 0.5)@@ -240,7 +238,7 @@ const SettingsModal: FC<SettingsModalProps> = ({</div><div className="w-full"><PermissionSelector- disabled={!localeCurrentDataset?.embedding_available || isCurrentWorkspaceDatasetOperator}+ disabled={!localeCurrentDataset?.embedding_available}permission={localeCurrentDataset.permission}value={selectedMemberIDs}onChange={v => handleValueChange('permission', v!)}diff --git a/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx b/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsxindex 01f3e2834a7..dca45fbbe74 100644--- a/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx+++ b/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx@@ -138,10 +138,12 @@ const createContextValue = (overrides: Partial<{modelConfig: ModelConfigsetInputs: (inputs: Inputs) => voidreadonly: boolean+ canTestAndRun: boolean}> = {}) => ({modelConfig: createModelConfig(),setInputs: mockSetInputs,readonly: false,+ canTestAndRun: true,...overrides,})@@ -485,49 +487,79 @@ describe('ChatUserInput', () => {})})- describe('Readonly Mode', () => {- it('should set string input as readonly when readonly is true', () => {+ describe('Debug Permission', () => {+ it('should keep string input editable when configuration is readonly but test/run is allowed', () => {mockUseContext.mockReturnValue(createContextValue({modelConfig: createModelConfig([createPromptVariable({ key: 'name', name: 'Name', type: 'string' }),]),readonly: true,+ canTestAndRun: true,+ }))++ render(<ChatUserInput inputs={{}} />)+ expect(screen.getByTestId('input-Name')).not.toHaveAttribute('readonly')+ })++ it('should set string input as readonly when test/run is denied even if configuration is editable', () => {+ mockUseContext.mockReturnValue(createContextValue({+ modelConfig: createModelConfig([+ createPromptVariable({ key: 'name', name: 'Name', type: 'string' }),+ ]),+ readonly: false,+ canTestAndRun: false,+ }))++ render(<ChatUserInput inputs={{}} />)+ expect(screen.getByTestId('input-Name')).toHaveAttribute('readonly')+ })++ it('should set string input as readonly when configuration is readonly and test/run is denied', () => {+ mockUseContext.mockReturnValue(createContextValue({+ modelConfig: createModelConfig([+ createPromptVariable({ key: 'name', name: 'Name', type: 'string' }),+ ]),+ readonly: true,+ canTestAndRun: false,}))render(<ChatUserInput inputs={{}} />)expect(screen.getByTestId('input-Name')).toHaveAttribute('readonly')})- it('should set paragraph input as readonly when readonly is true', () => {+ it('should set paragraph input as readonly when configuration is readonly and test/run is denied', () => {mockUseContext.mockReturnValue(createContextValue({modelConfig: createModelConfig([createPromptVariable({ key: 'desc', name: 'Description', type: 'paragraph' }),]),readonly: true,+ canTestAndRun: false,}))render(<ChatUserInput inputs={{}} />)expect(screen.getByRole('textbox', { name: 'Description' })).toHaveAttribute('readonly')})- it('should disable select when readonly is true', () => {+ it('should disable select when configuration is readonly and test/run is denied', () => {mockUseContext.mockReturnValue(createContextValue({modelConfig: createModelConfig([createPromptVariable({ key: 'choice', name: 'Choice', type: 'select', options: ['A', 'B'] }),]),readonly: true,+ canTestAndRun: false,}))render(<ChatUserInput inputs={{}} />)expect(screen.getByTestId('select-input')).toBeDisabled()})- it('should disable checkbox when readonly is true', () => {+ it('should disable checkbox when configuration is readonly and test/run is denied', () => {mockUseContext.mockReturnValue(createContextValue({modelConfig: createModelConfig([createPromptVariable({ key: 'enabled', name: 'Enabled', type: 'checkbox' }),]),readonly: true,+ canTestAndRun: false,}))render(<ChatUserInput inputs={{}} />)diff --git a/web/app/components/app/configuration/debug/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/__tests__/index.spec.tsxindex c17a74e24c3..b9e1400c67a 100644--- a/web/app/components/app/configuration/debug/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/debug/__tests__/index.spec.tsx@@ -258,6 +258,7 @@ vi.mock('../debug-with-single-model', () => {const createContextValue = (overrides: Partial<DebugContextValue> = {}): DebugContextValue => ({readonly: false,+ canTestAndRun: true,appId: 'app-id',isAPIKeySet: true,isTrailFinished: false,@@ -540,10 +541,23 @@ describe('Debug', () => {expect(screen.queryByTestId('chat-user-input')).not.toBeInTheDocument()})- it('should not render refresh action when readonly is true', () => {+ it('should keep refresh action available when readonly app still has test/run permission', () => {renderDebug({contextValue: {readonly: true,+ canTestAndRun: true,+ },+ })++ fireEvent.click(screen.getAllByTestId('action-button')[0]!)+ expect(mockState.mockHandleRestart).toHaveBeenCalledTimes(1)+ })++ it('should not render refresh action when test/run permission is missing', () => {+ renderDebug({+ contextValue: {+ readonly: false,+ canTestAndRun: false,},})@@ -907,6 +921,26 @@ describe('Debug', () => {expect(screen.getByRole('button', { name: 'common.modelProvider.addModel(4/4)' }))!.toBeDisabled()})+ it('should disable add-model button when test/run permission is missing', () => {+ const onMultipleModelConfigsChange = vi.fn()++ renderDebug({+ contextValue: {+ canTestAndRun: false,+ },+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: 'model-1', model: 'vision-model', provider: 'openai', parameters: {} }],+ onMultipleModelConfigsChange,+ },+ })++ const addModelButton = screen.getByRole('button', { name: 'common.modelProvider.addModel(1/4)' })+ expect(addModelButton).toBeDisabled()+ fireEvent.click(addModelButton)+ expect(onMultipleModelConfigsChange).not.toHaveBeenCalled()+ })+it('should emit completion event in multiple-model completion mode', () => {renderDebug({contextValue: {diff --git a/web/app/components/app/configuration/debug/chat-user-input.tsx b/web/app/components/app/configuration/debug/chat-user-input.tsxindex 65322cae1b1..251cf819e5d 100644--- a/web/app/components/app/configuration/debug/chat-user-input.tsx+++ b/web/app/components/app/configuration/debug/chat-user-input.tsx@@ -18,7 +18,8 @@ const ChatUserInput = ({inputs,}: Props) => {const { t } = useTranslation()- const { modelConfig, setInputs, readonly } = useContext(ConfigContext)+ const { modelConfig, setInputs, canTestAndRun = false } = useContext(ConfigContext)+ const debugInputReadonly = !canTestAndRunconst promptVariables = modelConfig.configs.prompt_variables.filter(({ key, name }) => {return key && key?.trim() && name && name?.trim()@@ -51,6 +52,8 @@ const ChatUserInput = ({}, [promptVariables, inputs, setInputs])const handleInputValueChange = (key: string, value: string | boolean) => {+ if (debugInputReadonly)+ returnif (!(key in promptVariableObj))return@@ -88,7 +91,7 @@ const ChatUserInput = ({placeholder={name}autoFocus={index === 0}maxLength={max_length}- readOnly={readonly}+ readOnly={debugInputReadonly}/>)}{type === 'paragraph' && (@@ -98,13 +101,13 @@ const ChatUserInput = ({placeholder={name}value={inputs[key] ? `${inputs[key]}` : ''}onValueChange={(value) => { handleInputValueChange(key, value) }}- readOnly={readonly}+ readOnly={debugInputReadonly}/>)}{type === 'select' && (<Selectvalue={inputs[key] ? String(inputs[key]) : null}- disabled={readonly}+ disabled={debugInputReadonly}onValueChange={(nextValue) => {if (!nextValue)return@@ -132,7 +135,7 @@ const ChatUserInput = ({placeholder={name}autoFocus={index === 0}maxLength={max_length}- readOnly={readonly}+ readOnly={debugInputReadonly}/>)}{type === 'checkbox' && (@@ -141,7 +144,7 @@ const ChatUserInput = ({value={!!inputs[key]}required={required}onChange={(value) => { handleInputValueChange(key, value) }}- readonly={readonly}+ readonly={debugInputReadonly}/>)}</div>diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsxindex 719479498a7..5117aced684 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx@@ -115,6 +115,7 @@ const createDefaultMocks = () => {appId: 'app-123',inputs: { key: 'value' },collectionList: [],+ canTestAndRun: true,})mockUseProviderContext.mockReturnValue({@@ -287,6 +288,7 @@ describe('ChatItem', () => {appId: 'app-123',inputs: {},collectionList: [],+ canTestAndRun: true,})renderComponent()@@ -522,6 +524,7 @@ describe('ChatItem', () => {{ id: 'collection1', icon: 'icon1' },{ id: 'collection2', icon: 'icon2' },],+ canTestAndRun: true,})renderComponent()@@ -545,6 +548,7 @@ describe('ChatItem', () => {appId: 'app-123',inputs: {},collectionList: [],+ canTestAndRun: true,})renderComponent()@@ -563,6 +567,7 @@ describe('ChatItem', () => {appId: 'app-123',inputs: {},collectionList: [],+ canTestAndRun: true,})renderComponent()@@ -631,6 +636,7 @@ describe('ChatItem', () => {appId: 'app-123',inputs: {},collectionList: [],+ canTestAndRun: true,})// This may throw since the code does agentConfig.tools?.forEachdiff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsxindex bd12ff2c142..6d678eebf13 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx@@ -29,10 +29,13 @@ let modelIdCounter = 0let featureState: FeatureStoreStatetype MockChatInputAreaProps = {+ readonly?: booleanonSend?: (message: string, files?: FileEntity[]) => voidonFeatureBarClick?: (state: boolean) => voidshowFeatureBar?: booleanshowFileUpload?: boolean+ featureBarReadonly?: boolean+ disabled?: booleaninputs?: Record<string, any>inputsForm?: InputForm[]speechToTextConfig?: unknown@@ -90,8 +93,8 @@ vi.mock('@/app/components/base/chat/chat/chat-input-area', () => ({capturedChatInputProps = propsreturn (<div data-testid="chat-input-area">- <button type="button" onClick={() => props.onSend?.('test message', mockFiles)}>send</button>- <button type="button" onClick={() => props.onFeatureBarClick?.(true)}>feature</button>+ <button type="button" disabled={props.disabled} onClick={() => props.onSend?.('test message', mockFiles)}>send</button>+ {props.showFeatureBar && <button type="button" disabled={props.featureBarReadonly} onClick={() => props.onFeatureBarClick?.(true)}>feature</button>}</div>)},@@ -150,12 +153,16 @@ type DebugConfiguration = {mode: AppModeEnuminputs: InputsmodelConfig: ModelConfig+ readonly: boolean+ canTestAndRun: boolean}const createDebugConfiguration = (overrides: Partial<DebugConfiguration> = {}): DebugConfiguration => ({mode: AppModeEnum.CHAT,inputs: {},modelConfig: createModelConfig(),+ readonly: false,+ canTestAndRun: true,...overrides,})@@ -438,6 +445,38 @@ describe('DebugWithMultipleModel', () => {expect(useAppStore.getState().showAppConfigureFeaturesModal).toBe(true)})+ it('should allow sending but disable feature configuration when configuration is readonly and test/run is allowed', () => {+ mockUseDebugConfigurationContext.mockReturnValue(createDebugConfiguration({+ readonly: true,+ canTestAndRun: true,+ }))++ renderComponent()+ fireEvent.click(screen.getByRole('button', { name: /send/i }))++ expect(capturedChatInputProps?.readonly).toBe(false)+ expect(capturedChatInputProps?.disabled).toBe(false)+ expect(capturedChatInputProps?.showFeatureBar).toBe(true)+ expect(capturedChatInputProps?.featureBarReadonly).toBe(true)+ expect(screen.getByRole('button', { name: /feature/i })).toBeDisabled()+ expect(mockEventEmitter.emit).toHaveBeenCalledWith(expect.objectContaining({+ type: APP_CHAT_WITH_MULTIPLE_MODEL,+ }))+ })++ it('should block sending when test/run permission is missing', () => {+ mockUseDebugConfigurationContext.mockReturnValue(createDebugConfiguration({+ canTestAndRun: false,+ }))++ renderComponent()+ fireEvent.click(screen.getByRole('button', { name: /send/i }))++ expect(capturedChatInputProps?.readonly).toBe(true)+ expect(capturedChatInputProps?.disabled).toBe(true)+ expect(mockEventEmitter.emit).not.toHaveBeenCalled()+ })+it('should render chat input in agent chat mode', () => {// ArrangemockUseDebugConfigurationContext.mockReturnValue(createDebugConfiguration({diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsxindex d5b353c899b..39f29972ea4 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx@@ -44,6 +44,7 @@ const ChatItem: FC<ChatItemProps> = ({appId,inputs,collectionList,+ canTestAndRun = false,} = useDebugConfigurationContext()const { textGenerationModelList } = useProviderContext()const features = useFeatures(s => s.features)@@ -84,6 +85,8 @@ const ChatItem: FC<ChatItemProps> = ({useFormattingChangedSubscription(chatList)const doSend: OnSend = useCallback((message, files) => {+ if (!canTestAndRun)+ returnconst currentProvider = textGenerationModelList.find(item => item.provider === modelAndParameter.provider)const currentModel = currentProvider?.models.find(model => model.model === modelAndParameter.model)const supportVision = currentModel?.features?.includes(ModelFeatureEnum.vision)@@ -116,7 +119,7 @@ const ChatItem: FC<ChatItemProps> = ({onGetSuggestedQuestions: (responseItemId, getAbortController) => fetchSuggestedQuestions(appId, responseItemId, getAbortController),},)- }, [appId, chatList, config, handleSend, inputs, modelAndParameter.model, modelAndParameter.parameters, modelAndParameter.provider, textGenerationModelList])+ }, [appId, canTestAndRun, chatList, config, handleSend, inputs, modelAndParameter.model, modelAndParameter.parameters, modelAndParameter.provider, textGenerationModelList])const { eventEmitter } = useEventEmitterContextContext()eventEmitter?.useSubscription((v: any) => {diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsxindex 11241fec67a..b219af3c6a3 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsx@@ -23,6 +23,8 @@ const DebugWithMultipleModel = () => {mode,inputs,modelConfig,+ readonly,+ canTestAndRun = false,} = useDebugConfigurationContext()const speech2text = useFeatures(s => s.features.speech2text)const file = useFeatures(s => s.features.file)@@ -35,6 +37,8 @@ const DebugWithMultipleModel = () => {const isChatMode = mode === AppModeEnum.CHAT || mode === AppModeEnum.AGENT_CHATconst handleSend = useCallback((message: string, files?: FileEntity[]) => {+ if (!canTestAndRun)+ returnif (checkCanSend && !checkCanSend())return@@ -45,7 +49,7 @@ const DebugWithMultipleModel = () => {files,},} as any)- }, [eventEmitter, checkCanSend])+ }, [canTestAndRun, eventEmitter, checkCanSend])const twoLine = multipleModelConfigs.length === 2const threeLine = multipleModelConfigs.length === 3@@ -141,7 +145,10 @@ const DebugWithMultipleModel = () => {<div className="shrink-0 px-6 pb-0"><ChatInputAreabotName="Bot"+ readonly={!canTestAndRun}+ disabled={!canTestAndRun}showFeatureBar+ featureBarReadonly={readonly}showFileUpload={false}onFeatureBarClick={setShowAppConfigureFeaturesModal}onSend={handleSend}diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsxindex 1cc359fe856..fc1df42ea4b 100644--- a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx@@ -164,6 +164,8 @@ vi.mock('@/next/navigation', () => ({// Mock complex context providersconst mockDebugConfigContext = {+ readonly: false,+ canTestAndRun: true,appId: 'test-app-id',isAPIKeySet: true,isTrailFinished: false,@@ -405,6 +407,7 @@ vi.mock('@/app/components/base/audio-btn/audio.player.manager', () => ({}))type MockChatProps = {+ readonly?: booleanchatList?: ChatItem[]isResponding?: booleanonSend?: (message: string, files?: FileEntity[]) => void@@ -418,6 +421,9 @@ type MockChatProps = {onAnnotationRemoved?: (index: number) => voidswitchSibling?: (siblingMessageId: string) => voidonFeatureBarClick?: (state: boolean) => void+ showFeatureBar?: boolean+ featureBarReadonly?: boolean+ inputDisabled?: boolean}const mockFile: FileEntity = {@@ -434,6 +440,7 @@ const mockFile: FileEntity = {// This is a pragmatic mock that tests the integration at DebugWithSingleModel levelvi.mock('@/app/components/base/chat/chat', () => ({default: function MockChat({+ readonly,chatList,isResponding,onSend,@@ -447,6 +454,9 @@ vi.mock('@/app/components/base/chat/chat', () => ({onAnnotationRemoved,switchSibling,onFeatureBarClick,+ showFeatureBar,+ featureBarReadonly,+ inputDisabled,}: MockChatProps) {const items = chatList || []const suggested = suggestedQuestions ?? []@@ -464,6 +474,8 @@ vi.mock('@/app/components/base/chat/chat', () => ({<textareadata-testid="chat-input"placeholder="Type a message"+ readOnly={readonly}+ disabled={inputDisabled}onChange={() => {// Simulate input change}}@@ -471,14 +483,14 @@ vi.mock('@/app/components/base/chat/chat', () => ({<buttondata-testid="send-button"onClick={() => onSend?.('test message', [])}- disabled={isResponding}+ disabled={isResponding || readonly || inputDisabled}>Send</button><buttondata-testid="send-with-files"onClick={() => onSend?.('test message', [mockFile])}- disabled={isResponding}+ disabled={isResponding || readonly || inputDisabled}>Send With Files</button>@@ -518,9 +530,10 @@ vi.mock('@/app/components/base/chat/chat', () => ({Switch</button>)}- {onFeatureBarClick && (+ {showFeatureBar && onFeatureBarClick && (<buttondata-testid="feature-bar-button"+ disabled={featureBarReadonly}onClick={() => onFeatureBarClick(true)}>Features@@ -649,6 +662,46 @@ describe('DebugWithSingleModel', () => {expect(useAppStore.getState().showAppConfigureFeaturesModal).toBe(true)})++ it('should allow sending but disable feature configuration when configuration is readonly and test/run is allowed', async () => {+ mockUseDebugConfigurationContext.mockReturnValue({+ ...mockDebugConfigContext,+ readonly: true,+ canTestAndRun: true,+ })++ render(<DebugWithSingleModel ref={ref as RefObject<DebugWithSingleModelRefType>} />)++ expect(screen.getByTestId('chat-input')).not.toHaveAttribute('readonly')+ expect(screen.getByTestId('feature-bar-button')).toBeDisabled()+ expect(screen.queryByTestId('add-annotation-button')).not.toBeInTheDocument()+ expect(screen.queryByTestId('edit-annotation-button')).not.toBeInTheDocument()+ expect(screen.queryByTestId('remove-annotation-button')).not.toBeInTheDocument()++ fireEvent.click(screen.getByTestId('send-button'))++ await waitFor(() => {+ expect(mockSsePost).toHaveBeenCalled()+ })+ })++ it('should block sending when test/run permission is missing', () => {+ mockUseDebugConfigurationContext.mockReturnValue({+ ...mockDebugConfigContext,+ readonly: false,+ canTestAndRun: false,+ })++ render(<DebugWithSingleModel ref={ref as RefObject<DebugWithSingleModelRefType>} />)++ expect(screen.getByTestId('chat-input')).toHaveAttribute('readonly')+ expect(screen.getByTestId('chat-input')).toBeDisabled()+ expect(screen.getByTestId('send-button')).toBeDisabled()+ expect(screen.getByTestId('feature-bar-button')).toBeInTheDocument()+ expect(screen.queryByTestId('add-annotation-button')).not.toBeInTheDocument()+ expect(screen.queryByTestId('edit-annotation-button')).not.toBeInTheDocument()+ expect(screen.queryByTestId('remove-annotation-button')).not.toBeInTheDocument()+ })})// Model Configuration Testsdiff --git a/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/index.tsxindex aef3d5ef9c4..0670a097366 100644--- a/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx+++ b/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx@@ -40,6 +40,7 @@ const DebugWithSingleModel = (const { userProfile } = useAppContext()const {readonly,+ canTestAndRun = false,modelConfig,appId,inputs,@@ -47,6 +48,8 @@ const DebugWithSingleModel = (completionParams,// isShowVisionConfig,} = useDebugConfigurationContext()+ const debugInputReadonly = !canTestAndRun+ const canManageAnnotation = !readonly && canTestAndRunconst { textGenerationModelList } = useProviderContext()const features = useFeatures(s => s.features)const configTemplate = useConfigFromDebugContext()@@ -91,6 +94,8 @@ const DebugWithSingleModel = (useFormattingChangedSubscription(chatList)const doSend: OnSend = useCallback((message, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {+ if (!canTestAndRun)+ returnif (checkCanSend && !checkCanSend())returnconst currentProvider = textGenerationModelList.find(item => item.provider === modelConfig.provider)@@ -125,7 +130,7 @@ const DebugWithSingleModel = (onGetSuggestedQuestions: (responseItemId, getAbortController) => fetchSuggestedQuestions(appId, responseItemId, getAbortController),},)- }, [appId, chatList, checkCanSend, completionParams, config, handleSend, inputs, modelConfig.mode, modelConfig.model_id, modelConfig.provider, textGenerationModelList])+ }, [appId, canTestAndRun, chatList, checkCanSend, completionParams, config, handleSend, inputs, modelConfig.mode, modelConfig.model_id, modelConfig.provider, textGenerationModelList])const doRegenerate = useCallback((chatItem: ChatItem, editedQuestion?: { message: string, files?: FileEntity[] }) => {const question = editedQuestion ? chatItem : chatList.find(item => item.id === chatItem.parentMessageId)!@@ -151,15 +156,17 @@ const DebugWithSingleModel = (return (<Chat- readonly={readonly}+ readonly={debugInputReadonly}config={config}chatList={chatList}isResponding={isResponding}chatContainerClassName="px-3 pt-6"chatFooterClassName="px-3 pt-10 pb-0"showFeatureBar+ featureBarReadonly={readonly}showFileUpload={false}onFeatureBarClick={setShowAppConfigureFeaturesModal}+ inputDisabled={!canTestAndRun}suggestedQuestions={suggestedQuestions}onSend={doSend}inputs={inputs}@@ -170,9 +177,9 @@ const DebugWithSingleModel = (showPromptLogquestionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xl" />}allToolIcons={allToolIcons}- onAnnotationEdited={handleAnnotationEdited}- onAnnotationAdded={handleAnnotationAdded}- onAnnotationRemoved={handleAnnotationRemoved}+ onAnnotationEdited={canManageAnnotation ? handleAnnotationEdited : undefined}+ onAnnotationAdded={canManageAnnotation ? handleAnnotationAdded : undefined}+ onAnnotationRemoved={canManageAnnotation ? handleAnnotationRemoved : undefined}noSpacing/>)diff --git a/web/app/components/app/configuration/debug/index.tsx b/web/app/components/app/configuration/debug/index.tsxindex 8ce019e004a..e3e840f7571 100644--- a/web/app/components/app/configuration/debug/index.tsx+++ b/web/app/components/app/configuration/debug/index.tsx@@ -77,7 +77,7 @@ const Debug: FC<IDebug> = ({}) => {const { t } = useTranslation()const {- readonly,+ canTestAndRun = false,appId,mode,modelModeType,@@ -303,6 +303,9 @@ const Debug: FC<IDebug> = ({}const handleSendTextCompletion = () => {+ if (!canTestAndRun)+ return+if (debugWithMultipleModel) {eventEmitter?.emit({type: APP_CHAT_WITH_MULTIPLE_MODEL,@@ -404,7 +407,7 @@ const Debug: FC<IDebug> = ({<Buttonvariant="ghost-accent"onClick={() => onMultipleModelConfigsChange(true, [...multipleModelConfigs, { id: `${Date.now()}`, model: '', provider: '', parameters: {} }])}- disabled={multipleModelConfigs.length >= 4}+ disabled={multipleModelConfigs.length >= 4 || !canTestAndRun}><RiAddLine className="mr-1 size-3.5" />{t('modelProvider.addModel', { ns: 'common' })}@@ -420,7 +423,7 @@ const Debug: FC<IDebug> = ({{mode !== AppModeEnum.COMPLETION && (<>{- !readonly && (+ canTestAndRun && (<Tooltip><TooltipTrigger render={<ActionButton onClick={clearConversation}><RefreshCcw01 className="size-4" /></ActionButton>} /><TooltipContent>@@ -434,7 +437,7 @@ const Debug: FC<IDebug> = ({varList.length > 0 && (<div className="relative mr-2 ml-1"><Tooltip>- <TooltipTrigger render={<ActionButton state={expanded ? ActionButtonState.Active : undefined} onClick={() => !readonly && setExpanded(!expanded)}><RiEqualizer2Line className="size-4" /></ActionButton>} />+ <TooltipTrigger render={<ActionButton state={expanded ? ActionButtonState.Active : undefined} disabled={!canTestAndRun} onClick={() => setExpanded(!expanded)}><RiEqualizer2Line className="size-4" /></ActionButton>} /><TooltipContent>{t('panel.userInputField', { ns: 'workflow' })}</TooltipContent>diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsxindex 1ebe300325f..bf1ea95cc36 100644--- a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx@@ -2,6 +2,7 @@import { act, renderHook, waitFor } from '@testing-library/react'import { updateAppModelConfig } from '@/service/apps'import { AppModeEnum, ModelModeType } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import { useConfiguration } from '../use-configuration'const mockSetShowAccountSettingModal = vi.fn()@@ -27,6 +28,7 @@ let latestAdvancedPromptConfigOptions: AdvancedPromptConfigOptions | undefinedlet mockTempStopState: string[] = []let mockCurrentModelFeatures = ['vision']let mockCurrentModelMode = ModelModeType.chat+let mockAppPermissionKeys: string[] = [AppACLPermission.Edit, AppACLPermission.ReleaseAndVersion]vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -53,6 +55,11 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({currentWorkspace: { id: 'workspace-1' },isLoadingCurrentWorkspace: false,+ workspacePermissionKeys: ['app.create_and_management'],+ }),+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: ['app.create_and_management'],}),}))@@ -76,6 +83,7 @@ vi.mock('@/app/components/app/store', () => ({updated_at: 1710000000,},mode: AppModeEnum.CHAT,+ permission_keys: mockAppPermissionKeys,},setAppSidebarExpand: mockSetAppSidebarExpand,showAppConfigureFeaturesModal: false,@@ -176,6 +184,7 @@ describe('useConfiguration', () => {mockTempStopState = []mockCurrentModelFeatures = ['vision']mockCurrentModelMode = ModelModeType.chat+ mockAppPermissionKeys = [AppACLPermission.Edit, AppACLPermission.ReleaseAndVersion]mockFetchCollectionList.mockResolvedValue([])mockFetchDatasets.mockResolvedValue({ data: [] })mockFetchAndMergeValidCompletionParams.mockResolvedValue({@@ -278,6 +287,92 @@ describe('useConfiguration', () => {}))})+ it('should block publishing when app release permission is missing', async () => {+ mockAppPermissionKeys = [AppACLPermission.ViewLayout]++ const { result } = renderHook(() => useConfiguration())++ await waitFor(() => {+ expect(result.current.showLoading).toBe(false)+ })++ expect(result.current.contextValue.readonly).toBe(true)+ expect(result.current.contextValue.canTestAndRun).toBe(false)+ expect(result.current.appPublisherProps.disabled).toBe(true)+ expect(result.current.appPublisherProps.publishDisabled).toBe(true)++ await act(async () => {+ await result.current.appPublisherProps.onPublish!(undefined, result.current.featuresData)+ })++ expect(updateAppModelConfig).not.toHaveBeenCalled()+ })++ it('should allow test and run while keeping configuration readonly when only app test/run permission exists', async () => {+ mockAppPermissionKeys = [AppACLPermission.TestAndRun]++ const { result } = renderHook(() => useConfiguration())++ await waitFor(() => {+ expect(result.current.showLoading).toBe(false)+ })++ expect(result.current.contextValue.readonly).toBe(true)+ expect(result.current.contextValue.canTestAndRun).toBe(true)+ expect(result.current.appPublisherProps.disabled).toBe(true)+ expect(result.current.appPublisherProps.publishDisabled).toBe(true)++ await act(async () => {+ await result.current.appPublisherProps.onPublish!(undefined, result.current.featuresData)+ })++ expect(updateAppModelConfig).not.toHaveBeenCalled()+ })++ it('should keep configuration editable but block publishing when only app edit permission exists', async () => {+ mockAppPermissionKeys = [AppACLPermission.Edit]++ const { result } = renderHook(() => useConfiguration())++ await waitFor(() => {+ expect(result.current.showLoading).toBe(false)+ })++ expect(result.current.contextValue.readonly).toBe(false)+ expect(result.current.contextValue.canTestAndRun).toBe(false)+ expect(result.current.appPublisherProps.disabled).toBe(true)+ expect(result.current.appPublisherProps.publishDisabled).toBe(true)++ await act(async () => {+ await result.current.appPublisherProps.onPublish!(undefined, result.current.featuresData)+ })++ expect(updateAppModelConfig).not.toHaveBeenCalled()+ })++ it('should allow publishing with app release permission even when configuration is readonly', async () => {+ mockAppPermissionKeys = [AppACLPermission.ReleaseAndVersion]++ const { result } = renderHook(() => useConfiguration())++ await waitFor(() => {+ expect(result.current.showLoading).toBe(false)+ })++ expect(result.current.contextValue.readonly).toBe(true)+ expect(result.current.contextValue.canTestAndRun).toBe(false)+ expect(result.current.appPublisherProps.disabled).toBe(false)+ expect(result.current.appPublisherProps.publishDisabled).toBe(false)++ await act(async () => {+ await result.current.appPublisherProps.onPublish!(undefined, result.current.featuresData)+ })++ expect(updateAppModelConfig).toHaveBeenCalledWith(expect.objectContaining({+ url: '/apps/app-1/model-config',+ }))+ })+it('should expose derived feature flags and imperative callbacks', async () => {mockCurrentModelFeatures = ['vision', 'document', 'audio', 'video']mockFetchAppDetailDirect.mockResolvedValueOnce({diff --git a/web/app/components/app/configuration/hooks/use-configuration.ts b/web/app/components/app/configuration/hooks/use-configuration.tsindex 8b29f4db887..17853d8c6af 100644--- a/web/app/components/app/configuration/hooks/use-configuration.ts+++ b/web/app/components/app/configuration/hooks/use-configuration.ts@@ -50,6 +50,7 @@ import { usePathname } from '@/next/navigation'import { updateAppModelConfig } from '@/service/apps'import { useFileUploadConfig } from '@/service/use-common'import { AppModeEnum, ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod } from '@/types/app'+import { getAppACLCapabilities } from '@/utils/permission'import { supportFunctionCall } from '@/utils/tool-call'import { basePath } from '@/utils/var'import {@@ -108,7 +109,7 @@ export type ConfigurationViewModel = {export const useConfiguration = (): ConfigurationViewModel => {const { t } = useTranslation()- const { isLoadingCurrentWorkspace, currentWorkspace } = useAppContext()+ const { isLoadingCurrentWorkspace, currentWorkspace, userProfile, workspacePermissionKeys } = useAppContext()const openIntegrationsSetting = useIntegrationsSetting()const { appDetail, showAppConfigureFeaturesModal, setAppSidebarExpand, setShowAppConfigureFeaturesModal } = useAppStore(useShallow(state => ({@@ -120,6 +121,12 @@ export const useConfiguration = (): ConfigurationViewModel => {const { data: fileUploadConfigResponse } = useFileUploadConfig()const latestPublishedAt = useMemo(() => appDetail?.model_config?.updated_at, [appDetail])+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId: userProfile?.id,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }), [appDetail?.maintainer, appDetail?.permission_keys, userProfile?.id, workspacePermissionKeys])+ const configurationReadonly = !appACLCapabilities.canEditconst [formattingChanged, setFormattingChanged] = useState(false)const [hasFetchedDetail, setHasFetchedDetail] = useState(false)const pathname = usePathname()@@ -482,6 +489,9 @@ export const useConfiguration = (): ConfigurationViewModel => {])const onPublish = useCallback(async (params?: AppPublisherPublishParams, features?: FeaturesData) => {+ if (!appACLCapabilities.canReleaseAndVersion)+ return+const modelAndParameter = params && 'model' in params && 'provider' in params && 'parameters' in params? params: undefined@@ -515,6 +525,7 @@ export const useConfiguration = (): ConfigurationViewModel => {textToSpeechConfig,})(updateAppModelConfig, modelAndParameter, features)}, [+ appACLCapabilities.canReleaseAndVersion,appId,chatPromptConfig,citationConfig,@@ -567,6 +578,8 @@ export const useConfiguration = (): ConfigurationViewModel => {}, [modelConfig, setModelConfig])const contextValue: DebugConfigurationValue = {+ readonly: configurationReadonly,+ canTestAndRun: appACLCapabilities.canTestAndRun,appId,isAPIKeySet,isTrailFinished: false,@@ -644,7 +657,8 @@ export const useConfiguration = (): ConfigurationViewModel => {return {appPublisherProps: {- publishDisabled: cannotPublish,+ disabled: !appACLCapabilities.canReleaseAndVersion,+ publishDisabled: cannotPublish || !appACLCapabilities.canReleaseAndVersion,publishedAt: (latestPublishedAt || 0) * 1000,debugWithMultipleModel,multipleModelConfigs,diff --git a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsxindex f935abcee6e..de12a55069c 100644--- a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx@@ -40,8 +40,13 @@ vi.mock('@/app/components/app/store', () => ({// Use real store - global zustand mock will auto-reset between testsvi.mock('@/app/components/base/features/new-feature-panel/feature-bar', () => ({- default: ({ onFeatureBarClick }: { onFeatureBarClick: () => void }) => (- <button type="button" onClick={onFeatureBarClick}>+ default: ({ onFeatureBarClick, disabled, hideEditEntrance }: { onFeatureBarClick: () => void, disabled?: boolean, hideEditEntrance?: boolean }) => (+ <button+ type="button"+ disabled={disabled}+ data-hide-edit-entrance={hideEditEntrance ? 'true' : 'false'}+ onClick={onFeatureBarClick}+ >feature bar</button>),@@ -126,6 +131,7 @@ const baseContextValue: any = {},},setInputs: mockSetInputs,+ canTestAndRun: true,mode: AppModeEnum.COMPLETION,isAdvancedMode: false,completionPromptConfig: {@@ -425,13 +431,42 @@ describe('PromptValuePanel', () => {expect(screen.getByTestId('bool-input-boolVar')).toBeInTheDocument()})- it('marks actions as disabled when readonly even if the prompt is runnable', () => {+ it('keeps debug actions enabled when readonly configuration still has test/run permission', () => {+ renderPanel({+ context: {+ readonly: true,+ canTestAndRun: true,+ },+ })++ expect(screen.getByRole('button', { name: 'common.operation.clear' })).toHaveAttribute('data-disabled', 'false')+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute('data-disabled', 'false')+ expect(screen.getByRole('button', { name: 'feature bar' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'feature bar' })).toHaveAttribute('data-hide-edit-entrance', 'true')+ })++ it('marks debug inputs and actions as disabled when test/run permission is missing even if configuration is editable', () => {+ renderPanel({+ context: {+ readonly: false,+ canTestAndRun: false,+ },+ })++ expect(screen.getByPlaceholderText('Text Var')).toHaveAttribute('readonly')+ expect(screen.getByRole('button', { name: 'common.operation.clear' })).toHaveAttribute('data-disabled', 'true')+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute('data-disabled', 'true')+ })++ it('marks debug inputs and actions as disabled when configuration is readonly and test/run permission is missing', () => {renderPanel({context: {readonly: true,+ canTestAndRun: false,},})+ expect(screen.getByPlaceholderText('Text Var')).toHaveAttribute('readonly')expect(screen.getByRole('button', { name: 'common.operation.clear' })).toHaveAttribute('data-disabled', 'true')expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute('data-disabled', 'true')})diff --git a/web/app/components/app/configuration/prompt-value-panel/index.tsx b/web/app/components/app/configuration/prompt-value-panel/index.tsxindex f86f3828c3e..8c8a97c3f5a 100644--- a/web/app/components/app/configuration/prompt-value-panel/index.tsx+++ b/web/app/components/app/configuration/prompt-value-panel/index.tsx@@ -40,7 +40,8 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({onVisionFilesChange,}) => {const { t } = useTranslation()- const { readonly, modelModeType, modelConfig, setInputs, mode, isAdvancedMode, completionPromptConfig, chatPromptConfig } = useContext(ConfigContext)+ const { readonly, canTestAndRun = false, modelModeType, modelConfig, setInputs, mode, isAdvancedMode, completionPromptConfig, chatPromptConfig } = useContext(ConfigContext)+ const debugInputReadonly = !canTestAndRunconst [userInputFieldCollapse, setUserInputFieldCollapse] = useState(false)const promptVariables = modelConfig.configs.prompt_variables.filter(({ key, name }) => {return key && key?.trim() && name && name?.trim()@@ -86,6 +87,8 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({}, [chatPromptConfig?.prompt, completionPromptConfig.prompt?.text, isAdvancedMode, mode, modelConfig.configs.prompt_template, modelModeType])const handleInputValueChange = (key: string, value: string | boolean) => {+ if (debugInputReadonly)+ returnif (!(key in promptVariableObj))return@@ -98,6 +101,8 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({}const onClear = () => {+ if (debugInputReadonly)+ returnconst newInputs: Inputs = {}promptVariables.forEach((item) => {newInputs[item.key] = ''@@ -146,7 +151,7 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({placeholder={name}autoFocus={index === 0}maxLength={max_length}- readOnly={readonly}+ readOnly={debugInputReadonly}/>)}{type === 'paragraph' && (@@ -156,13 +161,13 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({placeholder={name}value={inputs[key] ? `${inputs[key]}` : ''}onValueChange={(value) => { handleInputValueChange(key, value) }}- readOnly={readonly}+ readOnly={debugInputReadonly}/>)}{type === 'select' && (<Selectvalue={inputs[key] ? String(inputs[key]) : null}- disabled={readonly}+ disabled={debugInputReadonly}onValueChange={(nextValue) => {if (!nextValue)return@@ -190,7 +195,7 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({placeholder={name}autoFocus={index === 0}maxLength={max_length}- readOnly={readonly}+ readOnly={debugInputReadonly}/>)}{type === 'checkbox' && (@@ -199,7 +204,7 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({value={!!inputs[key]}required={required}onChange={(value) => { handleInputValueChange(key, value) }}- readonly={readonly}+ readonly={debugInputReadonly}/>)}</div>@@ -218,7 +223,7 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({url: fileItem.url,upload_file_id: fileItem.fileId,})))}- disabled={readonly}+ disabled={debugInputReadonly}/></div></div>@@ -227,14 +232,14 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({)}{!userInputFieldCollapse && (<div className="flex justify-between border-t border-divider-subtle p-4 pt-3">- <Button className="w-[72px]" disabled={readonly} onClick={onClear}>{t('operation.clear', { ns: 'common' })}</Button>+ <Button className="w-[72px]" disabled={debugInputReadonly} onClick={onClear}>{t('operation.clear', { ns: 'common' })}</Button>{canNotRun && (<Tooltip><TooltipTriggerrender={(<Buttonvariant="primary"- disabled={canNotRun || readonly}+ disabled={canNotRun || !canTestAndRun}onClick={() => onSend?.()}className="w-[96px]">@@ -251,7 +256,7 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({{!canNotRun && (<Buttonvariant="primary"- disabled={canNotRun || readonly}+ disabled={canNotRun || !canTestAndRun}onClick={() => onSend?.()}className="w-[96px]">diff --git a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsxindex 93d9699088b..bfcab9d4184 100644--- a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx+++ b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx@@ -14,6 +14,8 @@ const mockToastError = vi.fn()const mockTrackCreateApp = vi.fn()const mockInvalidateAppList = vi.hoisted(() => vi.fn())let latestDebounceFn = () => {}+let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']+let mockIsCurrentWorkspaceEditor = truevi.mock('ahooks', () => ({useDebounceFn: (fn: () => void) => {@@ -26,7 +28,10 @@ vi.mock('ahooks', () => ({},}))vi.mock('@/context/app-context', () => ({- useAppContext: () => ({ isCurrentWorkspaceEditor: true }),+ useAppContext: () => ({+ isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor,+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),}))vi.mock('nuqs', () => ({useQueryState: () => ['Recommended', vi.fn()],@@ -46,10 +51,11 @@ vi.mock('@/app/components/app/type-selector', () => ({),}))vi.mock('../../app-card', () => ({- default: ({ app, onCreate }: { app: { app: { name: string } }, onCreate: () => void }) => (+ default: ({ app, canCreate, onCreate }: { app: { app: { name: string } }, canCreate: boolean, onCreate: () => void }) => (<divdata-testid="app-card"data-name={app.app.name}+ data-can-create={canCreate ? 'true' : 'false'}onClick={onCreate}>{app.app.name}@@ -172,6 +178,8 @@ describe('Apps', () => {beforeEach(() => {vi.clearAllMocks()localStorage.clear()+ mockWorkspacePermissionKeys = ['app.create_and_management']+ mockIsCurrentWorkspaceEditor = truemockUseExploreAppList.mockReturnValue({data: defaultData,isLoading: false,@@ -180,7 +188,11 @@ describe('Apps', () => {export_data: 'dsl',mode: AppModeEnum.CHAT,})- mockImportDSL.mockResolvedValue({ app_id: 'created-app-id' })+ mockImportDSL.mockResolvedValue({+ app_id: 'created-app-id',+ app_mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.view_layout'],+ })})it('renders template cards when data is available', () => {@@ -198,6 +210,24 @@ describe('Apps', () => {expect(screen.getByTestId('create-from-template-modal'))!.toBeInTheDocument()})+ it('passes app.create_and_management permission to template cards even when user is not a workspace editor', () => {+ mockIsCurrentWorkspaceEditor = false+ mockWorkspacePermissionKeys = ['app.create_and_management']++ render(<Apps />)++ expect(screen.getAllByTestId('app-card')[0]).toHaveAttribute('data-can-create', 'true')+ })++ it('does not allow template creation when app.create_and_management permission is missing', () => {+ mockIsCurrentWorkspaceEditor = true+ mockWorkspacePermissionKeys = []++ render(<Apps />)++ expect(screen.getAllByTestId('app-card')[0]).toHaveAttribute('data-can-create', 'false')+ })+it('shows no template message when list is empty', () => {mockUseExploreAppList.mockReturnValueOnce({data: { allList: [], categories: [] },@@ -260,9 +290,10 @@ describe('Apps', () => {expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('created-app-id')expect(localStorage.getItem(NEED_REFRESH_APP_LIST_KEY)).toBe('1')expect(mockInvalidateAppList).toHaveBeenCalledTimes(1)- expect(mockGetRedirection).toHaveBeenCalledWith(true, {+ expect(mockGetRedirection).toHaveBeenCalledWith({id: 'created-app-id',mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.view_layout'],}, mockPush)})diff --git a/web/app/components/app/create-app-dialog/app-list/index.tsx b/web/app/components/app/create-app-dialog/app-list/index.tsxindex d6bb85bbe69..470de67aa29 100644--- a/web/app/components/app/create-app-dialog/app-list/index.tsx+++ b/web/app/components/app/create-app-dialog/app-list/index.tsx@@ -27,6 +27,7 @@ import { useExploreAppList } from '@/service/use-explore'import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { trackCreateApp } from '@/utils/create-app-tracking'+import { hasPermission } from '@/utils/permission'import AppCard from '../app-card'import Sidebar, { AppCategories, AppCategoryLabel } from './sidebar'@@ -45,7 +46,8 @@ const Apps = ({onCreateFromBlank,}: AppsProps) => {const { t } = useTranslation()- const { isCurrentWorkspaceEditor } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()+ const canCreateAppFromTemplate = hasPermission(workspacePermissionKeys, 'app.create_and_management')const { push } = useRouter()const invalidateAppList = useInvalidateAppList()const allCategoriesEn = AppCategories.RECOMMENDED@@ -142,7 +144,8 @@ const Apps = ({await handleCheckPluginDependencies(app.app_id)setNeedRefresh('1')invalidateAppList()- getRedirection(isCurrentWorkspaceEditor, { id: app.app_id!, mode }, push)+ if (app.app_id)+ getRedirection({ id: app.app_id, mode: app.app_mode, permission_keys: app.permission_keys }, push)}catch {toast.error(t('newApp.appCreateFailed', { ns: 'app' }))@@ -207,7 +210,7 @@ const Apps = ({<AppCardkey={app.app_id}app={app}- canCreate={isCurrentWorkspaceEditor}+ canCreate={canCreateAppFromTemplate}onCreate={() => {setCurrApp(app)setIsShowCreateModal(true)diff --git a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx b/web/app/components/app/create-app-modal/__tests__/index.spec.tsxindex eb3a2d15c15..df3b74255d5 100644--- a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx@@ -1,6 +1,5 @@import type { App } from '@/types/app'import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'@@ -13,8 +12,8 @@ import { getRedirection } from '@/utils/app-redirection'import { trackCreateApp } from '@/utils/create-app-tracking'import CreateAppModal from '../index'-const hotkeyMocks = vi.hoisted(() => ({- handlers: new Map<string, () => void>(),+const ahooksMocks = vi.hoisted(() => ({+ keyPressHandlers: [] as Array<() => void>,}))const mockInvalidateAppList = vi.hoisted(() => vi.fn())@@ -27,16 +26,12 @@ vi.mock('ahooks', () => ({},useHover: () => false,}))--vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()- return {- ...actual,- useHotkey: (hotkey: string, handler: () => void) => {- hotkeyMocks.handlers.set(hotkey, handler)- },- }-})+vi.mock('@tanstack/react-hotkeys', () => ({+ formatForDisplay: (key: string) => key,+ useHotkey: (_hotkey: string, handler: () => void) => {+ ahooksMocks.keyPressHandlers.push(handler)+ },+}))vi.mock('@/next/navigation', () => ({useRouter: vi.fn(),useParams: () => ({}),@@ -124,7 +119,7 @@ describe('CreateAppModal', () => {beforeEach(() => {vi.clearAllMocks()- hotkeyMocks.handlers.clear()+ ahooksMocks.keyPressHandlers.length = 0mockUseRouter.mockReturnValue({ push: mockPush } as unknown as ReturnType<typeof useRouter>)mockUseProviderContext.mockReturnValue({plan: {@@ -136,7 +131,8 @@ describe('CreateAppModal', () => {enableBilling: true,} as unknown as ReturnType<typeof useProviderContext>)mockUseAppContext.mockReturnValue({- isCurrentWorkspaceEditor: true,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: ['app.create_and_management'],} as unknown as ReturnType<typeof useAppContext>)mockSetItem.mockClear()Object.defineProperty(window, 'localStorage', {@@ -153,7 +149,7 @@ describe('CreateAppModal', () => {})it('creates an app, notifies success, and fires callbacks', async () => {- const mockApp: Partial<App> = { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT }+ const mockApp: Partial<App> = { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT, maintainer: 'user-1' }mockCreateApp.mockResolvedValue(mockApp as App)const { onClose, onSuccess } = renderModal()@@ -176,7 +172,13 @@ describe('CreateAppModal', () => {expect(onClose).toHaveBeenCalled()await waitFor(() => expect(mockSetItem).toHaveBeenCalledWith(NEED_REFRESH_APP_LIST_KEY, '1'))expect(mockInvalidateAppList).toHaveBeenCalledTimes(1)- await waitFor(() => expect(mockGetRedirection).toHaveBeenCalledWith(true, mockApp, mockPush))+ await waitFor(() =>+ expect(mockGetRedirection).toHaveBeenCalledWith(mockApp, mockPush, {+ currentUserId: 'user-1',+ resourceMaintainer: 'user-1',+ workspacePermissionKeys: ['app.create_and_management'],+ }),+ )})it('shows error toast when creation fails', async () => {@@ -217,26 +219,18 @@ describe('CreateAppModal', () => {expect(onCreateFromTemplate).toHaveBeenCalled()})- it('renders the create shortcut with kbd primitives', () => {- renderModal()-- const createButton = screen.getByRole('button', { name: /app\.newApp\.Create/ })- expect(createButton.querySelectorAll('kbd')).toHaveLength(2)- })-it('creates a beginner chat app with the keyboard shortcut and selected icon style', async () => {- const user = userEvent.setup()mockCreateApp.mockResolvedValue({ id: 'chat-app', mode: AppModeEnum.CHAT } as App)renderModal()fireEvent.click(screen.getByText('app.newApp.forBeginners'))fireEvent.click(screen.getByText('app.types.chatbot'))- await user.click(screen.getByText('open-icon-picker'))+ fireEvent.click(screen.getByText('open-icon-picker'))await waitFor(() => {expect(screen.getByPlaceholderText('Search emojis...')).toBeInTheDocument()})- await user.click(screen.getByRole('button', { name: '#E4FBCC' }))- await user.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))+ fireEvent.click(screen.getByRole('button', { name: '#E4FBCC' }))+ fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))await waitFor(() => {expect(screen.queryByPlaceholderText('Search emojis...')).not.toBeInTheDocument()})@@ -247,7 +241,7 @@ describe('CreateAppModal', () => {target: { value: 'Created from shortcut' },})- hotkeyMocks.handlers.get('Mod+Enter')?.()+ ahooksMocks.keyPressHandlers.at(-1)?.()await waitFor(() => {expect(mockCreateApp).toHaveBeenCalledWith({@@ -264,14 +258,13 @@ describe('CreateAppModal', () => {it('shows validation feedback when the keyboard shortcut runs without a name', () => {renderModal()- hotkeyMocks.handlers.get('Mod+Enter')?.()+ ahooksMocks.keyPressHandlers.at(-1)?.()expect(mockToastError).toHaveBeenCalledWith('app.newApp.nameNotEmpty')expect(mockCreateApp).not.toHaveBeenCalled()})it('ignores the keyboard shortcut when the app quota is exhausted and closes the icon picker', async () => {- const user = userEvent.setup()mockUseProviderContext.mockReturnValue({plan: {type: AppModeEnum.ADVANCED_CHAT,@@ -284,18 +277,18 @@ describe('CreateAppModal', () => {renderModal()- await user.click(screen.getByText('open-icon-picker'))+ fireEvent.click(screen.getByText('open-icon-picker'))await waitFor(() => {expect(screen.getByPlaceholderText('Search emojis...')).toBeInTheDocument()})- await user.click(screen.getByRole('button', { name: /iconPicker\.cancel/ }))+ fireEvent.click(screen.getByRole('button', { name: /iconPicker\.cancel/ }))await waitFor(() => {expect(screen.queryByPlaceholderText('Search emojis...')).not.toBeInTheDocument()})expect(screen.queryByPlaceholderText('Search emojis...')).not.toBeInTheDocument()- hotkeyMocks.handlers.get('Mod+Enter')?.()+ ahooksMocks.keyPressHandlers.at(-1)?.()expect(mockCreateApp).not.toHaveBeenCalled()})diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsxindex bd4f7ea40ec..359df8fa79b 100644--- a/web/app/components/app/create-app-modal/index.tsx+++ b/web/app/components/app/create-app-modal/index.tsx@@ -28,6 +28,7 @@ import { useInvalidateAppList } from '@/service/use-apps'import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { trackCreateApp } from '@/utils/create-app-tracking'+import { hasPermission } from '@/utils/permission'import { basePath } from '@/utils/var'import AppIconPicker from '../../base/app-icon-picker'import { CreateAppDialogShell } from '../create-app-dialog-shell'@@ -56,7 +57,8 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:const { plan, enableBilling } = useProviderContext()const isAppsFull = (enableBilling && plan.usage.buildApps >= plan.total.buildApps)- const { isCurrentWorkspaceEditor } = useAppContext()+ const { userProfile, workspacePermissionKeys } = useAppContext()+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const invalidateAppList = useInvalidateAppList()const isCreatingRef = useRef(false)@@ -64,6 +66,9 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:const setNeedRefresh = useSetLocalStorage<string>(NEED_REFRESH_APP_LIST_KEY, { raw: true })const onCreate = useCallback(async () => {+ if (!canCreateApp)+ return+if (!appMode) {toast.error(t('newApp.appTypeRequired', { ns: 'app' }))return@@ -92,17 +97,21 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:onClose()setNeedRefresh('1')invalidateAppList()- getRedirection(isCurrentWorkspaceEditor, app, push)+ getRedirection(app, push, {+ currentUserId: userProfile?.id,+ resourceMaintainer: app.maintainer,+ workspacePermissionKeys,+ })}catch (error) {toast.error(error instanceof Error ? error.message : t('newApp.appCreateFailed', { ns: 'app' }))}isCreatingRef.current = false- }, [name, t, appMode, appIcon, description, onSuccess, onClose, push, isCurrentWorkspaceEditor, setNeedRefresh, invalidateAppList])+ }, [canCreateApp, name, t, appMode, appIcon, description, onSuccess, onClose, push, userProfile?.id, workspacePermissionKeys, setNeedRefresh, invalidateAppList])const { run: handleCreateApp } = useDebounceFn(onCreate, { wait: 300 })useHotkey('Mod+Enter', () => {- if (isAppsFull)+ if (isAppsFull || !canCreateApp)returnhandleCreateApp()}, {@@ -272,7 +281,7 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:</button><div className="flex gap-2"><Button onClick={onClose}>{t('newApp.Cancel', { ns: 'app' })}</Button>- <Button disabled={isAppsFull || !name} className="gap-1" variant="primary" onClick={handleCreateApp}>+ <Button disabled={!canCreateApp || isAppsFull || !name} className="gap-1" variant="primary" onClick={handleCreateApp}><span>{t('newApp.Create', { ns: 'app' })}</span><KbdGroup>{['Mod', 'Enter'].map(key => (diff --git a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsxindex 55eeda20de0..f1b3468b098 100644--- a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx@@ -208,6 +208,7 @@ describe('CreateFromDSLModal', () => {status: DSLImportStatus.COMPLETED,app_id: 'app-1',app_mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.view_layout'],})render(@@ -244,8 +245,7 @@ describe('CreateFromDSLModal', () => {expect(mockInvalidateAppList).toHaveBeenCalledTimes(1)expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('app-1')expect(mockGetRedirection).toHaveBeenCalledWith(- true,- { id: 'app-1', mode: 'chat' },+ { id: 'app-1', mode: 'chat', permission_keys: ['app.acl.view_layout'] },mockPush,)})@@ -256,6 +256,7 @@ describe('CreateFromDSLModal', () => {status: DSLImportStatus.COMPLETED_WITH_WARNINGS,app_id: 'app-2',app_mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.view_layout'],})render(@@ -322,6 +323,7 @@ describe('CreateFromDSLModal', () => {status: DSLImportStatus.COMPLETED,app_id: 'app-3',app_mode: AppModeEnum.WORKFLOW,+ permission_keys: ['app.acl.view_layout'],})render(@@ -450,6 +452,7 @@ describe('CreateFromDSLModal', () => {status: DSLImportStatusapp_id: stringapp_mode: string+ permission_keys?: string[]}) => voidmockImportDSL.mockImplementationOnce(() =>@@ -478,6 +481,7 @@ describe('CreateFromDSLModal', () => {status: DSLImportStatus.COMPLETED,app_id: 'app-1',app_mode: AppModeEnum.CHAT,+ permission_keys: ['app.acl.view_layout'],})})@@ -498,6 +502,7 @@ describe('CreateFromDSLModal', () => {status: DSLImportStatus.COMPLETED,app_id: 'app-shortcut',app_mode: 'chat',+ permission_keys: ['app.acl.view_layout'],})render(diff --git a/web/app/components/app/create-from-dsl-modal/index.tsx b/web/app/components/app/create-from-dsl-modal/index.tsxindex 103d71840b3..87d4a21531d 100644--- a/web/app/components/app/create-from-dsl-modal/index.tsx+++ b/web/app/components/app/create-from-dsl-modal/index.tsx@@ -15,7 +15,6 @@ import Input from '@/app/components/base/input'import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'-import { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import {DSLImportMode,@@ -75,7 +74,6 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSsetFileContent('')}, [readFile])- const { isCurrentWorkspaceEditor } = useAppContext()const { plan, enableBilling } = useProviderContext()const isAppsFull = (enableBilling && plan.usage.buildApps >= plan.total.buildApps)const invalidateAppList = useInvalidateAppList()@@ -113,7 +111,7 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSif (!response)return- const { id, status, app_id, app_mode, imported_dsl_version, current_dsl_version } = response+ const { id, status, app_id, app_mode, imported_dsl_version, current_dsl_version, permission_keys } = responseif (status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS) {trackCreateApp({ source: 'studio_upload', appMode: app_mode })@@ -130,9 +128,10 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS})setNeedRefresh('1')invalidateAppList()- if (app_id)+ if (app_id) {await handleCheckPluginDependencies(app_id)- getRedirection(isCurrentWorkspaceEditor, { id: app_id!, mode: app_mode }, push)+ getRedirection({ id: app_id, mode: app_mode, permission_keys }, push)+ }}else if (status === DSLImportStatus.PENDING) {setVersions({@@ -171,7 +170,7 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSimport_id: importId,})- const { status, app_id, app_mode } = response+ const { status, app_id, app_mode, permission_keys } = responseif (status === DSLImportStatus.COMPLETED) {trackCreateApp({ source: 'studio_upload', appMode: app_mode })@@ -185,7 +184,8 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSawait handleCheckPluginDependencies(app_id)setNeedRefresh('1')invalidateAppList()- getRedirection(isCurrentWorkspaceEditor, { id: app_id!, mode: app_mode }, push)+ if (app_id)+ getRedirection({ id: app_id, mode: app_mode, permission_keys }, push)}else if (status === DSLImportStatus.FAILED) {toast.error(response.error || t('newApp.appCreateFailed', { ns: 'app' }))diff --git a/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsxindex 9d68c43d245..76b8274e16c 100644--- a/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx@@ -32,6 +32,37 @@ vi.mock('@/app/components/base/app-icon', () => ({),}))+vi.mock('@/app/components/base/app-icon-picker', () => ({+ default: ({+ onOpenChange,+ onSelect,+ }: {+ onOpenChange: (open: boolean) => void+ onSelect: (payload: { type: 'emoji', icon: string, background: string }) => void+ }) => {+ let selectedBackground = '#FFEAD5'+ return (+ <div>+ <input placeholder="Search emojis..." />+ <button type="button" onClick={() => {}}>+ <em-emoji />+ </button>+ <button type="button" aria-label="#E4FBCC" onClick={() => { selectedBackground = '#E4FBCC' }} />+ <button+ type="button"+ onClick={() => {+ onSelect({ type: 'emoji', icon: '🤖', background: selectedBackground })+ onOpenChange(false)+ }}+ >+ iconPicker.ok+ </button>+ <button type="button" onClick={() => onOpenChange(false)}>iconPicker.cancel</button>+ </div>+ )+ },+}))+describe('DuplicateAppModal', () => {beforeEach(() => {vi.clearAllMocks()@@ -88,8 +119,8 @@ describe('DuplicateAppModal', () => {await waitFor(() => {expect(screen.getByPlaceholderText('Search emojis...')).toBeInTheDocument()})- await user.click(screen.getByRole('button', { name: '#E4FBCC' }))- await user.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))+ await user.click(screen.getByRole('button', { name: '#E4FBCC', hidden: true }))+ await user.click(screen.getByRole('button', { name: /iconPicker\.ok/, hidden: true }))await waitFor(() => {expect(screen.queryByPlaceholderText('Search emojis...')).not.toBeInTheDocument()})@@ -145,7 +176,19 @@ describe('DuplicateAppModal', () => {await waitFor(() => {expect(screen.getByPlaceholderText('Search emojis...')).toBeInTheDocument()})- await user.click(screen.getByRole('button', { name: /iconPicker\.cancel/ }))+ const emojiButton = document.querySelector('em-emoji')?.closest('button')+ expect(emojiButton).toBeTruthy()+ await user.click(emojiButton!)+ await user.click(screen.getByRole('button', { name: '#E4FBCC', hidden: true }))+ await user.click(screen.getByRole('button', { name: /iconPicker\.ok/, hidden: true }))+ await waitFor(() => {+ expect(screen.queryByPlaceholderText('Search emojis...')).not.toBeInTheDocument()+ })+ await user.click(screen.getByText('open-icon-picker'))+ await waitFor(() => {+ expect(screen.getByPlaceholderText('Search emojis...')).toBeInTheDocument()+ })+ await user.click(screen.getByRole('button', { name: /iconPicker\.cancel/, hidden: true }))await waitFor(() => {expect(screen.queryByPlaceholderText('Search emojis...')).not.toBeInTheDocument()})@@ -153,9 +196,9 @@ describe('DuplicateAppModal', () => {expect(onConfirm).toHaveBeenCalledWith(expect.objectContaining({name: 'Image App',- icon_type: 'image',- icon: 'original-file',- icon_background: undefined,+ icon_type: 'emoji',+ icon: expect.any(String),+ icon_background: '#E4FBCC',}))})})diff --git a/web/app/components/app/log/empty-element.tsx b/web/app/components/app/log/empty-element.tsxindex 7b89ac40604..232e913b942 100644--- a/web/app/components/app/log/empty-element.tsx+++ b/web/app/components/app/log/empty-element.tsx@@ -3,6 +3,7 @@ import type { FC, SVGProps } from 'react'import type { App } from '@/types/app'import * as React from 'react'import { Trans, useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import Link from '@/next/link'import { AppModeEnum } from '@/types/app'import { getRedirectionPath } from '@/utils/app-redirection'@@ -18,6 +19,8 @@ const ThreeDotsIcon = ({ className }: SVGProps<SVGElement>) => {const EmptyElement: FC<{ appDetail: App }> = ({ appDetail }) => {const { t } = useTranslation()+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const getWebAppType = (appType: AppModeEnum) => {if (appType !== AppModeEnum.COMPLETION && appType !== AppModeEnum.WORKFLOW)@@ -37,8 +40,24 @@ const EmptyElement: FC<{ appDetail: App }> = ({ appDetail }) => {i18nKey="table.empty.element.content"ns="appLog"components={{- shareLink: <Link href={`${appDetail.site.app_base_url}${basePath}/${getWebAppType(appDetail.mode)}/${appDetail.site.access_token}`} className="text-util-colors-blue-blue-600" target="_blank" rel="noopener noreferrer" />,- testLink: <Link href={getRedirectionPath(true, appDetail)} className="text-util-colors-blue-blue-600" />,+ shareLink: (+ <Link+ href={`${appDetail.site.app_base_url}${basePath}/${getWebAppType(appDetail.mode)}/${appDetail.site.access_token}`}+ className="text-util-colors-blue-blue-600"+ target="_blank"+ rel="noopener noreferrer"+ />+ ),+ testLink: (+ <Link+ href={getRedirectionPath(appDetail, {+ currentUserId,+ resourceMaintainer: appDetail.maintainer,+ workspacePermissionKeys,+ })}+ className="text-util-colors-blue-blue-600"+ />+ ),}}/></div>diff --git a/web/app/components/app/overview/__tests__/app-card-sections.spec.tsx b/web/app/components/app/overview/__tests__/app-card-sections.spec.tsxindex 88d2bf6f91c..0e58a14781b 100644--- a/web/app/components/app/overview/__tests__/app-card-sections.spec.tsx+++ b/web/app/components/app/overview/__tests__/app-card-sections.spec.tsx@@ -149,7 +149,7 @@ describe('app-card-sections', () => {isAppaccessibleUrl="https://example.com/apps/demo"showConfirmDelete- isCurrentWorkspaceManager+ canRegenerateUrlgenLoading={false}onRegenerate={onRegenerate}onShowRegenerateConfirm={vi.fn()}diff --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 0a6d7f7dd75..11c2dd54bb1 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@@ -153,8 +153,8 @@ describe('app-card-utils', () => {appInfo: baseAppInfo,cardType: 'webapp',currentWorkflow: null,- isCurrentWorkspaceEditor: true,- isCurrentWorkspaceManager: true,+ canManageWebApp: true,+ canManageApi: true,})expect(state.isApp).toBe(true)@@ -168,8 +168,8 @@ describe('app-card-utils', () => {appInfo: { ...baseAppInfo, mode: AppModeEnum.WORKFLOW },cardType: 'webapp',currentWorkflow: null,- isCurrentWorkspaceEditor: true,- isCurrentWorkspaceManager: true,+ canManageWebApp: true,+ canManageApi: true,})expect(unpublishedState.appUnpublished).toBe(true)expect(unpublishedState.toggleDisabled).toBe(true)@@ -182,8 +182,8 @@ describe('app-card-utils', () => {nodes: [{ data: { type: BlockEnum.Answer } }],},},- isCurrentWorkspaceEditor: true,- isCurrentWorkspaceManager: true,+ canManageWebApp: true,+ canManageApi: true,})expect(missingStartState.missingStartNode).toBe(true)expect(missingStartState.runningStatus).toBe(false)@@ -210,13 +210,13 @@ describe('app-card-utils', () => {expect(getAppCardOperationKeys({cardType: 'api',appMode: AppModeEnum.COMPLETION,- isCurrentWorkspaceEditor: true,+ canManageSettings: true,})).toEqual(['develop'])expect(getAppCardOperationKeys({cardType: 'webapp',appMode: AppModeEnum.CHAT,- isCurrentWorkspaceEditor: false,+ canManageSettings: false,})).toEqual(['launch', 'embedded', 'customize'])})diff --git a/web/app/components/app/overview/__tests__/app-card.spec.tsx b/web/app/components/app/overview/__tests__/app-card.spec.tsxindex 77b6c51b297..bd801d71410 100644--- a/web/app/components/app/overview/__tests__/app-card.spec.tsx+++ b/web/app/components/app/overview/__tests__/app-card.spec.tsx@@ -5,6 +5,7 @@ import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-featuresimport { InputVarType } from '@/app/components/workflow/types'import { AccessMode } from '@/models/access-control'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import { basePath } from '@/utils/var'import AppCard from '../app-card'@@ -12,7 +13,6 @@ const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {systemFeatures: { webapp_auth: { enabled: true } },})-const mockFetchAppDetailDirect = vi.fn()const mockPush = vi.fn()const mockSetAppDetail = vi.fn()const mockOnChangeStatus = vi.fn()@@ -29,16 +29,6 @@ vi.mock('react-i18next', () => ({Trans: ({ i18nKey }: { i18nKey?: string }) => i18nKey ?? null,}))-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: true,- isCurrentWorkspaceEditor: true,- langGeniusVersionInfo: {- current_env: 'TESTING',- },- }),-}))-vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.example.com${path}`,}))@@ -63,16 +53,12 @@ vi.mock('@/service/use-workflow', () => ({}),}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useAppWhiteListSubjects: () => ({data: mockAccessSubjects,}),}))-vi.mock('@/service/apps', () => ({- fetchAppDetailDirect: (...args: unknown[]) => mockFetchAppDetailDirect(...args),-}))-vi.mock('@/app/components/develop/secret-key/secret-key-button', () => ({default: ({ appId }: { appId: string }) => <div data-testid="secret-key-button">{appId}</div>,}))@@ -113,6 +99,7 @@ describe('AppCard', () => {icon: 'app-icon',icon_background: '#fff',api_base_url: 'https://api.example.com',+ permission_keys: [AppACLPermission.Edit, AppACLPermission.ReleaseAndVersion],site: {app_base_url: 'https://example.com',access_token: 'access-token',@@ -138,10 +125,6 @@ describe('AppCard', () => {groups: [],members: [],}- mockFetchAppDetailDirect.mockResolvedValue({- id: 'app-1',- access_mode: AccessMode.PUBLIC,- })})it('should open the published webapp when launch is clicked', () => {@@ -344,6 +327,21 @@ describe('AppCard', () => {expect(screen.getByText('publishApp.notSet')).toBeInTheDocument()})+ it('should hide the access-control section when release permission is missing', () => {+ render(+ <AppCard+ appInfo={{+ ...appInfo,+ permission_keys: [AppACLPermission.Edit],+ }}+ onChangeStatus={mockOnChangeStatus}+ />,+ )++ expect(screen.queryByText('publishApp.title')).not.toBeInTheDocument()+ expect(screen.queryByText('publishApp.notSet')).not.toBeInTheDocument()+ })+it('should hide the address and operation sections for unpublished workflows', () => {mockWorkflow = null@@ -400,13 +398,14 @@ describe('AppCard', () => {})it('should refresh app detail after confirming access control changes', async () => {- render(+ const { queryClient } = render(<AppCardappInfo={appInfo}onChangeStatus={mockOnChangeStatus}onGenerateCode={mockOnGenerateCode}/>,)+ const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue()fireEvent.click(screen.getByText('publishApp.notSet'))expect(screen.getByTestId('access-control-modal')).toBeInTheDocument()@@ -414,11 +413,7 @@ describe('AppCard', () => {fireEvent.click(screen.getByText('confirm-access-control'))await waitFor(() => {- expect(mockFetchAppDetailDirect).toHaveBeenCalledWith({ url: '/apps', id: 'app-1' })- expect(mockSetAppDetail).toHaveBeenCalledWith({- id: 'app-1',- access_mode: AccessMode.PUBLIC,- })+ expect(invalidateQueriesSpy).toHaveBeenCalledWith({ queryKey: ['apps', 'detail', 'app-1'] })})})@@ -472,14 +467,14 @@ describe('AppCard', () => {it('should report refresh failures from access control updates', async () => {const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { })- mockFetchAppDetailDirect.mockRejectedValueOnce(new Error('refresh failed'))- render(+ const { queryClient } = render(<AppCardappInfo={appInfo}onChangeStatus={mockOnChangeStatus}/>,)+ vi.spyOn(queryClient, 'invalidateQueries').mockRejectedValueOnce(new Error('refresh failed'))fireEvent.click(screen.getByText('publishApp.notSet'))fireEvent.click(screen.getByText('confirm-access-control'))diff --git a/web/app/components/app/overview/__tests__/toggle-logic.test.ts b/web/app/components/app/overview/__tests__/toggle-logic.test.tsindex ee4c650d1f7..9127dca1040 100644--- a/web/app/components/app/overview/__tests__/toggle-logic.test.ts+++ b/web/app/components/app/overview/__tests__/toggle-logic.test.ts@@ -50,8 +50,8 @@ describe('app-card-utils', () => {appInfo: baseAppInfo,cardType: 'webapp',currentWorkflow: null,- isCurrentWorkspaceEditor: true,- isCurrentWorkspaceManager: true,+ canManageWebApp: true,+ canManageApi: true,})expect(state.appUnpublished).toBe(true)@@ -70,8 +70,8 @@ describe('app-card-utils', () => {nodes: [{ data: { type: 'start' } }],},},- isCurrentWorkspaceEditor: true,- isCurrentWorkspaceManager: true,+ canManageWebApp: true,+ canManageApi: true,})expect(state.appUnpublished).toBe(false)@@ -87,7 +87,7 @@ describe('app-card-utils', () => {expect(getAppCardOperationKeys({cardType: 'webapp',appMode: AppModeEnum.CHAT,- isCurrentWorkspaceEditor: true,+ canManageSettings: true,})).toEqual(['launch', 'embedded', 'customize', 'settings'])})@@ -95,7 +95,7 @@ describe('app-card-utils', () => {expect(getAppCardOperationKeys({cardType: 'api',appMode: AppModeEnum.COMPLETION,- isCurrentWorkspaceEditor: false,+ canManageSettings: false,})).toEqual(['develop'])})})diff --git a/web/app/components/app/overview/__tests__/trigger-card.spec.tsx b/web/app/components/app/overview/__tests__/trigger-card.spec.tsxindex 7e183a3b158..e7a838d0e6f 100644--- a/web/app/components/app/overview/__tests__/trigger-card.spec.tsx+++ b/web/app/components/app/overview/__tests__/trigger-card.spec.tsx@@ -1,6 +1,7 @@import type { AppDetailResponse } from '@/models/app'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import TriggerCard from '../trigger-card'vi.mock('react-i18next', () => ({@@ -17,6 +18,10 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceEditor: true,}),+ useSelector: <T,>(selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => T) => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],+ }),}))vi.mock('@/context/i18n', () => ({@@ -79,7 +84,8 @@ vi.mock('@langgenius/dify-ui/switch', () => ({data-testid="switch"data-checked={checked ? 'true' : 'false'}data-disabled={disabled ? 'true' : 'false'}- onClick={() => onCheckedChange(!checked)}+ disabled={disabled}+ onClick={() => !disabled && onCheckedChange(!checked)}>Switch</button>@@ -99,6 +105,7 @@ describe('TriggerCard', () => {updated_at: Date.now(),enable_site: true,enable_api: true,+ permission_keys: [AppACLPermission.Edit],} as AppDetailResponseconst mockOnToggleResult = vi.fn()@@ -341,7 +348,7 @@ describe('TriggerCard', () => {})})- describe('Editor Permissions', () => {+ describe('App ACL Permissions', () => {it('should render switches for triggers', () => {mockTriggers = [{@@ -358,6 +365,32 @@ describe('TriggerCard', () => {const switchBtn = screen.getByTestId('switch')expect(switchBtn).toBeInTheDocument()})++ it('should disable switches and skip updates without app edit permission', () => {+ mockTriggers = [+ {+ id: 'trigger-1',+ node_id: 'node-1',+ title: 'Test Trigger',+ trigger_type: 'trigger-webhook',+ status: 'enabled',+ },+ ]+ const appInfoWithoutEditPermission = {+ ...mockAppInfo,+ permission_keys: [],+ } as AppDetailResponse++ render(<TriggerCard appInfo={appInfoWithoutEditPermission} onToggleResult={mockOnToggleResult} />)++ const switchBtn = screen.getByTestId('switch')+ expect(switchBtn).toHaveAttribute('data-disabled', 'true')++ fireEvent.click(switchBtn)++ expect(mockUpdateTriggerStatus).not.toHaveBeenCalled()+ expect(mockSetTriggerStatus).not.toHaveBeenCalled()+ })})describe('Status Sync', () => {diff --git a/web/app/components/app/overview/app-card-sections.tsx b/web/app/components/app/overview/app-card-sections.tsxindex 61f509b27b4..b67808362d4 100644--- a/web/app/components/app/overview/app-card-sections.tsx+++ b/web/app/components/app/overview/app-card-sections.tsx@@ -226,7 +226,7 @@ export const AppCardUrlSection = ({isApp,accessibleUrl,showConfirmDelete,- isCurrentWorkspaceManager,+ canRegenerateUrl,genLoading,onRegenerate,onShowRegenerateConfirm,@@ -236,7 +236,7 @@ export const AppCardUrlSection = ({isApp: booleanaccessibleUrl: stringshowConfirmDelete: boolean- isCurrentWorkspaceManager: boolean+ canRegenerateUrl: booleangenLoading: booleanonRegenerate: () => voidonShowRegenerateConfirm: () => void@@ -277,7 +277,7 @@ export const AppCardUrlSection = ({</AlertDialogActions></AlertDialogContent></AlertDialog>- {isApp && isCurrentWorkspaceManager && (+ {isApp && canRegenerateUrl && (<MaybeTooltip content={t('overview.appInfo.regenerate', { ns: 'appOverview' }) || ''}><divclassName="size-6 cursor-pointer rounded-md hover:bg-state-base-hover"diff --git a/web/app/components/app/overview/app-card-utils.ts b/web/app/components/app/overview/app-card-utils.tsindex c08fa73b18a..9475da4300a 100644--- a/web/app/components/app/overview/app-card-utils.ts+++ b/web/app/components/app/overview/app-card-utils.ts@@ -221,22 +221,22 @@ export const getAppCardDisplayState = ({appInfo,cardType,currentWorkflow,- isCurrentWorkspaceEditor,- isCurrentWorkspaceManager,+ canManageWebApp,+ canManageApi,triggerModeDisabled = false,}: {appInfo: AppInfocardType: OverviewCardTypecurrentWorkflow: WorkflowLike- isCurrentWorkspaceEditor: boolean- isCurrentWorkspaceManager: boolean+ canManageWebApp: boolean+ canManageApi: booleantriggerModeDisabled?: boolean}): AppCardDisplayState => {const isApp = cardType === 'webapp'const isWorkflowApp = appInfo.mode === AppModeEnum.WORKFLOWconst appUnpublished = isWorkflowApp && !currentWorkflow?.graphconst missingStartNode = isWorkflowApp && !hasWorkflowStartNode(currentWorkflow)- const hasInsufficientPermissions = isApp ? !isCurrentWorkspaceEditor : !isCurrentWorkspaceManager+ const hasInsufficientPermissions = isApp ? !canManageWebApp : !canManageApiconst toggleDisabled = hasInsufficientPermissions || appUnpublished || missingStartNode || triggerModeDisabledconst runningStatus = (appUnpublished || missingStartNode) ? false : (isApp ? appInfo.enable_site : appInfo.enable_api)const appMode = getCardAppMode(appInfo.mode)@@ -269,11 +269,11 @@ export const isAppAccessConfigured = (appDetail: AppDetailResponse | null | undeexport const getAppCardOperationKeys = ({cardType,appMode,- isCurrentWorkspaceEditor,+ canManageSettings,}: {cardType: OverviewCardTypeappMode: AppModeEnum- isCurrentWorkspaceEditor: boolean+ canManageSettings: boolean}): OverviewOperationKey[] => {if (cardType === 'api')return ['develop']@@ -283,7 +283,7 @@ export const getAppCardOperationKeys = ({operationKeys.push('embedded')operationKeys.push('customize')- if (isCurrentWorkspaceEditor)+ if (canManageSettings)operationKeys.push('settings')return operationKeysdiff --git a/web/app/components/app/overview/app-card.tsx b/web/app/components/app/overview/app-card.tsxindex d116e165344..c074229cdae 100644--- a/web/app/components/app/overview/app-card.tsx+++ b/web/app/components/app/overview/app-card.tsx@@ -6,23 +6,24 @@ import type { AppSSO } from '@/types/app'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'-import { useSuspenseQuery } from '@tanstack/react-query'+import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import AppBasic from '@/app/components/app-sidebar/basic'import { useStore as useAppStore } from '@/app/components/app/store'import SecretKeyButton from '@/app/components/develop/secret-key/secret-key-button'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDocLink } from '@/context/i18n'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AccessMode } from '@/models/access-control'import { usePathname, useRouter } from '@/next/navigation'-import { useAppWhiteListSubjects } from '@/service/access-control'-import { fetchAppDetailDirect } from '@/service/apps'+import { useAppWhiteListSubjects } from '@/service/access-control/use-app-access-control'+import { appDetailQueryKeyPrefix } from '@/service/use-apps'import { useAppWorkflow } from '@/service/use-workflow'import { AppModeEnum } from '@/types/app'import { asyncRunSafe } from '@/utils'+import { getAppACLCapabilities } from '@/utils/permission'import {AppCardAccessControlSection,AppCardDialogs,@@ -68,12 +69,20 @@ function AppCard({}: IAppCardProps) {const router = useRouter()const pathname = usePathname()- const { isCurrentWorkspaceManager, isCurrentWorkspaceEditor } = useAppContext()+ const queryClient = useQueryClient()+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(appInfo.permission_keys, {+ currentUserId,+ resourceMaintainer: appInfo.maintainer,+ workspacePermissionKeys,+ }), [appInfo.maintainer, appInfo.permission_keys, currentUserId, workspacePermissionKeys])+ const canEditApp = appACLCapabilities.canEdit+ const canManageWebAppAccessControl = appACLCapabilities.canReleaseAndVersionconst shouldFetchWorkflow = appInfo.mode === AppModeEnum.WORKFLOW || appInfo.mode === AppModeEnum.ADVANCED_CHATconst { data: currentWorkflow } = useAppWorkflow(shouldFetchWorkflow ? appInfo.id : '')const docLink = useDocLink()const appDetail = useAppStore(state => state.appDetail)- const setAppDetail = useAppStore(state => state.setAppDetail)const [showSettingsModal, setShowSettingsModal] = useState(false)const [showEmbedded, setShowEmbedded] = useState(false)const [showCustomizeModal, setShowCustomizeModal] = useState(false)@@ -86,15 +95,15 @@ function AppCard({const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const { data: appAccessSubjects } = useAppWhiteListSubjects(appDetail?.id,- systemFeatures.webapp_auth.enabled && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS,+ systemFeatures.webapp_auth.enabled && canManageWebAppAccessControl && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS,)const cardState = getAppCardDisplayState({appInfo,cardType,currentWorkflow,- isCurrentWorkspaceEditor,- isCurrentWorkspaceManager,+ canManageWebApp: canEditApp,+ canManageApi: canEditApp,triggerModeDisabled,})@@ -137,31 +146,30 @@ function AppCard({}const handleClickAccessControl = useCallback(() => {- if (!appDetail)+ if (!appDetail || !canManageWebAppAccessControl)returnsetShowAccessControl(true)- }, [appDetail])+ }, [appDetail, canManageWebAppAccessControl])const handleAccessControlUpdate = useCallback(async () => {if (!appDetail)returntry {- const res = await fetchAppDetailDirect({ url: '/apps', id: appDetail.id })- setAppDetail(res)+ await queryClient.invalidateQueries({ queryKey: [...appDetailQueryKeyPrefix, appDetail.id] })setShowAccessControl(false)}catch (error) {console.error('Failed to fetch app detail:', error)}- }, [appDetail, setAppDetail])+ }, [appDetail, queryClient])const operationKeys = useMemo(() => getAppCardOperationKeys({cardType,appMode: cardState.appMode,- isCurrentWorkspaceEditor,- }), [cardState.appMode, cardType, isCurrentWorkspaceEditor])+ canManageSettings: canEditApp,+ }), [canEditApp, cardState.appMode, cardType])const handleLaunch = useCallback(() => {window.open(cardState.accessibleUrl, '_blank')@@ -335,7 +343,7 @@ function AppCard({isApp={isApp}accessibleUrl={cardState.accessibleUrl}showConfirmDelete={showConfirmDelete}- isCurrentWorkspaceManager={isCurrentWorkspaceManager}+ canRegenerateUrl={canEditApp}genLoading={genLoading}onRegenerate={() => {onGenCode()@@ -345,7 +353,7 @@ function AppCard({onHideRegenerateConfirm={() => setShowConfirmDelete(false)}/>)}- {!cardState.isMinimalState && isApp && systemFeatures.webapp_auth.enabled && appDetail && (+ {!cardState.isMinimalState && isApp && systemFeatures.webapp_auth.enabled && canManageWebAppAccessControl && appDetail && (<AppCardAccessControlSectiont={t}appDetail={appDetail}@@ -356,7 +364,7 @@ function AppCard({</div>{!cardState.isMinimalState && (<div className="flex items-center gap-1 self-stretch p-3">- {!isApp && <SecretKeyButton appId={appInfo.id} />}+ {!isApp && <SecretKeyButton appId={appInfo.id} canManage={canEditApp} />}<AppCardOperationst={t}operations={operations}diff --git a/web/app/components/app/overview/trigger-card.tsx b/web/app/components/app/overview/trigger-card.tsxindex d6bcb9efcff..5928f9140e7 100644--- a/web/app/components/app/overview/trigger-card.tsx+++ b/web/app/components/app/overview/trigger-card.tsx@@ -1,4 +1,5 @@'use client'+import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'import type { AppDetailResponse } from '@/models/app'import type { AppTrigger } from '@/service/use-tools'import type { AppSSO } from '@/types/app'@@ -7,11 +8,10 @@ import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'import * as React from 'react'import { useTranslation } from 'react-i18next'-import { TriggerAll } from '@/app/components/base/icons/src/vender/workflow'import BlockIcon from '@/app/components/workflow/block-icon'import { useTriggerStatusStore } from '@/app/components/workflow/store/trigger-status'import { BlockEnum } from '@/app/components/workflow/types'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDocLink } from '@/context/i18n'import Link from '@/next/link'import {@@ -22,13 +22,14 @@ import {} from '@/service/use-tools'import { useAllTriggerPlugins } from '@/service/use-triggers'import { canFindTool } from '@/utils'+import { getAppACLCapabilities } from '@/utils/permission'type ITriggerCardProps = {appInfo: AppDetailResponse & Partial<AppSSO>onToggleResult?: (err: Error | null, message?: I18nKeysByPrefix<'common', 'actionMsg.'>) => void}-const getTriggerIcon = (trigger: AppTrigger, triggerPlugins: any[]) => {+const getTriggerIcon = (trigger: AppTrigger, triggerPlugins: TriggerWithProvider[]) => {const { trigger_type, status, provider_name } = trigger// Get BlockEnum type from trigger_type@@ -55,7 +56,7 @@ const getTriggerIcon = (trigger: AppTrigger, triggerPlugins: any[]) => {|| triggerWithProvider.id.includes(provider_name)|| triggerWithProvider.name === provider_name,)- triggerIcon = foundTrigger?.icon+ triggerIcon = typeof foundTrigger?.icon === 'string' ? foundTrigger.icon : undefined}return (@@ -78,7 +79,13 @@ function TriggerCard({ appInfo, onToggleResult }: ITriggerCardProps) {const { t } = useTranslation()const docLink = useDocLink()const appId = appInfo.id- const { isCurrentWorkspaceEditor } = useAppContext()+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canEditApp = React.useMemo(() => getAppACLCapabilities(appInfo.permission_keys, {+ currentUserId,+ resourceMaintainer: appInfo.maintainer,+ workspacePermissionKeys,+ }).canEdit, [appInfo.maintainer, appInfo.permission_keys, currentUserId, workspacePermissionKeys])const { data: triggersResponse, isLoading } = useAppTriggers(appId)const { mutateAsync: updateTriggerStatus } = useUpdateTriggerStatus()const invalidateAppTriggers = useInvalidateAppTriggers()@@ -87,7 +94,7 @@ function TriggerCard({ appInfo, onToggleResult }: ITriggerCardProps) {// Zustand store for trigger status syncconst { setTriggerStatus, setTriggerStatuses } = useTriggerStatusStore()- const triggers = triggersResponse?.data || []+ const triggers = React.useMemo(() => triggersResponse?.data || [], [triggersResponse?.data])const triggerCount = triggers.length// Sync trigger statuses to Zustand store when data loads initially or after API calls@@ -105,6 +112,9 @@ function TriggerCard({ appInfo, onToggleResult }: ITriggerCardProps) {}, [triggers, setTriggerStatuses])const onToggleTrigger = async (trigger: AppTrigger, enabled: boolean) => {+ if (!canEditApp)+ return+try {// Immediately update Zustand store for real-time UI syncconst newStatus = enabled ? 'enabled' : 'disabled'@@ -149,7 +159,7 @@ function TriggerCard({ appInfo, onToggleResult }: ITriggerCardProps) {<div className="flex w-full items-center gap-3 self-stretch"><div className="flex grow items-center"><div className="mr-2 shrink-0 rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-purple-purple-500 p-1 shadow-md">- <TriggerAll className="size-4 text-text-primary-on-surface" />+ <div className="i-custom-vender-workflow-trigger-all size-4 text-text-primary-on-surface" /></div><div className="group w-full"><div className="min-w-0 overflow-hidden system-md-semibold break-normal text-ellipsis text-text-secondary group-hover:text-text-primary">@@ -185,7 +195,7 @@ function TriggerCard({ appInfo, onToggleResult }: ITriggerCardProps) {<Switchchecked={trigger.status === 'enabled'}onCheckedChange={enabled => onToggleTrigger(trigger, enabled)}- disabled={!isCurrentWorkspaceEditor}+ disabled={!canEditApp}/></div></div>diff --git a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsxindex 8e9cca423e8..5a541087bd6 100644--- a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx@@ -274,7 +274,10 @@ describe('SwitchAppModal', () => {const user = userEvent.setup()// Arrangeconst { appDetail, notify, onClose, onSuccess } = renderComponent()- mockSwitchApp.mockResolvedValueOnce({ new_app_id: 'new-app-001' })+ mockSwitchApp.mockResolvedValueOnce({+ new_app_id: 'new-app-001',+ permission_keys: ['app.acl.view_layout'],+ })// Actawait user.click(screen.getByRole('button', { name: 'app.switchStart' }))@@ -300,7 +303,10 @@ describe('SwitchAppModal', () => {it('should update the icon through the picker before switching apps', async () => {const user = userEvent.setup()const { appDetail } = renderComponent()- mockSwitchApp.mockResolvedValueOnce({ new_app_id: 'new-app-003' })+ mockSwitchApp.mockResolvedValueOnce({+ new_app_id: 'new-app-003',+ permission_keys: ['app.acl.view_layout'],+ })await user.click(screen.getByText('open-icon-picker'))await waitFor(() => {@@ -359,7 +365,10 @@ describe('SwitchAppModal', () => {const user = userEvent.setup()// Arrangeconst { appDetail } = renderComponent({ inAppDetail: true })- mockSwitchApp.mockResolvedValueOnce({ new_app_id: 'new-app-002' })+ mockSwitchApp.mockResolvedValueOnce({+ new_app_id: 'new-app-002',+ permission_keys: ['app.acl.view_layout'],+ })// Actawait user.click(screen.getByText('app.removeOriginal'))diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsxindex 0c794025062..fc3013adfb4 100644--- a/web/app/components/app/switch-app-modal/index.tsx+++ b/web/app/components/app/switch-app-modal/index.tsx@@ -25,7 +25,6 @@ import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alerimport Input from '@/app/components/base/input'import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'-import { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import { useRouter } from '@/next/navigation'import { deleteApp, switchApp } from '@/service/apps'@@ -46,7 +45,6 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onSuccess, onCloconst { t } = useTranslation()const setAppDetail = useAppStore(s => s.setAppDetail)- const { isCurrentWorkspaceEditor } = useAppContext()const { plan, enableBilling } = useProviderContext()const isAppsFull = (enableBilling && plan.usage.buildApps >= plan.total.buildApps)@@ -65,7 +63,7 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onSuccess, onCloconst goStart = async () => {try {- const { new_app_id: newAppID } = await switchApp({+ const { new_app_id: newAppID, permission_keys } = await switchApp({appID: appDetail.id,name,icon_type: appIcon.type,@@ -83,10 +81,10 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onSuccess, onCloawait deleteApp(appDetail.id)setNeedRefresh('1')getRedirection(- isCurrentWorkspaceEditor,{id: newAppID,mode: appDetail.mode === AppModeEnum.COMPLETION ? AppModeEnum.WORKFLOW : AppModeEnum.ADVANCED_CHAT,+ permission_keys,},removeOriginal ? replace : push,)diff --git a/web/app/components/app/workflow-log/__tests__/index.spec.tsx b/web/app/components/app/workflow-log/__tests__/index.spec.tsxindex 1fe3db30db9..af5f7ed85a8 100644--- a/web/app/components/app/workflow-log/__tests__/index.spec.tsx+++ b/web/app/components/app/workflow-log/__tests__/index.spec.tsx@@ -82,6 +82,10 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({userProfile: { timezone: 'UTC' },}),+ useSelector: (selector: (state: { userProfile: { id: string, timezone: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: 'user-1', timezone: 'UTC' },+ workspacePermissionKeys: ['app.create_and_management'],+ }),}))// Mock WorkflowContextProviderdiff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsxindex 831ad2f08bc..78c47fc865c 100644--- a/web/app/components/apps/__tests__/app-card.spec.tsx+++ b/web/app/components/apps/__tests__/app-card.spec.tsx@@ -8,7 +8,9 @@ import * as appsService from '@/service/apps'import * as exploreService from '@/service/explore'import * as workflowService from '@/service/workflow'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import { AppCard } from '../app-card'+import { StarredAppCard } from '../starred-app-card'let mockWebappAuthEnabled = false@@ -60,11 +62,16 @@ vi.mock('use-context-selector', () => ({}),}))+const mockAppContext = vi.hoisted(() => ({+ isCurrentWorkspaceEditor: true,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: ['app.create_and_management'] as string[],+}))+// Mock app contextvi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceEditor: true,- }),+ useAppContext: () => mockAppContext,+ useSelector: (selector: (state: typeof mockAppContext) => unknown) => selector(mockAppContext),}))// Mock provider context@@ -114,6 +121,13 @@ vi.mock('@/service/access-control', () => ({}),}))+vi.mock('@/service/access-control/use-app-access-control', () => ({+ useGetUserCanAccessApp: () => ({+ data: { result: true },+ isLoading: false,+ }),+}))+// Mock hooksconst mockOpenAsyncWindow = vi.fn()vi.mock('@/hooks/use-async-window-open', () => ({@@ -126,7 +140,7 @@ const { mockGetRedirection } = vi.hoisted(() => ({}))vi.mock('@/utils/app-redirection', () => ({- getRedirectionPath: (_isCurrentWorkspaceEditor: boolean, app: { id: string }) => `/app/${app.id}/configuration`,+ getRedirectionPath: (app: { id: string }) => `/app/${app.id}/configuration`,getRedirection: mockGetRedirection,}))@@ -305,8 +319,21 @@ vi.mock('@langgenius/dify-ui/dropdown-menu', () => {// AppCardTags has tag API dependencies - mock for isolated testingvi.mock('@/features/tag-management/components/app-card-tags', () => ({- AppCardTags: ({ tags }: { tags?: { id: string, name: string }[] }) => {- return React.createElement('div', { 'aria-label': 'tag-selector' }, tags?.map((tag: { id: string, name: string }) => React.createElement('span', { key: tag.id }, tag.name)))+ AppCardTags: ({+ tags,+ canBindOrUnbindTags,+ }: {+ tags?: { id: string, name: string }[]+ canBindOrUnbindTags?: boolean+ }) => {+ return React.createElement(+ 'div',+ {+ 'aria-label': 'tag-selector',+ 'data-can-bind-or-unbind-tags': String(Boolean(canBindOrUnbindTags)),+ },+ tags?.map((tag: { id: string, name: string }) => React.createElement('span', { key: tag.id }, tag.name)),+ )},}))@@ -325,6 +352,8 @@ const createMockApp = (overrides: Partial<App> = {}): App => ({icon_background: '#FFEAD5',icon_url: null,author_name: 'Test Author',+ created_by: 'user-1',+ maintainer: 'user-1',created_at: 1704067200,updated_at: 1704153600,tags: [],@@ -350,6 +379,9 @@ describe('AppCard', () => {mockWebappAuthEnabled = falsemockDeleteMutationPending = falsemockToggleStarMutationPending = false+ mockAppContext.isCurrentWorkspaceEditor = true+ mockAppContext.userProfile = { id: 'user-1' }+ mockAppContext.workspacePermissionKeys = ['app.create_and_management']})describe('Rendering', () => {@@ -426,6 +458,36 @@ describe('AppCard', () => {expect(screen.queryByText('Old Tag')).not.toBeInTheDocument()})+ it('should allow app edit permission to bind tags without workspace tag management permission', () => {+ mockAppContext.isCurrentWorkspaceEditor = false+ mockAppContext.workspacePermissionKeys = []+ mockAppContext.userProfile = { id: 'user-2' }+ const editableApp = createMockApp({+ maintainer: 'user-1',+ tags: [{ id: 'tag1', name: 'Tag 1', type: 'app' as const, binding_count: 0 }],+ permission_keys: [AppACLPermission.Edit],+ })++ render(<AppCard app={editableApp} />)++ expect(screen.getByLabelText('tag-selector')).toHaveAttribute('data-can-bind-or-unbind-tags', 'true')+ })++ it('should not render tag selector without app edit or workspace tag management permission', () => {+ mockAppContext.isCurrentWorkspaceEditor = false+ mockAppContext.workspacePermissionKeys = []+ mockAppContext.userProfile = { id: 'user-2' }+ const readonlyApp = createMockApp({+ maintainer: 'user-1',+ tags: [{ id: 'tag1', name: 'Tag 1', type: 'app' as const, binding_count: 0 }],+ permission_keys: [AppACLPermission.ViewLayout],+ })++ render(<AppCard app={readonlyApp} />)++ expect(screen.queryByLabelText('tag-selector')).not.toBeInTheDocument()+ })+it('should render with onRefresh callback', () => {render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)expect(screen.getByRole('link', { name: 'Test App' })).toBeInTheDocument()@@ -557,6 +619,38 @@ describe('AppCard', () => {})})+ it('should show duplicate option when user can create apps without app import export permission', async () => {+ const appWithoutImportExportPermission = createMockApp({+ created_by: 'another-user',+ maintainer: 'another-user',+ permission_keys: [AppACLPermission.ViewLayout],+ })+ render(<AppCard app={appWithoutImportExportPermission} />)++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))++ await waitFor(() => {+ expect(screen.getByText('app.duplicate')).toBeInTheDocument()+ })+ expect(screen.queryByText('app.export')).not.toBeInTheDocument()+ })++ it('should show duplicate option on starred cards when user can create apps without app import export permission', async () => {+ const appWithoutImportExportPermission = createMockApp({+ created_by: 'another-user',+ maintainer: 'another-user',+ permission_keys: [AppACLPermission.ViewLayout],+ })+ render(<StarredAppCard app={appWithoutImportExportPermission} />)++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))++ await waitFor(() => {+ expect(screen.getByText('app.duplicate')).toBeInTheDocument()+ })+ expect(screen.queryByText('app.export')).not.toBeInTheDocument()+ })+it('should show export option when dropdown menu is opened', async () => {render(<AppCard app={mockApp} />)@@ -588,6 +682,24 @@ describe('AppCard', () => {})})+ it('should show switch option when user can edit app without app creation permission', async () => {+ mockAppContext.workspacePermissionKeys = []+ const editableChatApp = createMockApp({+ created_by: 'another-user',+ maintainer: 'another-user',+ mode: AppModeEnum.CHAT,+ permission_keys: [AppACLPermission.Edit],+ })+ render(<AppCard app={editableChatApp} />)++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))++ await waitFor(() => {+ expect(screen.getByText(/switch/i)).toBeInTheDocument()+ })+ expect(screen.queryByText('app.duplicate')).not.toBeInTheDocument()+ })+it('should show switch option for completion mode apps', async () => {const completionApp = { ...mockApp, mode: AppModeEnum.COMPLETION }render(<AppCard app={completionApp} />)@@ -1623,6 +1735,54 @@ describe('AppCard', () => {})})+ it('should show access control option when user has app release and version permission', async () => {+ const appWithReleasePermission = createMockApp({+ created_by: 'another-user',+ maintainer: 'another-user',+ permission_keys: [AppACLPermission.ReleaseAndVersion],+ })+ render(<AppCard app={appWithReleasePermission} />)++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))++ await waitFor(() => {+ expect(screen.getByText('app.accessControl')).toBeInTheDocument()+ })+ })++ it('should show resource access option when user only has app access config permission', async () => {+ const appWithAccessConfigPermission = createMockApp({+ created_by: 'another-user',+ maintainer: 'another-user',+ permission_keys: [AppACLPermission.AccessConfig, AppACLPermission.Delete],+ })+ render(<AppCard app={appWithAccessConfigPermission} />)++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))++ await waitFor(() => {+ expect(screen.getByText('common.operation.delete')).toBeInTheDocument()+ })+ expect(screen.queryByText('app.accessControl')).not.toBeInTheDocument()+ expect(screen.getByText('common.settings.resourceAccess')).toBeInTheDocument()+ })++ it('should navigate to app access config when resource access is clicked', async () => {+ const appWithAccessConfigPermission = createMockApp({+ created_by: 'another-user',+ maintainer: 'another-user',+ permission_keys: [AppACLPermission.AccessConfig],+ })+ render(<AppCard app={appWithAccessConfigPermission} />)++ fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))+ await waitFor(() => {+ fireEvent.click(screen.getByText('common.settings.resourceAccess'))+ })++ expect(mockPush).toHaveBeenCalledWith('/app/test-app-id/access-config')+ })+it('should click access control button', async () => {render(<AppCard app={mockApp} />)diff --git a/web/app/components/apps/__tests__/index.spec.tsx b/web/app/components/apps/__tests__/index.spec.tsxindex 32ebd35eba6..7f6120afef0 100644--- a/web/app/components/apps/__tests__/index.spec.tsx+++ b/web/app/components/apps/__tests__/index.spec.tsx@@ -28,6 +28,7 @@ const mockHandleImportDSL = vi.fn()const mockHandleImportDSLConfirm = vi.fn()const mockTrackCreateApp = vi.fn()const mockFetchAppDetail = vi.mocked(fetchAppDetail)+let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']const mockTemplateApp: App = {app_id: 'template-1',@@ -68,6 +69,15 @@ vi.mock('@/app/education-apply/hooks', () => ({},}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+ useAppContext: () => ({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+vi.mock('@/hooks/use-import-dsl', () => ({useImportDSL: () => ({handleImportDSL: mockHandleImportDSL,@@ -193,6 +203,7 @@ describe('Apps', () => {vi.clearAllMocks()documentTitleCalls = []educationInitCalls = 0+ mockWorkspacePermissionKeys = ['app.create_and_management']mockSearchParams = new URLSearchParams()mockReplace.mockClear()mockFetchAppDetail.mockResolvedValue({@@ -351,6 +362,14 @@ describe('Apps', () => {expect(screen.getByTestId('template-id')).toHaveTextContent('tpl-42')})+ it('should not render the template modal without app.create_and_management permission', () => {+ mockWorkspacePermissionKeys = []+ mockSearchParams = new URLSearchParams('template-id=tpl-42')+ renderWithClient(<Apps />)++ expect(screen.queryByTestId('marketplace-template-modal')).not.toBeInTheDocument()+ })+it('should not render the template modal when no template-id is present', () => {renderWithClient(<Apps />)@@ -391,6 +410,16 @@ describe('Apps', () => {})})+ it('should not open create modal from template preview without app.create_and_management permission', async () => {+ mockWorkspacePermissionKeys = []+ renderWithClient(<Apps />)++ fireEvent.click(screen.getByTestId('open-preview'))+ fireEvent.click(await screen.findByTestId('try-app-create'))++ expect(screen.queryByTestId('create-app-modal')).not.toBeInTheDocument()+ })+it('should track marketplace template creation after confirming a pending import', async () => {mockHandleImportDSL.mockImplementation(async (_payload: unknown, options: { onPending?: () => void }) => {options.onPending?.()diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsxindex 6ff5ae6e10f..fda64f8ccb8 100644--- a/web/app/components/apps/__tests__/list.spec.tsx+++ b/web/app/components/apps/__tests__/list.spec.tsx@@ -65,13 +65,22 @@ vi.mock('@/service/client', () => ({},}))-const mockIsCurrentWorkspaceEditor = vi.fn(() => true)const mockIsCurrentWorkspaceDatasetOperator = vi.fn(() => false)+let mockWorkspacePermissionKeys = ['app.create_and_management']vi.mock('@/context/app-context', () => ({useAppContext: () => ({- isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor(),isCurrentWorkspaceDatasetOperator: mockIsCurrentWorkspaceDatasetOperator(),userProfile: { id: 'creator-1' },+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+ useSelector: (selector: (state: {+ isCurrentWorkspaceDatasetOperator: boolean+ userProfile: { id: string }+ workspacePermissionKeys: string[]+ }) => unknown) => selector({+ isCurrentWorkspaceDatasetOperator: mockIsCurrentWorkspaceDatasetOperator(),+ userProfile: { id: 'creator-1' },+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -355,8 +364,8 @@ const openAppSortSelect = async (user = userEvent.setup()) => {describe('List', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCurrentWorkspaceEditor.mockReturnValue(true)mockIsCurrentWorkspaceDatasetOperator.mockReturnValue(false)+ mockWorkspacePermissionKeys = ['app.create_and_management']mockDragging = falsemockOnDSLFileDropped = nullmockServiceState.error = null@@ -495,7 +504,7 @@ describe('List', () => {expect(screen.queryByTestId('new-app-card')).not.toBeInTheDocument()})- it('should render drop DSL hint for editors', () => {+ it('should render drop DSL hint when app creation permission is available', () => {renderList()expect(screen.getByText('app.newApp.dropDSLToCreateApp'))!.toBeInTheDocument()})@@ -742,8 +751,8 @@ describe('List', () => {expect(screen.getByTestId('create-dsl-modal'))!.toBeInTheDocument()})- it('should not render create button for non-editors', () => {- mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ it('should not render create button without app creation permission', () => {+ mockWorkspacePermissionKeys = []renderList()@@ -751,17 +760,17 @@ describe('List', () => {})})- describe('Non-Editor User', () => {- it('should not render new app card for non-editors', () => {- mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ describe('User Without App Creation Permission', () => {+ it('should not render new app card without app creation permission', () => {+ mockWorkspacePermissionKeys = []renderList()expect(screen.queryByTestId('new-app-card')).not.toBeInTheDocument()})- it('should not render drop DSL hint for non-editors', () => {- mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ it('should not render drop DSL hint without app creation permission', () => {+ mockWorkspacePermissionKeys = []renderList()diff --git a/web/app/components/apps/__tests__/new-app-card.spec.tsx b/web/app/components/apps/__tests__/new-app-card.spec.tsxindex 00be07998b5..4f7b8c4bf92 100644--- a/web/app/components/apps/__tests__/new-app-card.spec.tsx+++ b/web/app/components/apps/__tests__/new-app-card.spec.tsx@@ -4,6 +4,7 @@ import * as React from 'react'import CreateAppCard from '../new-app-card'const mockReplace = vi.fn()+let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']vi.mock('@/next/navigation', () => ({useRouter: () => ({replace: mockReplace,@@ -11,6 +12,12 @@ vi.mock('@/next/navigation', () => ({useSearchParams: () => new URLSearchParams(),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+const mockOnPlanInfoChanged = vi.fn()vi.mock('@/context/provider-context', () => ({useProviderContext: () => ({@@ -58,6 +65,7 @@ describe('CreateAppCard', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys = ['app.create_and_management']})describe('Rendering', () => {@@ -66,6 +74,14 @@ describe('CreateAppCard', () => {expect(screen.getByText('app.newApp.startFromBlank')).toBeInTheDocument()})+ it('should not render without app.create_and_management permission', () => {+ mockWorkspacePermissionKeys = []++ const { container } = render(<CreateAppCard ref={defaultRef} />)++ expect(container).toBeEmptyDOMElement()+ })+it('should render three create buttons', () => {render(<CreateAppCard ref={defaultRef} />)diff --git a/web/app/components/apps/app-card.tsx b/web/app/components/apps/app-card.tsxindex 09c7f7f8d25..da150571340 100644--- a/web/app/components/apps/app-card.tsx+++ b/web/app/components/apps/app-card.tsx@@ -40,7 +40,7 @@ import StarIcon from '@/app/components/base/icons/src/vender/Star'import { UserAvatarList } from '@/app/components/base/user-avatar-list'import { buildInstalledAppPath } from '@/app/components/explore/installed-app/routes'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextSelector } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AppCardTags } from '@/features/tag-management/components/app-card-tags'@@ -49,7 +49,7 @@ import { AccessMode } from '@/models/access-control'import dynamic from '@/next/dynamic'import Link from '@/next/link'import { useRouter } from '@/next/navigation'-import { useGetUserCanAccessApp } from '@/service/access-control'+import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'import { copyApp, exportAppConfig, updateAppInfo } from '@/service/apps'import { fetchInstalledAppList } from '@/service/explore'import { useDeleteAppMutation, useToggleAppStarMutation } from '@/service/use-apps'@@ -57,6 +57,7 @@ import { fetchWorkflowDraft } from '@/service/workflow'import { AppModeEnum } from '@/types/app'import { getRedirection, getRedirectionPath } from '@/utils/app-redirection'import { downloadBlob } from '@/utils/download'+import { getAppACLCapabilities, hasPermission } from '@/utils/permission'import { formatTime } from '@/utils/time'import { basePath } from '@/utils/var'@@ -101,6 +102,8 @@ type AppAccessModeIconProps = {accessMode?: AccessMode | null}+const getAppResourceMaintainer = (app: App) => app.maintainer+function AppAccessModeIcon({ accessMode }: AppAccessModeIconProps) {const { t } = useTranslation()@@ -129,31 +132,47 @@ function AppAccessModeIcon({ accessMode }: AppAccessModeIconProps) {type AppCardOperationsMenuProps = {app: App+ shouldShowEditOption: boolean+ shouldShowDuplicateOption: boolean+ shouldShowExportOption: booleanshouldShowSwitchOption: booleanshouldShowOpenInExploreOption: booleanshouldShowAccessControlOption: boolean+ shouldShowAccessConfigOption: boolean+ shouldShowDeleteOption: booleanonEdit: () => voidonDuplicate: () => voidonExport: () => voidonSwitch: () => voidonDelete: () => voidonAccessControl: () => void+ onAccessConfig: () => void}function AppCardOperationsMenu({app,+ shouldShowEditOption,+ shouldShowDuplicateOption,+ shouldShowExportOption,shouldShowSwitchOption,shouldShowOpenInExploreOption,shouldShowAccessControlOption,+ shouldShowAccessConfigOption,+ shouldShowDeleteOption,onEdit,onDuplicate,onExport,onSwitch,onDelete,onAccessControl,+ onAccessConfig,}: AppCardOperationsMenuProps) {const { t } = useTranslation()const openAsyncWindow = useAsyncWindowOpen()+ const hasEditGroup = shouldShowEditOption+ const hasCreateExportGroup = shouldShowDuplicateOption || shouldShowExportOption+ const hasSwitchOrExploreGroup = shouldShowSwitchOption || shouldShowOpenInExploreOption+ const hasAccessDeleteGroup = shouldShowAccessControlOption || shouldShowAccessConfigOption || shouldShowDeleteOptionfunction handleMenuAction(e: MouseEvent<HTMLElement>, action: () => void) {e.stopPropagation()@@ -184,50 +203,64 @@ function AppCardOperationsMenu({return (<>- <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onEdit)}>- <span className="system-sm-regular text-text-secondary">{t('editApp', { ns: 'app' })}</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onDuplicate)}>- <span className="system-sm-regular text-text-secondary">{t('duplicate', { ns: 'app' })}</span>- </DropdownMenuItem>- <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onExport)}>- <span className="system-sm-regular text-text-secondary">{t('export', { ns: 'app' })}</span>- </DropdownMenuItem>+ {shouldShowEditOption && (+ <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onEdit)}>+ <span className="system-sm-regular text-text-secondary">{t('editApp', { ns: 'app' })}</span>+ </DropdownMenuItem>+ )}+ {hasEditGroup && (hasCreateExportGroup || hasSwitchOrExploreGroup || hasAccessDeleteGroup) && (+ <DropdownMenuSeparator />+ )}+ {shouldShowDuplicateOption && (+ <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onDuplicate)}>+ <span className="system-sm-regular text-text-secondary">{t('duplicate', { ns: 'app' })}</span>+ </DropdownMenuItem>+ )}+ {shouldShowExportOption && (+ <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onExport)}>+ <span className="system-sm-regular text-text-secondary">{t('export', { ns: 'app' })}</span>+ </DropdownMenuItem>+ )}+ {hasCreateExportGroup && (hasSwitchOrExploreGroup || hasAccessDeleteGroup) && (+ <DropdownMenuSeparator />+ )}{shouldShowSwitchOption && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onSwitch)}>- <span className="text-sm/5 text-text-secondary">{t('switch', { ns: 'app' })}</span>- </DropdownMenuItem>- </>+ <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onSwitch)}>+ <span className="text-sm/5 text-text-secondary">{t('switch', { ns: 'app' })}</span>+ </DropdownMenuItem>)}{shouldShowOpenInExploreOption && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem className="gap-2 px-3" onClick={handleOpenInstalledApp}>- <span className="system-sm-regular text-text-secondary">{t('openInExplore', { ns: 'app' })}</span>- </DropdownMenuItem>- </>+ <DropdownMenuItem className="gap-2 px-3" onClick={handleOpenInstalledApp}>+ <span className="system-sm-regular text-text-secondary">{t('openInExplore', { ns: 'app' })}</span>+ </DropdownMenuItem>+ )}+ {hasSwitchOrExploreGroup && hasAccessDeleteGroup && (+ <DropdownMenuSeparator />)}- <DropdownMenuSeparator />{shouldShowAccessControlOption && (- <>- <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onAccessControl)}>- <span className="text-sm/5 text-text-secondary">{t('accessControl', { ns: 'app' })}</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- </>+ <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onAccessControl)}>+ <span className="text-sm/5 text-text-secondary">{t('accessControl', { ns: 'app' })}</span>+ </DropdownMenuItem>+ )}+ {shouldShowAccessConfigOption && (+ <DropdownMenuItem className="gap-2 px-3" onClick={e => handleMenuAction(e, onAccessConfig)}>+ <span className="text-sm/5 text-text-secondary">{t('settings.resourceAccess', { ns: 'common' })}</span>+ </DropdownMenuItem>+ )}+ {(shouldShowAccessControlOption || shouldShowAccessConfigOption) && shouldShowDeleteOption && (+ <DropdownMenuSeparator />+ )}+ {shouldShowDeleteOption && (+ <DropdownMenuItem+ variant="destructive"+ className="gap-2 px-3"+ onClick={e => handleMenuAction(e, onDelete)}+ >+ <span className="system-sm-regular">+ {t('operation.delete', { ns: 'common' })}+ </span>+ </DropdownMenuItem>)}- <DropdownMenuItem- variant="destructive"- className="gap-2 px-3"- onClick={e => handleMenuAction(e, onDelete)}- >- <span className="system-sm-regular">- {t('operation.delete', { ns: 'common' })}- </span>- </DropdownMenuItem></>)}@@ -263,7 +296,8 @@ type AppCardActionBarProps = {export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {const { t } = useTranslation()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const { isCurrentWorkspaceEditor } = useAppContext()+ const currentUserId = useAppContextSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)const { onPlanInfoChanged } = useProviderContext()const { push } = useRouter()@@ -278,6 +312,14 @@ export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {const { mutateAsync: mutateDeleteApp, isPending: isDeleting } = useDeleteAppMutation()const { mutateAsync: mutateToggleAppStar, isPending: isTogglingStar } = useToggleAppStarMutation()const setNeedRefresh = useSetLocalStorage<string>(NEED_REFRESH_APP_LIST_KEY, { raw: true })+ const resourceMaintainer = getAppResourceMaintainer(app)+ const maintainerPermissionOptions = useMemo(() => ({+ currentUserId,+ resourceMaintainer,+ workspacePermissionKeys,+ }), [currentUserId, resourceMaintainer, workspacePermissionKeys])+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(app.permission_keys, maintainerPermissionOptions), [app.permission_keys, maintainerPermissionOptions])+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const onConfirmDelete = useCallback(async () => {try {@@ -347,6 +389,11 @@ export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {})}, [])+ const handleOpenAccessConfig = useCallback(() => {+ setIsOperationsMenuOpen(false)+ push(`/app/${app.id}/access-config`)+ }, [app.id, push])+const onEdit: CreateAppModalProps['onConfirm'] = useCallback(async ({name,icon_type,@@ -391,7 +438,11 @@ export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {setNeedRefresh('1')onRefresh?.()onPlanInfoChanged()- getRedirection(isCurrentWorkspaceEditor, newApp, push)+ getRedirection(newApp, push, {+ currentUserId,+ resourceMaintainer: getAppResourceMaintainer(newApp),+ workspacePermissionKeys,+ })}catch {toast.error(t('newApp.appCreateFailed', { ns: 'app' }))@@ -461,8 +512,14 @@ export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {}}, [app.id, app.is_starred, isTogglingStar, mutateToggleAppStar, onRefresh, t])- const shouldShowSwitchOption = app.mode === AppModeEnum.COMPLETION || app.mode === AppModeEnum.CHAT- const shouldShowAccessControlOption = systemFeatures.webapp_auth.enabled && isCurrentWorkspaceEditor+ const shouldShowEditOption = appACLCapabilities.canEdit+ const shouldShowDuplicateOption = canCreateApp+ const shouldShowExportOption = appACLCapabilities.canImportExportDSL+ const shouldShowSwitchOption = canCreateApp && appACLCapabilities.canEdit && (app.mode === AppModeEnum.COMPLETION || app.mode === AppModeEnum.CHAT)+ const shouldShowAccessControlOption = systemFeatures.webapp_auth.enabled && appACLCapabilities.canReleaseAndVersion+ const shouldShowAccessConfigOption = appACLCapabilities.canAccessConfig+ const shouldShowDeleteOption = appACLCapabilities.canDelete+ const shouldShowOperationsMenu = shouldShowEditOption || shouldShowDuplicateOption || shouldShowExportOption || shouldShowSwitchOption || shouldShowAccessControlOption || shouldShowAccessConfigOption || shouldShowDeleteOptionconst operationsMenuWidthClassName = shouldShowSwitchOption ? 'w-[256px]' : 'w-[216px]'const starActionLabel = app.is_starred? t('studio.unstarApp', { ns: 'app' })@@ -500,7 +557,7 @@ export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {/><TooltipContent>{starActionLabel}</TooltipContent></Tooltip>- {isCurrentWorkspaceEditor && (+ {shouldShowOperationsMenu && (<DropdownMenu modal={false} open={isOperationsMenuOpen} onOpenChange={setIsOperationsMenuOpen}><DropdownMenuTriggeraria-label={t('operation.more', { ns: 'common' })}@@ -525,28 +582,40 @@ export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {? (<AppCardOperationsMenuContentapp={app}+ shouldShowEditOption={shouldShowEditOption}+ shouldShowDuplicateOption={shouldShowDuplicateOption}+ shouldShowExportOption={shouldShowExportOption}shouldShowSwitchOption={shouldShowSwitchOption}shouldShowAccessControlOption={shouldShowAccessControlOption}+ shouldShowAccessConfigOption={shouldShowAccessConfigOption}+ shouldShowDeleteOption={shouldShowDeleteOption}onEdit={handleShowEditModal}onDuplicate={handleShowDuplicateModal}onExport={exportCheck}onSwitch={handleShowSwitchModal}onDelete={handleShowDeleteConfirm}onAccessControl={handleShowAccessControl}+ onAccessConfig={handleOpenAccessConfig}/>): (<AppCardOperationsMenuapp={app}+ shouldShowEditOption={shouldShowEditOption}+ shouldShowDuplicateOption={shouldShowDuplicateOption}+ shouldShowExportOption={shouldShowExportOption}shouldShowSwitchOption={shouldShowSwitchOption}shouldShowOpenInExploreOption={!app.has_draft_trigger}shouldShowAccessControlOption={shouldShowAccessControlOption}+ shouldShowAccessConfigOption={shouldShowAccessConfigOption}+ shouldShowDeleteOption={shouldShowDeleteOption}onEdit={handleShowEditModal}onDuplicate={handleShowDuplicateModal}onExport={exportCheck}onSwitch={handleShowSwitchModal}onDelete={handleShowDeleteConfirm}onAccessControl={handleShowAccessControl}+ onAccessConfig={handleOpenAccessConfig}/>)}</DropdownMenuContent>@@ -654,7 +723,8 @@ export function AppCardActionBar({ app, onRefresh }: AppCardActionBarProps) {export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement = () => {} }: AppCardProps) {const { t } = useTranslation()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const { isCurrentWorkspaceEditor } = useAppContext()+ const currentUserId = useAppContextSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)const { onPlanInfoChanged } = useProviderContext()const { push } = useRouter()@@ -669,6 +739,15 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagementconst { mutateAsync: mutateDeleteApp, isPending: isDeleting } = useDeleteAppMutation()const { mutateAsync: mutateToggleAppStar, isPending: isTogglingStar } = useToggleAppStarMutation()const setNeedRefresh = useSetLocalStorage<string>(NEED_REFRESH_APP_LIST_KEY, { raw: true })+ const resourceMaintainer = getAppResourceMaintainer(app)+ const maintainerPermissionOptions = useMemo(() => ({+ currentUserId,+ resourceMaintainer,+ workspacePermissionKeys,+ }), [currentUserId, resourceMaintainer, workspacePermissionKeys])+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(app.permission_keys, maintainerPermissionOptions), [app.permission_keys, maintainerPermissionOptions])+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')+ const canManageAppTags = hasPermission(workspacePermissionKeys, 'app.tag.manage')async function onConfirmDelete() {try {@@ -738,6 +817,11 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement})}+ const handleOpenAccessConfig = useCallback(() => {+ setIsOperationsMenuOpen(false)+ push(`/app/${app.id}/access-config`)+ }, [app.id, push])+const onEdit: CreateAppModalProps['onConfirm'] = async ({name,icon_type,@@ -784,7 +868,11 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagementif (onRefresh)onRefresh()onPlanInfoChanged()- getRedirection(isCurrentWorkspaceEditor, newApp, push)+ getRedirection(newApp, push, {+ currentUserId,+ resourceMaintainer: getAppResourceMaintainer(newApp),+ workspacePermissionKeys,+ })}catch {toast.error(t('newApp.appCreateFailed', { ns: 'app' }))@@ -856,8 +944,15 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement}}, [app.id, app.is_starred, isTogglingStar, mutateToggleAppStar, onRefresh, t])- const shouldShowSwitchOption = app.mode === AppModeEnum.COMPLETION || app.mode === AppModeEnum.CHAT- const shouldShowAccessControlOption = systemFeatures.webapp_auth.enabled && isCurrentWorkspaceEditor+ const shouldShowEditOption = appACLCapabilities.canEdit+ const shouldShowDuplicateOption = canCreateApp+ const shouldShowExportOption = appACLCapabilities.canImportExportDSL+ const shouldShowSwitchOption = appACLCapabilities.canEdit && (app.mode === AppModeEnum.COMPLETION || app.mode === AppModeEnum.CHAT)+ const shouldShowAccessControlOption = systemFeatures.webapp_auth.enabled && appACLCapabilities.canReleaseAndVersion+ const shouldShowAccessConfigOption = appACLCapabilities.canAccessConfig+ const shouldShowDeleteOption = appACLCapabilities.canDelete+ const shouldShowOperationsMenu = shouldShowEditOption || shouldShowDuplicateOption || shouldShowExportOption || shouldShowSwitchOption || shouldShowAccessControlOption || shouldShowAccessConfigOption || shouldShowDeleteOption+ const shouldShowAppTags = appACLCapabilities.canEdit || canManageAppTagsconst operationsMenuWidthClassName = shouldShowSwitchOption ? 'w-[256px]' : 'w-[216px]'const editTimeText = useMemo(() => {@@ -900,7 +995,7 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement}, [app.id, onlineUsers])const appNameId = useId()const appDescriptionId = useId()- const appHref = getRedirectionPath(isCurrentWorkspaceEditor, app)+ const appHref = getRedirectionPath(app, maintainerPermissionOptions)const starActionLabel = app.is_starred? t('studio.unstarApp', { ns: 'app' }): t('studio.starApp', { ns: 'app' })@@ -956,7 +1051,7 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement</div></div></Link>- {isCurrentWorkspaceEditor && (+ {shouldShowAppTags && (<divclassName="absolute top-[104px] right-3 left-3 flex h-[26px] min-w-0 items-start"onClick={(e) => {@@ -967,6 +1062,7 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement<AppCardTagsappId={app.id}tags={app.tags}+ canBindOrUnbindTags={appACLCapabilities.canEdit}onOpenTagManagement={onOpenTagManagement}onTagsChange={onRefresh}/>@@ -1003,7 +1099,7 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement/><TooltipContent>{starActionLabel}</TooltipContent></Tooltip>- {isCurrentWorkspaceEditor && (+ {shouldShowOperationsMenu && (<DropdownMenu modal={false} open={isOperationsMenuOpen} onOpenChange={setIsOperationsMenuOpen}><DropdownMenuTriggeraria-label={t('operation.more', { ns: 'common' })}@@ -1028,28 +1124,40 @@ export function AppCard({ app, onlineUsers = [], onRefresh, onOpenTagManagement? (<AppCardOperationsMenuContentapp={app}+ shouldShowEditOption={shouldShowEditOption}+ shouldShowDuplicateOption={shouldShowDuplicateOption}+ shouldShowExportOption={shouldShowExportOption}shouldShowSwitchOption={shouldShowSwitchOption}shouldShowAccessControlOption={shouldShowAccessControlOption}+ shouldShowAccessConfigOption={shouldShowAccessConfigOption}+ shouldShowDeleteOption={shouldShowDeleteOption}onEdit={handleShowEditModal}onDuplicate={handleShowDuplicateModal}onExport={exportCheck}onSwitch={handleShowSwitchModal}onDelete={handleShowDeleteConfirm}onAccessControl={handleShowAccessControl}+ onAccessConfig={handleOpenAccessConfig}/>): (<AppCardOperationsMenuapp={app}+ shouldShowEditOption={shouldShowEditOption}+ shouldShowDuplicateOption={shouldShowDuplicateOption}+ shouldShowExportOption={shouldShowExportOption}shouldShowSwitchOption={shouldShowSwitchOption}shouldShowOpenInExploreOption={!app.has_draft_trigger}shouldShowAccessControlOption={shouldShowAccessControlOption}+ shouldShowAccessConfigOption={shouldShowAccessConfigOption}+ shouldShowDeleteOption={shouldShowDeleteOption}onEdit={handleShowEditModal}onDuplicate={handleShowDuplicateModal}onExport={exportCheck}onSwitch={handleShowSwitchModal}onDelete={handleShowDeleteConfirm}onAccessControl={handleShowAccessControl}+ onAccessConfig={handleOpenAccessConfig}/>)}</DropdownMenuContent>diff --git a/web/app/components/apps/app-list-creation-modals.tsx b/web/app/components/apps/app-list-creation-modals.tsxindex e9e0b30c2f9..de5675c864e 100644--- a/web/app/components/apps/app-list-creation-modals.tsx+++ b/web/app/components/apps/app-list-creation-modals.tsx@@ -14,6 +14,7 @@ const CreateAppTemplateDialog = dynamic(() => import('@/app/components/app/creat})export function AppListCreationModals({+ canCreateApp,category,droppedDSLFile,showCreateFromDSLModal,@@ -26,6 +27,7 @@ export function AppListCreationModals({onSetShowNewAppModal,onSetShowNewAppTemplateDialog,}: {+ canCreateApp: booleancategory: AppListCategorydroppedDSLFile?: FileshowCreateFromDSLModal: boolean@@ -38,6 +40,9 @@ export function AppListCreationModals({onSetShowNewAppModal: (show: boolean) => voidonSetShowNewAppTemplateDialog: (show: boolean) => void}) {+ if (!canCreateApp)+ return null+return (<>{showCreateFromDSLModal && (diff --git a/web/app/components/apps/index.tsx b/web/app/components/apps/index.tsxindex 9c994118839..66a9cd6b67f 100644--- a/web/app/components/apps/index.tsx+++ b/web/app/components/apps/index.tsx@@ -5,6 +5,7 @@ import type { TrackCreateAppParams } from '@/utils/create-app-tracking'import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { useEducationInit } from '@/app/education-apply/hooks'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import AppListContext from '@/context/app-list-context'import useDocumentTitle from '@/hooks/use-document-title'import { useImportDSL } from '@/hooks/use-import-dsl'@@ -13,6 +14,7 @@ import dynamic from '@/next/dynamic'import { useRouter, useSearchParams } from '@/next/navigation'import { fetchAppDetail } from '@/service/explore'import { trackCreateApp } from '@/utils/create-app-tracking'+import { hasPermission } from '@/utils/permission'import List from './list'const DSLConfirmModal = dynamic(() => import('../app/create-from-dsl-modal/dsl-confirm-modal'), { ssr: false })@@ -24,6 +26,8 @@ const Apps = () => {const { t } = useTranslation()const searchParams = useSearchParams()const { replace } = useRouter()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const templateId = searchParams.get('template-id')const templateDismissedRef = useRef(false)@@ -48,12 +52,15 @@ const Apps = () => {const [isShowCreateModal, setIsShowCreateModal] = useState(false)const handleShowFromTryApp = useCallback(() => {+ if (!canCreateApp)+ return+currentCreateAppTrackingRef.current = {source: 'studio_template_preview',templateId: currentTryAppParams?.appId || currentTryAppParams?.app.app_id,}setIsShowCreateModal(true)- }, [currentTryAppParams?.app.app_id, currentTryAppParams?.appId])+ }, [canCreateApp, currentTryAppParams?.app.app_id, currentTryAppParams?.appId])const trackCurrentCreateApp = useCallback((appMode?: TryAppSelection['app']['app']['mode'] | null) => {const currentCreateAppTracking = currentCreateAppTrackingRef.currentconst resolvedAppMode = appMode ?? currentCreateAppModeRef.current@@ -102,6 +109,9 @@ const Apps = () => {}, [handleImportDSLConfirm, onSuccess, trackCurrentCreateApp])const handleMarketplaceTemplateConfirm = useCallback(async (dslContent: string) => {+ if (!canCreateApp)+ return+currentCreateAppModeRef.current = nullcurrentCreateAppTrackingRef.current = {source: 'external',@@ -121,7 +131,7 @@ const Apps = () => {setShowDSLConfirmModal(true)},})- }, [handleImportDSL, handleCloseTemplateModal, onSuccess, templateId, trackCurrentCreateApp])+ }, [canCreateApp, handleImportDSL, handleCloseTemplateModal, onSuccess, templateId, trackCurrentCreateApp])const onCreate: CreateAppModalProps['onConfirm'] = useCallback(async ({name,@@ -130,6 +140,9 @@ const Apps = () => {icon_background,description,}) => {+ if (!canCreateApp)+ return+hideTryAppPanel()const { export_data, mode } = await fetchAppDetail(@@ -154,7 +167,7 @@ const Apps = () => {setShowDSLConfirmModal(true)},})- }, [currApp?.app.id, handleImportDSL, hideTryAppPanel, trackCurrentCreateApp])+ }, [canCreateApp, currApp?.app.id, handleImportDSL, hideTryAppPanel, trackCurrentCreateApp])return (<AppListContext.Provider value={{@@ -202,7 +215,7 @@ const Apps = () => {/>)}- {templateId && !templateDismissedRef.current && (+ {canCreateApp && templateId && !templateDismissedRef.current && (<ImportFromMarketplaceTemplateModaltemplateId={templateId}onClose={handleCloseTemplateModal}diff --git a/web/app/components/apps/list.tsx b/web/app/components/apps/list.tsxindex 58f9604b958..3c7e0c8c72c 100644--- a/web/app/components/apps/list.tsx+++ b/web/app/components/apps/list.tsx@@ -15,6 +15,7 @@ import { CheckModal } from '@/hooks/use-pay'import { usePathname, useRouter, useSearchParams } from '@/next/navigation'import { consoleQuery } from '@/service/client'import { AppModeEnum } from '@/types/app'+import { hasPermission } from '@/utils/permission'import { AppCard } from './app-card'import { AppCardSkeleton } from './app-card-skeleton'import { AppListCreationModals } from './app-list-creation-modals'@@ -40,7 +41,7 @@ function List({}: Props) {const { t } = useTranslation()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()const { onPlanInfoChanged } = useProviderContext()const searchParams = useSearchParams()const pathname = usePathname()@@ -63,16 +64,20 @@ function List({const [showCreateFromDSLModal, setShowCreateFromDSLModal] = useState(false)const [droppedDSLFile, setDroppedDSLFile] = useState<File | undefined>()const [needsRefreshAppList, setNeedsRefreshAppList] = useLocalStorage<string>(NEED_REFRESH_APP_LIST_KEY, '0', { raw: true })+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const handleDSLFileDropped = useCallback((file: File) => {+ if (!canCreateApp)+ return+setDroppedDSLFile(file)setShowCreateFromDSLModal(true)- }, [])+ }, [canCreateApp])const { dragging } = useDSLDragDrop({onDSLFileDropped: handleDSLFileDropped,containerRef,- enabled: isCurrentWorkspaceEditor,+ enabled: canCreateApp,})useEffect(() => {@@ -116,7 +121,6 @@ function List({initialPageParam: 1,placeholderData: keepPreviousData,}),- enabled: !isCurrentWorkspaceDatasetOperator,refetchInterval: systemFeatures.enable_collaboration_mode ? 10000 : false,})@@ -135,7 +139,6 @@ function List({query: starredAppListQuery,},}),- enabled: !isCurrentWorkspaceDatasetOperator,})const refreshAppLists = useCallback(() => {@@ -158,8 +161,6 @@ function List({}, [needsRefreshAppList, refetch, setNeedsRefreshAppList])useEffect(() => {- if (isCurrentWorkspaceDatasetOperator)- returnconst hasMore = hasNextPage ?? truelet observer: IntersectionObserver | undefined@@ -184,7 +185,7 @@ function List({observer.observe(anchorRef.current)}return () => observer?.disconnect()- }, [isLoading, isFetchingNextPage, fetchNextPage, error, hasNextPage, isCurrentWorkspaceDatasetOperator])+ }, [isLoading, isFetchingNextPage, fetchNextPage, error, hasNextPage])const pages = useMemo(() => data?.pages ?? [], [data?.pages])const apps = useMemo(() => pages.flatMap(({ data: pageApps }) => pageApps), [pages])@@ -210,7 +211,19 @@ function List({const hasAnyApp = (pages[0]?.total ?? 0) > 0const hasActiveFilters = category !== 'all' || tagIDs.length > 0 || keywords.trim().length > 0 || debouncedKeywords.trim().length > 0 || creatorIDs.length > 0const showSkeleton = isLoading || (isFetching && pages.length === 0)- const showFirstEmptyState = !showSkeleton && !hasAnyApp && isCurrentWorkspaceEditor && hasResolvedFirstPage && !hasActiveFilters+ const showFirstEmptyState = !showSkeleton && !hasAnyApp && canCreateApp && hasResolvedFirstPage && !hasActiveFilters+ const openCreateBlankModal = useCallback(() => {+ if (canCreateApp)+ setShowNewAppModal(true)+ }, [canCreateApp])+ const openCreateTemplateDialog = useCallback(() => {+ if (canCreateApp)+ setShowNewAppTemplateDialog(true)+ }, [canCreateApp])+ const openCreateFromDSLModal = useCallback(() => {+ if (canCreateApp)+ setShowCreateFromDSLModal(true)+ }, [canCreateApp])return (<>@@ -238,19 +251,19 @@ function List({onKeywordsChange={setKeywords}onCreatorIDsChange={setCreatorIDs}onSortByChange={setSortBy}- onCreateBlank={() => setShowNewAppModal(true)}- onCreateTemplate={() => setShowNewAppTemplateDialog(true)}- onImportDSL={() => setShowCreateFromDSLModal(true)}+ onCreateBlank={openCreateBlankModal}+ onCreateTemplate={openCreateTemplateDialog}+ onImportDSL={openCreateFromDSLModal}onOpenTagManagement={() => setShowTagManagementModal(true)}- showCreateButton={isCurrentWorkspaceEditor}+ showCreateButton={canCreateApp}/></StudioListHeader>{showFirstEmptyState? (<FirstEmptyState- onCreateBlank={() => setShowNewAppModal(true)}- onCreateTemplate={() => setShowNewAppTemplateDialog(true)}- onImportDSL={() => setShowCreateFromDSLModal(true)}+ onCreateBlank={openCreateBlankModal}+ onCreateTemplate={openCreateTemplateDialog}+ onImportDSL={openCreateFromDSLModal}/>): (@@ -258,7 +271,6 @@ function List({{starredApps.length > 0 && (<StarredAppListapps={starredApps}- isCurrentWorkspaceEditor={isCurrentWorkspaceEditor}onRefresh={refreshAppLists}/>)}@@ -287,7 +299,7 @@ function List({</>)}- {isCurrentWorkspaceEditor && !showFirstEmptyState && (+ {canCreateApp && !showFirstEmptyState && (<divclassName={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}role="region"@@ -307,6 +319,7 @@ function List({</div><AppListCreationModals+ canCreateApp={canCreateApp}category={category}droppedDSLFile={droppedDSLFile}showCreateFromDSLModal={showCreateFromDSLModal}diff --git a/web/app/components/apps/new-app-card.tsx b/web/app/components/apps/new-app-card.tsxindex 907e98544e4..bc2c5b767fd 100644--- a/web/app/components/apps/new-app-card.tsx+++ b/web/app/components/apps/new-app-card.tsx@@ -9,6 +9,7 @@ import CreateResourceCard, {createResourceCardActionClassName,createResourceCardActionIconClassName,} from '@/app/components/base/create-resource-card'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import AppListContext from '@/context/app-list-context'import { useProviderContext } from '@/context/provider-context'import dynamic from '@/next/dynamic'@@ -17,6 +18,7 @@ import {useSearchParams,} from '@/next/navigation'import { AppModeEnum } from '@/types/app'+import { hasPermission } from '@/utils/permission'const CreateAppModal = dynamic(() => import('@/app/components/app/create-app-modal'), {ssr: false,@@ -48,10 +50,12 @@ const CreateAppCard = ({const searchParams = useSearchParams()const { replace } = useRouter()const dslUrl = searchParams.get('remoteInstallUrl') || undefined+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const [showNewAppTemplateDialog, setShowNewAppTemplateDialog] = useState(false)const [showNewAppModal, setShowNewAppModal] = useState(false)- const [showCreateFromDSLModal, setShowCreateFromDSLModal] = useState(!!dslUrl)+ const [showCreateFromDSLModal, setShowCreateFromDSLModal] = useState(canCreateApp && !!dslUrl)const activeTab = useMemo(() => {if (dslUrl)@@ -86,6 +90,18 @@ const CreateAppCard = ({}}, [controlHideCreateFromTemplatePanel])+ useEffect(() => {+ if (canCreateApp)+ return++ setShowNewAppModal(false)+ setShowNewAppTemplateDialog(false)+ setShowCreateFromDSLModal(false)+ }, [canCreateApp])++ if (!canCreateApp)+ return null+return (<><CreateResourceCarddiff --git a/web/app/components/apps/starred-app-card.tsx b/web/app/components/apps/starred-app-card.tsxindex 2d03d766962..1d22a3a4b3b 100644--- a/web/app/components/apps/starred-app-card.tsx+++ b/web/app/components/apps/starred-app-card.tsx@@ -5,6 +5,7 @@ import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { AppTypeIcon } from '@/app/components/app/type-selector'import AppIcon from '@/app/components/base/app-icon'+import { useSelector as useAppContextSelector } from '@/context/app-context'import Link from '@/next/link'import { getRedirectionPath } from '@/utils/app-redirection'import { formatTime } from '@/utils/time'@@ -12,12 +13,13 @@ import { AppCardActionBar } from './app-card'type StarredAppCardProps = {app: App- isCurrentWorkspaceEditor: booleanonRefresh?: () => void}-export function StarredAppCard({ app, isCurrentWorkspaceEditor, onRefresh }: StarredAppCardProps) {+export function StarredAppCard({ app, onRefresh }: StarredAppCardProps) {const { t } = useTranslation()+ const currentUserId = useAppContextSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)const editTimeText = useMemo(() => {const timestamp = app.updated_at || app.created_at@@ -30,11 +32,16 @@ export function StarredAppCard({ app, isCurrentWorkspaceEditor, onRefresh }: Sta})return `${t('segment.editedAt', { ns: 'datasetDocuments' })} ${timeText}`}, [app.created_at, app.updated_at, t])+ const href = getRedirectionPath(app, {+ currentUserId,+ resourceMaintainer: app.maintainer,+ workspacePermissionKeys,+ })return (<div className="group relative"><Link- href={getRedirectionPath(isCurrentWorkspaceEditor, app)}+ href={href}className="flex h-[72px] min-w-0 items-center gap-3 overflow-hidden rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg px-4 py-3 shadow-xs outline-hidden transition-shadow duration-200 hover:shadow-lg focus-visible:ring-2 focus-visible:ring-state-accent-solid"><div className="relative shrink-0">diff --git a/web/app/components/apps/starred-app-list.tsx b/web/app/components/apps/starred-app-list.tsxindex 2b106cff515..de527a07a7b 100644--- a/web/app/components/apps/starred-app-list.tsx+++ b/web/app/components/apps/starred-app-list.tsx@@ -7,7 +7,6 @@ import { StarredAppCard } from './starred-app-card'type StarredAppListProps = {apps: App[]- isCurrentWorkspaceEditor: booleanonRefresh?: () => void}@@ -23,7 +22,6 @@ function SectionDivider({ label }: { label: string }) {export function StarredAppList({apps,- isCurrentWorkspaceEditor,onRefresh,}: StarredAppListProps) {const { t } = useTranslation()@@ -39,7 +37,6 @@ export function StarredAppList({<StarredAppCardkey={app.id}app={app}- isCurrentWorkspaceEditor={isCurrentWorkspaceEditor}onRefresh={onRefresh}/>))}diff --git a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsxindex bd3de0cec3a..8281de6fced 100644--- a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx+++ b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx@@ -150,6 +150,7 @@ const mockContextValue: ChatContextValue = {onAnnotationAdded: vi.fn(),onAnnotationEdited: vi.fn(),onAnnotationRemoved: vi.fn(),+ readonly: false,}vi.mock('../../context', () => ({@@ -205,6 +206,7 @@ describe('Operation', () => {mockContextValue.onAnnotationAdded = vi.fn()mockContextValue.onAnnotationEdited = vi.fn()mockContextValue.onAnnotationRemoved = vi.fn()+ mockContextValue.readonly = falsemockProviderContext.plan.usage.annotatedResponse = 0mockProviderContext.enableBilling = falsemockAddAnnotation.mockResolvedValue({ id: 'ann-new', account: { name: 'Test User' } })@@ -243,6 +245,30 @@ describe('Operation', () => {expect(screen.getByTestId('annotation-ctrl'))!.toBeInTheDocument()})+ it('should hide annotation button when chat is readonly', () => {+ mockContextValue.readonly = true+ mockContextValue.config = makeChatConfig({+ supportAnnotation: true,+ annotation_reply: { id: 'ar-1', score_threshold: 0.5, embedding_model: { embedding_provider_name: '', embedding_model_name: '' }, enabled: true },+ })++ renderOperation()++ expect(screen.queryByTestId('annotation-ctrl')).not.toBeInTheDocument()+ })++ it('should hide annotation button when annotation callbacks are incomplete', () => {+ mockContextValue.onAnnotationEdited = undefined+ mockContextValue.config = makeChatConfig({+ supportAnnotation: true,+ annotation_reply: { id: 'ar-1', score_threshold: 0.5, embedding_model: { embedding_provider_name: '', embedding_model_name: '' }, enabled: true },+ })++ renderOperation()++ expect(screen.queryByTestId('annotation-ctrl')).not.toBeInTheDocument()+ })+it('should show prompt log when showPromptLog is true', () => {renderOperation({ ...baseProps, showPromptLog: true })expect(screen.getByTestId('log-btn'))!.toBeInTheDocument()@@ -307,6 +333,7 @@ describe('Operation', () => {renderOperation({ ...baseProps, item })expect(screen.queryByTestId('audio-btn')).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: 'operation.copy' })).not.toBeInTheDocument()+ expect(screen.queryByTestId('annotation-ctrl')).not.toBeInTheDocument()})})@@ -804,40 +831,22 @@ describe('Operation', () => {expect(copy).toHaveBeenCalledWith('Hello world')})- it('should handle editing annotation missing onAnnotationEdited gracefully', async () => {- const user = userEvent.setup()+ it('should hide cached annotation edit controls when chat is readonly', () => {+ mockContextValue.readonly = truemockContextValue.config = makeChatConfig({supportAnnotation: true,annotation_reply: { id: 'ar-1', score_threshold: 0.5, embedding_model: { embedding_provider_name: '', embedding_model_name: '' }, enabled: true },appId: 'test-app',})- mockContextValue.onAnnotationEdited = undefinedconst item = { ...baseItem, annotation: { id: 'ann-1', created_at: 123, authorName: 'test author' } as unknown as Record<string, unknown> } as unknown as ChatItem- renderOperation({ ...baseProps, item })- const editBtn = screen.getByTestId('annotation-edit-btn')- await user.click(editBtn)- await user.click(screen.getByTestId('modal-edit'))- expect(mockContextValue.onAnnotationEdited).toBeUndefined()- })- it('should handle adding annotation missing onAnnotationAdded gracefully', async () => {- const user = userEvent.setup()- mockContextValue.config = makeChatConfig({- supportAnnotation: true,- annotation_reply: { id: 'ar-1', score_threshold: 0.5, embedding_model: { embedding_provider_name: '', embedding_model_name: '' }, enabled: true },- appId: 'test-app',- })- mockContextValue.onAnnotationAdded = undefined- const item = { ...baseItem, annotation: { id: 'ann-1', created_at: 123, authorName: 'test author' } as unknown as Record<string, unknown> } as unknown as ChatItemrenderOperation({ ...baseProps, item })- const editBtn = screen.getByTestId('annotation-edit-btn')- await user.click(editBtn)- await user.click(screen.getByTestId('modal-add'))- expect(mockContextValue.onAnnotationAdded).toBeUndefined()++ expect(screen.queryByTestId('annotation-edit-btn')).not.toBeInTheDocument()+ expect(screen.queryByTestId('edit-reply-modal')).not.toBeInTheDocument()})- it('should handle removing annotation missing onAnnotationRemoved gracefully', async () => {- const user = userEvent.setup()+ it('should hide cached annotation edit controls when mutation callbacks are missing', () => {mockContextValue.config = makeChatConfig({supportAnnotation: true,annotation_reply: { id: 'ar-1', score_threshold: 0.5, embedding_model: { embedding_provider_name: '', embedding_model_name: '' }, enabled: true },@@ -845,11 +854,11 @@ describe('Operation', () => {})mockContextValue.onAnnotationRemoved = undefinedconst item = { ...baseItem, annotation: { id: 'ann-1', created_at: 123, authorName: 'test author' } as unknown as Record<string, unknown> } as unknown as ChatItem+renderOperation({ ...baseProps, item })- const editBtn = screen.getByTestId('annotation-edit-btn')- await user.click(editBtn)- await user.click(screen.getByTestId('modal-remove'))- expect(mockContextValue.onAnnotationRemoved).toBeUndefined()++ expect(screen.queryByTestId('annotation-edit-btn')).not.toBeInTheDocument()+ expect(screen.queryByTestId('edit-reply-modal')).not.toBeInTheDocument()})})})diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsxindex 0fac08ede14..f0097eeee8f 100644--- a/web/app/components/base/chat/chat/answer/operation.tsx+++ b/web/app/components/base/chat/chat/answer/operation.tsx@@ -73,6 +73,7 @@ function Operation({onAnnotationRemoved,onFeedback,onRegenerate,+ readonly,} = useChatContext()const [isShowReplyModal, setIsShowReplyModal] = useState(false)const [isShowFeedbackModal, setIsShowFeedbackModal] = useState(false)@@ -108,6 +109,8 @@ function Operation({const shouldShowUserFeedbackBar = !isOpeningStatement && config?.supportFeedback && !!onFeedback && !config?.supportAnnotationconst shouldShowAdminFeedbackBar = !isOpeningStatement && config?.supportFeedback && !!onFeedback && !!config?.supportAnnotation+ const canManageAnnotation = !readonly && !!onAnnotationAdded && !!onAnnotationEdited && !!onAnnotationRemoved+ const shouldShowAnnotationAction = canManageAnnotation && !!config?.supportAnnotation && !!config.annotation_reply?.enabled && !humanInputFormDataList?.lengthconst userFeedbackLabel = t('table.header.userRate', { ns: 'appLog' }) || 'User feedback'const adminFeedbackLabel = t('table.header.adminRate', { ns: 'appLog' }) || 'Admin feedback'@@ -174,7 +177,7 @@ function Operation({width += 28 + 8if (!isOpeningStatement && config?.text_to_speech?.enabled)width += 26- if (!isOpeningStatement && config?.supportAnnotation && config?.annotation_reply?.enabled)+ if (!isOpeningStatement && shouldShowAnnotationAction)width += 26if (shouldShowUserFeedbackBar)width += hasUserFeedback ? 28 + 8 : 60 + 8@@ -182,7 +185,7 @@ function Operation({width += (hasAdminFeedback ? 28 : 60) + 8 + (hasUserFeedback ? 28 : 0)return width- }, [config?.annotation_reply?.enabled, config?.supportAnnotation, config?.text_to_speech?.enabled, hasAdminFeedback, hasUserFeedback, isOpeningStatement, shouldShowAdminFeedbackBar, shouldShowUserFeedbackBar, showPromptLog])+ }, [config?.text_to_speech?.enabled, hasAdminFeedback, hasUserFeedback, isOpeningStatement, shouldShowAdminFeedbackBar, shouldShowAnnotationAction, shouldShowUserFeedbackBar, showPromptLog])const positionRight = useMemo(() => operationWidth < maxSize, [operationWidth, maxSize])@@ -339,7 +342,7 @@ function Operation({<span aria-hidden="true" className="i-ri-reset-left-line size-4" /></ActionButton>)}- {config?.supportAnnotation && config.annotation_reply?.enabled && !humanInputFormDataList?.length && (+ {shouldShowAnnotationAction && (<AnnotationCtrlButtonappId={config?.appId || ''}messageId={id}@@ -353,19 +356,21 @@ function Operation({</div>)}</div>- <EditReplyModal- isShow={isShowReplyModal}- onHide={() => setIsShowReplyModal(false)}- query={question}- answer={content}- onEdited={(editedQuery, editedAnswer) => onAnnotationEdited?.(editedQuery, editedAnswer, index)}- onAdded={(annotationId, authorName, editedQuery, editedAnswer) => onAnnotationAdded?.(annotationId, authorName, editedQuery, editedAnswer, index)}- appId={config?.appId || ''}- messageId={id}- annotationId={annotation?.id || ''}- createdAt={annotation?.created_at}- onRemove={() => onAnnotationRemoved?.(index)}- />+ {canManageAnnotation && (+ <EditReplyModal+ isShow={isShowReplyModal}+ onHide={() => setIsShowReplyModal(false)}+ query={question}+ answer={content}+ onEdited={(editedQuery, editedAnswer) => onAnnotationEdited?.(editedQuery, editedAnswer, index)}+ onAdded={(annotationId, authorName, editedQuery, editedAnswer) => onAnnotationAdded?.(annotationId, authorName, editedQuery, editedAnswer, index)}+ appId={config?.appId || ''}+ messageId={id}+ annotationId={annotation?.id || ''}+ createdAt={annotation?.created_at}+ onRemove={() => onAnnotationRemoved?.(index)}+ />+ )}{isShowFeedbackModal && (<Dialogopendiff --git a/web/app/components/base/chat/chat/chat-input-area/index.tsx b/web/app/components/base/chat/chat/chat-input-area/index.tsxindex 406748126ea..ea9e631cba9 100644--- a/web/app/components/base/chat/chat/chat-input-area/index.tsx+++ b/web/app/components/base/chat/chat/chat-input-area/index.tsx@@ -25,6 +25,7 @@ type ChatInputAreaProps = {botName?: stringshowFeatureBar?: booleanshowFileUpload?: boolean+ featureBarReadonly?: booleanfeatureBarDisabled?: booleanonFeatureBarClick?: (state: boolean) => voidvisionConfig?: FileUpload@@ -43,7 +44,7 @@ type ChatInputAreaProps = {*/sendOnEnter?: boolean}-const ChatInputArea = ({ readonly, botName, showFeatureBar, showFileUpload, featureBarDisabled, onFeatureBarClick, visionConfig, speechToTextConfig = { enabled: true }, onSend, inputs = {}, inputsForm = [], theme, isResponding, disabled, sendOnEnter = true }: ChatInputAreaProps) => {+const ChatInputArea = ({ readonly, botName, showFeatureBar, showFileUpload, featureBarReadonly = readonly, featureBarDisabled, onFeatureBarClick, visionConfig, speechToTextConfig = { enabled: true }, onSend, inputs = {}, inputsForm = [], theme, isResponding, disabled, sendOnEnter = true }: ChatInputAreaProps) => {const { t } = useTranslation()const { wrapperRef, textareaRef, textValueRef, holdSpaceRef, handleTextareaResize, isMultipleLine } = useTextAreaHeight()const [query, setQuery] = useState('')@@ -154,7 +155,7 @@ const ChatInputArea = ({ readonly, botName, showFeatureBar, showFileUpload, feat</div>{isMultipleLine && (<div className="px-[9px]">{operation}</div>)}</div>- {showFeatureBar && (<FeatureBar showFileUpload={showFileUpload} disabled={featureBarDisabled} onFeatureBarClick={readonly ? noop : onFeatureBarClick} hideEditEntrance={readonly} />)}+ {showFeatureBar && (<FeatureBar showFileUpload={showFileUpload} disabled={featureBarDisabled} onFeatureBarClick={featureBarReadonly ? noop : onFeatureBarClick} hideEditEntrance={featureBarReadonly} />)}</>)}diff --git a/web/app/components/base/chat/chat/index.tsx b/web/app/components/base/chat/chat/index.tsxindex f4a32e56072..ffa4158521e 100644--- a/web/app/components/base/chat/chat/index.tsx+++ b/web/app/components/base/chat/chat/index.tsx@@ -64,6 +64,7 @@ export type ChatProps = {switchSibling?: (siblingMessageId: string) => voidshowFeatureBar?: booleanshowFileUpload?: boolean+ featureBarReadonly?: booleanonFeatureBarClick?: (state: boolean) => voidnoSpacing?: booleaninputDisabled?: boolean@@ -109,6 +110,7 @@ const Chat: FC<ChatProps> = ({switchSibling,showFeatureBar,showFileUpload,+ featureBarReadonly,onFeatureBarClick,noSpacing,inputDisabled,@@ -242,6 +244,7 @@ const Chat: FC<ChatProps> = ({disabled={inputDisabled}showFeatureBar={showFeatureBar}showFileUpload={showFileUpload}+ featureBarReadonly={featureBarReadonly}featureBarDisabled={isResponding}onFeatureBarClick={onFeatureBarClick}visionConfig={config?.file_upload}diff --git a/web/app/components/base/icons/src/vender/solid/arrows/index.ts b/web/app/components/base/icons/src/vender/solid/arrows/index.tsindex d89a969bd44..e27f5526a31 100644--- a/web/app/components/base/icons/src/vender/solid/arrows/index.ts+++ b/web/app/components/base/icons/src/vender/solid/arrows/index.ts@@ -1,3 +1 @@-export { default as ArrowDownDoubleLine } from './ArrowDownDoubleLine'export { default as ArrowDownRoundFill } from './ArrowDownRoundFill'-export { default as ArrowUpDoubleLine } from './ArrowUpDoubleLine'diff --git a/web/app/components/base/param-item/index.tsx b/web/app/components/base/param-item/index.tsxindex 8599a607232..d4cb2979fe1 100644--- a/web/app/components/base/param-item/index.tsx+++ b/web/app/components/base/param-item/index.tsx@@ -25,11 +25,12 @@ type Props = Readonly<{min?: numbermax: numberonChange: (key: string, value: number) => void+ disabled?: booleanhasSwitch?: booleanonSwitchChange?: (key: string, enable: boolean) => void}>-const ParamItem: FC<Props> = ({ className, id, name, noTooltip, tip, step = 0.1, min = 0, max, value, enable, onChange, hasSwitch, onSwitchChange }) => {+const ParamItem: FC<Props> = ({ className, id, name, noTooltip, tip, step = 0.1, min = 0, max, value, enable, onChange, disabled = false, hasSwitch, onSwitchChange }) => {return (<FieldsetRoot className={className}><FieldsetLegend className="sr-only">{name}</FieldsetLegend>@@ -40,6 +41,7 @@ const ParamItem: FC<Props> = ({ className, id, name, noTooltip, tip, step = 0.1,size="md"className="mr-2"checked={enable}+ disabled={disabled}onCheckedChange={async (val) => {onSwitchChange?.(id, val)}}@@ -56,7 +58,7 @@ const ParamItem: FC<Props> = ({ className, id, name, noTooltip, tip, step = 0.1,<div className="mt-1 flex items-center"><div className="mr-3 flex shrink-0 items-center"><NumberField- disabled={!enable}+ disabled={disabled || !enable}min={min}max={max}step={step}@@ -75,7 +77,7 @@ const ParamItem: FC<Props> = ({ className, id, name, noTooltip, tip, step = 0.1,<div className="flex grow items-center"><SliderclassName="w-full"- disabled={!enable}+ disabled={disabled || !enable}value={max < 5 ? value * 100 : value}min={min < 1 ? min * 100 : min}max={max < 5 ? max * 100 : max}diff --git a/web/app/components/base/param-item/score-threshold-item.tsx b/web/app/components/base/param-item/score-threshold-item.tsxindex dbbf0a96edd..5c7540d1404 100644--- a/web/app/components/base/param-item/score-threshold-item.tsx+++ b/web/app/components/base/param-item/score-threshold-item.tsx@@ -11,6 +11,7 @@ type Props = Readonly<{enable: booleanhasSwitch?: booleanonSwitchChange?: (key: string, enable: boolean) => void+ disabled?: boolean}>const VALUE_LIMIT = {@@ -39,6 +40,7 @@ const ScoreThresholdItem: FC<Props> = ({onChange,hasSwitch,onSwitchChange,+ disabled = false,}) => {const { t } = useTranslation()const handleParamChange = (key: string, nextValue: number) => {@@ -56,6 +58,7 @@ const ScoreThresholdItem: FC<Props> = ({value={safeValue}enable={enable}onChange={handleParamChange}+ disabled={disabled}hasSwitch={hasSwitch}onSwitchChange={onSwitchChange}/>diff --git a/web/app/components/base/param-item/top-k-item.tsx b/web/app/components/base/param-item/top-k-item.tsxindex 0449eb34d7f..120d3e0b453 100644--- a/web/app/components/base/param-item/top-k-item.tsx+++ b/web/app/components/base/param-item/top-k-item.tsx@@ -10,6 +10,7 @@ type Props = Readonly<{value: numberonChange: (key: string, value: number) => voidenable: boolean+ disabled?: boolean}>const maxTopK = env.NEXT_PUBLIC_TOP_K_MAX_VALUE@@ -25,6 +26,7 @@ const TopKItem: FC<Props> = ({value,enable,onChange,+ disabled = false,}) => {const { t } = useTranslation()const handleParamChange = (key: string, value: number) => {@@ -42,6 +44,7 @@ const TopKItem: FC<Props> = ({{...VALUE_LIMIT}value={value}enable={enable}+ disabled={disabled}onChange={handleParamChange}/>)diff --git a/web/app/components/billing/apps-full-in-dialog/__tests__/index.spec.tsx b/web/app/components/billing/apps-full-in-dialog/__tests__/index.spec.tsxindex 701be3f5a8a..ca0a355c547 100644--- a/web/app/components/billing/apps-full-in-dialog/__tests__/index.spec.tsx+++ b/web/app/components/billing/apps-full-in-dialog/__tests__/index.spec.tsx@@ -109,6 +109,7 @@ const buildAppContext = (overrides: Partial<AppContextValue> = {}): AppContextValangGeniusVersionInfo,isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],}const useSelector: AppContextValue['useSelector'] = selector => selector({ ...base, useSelector })return {diff --git a/web/app/components/billing/billing-page/__tests__/index.spec.tsx b/web/app/components/billing/billing-page/__tests__/index.spec.tsxindex 929e16afb20..d9f296e7978 100644--- a/web/app/components/billing/billing-page/__tests__/index.spec.tsx+++ b/web/app/components/billing/billing-page/__tests__/index.spec.tsx@@ -5,10 +5,19 @@ let currentBillingUrl: string | null = 'https://billing'let fetching = falselet isManager = truelet enableBilling = true+let workspacePermissionKeys: string[] = ['billing.subscription.manage']const refetchMock = vi.fn()const openAsyncWindowMock = vi.fn()+type BillingUrlCallback = () => Promise<string | null>+type BillingWindowOptions = {+ immediateUrl: string | null+ features: string+ onError: (err: Error) => void+}+type OpenAsyncWindowCall = [BillingUrlCallback, BillingWindowOptions]+vi.mock('@/service/use-billing', () => ({useBillingUrl: () => ({data: currentBillingUrl,@@ -24,6 +33,7 @@ vi.mock('@/hooks/use-async-window-open', () => ({vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: isManager,+ workspacePermissionKeys,}),}))@@ -44,16 +54,25 @@ describe('Billing', () => {fetching = falseisManager = trueenableBilling = true+ workspacePermissionKeys = ['billing.subscription.manage']refetchMock.mockResolvedValue({ data: 'https://billing' })})- it('hides the billing action when user is not manager or billing is disabled', () => {+ it('shows the billing action when subscription management permission is granted without manager role', () => {isManager = false++ render(<Billing />)++ expect(screen.getByRole('button', { name: /billing\.viewBillingTitle/ })).toBeInTheDocument()+ })++ it('hides the billing action when subscription management permission is missing or billing is disabled', () => {+ workspacePermissionKeys = []render(<Billing />)expect(screen.queryByRole('button', { name: /billing\.viewBillingTitle/ })).not.toBeInTheDocument()vi.clearAllMocks()- isManager = true+ workspacePermissionKeys = ['billing.subscription.manage']enableBilling = falserender(<Billing />)expect(screen.queryByRole('button', { name: /billing\.viewBillingTitle/ })).not.toBeInTheDocument()@@ -66,7 +85,7 @@ describe('Billing', () => {fireEvent.click(actionButton)await waitFor(() => expect(openAsyncWindowMock).toHaveBeenCalled())- const [, options] = (openAsyncWindowMock.mock.calls[0] ?? []) as [unknown, any]+ const [, options] = openAsyncWindowMock.mock.calls[0] as OpenAsyncWindowCallexpect(options).toMatchObject({immediateUrl: currentBillingUrl,features: 'noopener,noreferrer',@@ -82,7 +101,7 @@ describe('Billing', () => {fireEvent.click(actionButton)await waitFor(() => expect(openAsyncWindowMock).toHaveBeenCalled())- const [asyncCallback] = (openAsyncWindowMock.mock.calls[0] ?? []) as [any]+ const [asyncCallback] = openAsyncWindowMock.mock.calls[0] as OpenAsyncWindowCall// Execute the async callback passed to openAsyncWindowconst result = await asyncCallback()@@ -98,7 +117,7 @@ describe('Billing', () => {fireEvent.click(actionButton)await waitFor(() => expect(openAsyncWindowMock).toHaveBeenCalled())- const [asyncCallback] = (openAsyncWindowMock.mock.calls[0] ?? []) as [any]+ const [asyncCallback] = openAsyncWindowMock.mock.calls[0] as OpenAsyncWindowCall// Execute the async callback when url is nullconst result = await asyncCallback()@@ -113,7 +132,7 @@ describe('Billing', () => {fireEvent.click(actionButton)await waitFor(() => expect(openAsyncWindowMock).toHaveBeenCalled())- const [, options] = (openAsyncWindowMock.mock.calls[0] ?? []) as [unknown, any]+ const [, options] = openAsyncWindowMock.mock.calls[0] as OpenAsyncWindowCall// Execute the onError callbackconst testError = new Error('Test error')diff --git a/web/app/components/billing/billing-page/index.tsx b/web/app/components/billing/billing-page/index.tsxindex afafbe447f7..4b1d4424c04 100644--- a/web/app/components/billing/billing-page/index.tsx+++ b/web/app/components/billing/billing-page/index.tsx@@ -1,21 +1,20 @@'use client'import type { FC } from 'react'-import {- RiArrowRightUpLine,-} from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'import { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'import { useBillingUrl } from '@/service/use-billing'+import { BillingPermission, hasPermission } from '@/utils/permission'import PlanComp from '../plan'const Billing: FC = () => {const { t } = useTranslation()- const { isCurrentWorkspaceManager } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()const { enableBilling } = useProviderContext()- const { data: billingUrl, isFetching, refetch } = useBillingUrl(enableBilling && isCurrentWorkspaceManager)+ const canManageBillingSubscription = hasPermission(workspacePermissionKeys, BillingPermission.SubscriptionManage)+ const { data: billingUrl, isFetching, refetch } = useBillingUrl(enableBilling && canManageBillingSubscription)const openAsyncWindow = useAsyncWindowOpen()const handleOpenBilling = async () => {@@ -36,7 +35,7 @@ const Billing: FC = () => {return (<div><PlanComp loc="billing-page" />- {enableBilling && isCurrentWorkspaceManager && (+ {enableBilling && canManageBillingSubscription && (<buttontype="button"className="mt-3 flex w-full items-center justify-between rounded-xl bg-background-section-burn px-4 py-3"@@ -49,7 +48,7 @@ const Billing: FC = () => {</div><span className="inline-flex h-8 w-24 items-center justify-center gap-0.5 rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 py-2 text-saas-dify-blue-accessible shadow-[0_1px_2px_rgba(9,9,11,0.05)] backdrop-blur-[5px]"><span className="system-sm-medium leading-none">{t('viewBillingAction', { ns: 'billing' })}</span>- <RiArrowRightUpLine className="size-4" />+ <span className="i-ri-arrow-right-up-line size-4" /></span></button>)}diff --git a/web/app/components/billing/hooks/use-education-discount.ts b/web/app/components/billing/hooks/use-education-discount.tsindex dedad4707ee..07977bf4f16 100644--- a/web/app/components/billing/hooks/use-education-discount.ts+++ b/web/app/components/billing/hooks/use-education-discount.ts@@ -4,18 +4,20 @@ import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { useAppContext } from '@/context/app-context'import { fetchSubscriptionUrls } from '@/service/billing'+import { BillingPermission, hasPermission } from '@/utils/permission'import { Plan } from '../type'export const useEducationDiscount = () => {const { t } = useTranslation()- const { isCurrentWorkspaceManager } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()const [isEducationDiscountLoading, setIsEducationDiscountLoading] = useState(false)+ const canManageBilling = hasPermission(workspacePermissionKeys, BillingPermission.Manage)const handleEducationDiscount = useCallback(async () => {if (isEducationDiscountLoading)return- if (!isCurrentWorkspaceManager) {+ if (!canManageBilling) {toast.error(t('buyPermissionDeniedTip', { ns: 'billing' }))return}@@ -28,7 +30,7 @@ export const useEducationDiscount = () => {finally {setIsEducationDiscountLoading(false)}- }, [isCurrentWorkspaceManager, isEducationDiscountLoading, t])+ }, [canManageBilling, isEducationDiscountLoading, t])return {handleEducationDiscount,diff --git a/web/app/components/billing/plan/__tests__/index.spec.tsx b/web/app/components/billing/plan/__tests__/index.spec.tsxindex 618da01749e..103cd5e8a10 100644--- a/web/app/components/billing/plan/__tests__/index.spec.tsx+++ b/web/app/components/billing/plan/__tests__/index.spec.tsx@@ -12,6 +12,7 @@ let currentPath = '/billing'const push = vi.fn()let isCurrentWorkspaceManager = true+let workspacePermissionKeys = ['billing.manage']let assignedHref = ''const originalLocation = window.location@@ -42,6 +43,7 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({userProfile: { email: '[email protected]' },isCurrentWorkspaceManager,+ workspacePermissionKeys,}),}))@@ -127,6 +129,7 @@ describe('PlanComp', () => {currentPath = '/billing'isPending = falseisCurrentWorkspaceManager = true+ workspacePermissionKeys = ['billing.manage']mockConfig.isCloudEdition = trueassignedHref = ''providerContextMock.mockReturnValue({@@ -255,8 +258,9 @@ describe('PlanComp', () => {expect(screen.queryByText('education.useEducationDiscount')).not.toBeInTheDocument()})- it('does not show education discount button for non-manager sandbox education accounts', () => {+ it('does not show education discount button without billing manage permission', () => {isCurrentWorkspaceManager = false+ workspacePermissionKeys = []providerContextMock.mockReturnValue({plan: { ...planMock, type: Plan.sandbox },enableEducationPlan: true,diff --git a/web/app/components/billing/plan/index.tsx b/web/app/components/billing/plan/index.tsxindex e9519c9edf0..337c88e9597 100644--- a/web/app/components/billing/plan/index.tsx+++ b/web/app/components/billing/plan/index.tsx@@ -4,7 +4,6 @@ import { Button } from '@langgenius/dify-ui/button'import {RiBook2Line,RiFileEditLine,- RiGraduationCapLine,RiGroupLine,} from '@remixicon/react'import { useUnmountedRef } from 'ahooks'@@ -22,6 +21,7 @@ import { useModalContextSelector } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { usePathname, useRouter } from '@/next/navigation'import { useEducationVerify } from '@/service/use-education'+import { BillingPermission, hasPermission } from '@/utils/permission'import { getDaysUntilEndOfMonth } from '@/utils/time'import { Loading } from '../../base/icons/src/public/thought'import { NUM_INFINITE } from '../config'@@ -42,7 +42,7 @@ const PlanComp: FC<Props> = ({const { t } = useTranslation()const router = useRouter()const path = usePathname()- const { userProfile, isCurrentWorkspaceManager } = useAppContext()+ const { userProfile, workspacePermissionKeys } = useAppContext()const { plan, enableEducationPlan, allowRefreshEducationVerify, isEducationAccount } = useProviderContext()const isAboutToExpire = allowRefreshEducationVerifyconst {@@ -70,6 +70,7 @@ const PlanComp: FC<Props> = ({const [showModal, setShowModal] = React.useState(false)const { handleEducationDiscount, isEducationDiscountLoading } = useEducationDiscount()+ const canManageBilling = hasPermission(workspacePermissionKeys, BillingPermission.Manage)const { mutateAsync, isPending } = useEducationVerify()const setShowAccountSettingModal = useModalContextSelector(s => s.setShowAccountSettingModal)const setEducationVerifying = useSetLocalStorage<string>(EDUCATION_VERIFYING_LOCALSTORAGE_ITEM, { raw: true })@@ -116,14 +117,14 @@ const PlanComp: FC<Props> = ({<div className="flex shrink-0 items-center gap-1">{IS_CLOUD_EDITION && enableEducationPlan && (!isEducationAccount || isAboutToExpire) && (<Button variant="ghost" onClick={handleVerify} disabled={isPending}>- <RiGraduationCapLine className="mr-1 size-4" />+ <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 && enableEducationPlan && isEducationAccount && type === Plan.sandbox && isCurrentWorkspaceManager && (+ {IS_CLOUD_EDITION && enableEducationPlan && isEducationAccount && type === Plan.sandbox && canManageBilling && (<Button variant="ghost" onClick={handleEducationDiscount} disabled={isEducationDiscountLoading}>- <RiGraduationCapLine className="mr-1 size-4" />+ <span className="mr-1 i-ri-graduation-cap-line size-4" />{t('useEducationDiscount', { ns: 'education' })}{isEducationDiscountLoading && <Loading className="ml-1 animate-spin-slow" />}</Button>diff --git a/web/app/components/billing/pricing/__tests__/dialog.spec.tsx b/web/app/components/billing/pricing/__tests__/dialog.spec.tsxindex c1ed3898de4..9b166980207 100644--- a/web/app/components/billing/pricing/__tests__/dialog.spec.tsx+++ b/web/app/components/billing/pricing/__tests__/dialog.spec.tsx@@ -70,7 +70,10 @@ describe('Pricing dialog lifecycle', () => {beforeEach(() => {vi.clearAllMocks()latestOnOpenChange = undefined- ;(useAppContext as Mock).mockReturnValue({ isCurrentWorkspaceManager: true })+ ;(useAppContext as Mock).mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['billing.manage'],+ });(useProviderContext as Mock).mockReturnValue({plan: {type: Plan.sandbox,diff --git a/web/app/components/billing/pricing/__tests__/index.spec.tsx b/web/app/components/billing/pricing/__tests__/index.spec.tsxindex 264c80c5e76..3a6d81aa0a2 100644--- a/web/app/components/billing/pricing/__tests__/index.spec.tsx+++ b/web/app/components/billing/pricing/__tests__/index.spec.tsx@@ -53,7 +53,10 @@ describe('Pricing', () => {beforeEach(() => {vi.clearAllMocks()mockLanguage = 'en'- ;(useAppContext as Mock).mockReturnValue({ isCurrentWorkspaceManager: true })+ ;(useAppContext as Mock).mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['billing.manage'],+ });(useProviderContext as Mock).mockReturnValue({plan: {type: Plan.sandbox,@@ -76,6 +79,10 @@ describe('Pricing', () => {})it('should default to yearly billing for education accounts', () => {+ ;(useAppContext as Mock).mockReturnValue({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.manage'],+ });(useProviderContext as Mock).mockReturnValue({plan: {type: Plan.sandbox,@@ -91,8 +98,11 @@ describe('Pricing', () => {expect(screen.getByRole('switch')).toBeChecked()})- it('should not default to yearly billing for non-manager education accounts', () => {- ;(useAppContext as Mock).mockReturnValue({ isCurrentWorkspaceManager: false })+ it('should not default to yearly billing when billing manage permission is missing', () => {+ ;(useAppContext as Mock).mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [],+ });(useProviderContext as Mock).mockReturnValue({plan: {type: Plan.sandbox,diff --git a/web/app/components/billing/pricing/index.tsx b/web/app/components/billing/pricing/index.tsxindex 268c655e85e..5f8d4cc0974 100644--- a/web/app/components/billing/pricing/index.tsx+++ b/web/app/components/billing/pricing/index.tsx@@ -15,6 +15,7 @@ import { useState } from 'react'import { useAppContext } from '@/context/app-context'import { useGetPricingPageLanguage } from '@/context/i18n'import { useProviderContext } from '@/context/provider-context'+import { BillingPermission, hasPermission } from '@/utils/permission'import { NoiseBottom, NoiseTop } from './assets'import Footer from './footer'import Header from './header'@@ -40,12 +41,13 @@ const Pricing: FC<PricingProps> = ({onCancel,}) => {const { plan, enableEducationPlan, isEducationAccount } = useProviderContext()- const { isCurrentWorkspaceManager } = useAppContext()- const shouldDefaultToYearly = isCurrentWorkspaceManager && enableEducationPlan && isEducationAccount+ const { workspacePermissionKeys } = useAppContext()+ const canManageBilling = hasPermission(workspacePermissionKeys, BillingPermission.Manage)+ const shouldDefaultToYearly = canManageBilling && enableEducationPlan && isEducationAccountconst [selectedPlanRange, setSelectedPlanRange] = React.useState<PlanRange>()const planRange = selectedPlanRange ?? (shouldDefaultToYearly ? PlanRange.yearly : PlanRange.monthly)const [currentCategory, setCurrentCategory] = useState<Category>(CategoryEnum.CLOUD)- const canPay = isCurrentWorkspaceManager+ const canPay = canManageBillingconst pricingPageLanguage = useGetPricingPageLanguage()const pricingPageURL = pricingPageLanguagediff --git a/web/app/components/billing/pricing/plans/cloud-plan-item/__tests__/index.spec.tsx b/web/app/components/billing/pricing/plans/cloud-plan-item/__tests__/index.spec.tsxindex 65c710e37ea..4e33b2c99c4 100644--- a/web/app/components/billing/pricing/plans/cloud-plan-item/__tests__/index.spec.tsx+++ b/web/app/components/billing/pricing/plans/cloud-plan-item/__tests__/index.spec.tsx@@ -77,7 +77,14 @@ beforeAll(() => {beforeEach(() => {vi.clearAllMocks()toast.dismiss()- mockUseAppContext.mockReturnValue({ isCurrentWorkspaceManager: true })+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [+ 'billing.view',+ 'billing.manage',+ 'billing.subscription.manage',+ ],+ })mockUseProviderContext.mockReturnValue({enableEducationPlan: false,isEducationAccount: false,@@ -173,8 +180,11 @@ describe('CloudPlanItem', () => {// Payment actions triggered from the CTAdescribe('Plan purchase flow', () => {- it('should show toast when non-manager tries to buy a plan', () => {- mockUseAppContext.mockReturnValue({ isCurrentWorkspaceManager: false })+ it('should show toast when billing manage permission is missing for plan purchase', () => {+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['billing.subscription.manage'],+ })renderWithToastHost(<CloudPlanItem@@ -188,11 +198,16 @@ describe('CloudPlanItem', () => {fireEvent.click(screen.getByRole('button', { name: 'billing.plansCommon.startBuilding' }))expect(screen.getByText('billing.buyPermissionDeniedTip'))!.toBeInTheDocument()expect(mockBillingInvoices).not.toHaveBeenCalled()+ expect(mockFetchSubscriptionUrls).not.toHaveBeenCalled()})it('should open billing portal when upgrading current paid plan', async () => {const openWindow = vi.fn(async (cb: () => Promise<string>) => await cb())mockUseAsyncWindowOpen.mockReturnValue(openWindow)+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.subscription.manage'],+ })render(<CloudPlanItem@@ -212,6 +227,11 @@ describe('CloudPlanItem', () => {})it('should redirect to subscription url when selecting a new paid plan', async () => {+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.manage'],+ })+render(<CloudPlanItemplan={Plan.professional}@@ -293,8 +313,11 @@ describe('CloudPlanItem', () => {})})- it('should show default CTA and hide warning when current user is not workspace manager', () => {- mockUseAppContext.mockReturnValue({ isCurrentWorkspaceManager: false })+ it('should show default CTA and hide warning when billing manage permission is missing', () => {+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [],+ })mockUseProviderContext.mockReturnValue({enableEducationPlan: true,isEducationAccount: true,@@ -314,8 +337,11 @@ describe('CloudPlanItem', () => {expect(screen.queryByText('education.planNotSupportEducationDiscount')).not.toBeInTheDocument()})- it('should hide education unsupported warning when current user is not workspace manager', () => {- mockUseAppContext.mockReturnValue({ isCurrentWorkspaceManager: false })+ it('should hide education unsupported warning when billing manage permission is missing', () => {+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [],+ })mockUseProviderContext.mockReturnValue({enableEducationPlan: true,isEducationAccount: true,diff --git a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsxindex 9dfc1453033..9c10aa50688 100644--- a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx+++ b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx@@ -18,6 +18,7 @@ import { useProviderContext } from '@/context/provider-context'import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'import { fetchSubscriptionUrls } from '@/service/billing'import { consoleClient } from '@/service/client'+import { BillingPermission, hasPermission } from '@/utils/permission'import { ALL_PLANS } from '../../../config'import { useEducationDiscount } from '../../../hooks/use-education-discount'import { Plan } from '../../../type'@@ -55,7 +56,9 @@ const CloudPlanItem: FC<CloudPlanItemProps> = ({const isCurrent = plan === currentPlanconst isCurrentPaidPlan = isCurrent && !isFreePlanconst isPlanDisabled = isCurrentPaidPlan ? false : planInfo.level <= ALL_PLANS[currentPlan].level- const { isCurrentWorkspaceManager } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()+ const canManageBilling = hasPermission(workspacePermissionKeys, BillingPermission.Manage)+ const canManageBillingSubscription = hasPermission(workspacePermissionKeys, BillingPermission.SubscriptionManage)const { enableEducationPlan, isEducationAccount } = useProviderContext()const isEducationDiscountMode = enableEducationPlan && isEducationAccountconst isEducationDiscountSupportedPlan = plan === Plan.professional && isYear@@ -87,18 +90,14 @@ const CloudPlanItem: FC<CloudPlanItemProps> = ({if (isPlanDisabled)return- if (isEducationDiscountMode && isEducationDiscountSupportedPlan && !isCurrentPaidPlan) {- await handleEducationDiscount()- return- }-- if (!isCurrentWorkspaceManager) {- toast.error(t('buyPermissionDeniedTip', { ns: 'billing' }))- return- }setLoading(true)try {if (isCurrentPaidPlan) {+ if (!canManageBillingSubscription) {+ toast.error(t('buyPermissionDeniedTip', { ns: 'billing' }))+ return+ }+await openAsyncWindow(async () => {const res = await consoleClient.billing.invoices()if (res.url)@@ -115,6 +114,16 @@ const CloudPlanItem: FC<CloudPlanItemProps> = ({if (isFreePlan)return+ if (!canManageBilling) {+ toast.error(t('buyPermissionDeniedTip', { ns: 'billing' }))+ return+ }++ if (isEducationDiscountMode && isEducationDiscountSupportedPlan) {+ await handleEducationDiscount()+ return+ }+const res = await fetchSubscriptionUrls(plan, isYear ? 'year' : 'month')// Adb Block additional tracking block the gtag, so we need to redirect directlywindow.location.href = res.urldiff --git a/web/app/components/billing/pricing/plans/self-hosted-plan-item/__tests__/index.spec.tsx b/web/app/components/billing/pricing/plans/self-hosted-plan-item/__tests__/index.spec.tsxindex 1a2a8b10a13..c2923f98071 100644--- a/web/app/components/billing/pricing/plans/self-hosted-plan-item/__tests__/index.spec.tsx+++ b/web/app/components/billing/pricing/plans/self-hosted-plan-item/__tests__/index.spec.tsx@@ -59,7 +59,10 @@ beforeAll(() => {beforeEach(() => {vi.clearAllMocks()toast.dismiss()- mockUseAppContext.mockReturnValue({ isCurrentWorkspaceManager: true })+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['billing.manage'],+ })assignedHref = ''})@@ -90,8 +93,11 @@ describe('SelfHostedPlanItem', () => {})describe('CTA interactions', () => {- it('should show toast when non-manager tries to proceed', () => {- mockUseAppContext.mockReturnValue({ isCurrentWorkspaceManager: false })+ it('should show toast when billing manage permission is missing', () => {+ mockUseAppContext.mockReturnValue({+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [],+ })renderWithToastHost(<SelfHostedPlanItem plan={SelfHostedPlan.premium} />)fireEvent.click(screen.getByRole('button', { name: /billing\.plans\.premium\.btnText/ }))diff --git a/web/app/components/billing/pricing/plans/self-hosted-plan-item/index.tsx b/web/app/components/billing/pricing/plans/self-hosted-plan-item/index.tsxindex 5851a47e87d..233f26ceb3f 100644--- a/web/app/components/billing/pricing/plans/self-hosted-plan-item/index.tsx+++ b/web/app/components/billing/pricing/plans/self-hosted-plan-item/index.tsx@@ -7,6 +7,7 @@ import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { Azure, GoogleCloud } from '@/app/components/base/icons/src/public/billing'import { useAppContext } from '@/context/app-context'+import { BillingPermission, hasPermission } from '@/utils/permission'import { contactSalesUrl, getStartedWithCommunityUrl, getWithPremiumUrl } from '../../../config'import { SelfHostedPlan } from '../../../type'import { Community, Enterprise, EnterpriseNoise, Premium, PremiumNoise } from '../../assets'@@ -51,11 +52,11 @@ const SelfHostedPlanItem: FC<SelfHostedPlanItemProps> = ({const isFreePlan = plan === SelfHostedPlan.communityconst isPremiumPlan = plan === SelfHostedPlan.premiumconst isEnterprisePlan = plan === SelfHostedPlan.enterprise- const { isCurrentWorkspaceManager } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()+ const canManageBilling = hasPermission(workspacePermissionKeys, BillingPermission.Manage)const handleGetPayUrl = useCallback(() => {- // Only workspace manager can buy plan- if (!isCurrentWorkspaceManager) {+ if (!canManageBilling) {toast.error(t('buyPermissionDeniedTip', { ns: 'billing' }))return}@@ -70,7 +71,7 @@ const SelfHostedPlanItem: FC<SelfHostedPlanItemProps> = ({if (isEnterprisePlan)window.location.href = contactSalesUrl- }, [isCurrentWorkspaceManager, isFreePlan, isPremiumPlan, isEnterprisePlan, t])+ }, [canManageBilling, isFreePlan, isPremiumPlan, isEnterprisePlan, t])return (<div className="relative flex flex-1 flex-col overflow-hidden">diff --git a/web/app/components/custom/custom-page/__tests__/index.spec.tsx b/web/app/components/custom/custom-page/__tests__/index.spec.tsxindex 585156c9a18..fdfa4377bea 100644--- a/web/app/components/custom/custom-page/__tests__/index.spec.tsx+++ b/web/app/components/custom/custom-page/__tests__/index.spec.tsx@@ -103,6 +103,7 @@ const createAppContextValue = (): AppContextValue => ({useSelector: vi.fn() as unknown as AppContextValue['useSelector'],isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],})describe('CustomPage', () => {diff --git a/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsx b/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsxindex fd78377e6df..4c2574c10bd 100644--- a/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsx+++ b/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsx@@ -19,7 +19,7 @@ const createHookState = (overrides: Partial<ReturnType<typeof useWebAppBrand>> =uploadDisabled: false,workspaceLogo: 'https://example.com/workspace-logo.png',isSandbox: false,- isCurrentWorkspaceManager: true,+ canManageCustomBrand: true,handleApply: vi.fn(),handleCancel: vi.fn(),handleChange: vi.fn(),@@ -91,6 +91,19 @@ describe('CustomWebAppBrand', () => {expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')})+ it('should disable write controls when customization management permission is missing', () => {+ renderComponent({+ fileId: 'new-logo',+ canManageCustomBrand: false,+ uploadDisabled: true,+ })++ expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')+ expect(screen.getByRole('button', { name: 'custom.change' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'custom.apply' })).toBeDisabled()+ })+it('should default the switch to unchecked when brand removal state is missing', () => {const { container } = renderComponent({webappBrandRemoved: undefined,diff --git a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsxindex 758d0126c2b..1a096a38dc5 100644--- a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx+++ b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx@@ -107,6 +107,7 @@ const createAppContextValue = (overrides: Partial<AppContextValue> = {}): AppConisCurrentWorkspaceOwner: false,isCurrentWorkspaceEditor: false,isCurrentWorkspaceDatasetOperator: false,+ workspacePermissionKeys: ['customization.manage'],mutateCurrentWorkspace: vi.fn(),langGeniusVersionInfo: initialLangGeniusVersionInfo,useSelector: vi.fn() as unknown as AppContextValue['useSelector'],@@ -139,10 +140,35 @@ describe('useWebAppBrand', () => {expect(result.current.webappLogo).toBe('https://example.com/replace.png')expect(result.current.workspaceLogo).toBe('https://example.com/workspace-logo.png')+ expect(result.current.canManageCustomBrand).toBe(true)expect(result.current.uploadDisabled).toBe(false)expect(result.current.uploading).toBe(false)})+ it('should disable uploads when customization management permission is missing', () => {+ appContextValue = createAppContextValue({+ workspacePermissionKeys: [],+ isCurrentWorkspaceManager: true,+ })++ const { result } = renderHook(() => useWebAppBrand())++ expect(result.current.canManageCustomBrand).toBe(false)+ expect(result.current.uploadDisabled).toBe(true)+ })++ it('should allow uploads for non-manager users with customization management permission', () => {+ appContextValue = createAppContextValue({+ workspacePermissionKeys: ['customization.manage'],+ isCurrentWorkspaceManager: false,+ })++ const { result } = renderHook(() => useWebAppBrand())++ expect(result.current.canManageCustomBrand).toBe(true)+ expect(result.current.uploadDisabled).toBe(false)+ })+it('should disable uploads in sandbox workspaces and when branding is removed', () => {mockUseProviderContext.mockReturnValue(createProviderContext({enableBilling: true,diff --git a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.tsindex f8b0ebce5e5..397334bb2ec 100644--- a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts+++ b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts@@ -9,6 +9,7 @@ import { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { updateCurrentWorkspace } from '@/service/common'+import { hasPermission } from '@/utils/permission'const MAX_LOGO_FILE_SIZE = 5 * 1024 * 1024const CUSTOM_CONFIG_URL = '/workspaces/custom-config'@@ -16,7 +17,7 @@ const WEB_APP_LOGO_UPLOAD_URL = '/workspaces/custom-config/webapp-logo/upload'const useWebAppBrand = () => {const { t } = useTranslation()const { plan, enableBilling } = useProviderContext()- const { currentWorkspace, mutateCurrentWorkspace, isCurrentWorkspaceManager } = useAppContext()+ const { currentWorkspace, mutateCurrentWorkspace, workspacePermissionKeys } = useAppContext()const [fileId, setFileId] = useState('')const [imgKey, setImgKey] = useState(() => Date.now())const [uploadProgress, setUploadProgress] = useState(0)@@ -25,7 +26,8 @@ const useWebAppBrand = () => {const uploading = uploadProgress > 0 && uploadProgress < 100const webappLogo = currentWorkspace.custom_config?.replace_webapp_logo || ''const webappBrandRemoved = currentWorkspace.custom_config?.remove_webapp_brand- const uploadDisabled = isSandbox || webappBrandRemoved || !isCurrentWorkspaceManager+ const canManageCustomBrand = hasPermission(workspacePermissionKeys, 'customization.manage')+ const uploadDisabled = isSandbox || webappBrandRemoved || !canManageCustomBrandconst workspaceLogo = systemFeatures.branding.enabled ? systemFeatures.branding.workspace_logo : ''const persistWorkspaceBrand = async (body: Record<string, unknown>) => {await updateCurrentWorkspace({@@ -89,7 +91,7 @@ const useWebAppBrand = () => {uploadDisabled,workspaceLogo,isSandbox,- isCurrentWorkspaceManager,+ canManageCustomBrand,handleApply,handleCancel,handleChange,diff --git a/web/app/components/custom/custom-web-app-brand/index.tsx b/web/app/components/custom/custom-web-app-brand/index.tsxindex 0eae4261ccc..74ceea608ca 100644--- a/web/app/components/custom/custom-web-app-brand/index.tsx+++ b/web/app/components/custom/custom-web-app-brand/index.tsx@@ -20,7 +20,7 @@ const CustomWebAppBrand = () => {webappBrandRemoved,uploadDisabled,workspaceLogo,- isCurrentWorkspaceManager,+ canManageCustomBrand,isSandbox,handleApply,handleCancel,@@ -36,7 +36,7 @@ const CustomWebAppBrand = () => {<Switchsize="lg"checked={webappBrandRemoved ?? false}- disabled={isSandbox || !isCurrentWorkspaceManager}+ disabled={isSandbox || !canManageCustomBrand}onCheckedChange={handleSwitch}/></div>@@ -98,7 +98,7 @@ const CustomWebAppBrand = () => {<ButtonclassName="mr-2"onClick={handleCancel}- disabled={webappBrandRemoved || !isCurrentWorkspaceManager}+ disabled={webappBrandRemoved || !canManageCustomBrand}>{t('operation.cancel', { ns: 'common' })}</Button>@@ -106,7 +106,7 @@ const CustomWebAppBrand = () => {variant="primary"className="mr-2"onClick={handleApply}- disabled={webappBrandRemoved || !isCurrentWorkspaceManager}+ disabled={webappBrandRemoved || !canManageCustomBrand}>{t('apply', { ns: 'custom' })}</Button>diff --git a/web/app/components/datasets/access-config/__tests__/index.spec.tsx b/web/app/components/datasets/access-config/__tests__/index.spec.tsxnew file mode 100644index 00000000000..e93c0ef9433--- /dev/null+++ b/web/app/components/datasets/access-config/__tests__/index.spec.tsx@@ -0,0 +1,198 @@+import type { AccessRulesEditorProps } from '@/app/components/access-rules-editor'+import { render, screen } from '@testing-library/react'+import {+ useDatasetAccessRules,+ useDatasetUserAccessSettings,+} from '@/service/access-control/use-dataset-access-config'+import { DatasetACLPermission } from '@/utils/permission'+import DatasetAccessConfigPage from '../index'++const mockDatasetAccessRules = vi.hoisted(() => ({+ items: [] as AccessRulesEditorProps['rules'],+ isLoading: false,+}))++const mockDatasetUserAccessSettings = vi.hoisted(() => ({+ data: [] as NonNullable<AccessRulesEditorProps['userAccessSettings']>,+ scope: 'specific' as AccessRulesEditorProps['openScope'],+ isLoading: false,+}))++const mockDatasetDetail = vi.hoisted(() => ({+ dataset: undefined as { maintainer?: string | null, permission_keys?: string[] } | undefined,+}))++const mockAppContextState = vi.hoisted(() => ({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [] as string[],+}))++const mockAccessRulesEditor = vi.hoisted(() => ({+ props: null as AccessRulesEditorProps | null,+}))++const mockMutations = vi.hoisted(() => ({+ updateOpenScope: vi.fn(),+ updateUserAccessSettings: vi.fn(),+ removeMemberBindings: vi.fn(),+}))++vi.mock('@/service/access-control/use-dataset-access-config', () => ({+ useDatasetAccessRules: vi.fn(() => ({+ data: { items: mockDatasetAccessRules.items },+ isLoading: mockDatasetAccessRules.isLoading,+ })),+ useDatasetUserAccessSettings: vi.fn(() => ({+ data: mockDatasetUserAccessSettings.scope+ ? { data: mockDatasetUserAccessSettings.data, scope: mockDatasetUserAccessSettings.scope }+ : undefined,+ isLoading: mockDatasetUserAccessSettings.isLoading,+ })),+ useUpdateDatasetOpenScope: vi.fn(() => ({+ mutate: mockMutations.updateOpenScope,+ isPending: false,+ })),+ useUpdateDatasetUserAccessSettings: vi.fn(() => ({+ mutate: mockMutations.updateUserAccessSettings,+ })),+ useRemoveDatasetAccessPolicyMemberBindings: vi.fn(() => ({+ mutate: mockMutations.removeMemberBindings,+ })),+}))++vi.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContextWithSelector: vi.fn((selector: (state: { dataset?: { maintainer?: string | null, permission_keys?: string[] } }) => unknown) => {+ return selector({ dataset: mockDatasetDetail.dataset })+ }),+}))++vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn((selector: (state: typeof mockAppContextState) => unknown) => selector(mockAppContextState)),+}))++vi.mock('@/app/components/access-rules-editor', () => ({+ default: (props: AccessRulesEditorProps) => {+ mockAccessRulesEditor.props = props+ return (+ <div data-testid="access-rules-editor" />+ )+ },+}))++describe('DatasetAccessConfigPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockDatasetAccessRules.items = []+ mockDatasetAccessRules.isLoading = false+ mockDatasetUserAccessSettings.data = []+ mockDatasetUserAccessSettings.scope = 'specific'+ mockDatasetUserAccessSettings.isLoading = false+ mockDatasetDetail.dataset = {+ maintainer: 'maintainer-1',+ permission_keys: [DatasetACLPermission.AccessConfig],+ }+ mockAppContextState.userProfile = { id: 'user-1' }+ mockAppContextState.workspacePermissionKeys = []+ mockAccessRulesEditor.props = null+ })++ // Rendering wires dataset access rules into the shared editor.+ describe('Rendering', () => {+ it('should render access config title and pass dataset rules to the editor', () => {+ render(<DatasetAccessConfigPage datasetId="dataset-1" />)++ expect(screen.getByRole('heading', { name: 'common.settings.resourceAccess' })).toBeInTheDocument()+ expect(screen.getByText('permission.accessRule.datasetDescription')).toBeInTheDocument()+ expect(screen.getByTestId('access-rules-editor')).toBeInTheDocument()+ expect(mockAccessRulesEditor.props?.className).toBe('w-full max-w-200')+ expect(mockAccessRulesEditor.props?.rules).toEqual([])+ expect(mockAccessRulesEditor.props?.userAccessSettings).toEqual([])+ expect(mockAccessRulesEditor.props?.openScope).toBe('specific')+ })++ it('should not pass open scope before user access settings finish loading', () => {+ mockDatasetUserAccessSettings.scope = undefined+ mockDatasetUserAccessSettings.isLoading = true++ render(<DatasetAccessConfigPage datasetId="dataset-1" />)++ expect(mockAccessRulesEditor.props?.openScope).toBeUndefined()+ })++ it('should pass the user access settings open scope to the editor', () => {+ mockDatasetUserAccessSettings.scope = 'all'++ render(<DatasetAccessConfigPage datasetId="dataset-1" />)++ expect(mockAccessRulesEditor.props?.openScope).toBe('all')+ })++ it('should pass access rule loading state to the editor', () => {+ mockDatasetAccessRules.isLoading = true+ mockDatasetUserAccessSettings.isLoading = true++ render(<DatasetAccessConfigPage datasetId="dataset-1" />)++ expect(mockAccessRulesEditor.props?.isLoadingRules).toBe(true)+ expect(mockAccessRulesEditor.props?.isLoadingUserAccessSettings).toBe(true)+ expect(mockAccessRulesEditor.props?.isUpdatingOpenScope).toBe(true)+ })++ it('should pass the dataset maintainer id from dataset detail to the editor', () => {+ mockDatasetDetail.dataset = {+ maintainer: 'account-1',+ permission_keys: [DatasetACLPermission.AccessConfig],+ }++ render(<DatasetAccessConfigPage datasetId="dataset-1" />)++ expect(mockAccessRulesEditor.props?.maintainerId).toBe('account-1')+ })++ it('should disable access config queries and hide the editor when access config permission is missing', () => {+ mockDatasetDetail.dataset = {+ maintainer: 'account-1',+ permission_keys: [],+ }++ render(<DatasetAccessConfigPage datasetId="dataset-1" />)++ expect(screen.queryByTestId('access-rules-editor')).not.toBeInTheDocument()+ expect(vi.mocked(useDatasetAccessRules)).toHaveBeenCalledWith('dataset-1', expect.any(String), { enabled: false })+ expect(vi.mocked(useDatasetUserAccessSettings)).toHaveBeenCalledWith('dataset-1', expect.any(String), { enabled: false })+ })++ it('should wire open scope and user policy updates', () => {+ render(<DatasetAccessConfigPage datasetId="dataset-1" />)++ mockAccessRulesEditor.props?.onOpenScopeChange?.('all')+ expect(mockMutations.updateOpenScope).toHaveBeenCalledWith('all', expect.objectContaining({+ onError: expect.any(Function),+ }))++ mockAccessRulesEditor.props?.onUserAccessPoliciesChange?.('account-1', ['policy-1'])+ expect(mockMutations.updateUserAccessSettings).toHaveBeenCalledWith({+ accountId: 'account-1',+ accessPolicyIds: ['policy-1'],+ }, expect.objectContaining({+ onSettled: expect.any(Function),+ }))++ mockAccessRulesEditor.props?.onAddAccessSubject?.('account-2', ['default'])+ expect(mockMutations.updateUserAccessSettings).toHaveBeenCalledWith({+ accountId: 'account-2',+ accessPolicyIds: ['default'],+ }, expect.objectContaining({+ onSettled: expect.any(Function),+ }))++ mockAccessRulesEditor.props?.onRemoveAccessPolicyMemberBinding?.('account-3', 'policy-3')+ expect(mockMutations.removeMemberBindings).toHaveBeenCalledWith({+ accessPolicyId: 'policy-3',+ accountIds: ['account-3'],+ }, expect.objectContaining({+ onSettled: expect.any(Function),+ }))+ })+ })+})diff --git a/web/app/components/datasets/access-config/index.tsx b/web/app/components/datasets/access-config/index.tsxnew file mode 100644index 00000000000..fd9a851ccf1--- /dev/null+++ b/web/app/components/datasets/access-config/index.tsx@@ -0,0 +1,120 @@+'use client'++import type { ResourceOpenScope } from '@/models/access-control'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useCallback, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import AccessRulesEditor from '@/app/components/access-rules-editor'+import Loading from '@/app/components/base/loading'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import {+ useDatasetAccessRules,+ useDatasetUserAccessSettings,+ useRemoveDatasetAccessPolicyMemberBindings,+ useUpdateDatasetOpenScope,+ useUpdateDatasetUserAccessSettings,+} from '@/service/access-control/use-dataset-access-config'+import { getDatasetACLCapabilities } from '@/utils/permission'++type DatasetAccessConfigPageProps = {+ datasetId: string+}++const DatasetAccessConfigPage = ({ datasetId }: DatasetAccessConfigPageProps) => {+ const { t } = useTranslation()+ const locale = useLocale()+ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])+ const dataset = useDatasetDetailContextWithSelector(state => state.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canAccessConfig = useMemo(() => getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }).canAccessConfig, [currentUserId, dataset?.maintainer, dataset?.permission_keys, workspacePermissionKeys])+ const { data: datasetAccessRulesResponse, isLoading: isLoadingDatasetAccessRules } = useDatasetAccessRules(datasetId, language, { enabled: canAccessConfig })+ const { data: datasetUserAccessSettingsResponse, isLoading: isLoadingDatasetUserAccessSettings } = useDatasetUserAccessSettings(datasetId, language, { enabled: canAccessConfig })+ const { mutate: updateDatasetOpenScope, isPending: isUpdatingDatasetOpenScope } = useUpdateDatasetOpenScope(datasetId)+ const { mutate: updateDatasetUserAccessSettings } = useUpdateDatasetUserAccessSettings(datasetId)+ const { mutate: removeDatasetAccessPolicyMemberBindings } = useRemoveDatasetAccessPolicyMemberBindings(datasetId)+ const [optimisticOpenScope, setOptimisticOpenScope] = useState<ResourceOpenScope | null>(null)+ const [updatingAccountId, setUpdatingAccountId] = useState<string | null>(null)++ const datasetAccessRules = datasetAccessRulesResponse?.items || []+ const datasetUserAccessSettings = datasetUserAccessSettingsResponse?.data || []+ const openScope = optimisticOpenScope || datasetUserAccessSettingsResponse?.scope++ const handleOpenScopeChange = useCallback((nextOpenScope: ResourceOpenScope) => {+ if (!canAccessConfig)+ return+ if (nextOpenScope === openScope)+ return++ const previousOptimisticOpenScope = optimisticOpenScope+ setOptimisticOpenScope(nextOpenScope)+ updateDatasetOpenScope(nextOpenScope, {+ onError: () => setOptimisticOpenScope(previousOptimisticOpenScope),+ })+ }, [canAccessConfig, openScope, optimisticOpenScope, updateDatasetOpenScope])++ const handleUserAccessPoliciesChange = useCallback((accountId: string, accessPolicyIds: string[]) => {+ if (!canAccessConfig)+ return++ setUpdatingAccountId(accountId)+ updateDatasetUserAccessSettings(+ { accountId, accessPolicyIds },+ { onSettled: () => setUpdatingAccountId(null) },+ )+ }, [canAccessConfig, updateDatasetUserAccessSettings])++ const handleRemoveAccessPolicyMemberBinding = useCallback((accountId: string, accessPolicyId: string) => {+ if (!canAccessConfig)+ return++ setUpdatingAccountId(accountId)+ removeDatasetAccessPolicyMemberBindings(+ { accessPolicyId, accountIds: [accountId] },+ { onSettled: () => setUpdatingAccountId(null) },+ )+ }, [canAccessConfig, removeDatasetAccessPolicyMemberBindings])++ if (!canAccessConfig)+ return <Loading type="app" />++ return (+ <ScrollArea+ className="h-full bg-background-default-subtle"+ slotClassNames={{ viewport: 'overscroll-contain' }}+ >+ <header className="flex min-h-15.5 flex-col justify-center px-6 py-3">+ <h1 className="system-sm-semibold text-text-primary">{t('settings.resourceAccess', { ns: 'common' })}</h1>+ <p className="mt-0.5 system-xs-regular text-text-tertiary">+ {t('accessRule.datasetDescription', { ns: 'permission' })}+ </p>+ </header>+ <main className="w-full px-6 pt-8 pb-10">+ <AccessRulesEditor+ className="w-full max-w-200"+ rules={datasetAccessRules}+ userAccessSettings={datasetUserAccessSettings}+ isLoadingRules={isLoadingDatasetAccessRules}+ isLoadingUserAccessSettings={isLoadingDatasetUserAccessSettings}+ openScope={openScope}+ isUpdatingOpenScope={isLoadingDatasetUserAccessSettings || isUpdatingDatasetOpenScope}+ updatingAccountId={updatingAccountId}+ maintainerId={dataset?.maintainer}+ onOpenScopeChange={handleOpenScopeChange}+ onUserAccessPoliciesChange={handleUserAccessPoliciesChange}+ onRemoveAccessPolicyMemberBinding={handleRemoveAccessPolicyMemberBinding}+ onAddAccessSubject={handleUserAccessPoliciesChange}+ />+ </main>+ </ScrollArea>+ )+}++export default DatasetAccessConfigPagediff --git a/web/app/components/datasets/common/economical-retrieval-method-config/index.tsx b/web/app/components/datasets/common/economical-retrieval-method-config/index.tsxindex 65facad266f..77d88bf2520 100644--- a/web/app/components/datasets/common/economical-retrieval-method-config/index.tsx+++ b/web/app/components/datasets/common/economical-retrieval-method-config/index.tsx@@ -40,6 +40,7 @@ const EconomicalRetrievalMethodConfig: FC<Props> = ({type={RETRIEVE_METHOD.keywordSearch}value={value}onChange={onChange}+ disabled={disabled}/></OptionCard>)diff --git a/web/app/components/datasets/common/retrieval-method-config/index.tsx b/web/app/components/datasets/common/retrieval-method-config/index.tsxindex 52fdfa97529..ea792628739 100644--- a/web/app/components/datasets/common/retrieval-method-config/index.tsx+++ b/web/app/components/datasets/common/retrieval-method-config/index.tsx@@ -114,6 +114,7 @@ const RetrievalMethodConfig: FC<Props> = ({value={value}onChange={onChange}showMultiModalTip={showMultiModalTip}+ disabled={disabled}/></OptionCard>)}@@ -137,6 +138,7 @@ const RetrievalMethodConfig: FC<Props> = ({value={value}onChange={onChange}showMultiModalTip={showMultiModalTip}+ disabled={disabled}/></OptionCard>)}@@ -161,6 +163,7 @@ const RetrievalMethodConfig: FC<Props> = ({value={value}onChange={onChange}showMultiModalTip={showMultiModalTip}+ disabled={disabled}/></OptionCard>)}diff --git a/web/app/components/datasets/common/retrieval-param-config/index.tsx b/web/app/components/datasets/common/retrieval-param-config/index.tsxindex fe9152944c2..64f07e59ec6 100644--- a/web/app/components/datasets/common/retrieval-param-config/index.tsx+++ b/web/app/components/datasets/common/retrieval-param-config/index.tsx@@ -31,6 +31,7 @@ type Props = Readonly<{type: RETRIEVE_METHODvalue: RetrievalConfigshowMultiModalTip?: boolean+ disabled?: booleanonChange: (value: RetrievalConfig) => void}>@@ -38,6 +39,7 @@ const RetrievalParamConfig: FC<Props> = ({type,value,showMultiModalTip = false,+ disabled = false,onChange,}) => {const { t } = useTranslation()@@ -59,13 +61,15 @@ const RetrievalParamConfig: FC<Props> = ({)const handleToggleRerankEnable = useCallback((enable: boolean) => {+ if (disabled)+ returnif (enable && !currentModel)toast.error(t('errorMsg.rerankModelRequired', { ns: 'workflow' }))onChange({...value,reranking_enable: enable,})- }, [currentModel, onChange, value])+ }, [currentModel, disabled, onChange, t, value])const rerankModel = useMemo(() => {return {@@ -75,6 +79,8 @@ const RetrievalParamConfig: FC<Props> = ({}, [value.reranking_model])const handleChangeRerankMode = (v: RerankingModeEnum) => {+ if (disabled)+ returnif (v === value.reranking_mode)return@@ -124,6 +130,7 @@ const RetrievalParamConfig: FC<Props> = ({size="md"checked={value.reranking_enable}onCheckedChange={handleToggleRerankEnable}+ disabled={disabled}/>)}<div className="flex items-center">@@ -143,6 +150,8 @@ const RetrievalParamConfig: FC<Props> = ({defaultModel={rerankModel && { provider: rerankModel.provider_name, model: rerankModel.model_name }}modelList={rerankModelList}onSelect={(v) => {+ if (disabled)+ returnonChange({...value,reranking_model: {@@ -151,6 +160,7 @@ const RetrievalParamConfig: FC<Props> = ({},})}}+ readonly={disabled}/>{showMultiModalTip && (<div className="mt-2 flex h-10 items-center gap-x-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs backdrop-blur-[5px]">@@ -175,18 +185,23 @@ const RetrievalParamConfig: FC<Props> = ({className="grow"value={value.top_k}onChange={(_key, v) => {+ if (disabled)+ returnonChange({...value,top_k: v,})}}enable={true}+ disabled={disabled}/>{(!isEconomical && !(value.search_method === RETRIEVE_METHOD.fullText && !value.reranking_enable)) && (<ScoreThresholdItemclassName="grow"value={value.score_threshold}onChange={(_key, v) => {+ if (disabled)+ returnonChange({...value,score_threshold: v,@@ -194,7 +209,10 @@ const RetrievalParamConfig: FC<Props> = ({}}enable={value.score_threshold_enabled}hasSwitch={true}+ disabled={disabled}onSwitchChange={(_key, v) => {+ if (disabled)+ returnonChange({...value,score_threshold_enabled: v,@@ -246,6 +264,8 @@ const RetrievalParamConfig: FC<Props> = ({],}}onChange={(v) => {+ if (disabled)+ returnonChange({...value,weights: {@@ -271,6 +291,8 @@ const RetrievalParamConfig: FC<Props> = ({defaultModel={rerankModel && { provider: rerankModel.provider_name, model: rerankModel.model_name }}modelList={rerankModelList}onSelect={(v) => {+ if (disabled)+ returnonChange({...value,reranking_model: {@@ -279,6 +301,7 @@ const RetrievalParamConfig: FC<Props> = ({},})}}+ readonly={disabled}/>{showMultiModalTip && (<div className="mt-2 flex h-10 items-center gap-x-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs backdrop-blur-[5px]">@@ -299,17 +322,22 @@ const RetrievalParamConfig: FC<Props> = ({className="grow"value={value.top_k}onChange={(_key, v) => {+ if (disabled)+ returnonChange({...value,top_k: v,})}}enable={true}+ disabled={disabled}/><ScoreThresholdItemclassName="grow"value={value.score_threshold}onChange={(_key, v) => {+ if (disabled)+ returnonChange({...value,score_threshold: v,@@ -317,7 +345,10 @@ const RetrievalParamConfig: FC<Props> = ({}}enable={value.score_threshold_enabled}hasSwitch={true}+ disabled={disabled}onSwitchChange={(_key, v) => {+ if (disabled)+ returnonChange({...value,score_threshold_enabled: v,diff --git a/web/app/components/datasets/create/__tests__/index.spec.tsx b/web/app/components/datasets/create/__tests__/index.spec.tsxindex b63058af04d..7668e778d94 100644--- a/web/app/components/datasets/create/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create/__tests__/index.spec.tsx@@ -30,6 +30,30 @@ vi.mock('@/next/link', () => {}})+const mockReplace = vi.fn()+vi.mock('@/next/navigation', () => ({+ useRouter: () => ({+ replace: mockReplace,+ }),+}))++let mockCurrentUserId = 'user-1'+let mockWorkspacePermissionKeys = ['dataset.create_and_management']+let mockIsLoadingWorkspacePermissionKeys = false+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: {+ userProfile: { id: string }+ workspacePermissionKeys: string[]+ isLoadingWorkspacePermissionKeys: boolean+ }) => unknown) => {+ return selector({+ userProfile: { id: mockCurrentUserId },+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ isLoadingWorkspacePermissionKeys: mockIsLoadingWorkspacePermissionKeys,+ })+ },+}))+// Mock modal contextconst mockSetShowAccountSettingModal = vi.fn()vi.mock('@/context/modal-context', () => ({@@ -165,6 +189,7 @@ vi.mock('../step-two', () => ({<span data-testid="step-two-is-api-key-set">{String(props.isAPIKeySet)}</span><span data-testid="step-two-data-source-type">{props.dataSourceType}</span><span data-testid="step-two-files-count">{props.files?.length || 0}</span>+ <span data-testid="step-two-can-create-document">{String(props.canCreateDocument)}</span><button data-testid="step-two-prev" onClick={() => props.onStepChange!(-1)}>Prev Step</button><button data-testid="step-two-next" onClick={() => props.onStepChange!(1)}>Next Step</button><button data-testid="step-two-setting" onClick={props.onSetting}>Open Settings</button>@@ -274,6 +299,7 @@ const createMockDataset = (overrides?: Partial<DataSet>): DataSet => ({runtime_mode: 'general' as const,enable_api: false,is_multimodal: false,+ permission_keys: ['dataset.acl.use', 'dataset.acl.edit'],...overrides,})@@ -293,6 +319,9 @@ describe('DatasetUpdateForm', () => {mockDataSourceList = { result: [createMockDataSourceAuth()] }mockIsLoadingDataSourceList = falsemockFetchingError = false+ mockCurrentUserId = 'user-1'+ mockWorkspacePermissionKeys = ['dataset.create_and_management']+ mockIsLoadingWorkspacePermissionKeys = false// Reset captured propsstepOneProps = {} as StepOnePropsstepTwoProps = {} as StepTwoProps@@ -750,6 +779,26 @@ describe('DatasetUpdateForm', () => {expect(screen.getByTestId('step-two'))!.toBeInTheDocument()})+ it('should redirect when existing dataset does not grant add document permission', async () => {+ mockDatasetDetail = createMockDataset({ permission_keys: ['dataset.acl.edit'] })++ render(<DatasetUpdateForm datasetId="dataset-123" />)++ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledWith('/datasets/dataset-123/documents')+ })+ expect(screen.queryByTestId('step-one')).not.toBeInTheDocument()+ })++ it('should pass add document permission to StepTwo for existing dataset', () => {+ mockDatasetDetail = createMockDataset()++ render(<DatasetUpdateForm datasetId="dataset-123" />)+ fireEvent.click(screen.getByTestId('step-one-next'))++ expect(screen.getByTestId('step-two-can-create-document')).toHaveTextContent('true')+ })+it('should pass indexingType from datasetDetail to StepTwo', () => {mockDatasetDetail = createMockDataset({ indexing_technique: IndexingTypeValues.ECONOMICAL })render(<DatasetUpdateForm datasetId="dataset-123" />)diff --git a/web/app/components/datasets/create/index.tsx b/web/app/components/datasets/create/index.tsxindex e5e8eda2382..71d34e9649b 100644--- a/web/app/components/datasets/create/index.tsx+++ b/web/app/components/datasets/create/index.tsx@@ -4,16 +4,19 @@ import type { CrawlOptions, CrawlResultItem, createDocumentResponse, FileItem }import type { RETRIEVE_METHOD } from '@/types/app'import { produce } from 'immer'import * as React from 'react'-import { useCallback, useState } from 'react'+import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import { useIntegrationsSetting } from '@/app/components/header/account-setting/use-integrations-setting'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { DataSourceProvider } from '@/models/common'import { DataSourceType } from '@/models/datasets'+import { useRouter } from '@/next/navigation'import { useGetDefaultDataSourceListAuth } from '@/service/use-datasource'+import { getDatasetACLCapabilities } from '@/utils/permission'import AppUnavailable from '../../base/app-unavailable'import { ModelTypeEnum } from '../../header/account-setting/model-provider-page/declarations'import StepOne from './step-one'@@ -37,9 +40,22 @@ const DEFAULT_CRAWL_OPTIONS: CrawlOptions = {const DatasetUpdateForm = ({ datasetId }: DatasetUpdateFormProps) => {const { t } = useTranslation()+ const router = useRouter()const openIntegrationsSetting = useIntegrationsSetting()const datasetDetail = useDatasetDetailContextWithSelector(state => state.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const isLoadingWorkspacePermissionKeys = useAppContextWithSelector(state => state.isLoadingWorkspacePermissionKeys)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const { data: embeddingsDefaultModel } = useDefaultModel(ModelTypeEnum.textEmbedding)+ const canAddDocumentsToDataset = !datasetId || getDatasetACLCapabilities(datasetDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: datasetDetail?.maintainer,+ workspacePermissionKeys,+ }).canUse+ const shouldRedirectToDocuments = !!datasetId+ && !!datasetDetail+ && !isLoadingWorkspacePermissionKeys+ && !canAddDocumentsToDatasetconst [dataSourceType, setDataSourceType] = useState<DataSourceType>(DataSourceType.FILE)const [step, setStep] = useState(1)@@ -103,6 +119,14 @@ const DatasetUpdateForm = ({ datasetId }: DatasetUpdateFormProps) => {setStep(step + delta)}, [step, setStep])+ useEffect(() => {+ if (shouldRedirectToDocuments && datasetId)+ router.replace(`/datasets/${datasetId}/documents`)+ }, [datasetId, router, shouldRedirectToDocuments])++ if ((!!datasetId && isLoadingWorkspacePermissionKeys) || shouldRedirectToDocuments)+ return <Loading type="app" />+if (fetchingAuthedDataSourceListError)return <AppUnavailable code={500} unknownReason={t('error.unavailable', { ns: 'datasetCreation' }) as string} />@@ -156,6 +180,7 @@ const DatasetUpdateForm = ({ datasetId }: DatasetUpdateFormProps) => {websiteCrawlProvider={websiteCrawlProvider}websiteCrawlJobId={websiteCrawlJobId}onStepChange={changeStep}+ canCreateDocument={canAddDocumentsToDataset}updateIndexingTypeCache={updateIndexingTypeCache}updateRetrievalMethodCache={updateRetrievalMethodCache}updateResultCache={updateResultCache}diff --git a/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.ts b/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.tsindex 52099668ec6..cb6fadde4ee 100644--- a/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.ts+++ b/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.ts@@ -1,4 +1,4 @@-import type { CustomFile, FullDocumentDetail, ProcessRule } from '@/models/datasets'+import type { CreateDocumentReq, CustomFile, FullDocumentDetail, ProcessRule } from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'import { renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -183,6 +183,44 @@ describe('useDocumentCreation', () => {})})+ describe('executeCreation', () => {+ it('should not create document when existing dataset cannot add documents', async () => {+ const onStepChange = vi.fn()+ const { result } = renderHook(() =>+ useDocumentCreation({+ ...defaultOptions,+ datasetId: 'dataset-1',+ canCreateDocument: false,+ onStepChange,+ }),+ )++ await result.current.executeCreation({} as CreateDocumentReq, IndexingType.QUALIFIED, defaultValidationParams.retrievalConfig)++ expect(mocks.mutateAsync).not.toHaveBeenCalled()+ expect(mocks.invalidDatasetList).not.toHaveBeenCalled()+ expect(onStepChange).not.toHaveBeenCalled()+ })++ it('should allow setting saves even when document creation permission is false', async () => {+ const onSave = vi.fn()+ const { result } = renderHook(() =>+ useDocumentCreation({+ ...defaultOptions,+ datasetId: 'dataset-1',+ canCreateDocument: false,+ isSetting: true,+ onSave,+ }),+ )++ await result.current.executeCreation({} as CreateDocumentReq, IndexingType.QUALIFIED, defaultValidationParams.retrievalConfig)++ expect(mocks.mutateAsync).toHaveBeenCalled()+ expect(onSave).toHaveBeenCalled()+ })+ })+describe('isCreating', () => {it('should reflect mutation pending state', () => {const { result } = renderHook(() => useDocumentCreation(defaultOptions))diff --git a/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts b/web/app/components/datasets/create/step-two/hooks/use-document-creation.tsindex 27d96e66099..9fcf7980584 100644--- a/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts+++ b/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts@@ -26,6 +26,7 @@ type UseDocumentCreationOptions = {crawlOptions?: CrawlOptionswebsiteCrawlProvider?: DataSourceProviderwebsiteCrawlJobId?: string+ canCreateDocument?: boolean// CallbacksonStepChange?: (delta: number) => voidupdateIndexingTypeCache?: (type: string) => void@@ -46,7 +47,7 @@ type ValidationParams = {}export const useDocumentCreation = (options: UseDocumentCreationOptions) => {const { t } = useTranslation()- const { datasetId, isSetting, documentDetail, dataSourceType, files, notionPages, notionCredentialId, websitePages, crawlOptions, websiteCrawlProvider = DataSourceProvider.jinaReader, websiteCrawlJobId = '', onStepChange, updateIndexingTypeCache, updateResultCache, updateRetrievalMethodCache, onSave, mutateDatasetRes } = options+ const { datasetId, isSetting, documentDetail, dataSourceType, files, notionPages, notionCredentialId, websitePages, crawlOptions, websiteCrawlProvider = DataSourceProvider.jinaReader, websiteCrawlJobId = '', canCreateDocument = true, onStepChange, updateIndexingTypeCache, updateResultCache, updateRetrievalMethodCache, onSave, mutateDatasetRes } = optionsconst createFirstDocumentMutation = useCreateFirstDocument()const createDocumentMutation = useCreateDocument(datasetId!)const invalidDatasetList = useInvalidDatasetList()@@ -140,6 +141,9 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {])// Execute creationconst executeCreation = useCallback(async (params: CreateDocumentReq, indexType: IndexingType, retrievalConfig: RetrievalConfig) => {+ if (datasetId && !isSetting && !canCreateDocument)+ return+if (!datasetId) {await createFirstDocumentMutation.mutateAsync(params, {onSuccess(data) {@@ -179,6 +183,7 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {dataSourceType,onStepChange,isSetting,+ canCreateDocument,onSave,])// Validate preview paramsdiff --git a/web/app/components/datasets/create/step-two/index.tsx b/web/app/components/datasets/create/step-two/index.tsxindex e3144c411da..39c9688c3b5 100644--- a/web/app/components/datasets/create/step-two/index.tsx+++ b/web/app/components/datasets/create/step-two/index.tsx@@ -17,6 +17,7 @@ import { useFetchDefaultProcessRule } from '@/service/knowledge/use-create-datasimport { GeneralChunkingOptions, IndexingModeSection, ParentChildOptions, PreviewPanel, StepTwoFooter } from './components'import { IndexingType, MAXIMUM_CHUNK_TOKEN_LENGTH, useDocumentCreation, useIndexingConfig, useIndexingEstimate, usePreviewState, useSegmentationState } from './hooks'+// eslint-disable-next-line no-barrel-files/no-barrel-filesexport { IndexingType }const StepTwo: FC<StepTwoProps> = ({@@ -33,6 +34,7 @@ const StepTwo: FC<StepTwoProps> = ({crawlOptions,websiteCrawlProvider = DataSourceProvider.jinaReader,websiteCrawlJobId = '',+ canCreateDocument = true,onStepChange,updateIndexingTypeCache,updateResultCache,@@ -88,6 +90,7 @@ const StepTwo: FC<StepTwoProps> = ({crawlOptions,websiteCrawlProvider,websiteCrawlJobId,+ canCreateDocument,onStepChange,updateIndexingTypeCache,updateResultCache,@@ -146,6 +149,9 @@ const StepTwo: FC<StepTwoProps> = ({}, [segmentation, t, estimateHook])const handleCreate = useCallback(async () => {+ if (!canCreateDocument)+ return+const isValid = creation.validateParams({segmentationType: segmentation.segmentationType,maxChunkLength: segmentation.maxChunkLength,@@ -162,7 +168,7 @@ const StepTwo: FC<StepTwoProps> = ({if (!params)returnawait creation.executeCreation(params, indexing.indexType, indexing.retrievalConfig)- }, [creation, segmentation, indexing, currentDocForm, docLanguage])+ }, [canCreateDocument, creation, segmentation, indexing, currentDocForm, docLanguage])const handlePickerChange = useCallback((selected: { id: string, name: string }) => {estimateHook.reset()@@ -187,7 +193,7 @@ const StepTwo: FC<StepTwoProps> = ({segmentation.applyConfigFromRules(rules, isHierarchical)segmentation.setSegmentationType(documentDetail.dataset_process_rule.mode)}- // eslint-disable-next-line react-hooks/exhaustive-deps+ // eslint-disable-next-line react/exhaustive-deps}, [])// Show options conditionsdiff --git a/web/app/components/datasets/create/step-two/types.ts b/web/app/components/datasets/create/step-two/types.tsindex 7f5291fb13b..3868bb0ef4f 100644--- a/web/app/components/datasets/create/step-two/types.ts+++ b/web/app/components/datasets/create/step-two/types.ts@@ -19,6 +19,7 @@ export type StepTwoProps = {crawlOptions?: CrawlOptionswebsiteCrawlProvider?: DataSourceProviderwebsiteCrawlJobId?: string+ canCreateDocument?: booleanonStepChange?: (delta: number) => voidupdateIndexingTypeCache?: (type: string) => voidupdateRetrievalMethodCache?: (method: RETRIEVE_METHOD | '') => voiddiff --git a/web/app/components/datasets/documents/__tests__/index.spec.tsx b/web/app/components/datasets/documents/__tests__/index.spec.tsxindex 2dd91dd7f38..fa09e9c0766 100644--- a/web/app/components/datasets/documents/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/__tests__/index.spec.tsx@@ -33,6 +33,8 @@ vi.mock('@/context/dataset-detail', () => ({embedding_available: true,data_source_type: DataSourceType.FILE,runtime_mode: 'rag',+ created_by: 'test-user',+ permission_keys: ['dataset.acl.use', 'dataset.acl.edit'],},}return selector(mockState as MockState)@@ -45,6 +47,14 @@ vi.mock('@/context/provider-context', () => ({})),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ userProfile: { id: 'test-user' },+ workspacePermissionKeys: ['dataset.create_and_management'],+ }),+}))+// Mock document service hooksconst mockInvalidDocumentList = vi.fn()const mockInvalidDocumentDetail = vi.fn()@@ -278,6 +288,8 @@ describe('Documents', () => {embedding_available: true,data_source_type: DataSourceType.FILE,runtime_mode: 'rag',+ created_by: 'test-user',+ permission_keys: ['dataset.acl.use', 'dataset.acl.edit'],},}return selector(mockState as MockState)@@ -362,6 +374,8 @@ describe('Documents', () => {embedding_available: true,data_source_type: DataSourceType.NOTION,runtime_mode: 'rag',+ created_by: 'test-user',+ permission_keys: ['dataset.acl.use', 'dataset.acl.edit'],},}return selector(mockState as MockState)@@ -466,6 +480,8 @@ describe('Documents', () => {embedding_available: true,data_source_type: DataSourceType.FILE,runtime_mode: 'rag_pipeline',+ created_by: 'test-user',+ permission_keys: ['dataset.acl.use', 'dataset.acl.edit'],},}return selector(mockState as MockState)@@ -487,6 +503,8 @@ describe('Documents', () => {embedding_available: true,data_source_type: DataSourceType.FILE,runtime_mode: 'rag',+ created_by: 'test-user',+ permission_keys: ['dataset.acl.use', 'dataset.acl.edit'],},}return selector(mockState as MockState)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 0289a79e2a4..664b05cbe35 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@@ -32,6 +32,9 @@ describe('DocumentsHeader', () => {datasetId: 'dataset-123',dataSourceType: DataSourceType.FILE,embeddingAvailable: true,+ canManageMetadata: true,+ canAddDocument: true,+ canEditDocument: true,isFreePlan: false,statusFilterValue: 'all',sortValue: 'created_at' as SortType,@@ -86,6 +89,22 @@ describe('DocumentsHeader', () => {render(<DocumentsHeader {...defaultProps} />)expect(screen.getByRole('textbox')).toBeInTheDocument()})++ it('should hide action controls by default when permissions are omitted', () => {+ const {+ canManageMetadata: _canManageMetadata,+ canAddDocument: _canAddDocument,+ canEditDocument: _canEditDocument,+ ...propsWithoutPermissions+ } = defaultProps++ render(<DocumentsHeader {...propsWithoutPermissions} />)++ expect(screen.queryByTestId('auto-disabled-document')).not.toBeInTheDocument()+ expect(screen.queryByTestId('index-failed')).not.toBeInTheDocument()+ expect(screen.queryByText(/metadata\.metadata/i)).not.toBeInTheDocument()+ expect(screen.queryByText(/list\.addFile/i)).not.toBeInTheDocument()+ })})describe('AutoDisabledDocument', () => {@@ -98,6 +117,11 @@ describe('DocumentsHeader', () => {render(<DocumentsHeader {...defaultProps} isFreePlan={true} />)expect(screen.queryByTestId('auto-disabled-document')).not.toBeInTheDocument()})++ it('should not show AutoDisabledDocument without document edit permission', () => {+ render(<DocumentsHeader {...defaultProps} canEditDocument={false} />)+ expect(screen.queryByTestId('auto-disabled-document')).not.toBeInTheDocument()+ })})describe('IndexFailed', () => {@@ -105,6 +129,11 @@ describe('DocumentsHeader', () => {render(<DocumentsHeader {...defaultProps} />)expect(screen.getByTestId('index-failed')).toBeInTheDocument()})++ it('should not show IndexFailed without document edit permission', () => {+ render(<DocumentsHeader {...defaultProps} canEditDocument={false} />)+ expect(screen.queryByTestId('index-failed')).not.toBeInTheDocument()+ })})describe('Embedding Availability', () => {diff --git a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsxindex a1ee53fa3f7..957b7b7dd0d 100644--- a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx+++ b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx@@ -86,6 +86,10 @@ describe('Operations', () => {datasetId: 'dataset-1',detail: defaultDetail,onUpdate: mockOnUpdate,+ canEdit: true,+ canDownload: true,+ canDelete: true,+ canViewSettings: true,}beforeEach(() => {@@ -124,6 +128,54 @@ describe('Operations', () => {const disabledSwitch = screen.getByRole('switch')expect(disabledSwitch)!.toHaveAttribute('aria-disabled', 'true')})++ it('should not render an operations menu and should disable switch without any document operation permissions', async () => {+ vi.useFakeTimers()+ render(+ <Operations+ {...defaultProps}+ canEdit={false}+ canDownload={false}+ canDelete={false}+ canViewSettings={false}+ />,+ )++ expect(screen.queryByRole('button', { name: 'common.operation.more' })).not.toBeInTheDocument()++ const switchElement = screen.getByRole('switch')+ expect(switchElement)!.toHaveAttribute('aria-disabled', 'true')+ await act(async () => {+ fireEvent.click(switchElement)+ vi.advanceTimersByTime(600)+ })+ expect(mockEnable).not.toHaveBeenCalled()+ expect(mockDisable).not.toHaveBeenCalled()+ vi.useRealTimers()+ })++ it('should only render download action when download is the only granted document operation', async () => {+ render(+ <Operations+ {...defaultProps}+ canEdit={false}+ canDownload+ canDelete={false}+ canViewSettings={false}+ />,+ )++ const moreButton = screen.getByRole('button', { name: 'common.operation.more' })+ await act(async () => {+ fireEvent.click(moreButton)+ })++ expect(screen.getByText('datasetDocuments.list.action.download'))!.toBeInTheDocument()+ expect(screen.queryByText('datasetDocuments.list.table.rename')).not.toBeInTheDocument()+ expect(screen.queryByText('datasetDocuments.list.action.settings')).not.toBeInTheDocument()+ expect(screen.queryByText('datasetDocuments.list.action.archive')).not.toBeInTheDocument()+ expect(screen.queryByText('datasetDocuments.list.action.delete')).not.toBeInTheDocument()+ })})describe('switch toggle', () => {@@ -223,6 +275,17 @@ describe('Operations', () => {})expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-1/documents/doc-1/settings')})++ it('should hide document settings when settings permission is not granted', async () => {+ render(<Operations {...defaultProps} canViewSettings={false} />)++ const moreButton = screen.getByRole('button', { name: 'common.operation.more' })+ await act(async () => {+ fireEvent.click(moreButton)+ })++ expect(screen.queryByText('datasetDocuments.list.action.settings')).not.toBeInTheDocument()+ })})describe('detail scene', () => {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 9002e29f01a..3840223e2db 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@@ -24,8 +24,22 @@ vi.mock('@/next/navigation', () => ({}))vi.mock('@/context/dataset-detail', () => ({- useDatasetDetailContextWithSelector: (selector: (state: { dataset: { doc_form: string } }) => unknown) =>- selector({ dataset: { doc_form: ChunkingMode.text } }),+ useDatasetDetailContextWithSelector: (selector: (state: { dataset: { doc_form: string, created_by: string, permission_keys: string[] } }) => unknown) =>+ selector({+ dataset: {+ doc_form: ChunkingMode.text,+ created_by: 'user-1',+ permission_keys: ['dataset.acl.edit', 'dataset.acl.use'],+ },+ }),+}))++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: ['dataset.create_and_management'],+ }),}))vi.mock('@/app/components/datasets/metadata/hooks/use-batch-edit-document-metadata', () => ({@@ -384,15 +398,14 @@ describe('DocumentList', () => {})it('should show rename modal when rename button is clicked', async () => {- const { container } = render(<DocumentList {...defaultProps} />, { wrapper: createWrapper() })+ render(<DocumentList {...defaultProps} />, { wrapper: createWrapper() })- // Find and click the rename button in the first row- const renameButtons = container.querySelectorAll('.cursor-pointer.rounded-md')- if (renameButtons.length > 0) {- await act(async () => {- fireEvent.click(renameButtons[0]!)- })- }+ await act(async () => {+ fireEvent.click(screen.getAllByRole('button', { name: 'common.operation.more' })[0]!)+ })+ await act(async () => {+ fireEvent.click(await screen.findByText('datasetDocuments.list.table.rename'))+ })expect(screen.getByRole('dialog', { name: 'datasetDocuments.list.table.rename' }))!.toBeInTheDocument()})diff --git a/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx b/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsxindex e4c4fe31c17..7fedde10168 100644--- a/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx+++ b/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx@@ -9,10 +9,13 @@ import ChunkingModeLabel from '@/app/components/datasets/common/chunking-mode-laimport Operations from '@/app/components/datasets/documents/components/operations'import SummaryStatus from '@/app/components/datasets/documents/detail/completed/common/summary-status'import StatusItem from '@/app/components/datasets/documents/status-item'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import useTimestamp from '@/hooks/use-timestamp'import { DataSourceType } from '@/models/datasets'import { useRouter, useSearchParams } from '@/next/navigation'import { formatNumber } from '@/utils/format'+import { getDatasetACLCapabilities } from '@/utils/permission'import DocumentSourceIcon from './document-source-icon'import { renderTdValue } from './utils'@@ -58,6 +61,14 @@ const DocumentTableRow = React.memo(({const router = useRouter()const searchParams = useSearchParams()const documentNameId = React.useId()+ const dataset = useDatasetDetailContextWithSelector(s => s.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const datasetACLCapabilities = React.useMemo(() => getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }), [dataset?.maintainer, dataset?.permission_keys, currentUserId, workspacePermissionKeys])const isFile = doc.data_source_type === DataSourceType.FILEconst fileType = isFile ? doc.data_source_detail_dict?.upload_file?.extension : ''@@ -67,7 +78,7 @@ const DocumentTableRow = React.memo(({router.push(`/datasets/${datasetId}/documents/${doc.id}${queryString ? `?${queryString}` : ''}`)}, [router, datasetId, doc.id, queryString])- const handleCheckboxClick = useCallback((e: React.MouseEvent) => {+ const stopPropagation = useCallback((e: React.SyntheticEvent) => {e.stopPropagation()}, [])@@ -82,7 +93,7 @@ const DocumentTableRow = React.memo(({onClick={handleRowClick}><td className="text-left align-middle text-xs text-text-tertiary">- <div className="flex items-center" onClick={handleCheckboxClick}>+ <div className="flex items-center" role="presentation" onClick={stopPropagation} onKeyDown={stopPropagation}><CheckboxclassName="mr-2 shrink-0"value={doc.id}@@ -111,23 +122,26 @@ const DocumentTableRow = React.memo(({<SummaryStatus status={doc.summary_index_status} /></div>)}- <div className="hidden shrink-0 group-hover:ml-auto group-hover:flex">- <Tooltip>- <TooltipTrigger- render={(- <div- className="cursor-pointer rounded-md p-1 hover:bg-state-base-hover"- onClick={handleRenameClick}- >- <span className="i-ri-edit-line size-4 text-text-tertiary" />- </div>- )}- />- <TooltipContent>- {t('list.table.rename', { ns: 'datasetDocuments' })}- </TooltipContent>- </Tooltip>- </div>+ {datasetACLCapabilities.canEdit && (+ <div className="hidden shrink-0 group-hover:ml-auto group-hover:flex">+ <Tooltip>+ <TooltipTrigger+ render={(+ <button+ type="button"+ className="cursor-pointer rounded-md border-none bg-transparent p-1 hover:bg-state-base-hover"+ onClick={handleRenameClick}+ >+ <span className="i-ri-edit-line size-4 text-text-tertiary" />+ </button>+ )}+ />+ <TooltipContent>+ {t('list.table.rename', { ns: 'datasetDocuments' })}+ </TooltipContent>+ </Tooltip>+ </div>+ )}</div></td><td>@@ -152,6 +166,10 @@ const DocumentTableRow = React.memo(({datasetId={datasetId}detail={pick(doc, ['name', 'enabled', 'archived', 'id', 'data_source_type', 'doc_form', 'display_status'])}onUpdate={onUpdate}+ canEdit={datasetACLCapabilities.canEdit}+ canDownload={datasetACLCapabilities.canDocumentDownload}+ canDelete={datasetACLCapabilities.canDeleteFile}+ canViewSettings={datasetACLCapabilities.canEdit}/></td></tr>diff --git a/web/app/components/datasets/documents/components/documents-header.tsx b/web/app/components/datasets/documents/components/documents-header.tsxindex 3e9f6463f78..bef76cf06a6 100644--- a/web/app/components/datasets/documents/components/documents-header.tsx+++ b/web/app/components/datasets/documents/components/documents-header.tsx@@ -2,9 +2,7 @@import type { FC } from 'react'import type { BuiltInMetadataItem, MetadataItemWithValueLength } from '@/app/components/datasets/metadata/types'import type { SortType } from '@/service/datasets'-import { PlusIcon } from '@heroicons/react/24/solid'import { Button } from '@langgenius/dify-ui/button'-import { RiDraftLine, RiExternalLinkLine } from '@remixicon/react'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import Chip from '@/app/components/base/chip'@@ -28,6 +26,9 @@ type DocumentsHeaderProps = {datasetId: stringdataSourceType?: DataSourceTypeembeddingAvailable: boolean+ canManageMetadata?: boolean+ canAddDocument?: boolean+ canEditDocument?: booleanisFreePlan: boolean// Filter & sort@@ -59,6 +60,9 @@ const DocumentsHeader: FC<DocumentsHeaderProps> = ({datasetId,dataSourceType,embeddingAvailable,+ canManageMetadata = false,+ canAddDocument = false,+ canEditDocument = false,isFreePlan,statusFilterValue,sortValue,@@ -128,7 +132,7 @@ const DocumentsHeader: FC<DocumentsHeaderProps> = ({href={docLink('/use-dify/knowledge/integrate-knowledge-within-application')}><span>{t('list.learnMore', { ns: 'datasetDocuments' })}</span>- <RiExternalLinkLine className="size-3" />+ <span className="i-ri-external-link-line size-3" /></a></div></div>@@ -164,17 +168,17 @@ const DocumentsHeader: FC<DocumentsHeaderProps> = ({{/* Right: Actions */}<div className="flex h-8! items-center justify-center gap-2">- {!isFreePlan && <AutoDisabledDocument datasetId={datasetId} />}- <IndexFailed datasetId={datasetId} />+ {!isFreePlan && canEditDocument && <AutoDisabledDocument datasetId={datasetId} />}+ {canEditDocument && <IndexFailed datasetId={datasetId} />}{!embeddingAvailable && (<StatusWithActiontype="warning"description={t('embeddingModelNotAvailable', { ns: 'dataset' })}/>)}- {embeddingAvailable && (+ {embeddingAvailable && canManageMetadata && (<Button variant="secondary" className="shrink-0" onClick={showEditMetadataModal}>- <RiDraftLine className="mr-1 size-4" />+ <span className="mr-1 i-ri-draft-line size-4" />{t('metadata.metadata', { ns: 'dataset' })}</Button>)}@@ -190,9 +194,9 @@ const DocumentsHeader: FC<DocumentsHeaderProps> = ({onIsBuiltInEnabledChange={onBuiltInEnabledChange}/>)}- {embeddingAvailable && (+ {embeddingAvailable && canAddDocument && (<Button variant="primary" onClick={onAddDocument} className="shrink-0">- <PlusIcon className="mr-2 size-4 stroke-current" />+ <span className="mr-2 i-heroicons-plus-solid size-4 stroke-current" />{addButtonText}</Button>)}diff --git a/web/app/components/datasets/documents/components/empty-element.tsx b/web/app/components/datasets/documents/components/empty-element.tsxindex 506b8ab6dbb..af035622ee0 100644--- a/web/app/components/datasets/documents/components/empty-element.tsx+++ b/web/app/components/datasets/documents/components/empty-element.tsx@@ -12,7 +12,7 @@ type EmptyElementProps = {type?: 'upload' | 'sync'}-const EmptyElement: FC<EmptyElementProps> = ({ canAdd = true, onClick, type = 'upload' }) => {+const EmptyElement: FC<EmptyElementProps> = ({ canAdd = false, onClick, type = 'upload' }) => {const { t } = useTranslation()return (<div className={s.emptyWrapper}>diff --git a/web/app/components/datasets/documents/components/list.tsx b/web/app/components/datasets/documents/components/list.tsxindex 4144cad169c..ef965554b9c 100644--- a/web/app/components/datasets/documents/components/list.tsx+++ b/web/app/components/datasets/documents/components/list.tsx@@ -8,8 +8,10 @@ import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import EditMetadataBatchModal from '@/app/components/datasets/metadata/edit-metadata-batch/modal'import useBatchEditDocumentMetadata from '@/app/components/datasets/metadata/hooks/use-batch-edit-document-metadata'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector as useDatasetDetailContext } from '@/context/dataset-detail'import { ChunkingMode, DocumentActionType } from '@/models/datasets'+import { getDatasetACLCapabilities } from '@/utils/permission'import BatchAction from '../detail/completed/common/batch-action'import s from '../style.module.css'import { DocumentTableRow, SortHeader } from './document-list/components'@@ -59,6 +61,13 @@ const DocumentList = ({const pageSize = pagination.limit ?? 10const totalPages = Math.max(Math.ceil(pagination.total / pageSize), 1)const datasetConfig = useDatasetDetailContext(s => s.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const datasetACLCapabilities = useMemo(() => getDatasetACLCapabilities(datasetConfig?.permission_keys, {+ currentUserId,+ resourceMaintainer: datasetConfig?.maintainer,+ workspacePermissionKeys,+ }), [datasetConfig?.maintainer, datasetConfig?.permission_keys, currentUserId, workspacePermissionKeys])const chunkingMode = datasetConfig?.doc_formconst isGeneralMode = chunkingMode !== ChunkingMode.parentChildconst isQAMode = chunkingMode === ChunkingMode.qa@@ -194,14 +203,14 @@ const DocumentList = ({<BatchActionclassName="absolute bottom-16 left-0 z-20"selectedIds={selectedIds}- onArchive={handleAction(DocumentActionType.archive)}- onBatchSummary={handleAction(DocumentActionType.summary)}- onBatchEnable={handleAction(DocumentActionType.enable)}- onBatchDisable={handleAction(DocumentActionType.disable)}- onBatchDownload={downloadableSelectedIds.length > 0 ? handleBatchDownload : undefined}- onBatchDelete={handleAction(DocumentActionType.delete)}- onEditMetadata={showEditModal}- onBatchReIndex={hasErrorDocumentsSelected ? handleBatchReIndex : undefined}+ onArchive={datasetACLCapabilities.canEdit ? handleAction(DocumentActionType.archive) : undefined}+ onBatchSummary={datasetACLCapabilities.canEdit ? handleAction(DocumentActionType.summary) : undefined}+ onBatchEnable={datasetACLCapabilities.canEdit ? handleAction(DocumentActionType.enable) : undefined}+ onBatchDisable={datasetACLCapabilities.canEdit ? handleAction(DocumentActionType.disable) : undefined}+ onBatchDownload={datasetACLCapabilities.canDocumentDownload && downloadableSelectedIds.length > 0 ? handleBatchDownload : undefined}+ onBatchDelete={datasetACLCapabilities.canDeleteFile ? handleAction(DocumentActionType.delete) : undefined}+ onEditMetadata={datasetACLCapabilities.canEdit ? showEditModal : undefined}+ onBatchReIndex={datasetACLCapabilities.canEdit && hasErrorDocumentsSelected ? handleBatchReIndex : undefined}onCancel={clearSelection}/>)}diff --git a/web/app/components/datasets/documents/components/operations.tsx b/web/app/components/datasets/documents/components/operations.tsxindex 2f6425d880a..c821211da09 100644--- a/web/app/components/datasets/documents/components/operations.tsx+++ b/web/app/components/datasets/documents/components/operations.tsx@@ -51,8 +51,25 @@ type OperationsProps = {onUpdate: (operationName?: string) => voidscene?: 'list' | 'detail'className?: string+ canEdit: boolean+ canDownload: boolean+ canDelete: boolean+ canViewSettings: boolean}-const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSelectedIdChange, onUpdate, scene = 'list', className = '' }: OperationsProps) => {+const Operations = ({+ embeddingAvailable,+ datasetId,+ detail,+ selectedIds,+ onSelectedIdChange,+ onUpdate,+ scene = 'list',+ className = '',+ canEdit,+ canDownload,+ canDelete,+ canViewSettings,+}: OperationsProps) => {const { id, name, enabled = false, archived = false, data_source_type, display_status } = detail || {}const [showModal, setShowModal] = useState(false)const [isOperationsMenuOpen, setIsOperationsMenuOpen] = useState(false)@@ -71,7 +88,29 @@ const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSeleconst { mutateAsync: pauseDocument } = useDocumentPause()const { mutateAsync: resumeDocument } = useDocumentResume()const isListScene = scene === 'list'+ const canShowRenameAction = canEdit && !archived+ const canShowSummaryAction = canEdit && !archived && IS_CE_EDITION+ const canShowSettingsAction = canViewSettings+ const canShowDownloadAction = canDownload && data_source_type === DataSourceType.FILE+ const canShowSyncAction = canEdit && !archived && ['notion_import', DataSourceType.WEB].includes(data_source_type)+ const canShowPauseAction = canEdit && !archived && display_status?.toLowerCase() === 'indexing'+ const canShowResumeAction = canEdit && !archived && display_status?.toLowerCase() === 'paused'+ const canShowArchiveAction = canEdit && !archived+ const canShowUnarchiveAction = canEdit && archived+ const canShowDeleteAction = canDelete+ const canShowPrimarySection = canShowRenameAction || canShowSummaryAction || canShowSettingsAction || canShowDownloadAction || canShowSyncAction+ const canShowStatusSection = canShowPauseAction || canShowResumeAction || canShowArchiveAction || canShowUnarchiveAction+ const hasOperationsMenu = embeddingAvailable && (canShowPrimarySection || canShowStatusSection || canShowDeleteAction)+ const canOperate = useCallback((operationName: OperationName) => {+ if (operationName === DocumentActionType.delete)+ return canDelete++ return canEdit+ }, [canDelete, canEdit])const onOperate = useCallback(async (operationName: OperationName) => {+ if (!canOperate(operationName))+ return+let opApiswitch (operationName) {case 'archive':@@ -121,6 +160,7 @@ const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSelesetDeleting(false)}, [archiveDocument,+ canOperate,data_source_type,datasetId,deleteDocument,@@ -139,6 +179,8 @@ const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSeleunArchiveDocument,])const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {+ if (!canEdit)+ returnif (operationName === DocumentActionType.enable && enabled)returnif (operationName === DocumentActionType.disable && !enabled)@@ -154,16 +196,24 @@ const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSeleid: stringname: string}) => {+ if (!canEdit)+ return+setCurrDocument(doc)setShowRenameModalTrue()- }, [setShowRenameModalTrue])+ }, [canEdit, setShowRenameModalTrue])const handleRenamed = useCallback(() => {onUpdate()}, [onUpdate])const closeOperationsMenu = useCallback(() => {setIsOperationsMenuOpen(false)}, [])+ const stopPropagation = useCallback((e: React.SyntheticEvent) => {+ e.stopPropagation()+ }, [])const handleDownload = useCallback(async () => {+ if (!canDownload)+ return// Avoid repeated clicks while the signed URL request is in-flight.if (isDownloading)return@@ -175,7 +225,7 @@ const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSele}// Trigger download without navigating away (helps avoid duplicate downloads in some browsers).downloadUrl({ url: res.url, fileName: name })- }, [datasetId, downloadDocument, id, isDownloading, name, t])+ }, [canDownload, datasetId, downloadDocument, id, isDownloading, name, t])const handleShowRename = useCallback(() => {closeOperationsMenu()handleShowRenameModal({@@ -188,50 +238,68 @@ const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSelevoid onOperate(operationName)}, [closeOperationsMenu, onOperate])const handleDeleteClick = useCallback(() => {+ if (!canDelete)+ return+closeOperationsMenu()setShowModal(true)- }, [closeOperationsMenu])+ }, [canDelete, closeOperationsMenu])const handleDownloadClick = useCallback((evt: React.MouseEvent<HTMLElement>) => {evt.preventDefault()evt.stopPropagation()evt.nativeEvent.stopImmediatePropagation?.()+ if (!canDownload)+ return+closeOperationsMenu()void handleDownload()- }, [closeOperationsMenu, handleDownload])+ }, [canDownload, closeOperationsMenu, handleDownload])const menuActionClassName = cn(s.actionItem, 'border-none bg-transparent')const menuDeleteActionClassName = cn(menuActionClassName, s.deleteActionItem, 'group')const handleSettingsClick = useCallback((evt: React.MouseEvent<HTMLElement>) => {evt.preventDefault()evt.stopPropagation()evt.nativeEvent.stopImmediatePropagation?.()+ if (!canViewSettings)+ return+closeOperationsMenu()router.push(`/datasets/${datasetId}/documents/${detail.id}/settings`)- }, [closeOperationsMenu, datasetId, detail.id, router])+ }, [canViewSettings, closeOperationsMenu, datasetId, detail.id, router])const settingsMenuItem = (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={handleSettingsClick}><span aria-hidden className="i-ri-equalizer-2-line size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.settings', { ns: 'datasetDocuments' })}</span></button>)+ const renderListSwitch = () => {+ if (!canEdit)+ return <Switch checked={archived ? false : enabled} onCheckedChange={noop} disabled={true} size="md" />++ if (archived) {+ return (+ <Popover>+ <PopoverTrigger nativeButton={false} openOnHover render={<div><Switch checked={false} onCheckedChange={noop} disabled={true} size="md" /></div>} />+ <PopoverContent popupClassName="px-3 py-2 font-semibold system-xs-regular text-text-tertiary">+ {t('list.action.enableWarning', { ns: 'datasetDocuments' })}+ </PopoverContent>+ </Popover>+ )+ }++ return <Switch checked={enabled} onCheckedChange={v => handleSwitch(v ? 'enable' : 'disable')} size="md" />+ }+return (- <div className="flex items-center" onClick={e => e.stopPropagation()}>+ <div className="flex items-center" role="presentation" onClick={stopPropagation} onKeyDown={stopPropagation}>{isListScene && !embeddingAvailable && (<Switch checked={false} onCheckedChange={noop} disabled={true} size="md" />)}{isListScene && embeddingAvailable && (<>- {archived- ? (- <Popover>- <PopoverTrigger nativeButton={false} openOnHover render={<div><Switch checked={false} onCheckedChange={noop} disabled={true} size="md" /></div>} />- <PopoverContent popupClassName="px-3 py-2 font-semibold system-xs-regular text-text-tertiary">- {t('list.action.enableWarning', { ns: 'datasetDocuments' })}- </PopoverContent>- </Popover>- )- : <Switch checked={enabled} onCheckedChange={v => handleSwitch(v ? 'enable' : 'disable')} size="md" />}- <Divider className="mr-2! ml-4! h-3!" type="vertical" />+ {renderListSwitch()}+ {hasOperationsMenu && <Divider className="mr-2! ml-4! h-3!" type="vertical" />}</>)}- {embeddingAvailable && (+ {hasOperationsMenu && (<><DropdownMenu open={isOperationsMenuOpen} onOpenChange={setIsOperationsMenuOpen}><DropdownMenuTrigger@@ -258,74 +326,66 @@ const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSelepopupClassName={cn('w-[200px] py-0', className)}><div className="w-full py-1">- {!archived && (+ {canShowPrimarySection && (<>- <button type="button" className={cn(menuActionClassName, 'text-left')} onClick={handleShowRename}>- <span aria-hidden className="i-ri-edit-line size-4 text-text-tertiary" />- <span className={s.actionName}>{t('list.table.rename', { ns: 'datasetDocuments' })}</span>- </button>- {IS_CE_EDITION && (+ {canShowRenameAction && (+ <button type="button" className={cn(menuActionClassName, 'text-left')} onClick={handleShowRename}>+ <span aria-hidden className="i-ri-edit-line size-4 text-text-tertiary" />+ <span className={s.actionName}>{t('list.table.rename', { ns: 'datasetDocuments' })}</span>+ </button>+ )}+ {canShowSummaryAction && (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={() => handleMenuOperation('summary')}><span aria-hidden className="i-custom-vender-knowledge-search-lines-sparkle size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.summary', { ns: 'datasetDocuments' })}</span></button>)}- {settingsMenuItem}- {data_source_type === DataSourceType.FILE && (+ {canShowSettingsAction && settingsMenuItem}+ {canShowDownloadAction && (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={handleDownloadClick}><span aria-hidden className="i-ri-download-2-line size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.download', { ns: 'datasetDocuments' })}</span></button>)}- {['notion_import', DataSourceType.WEB].includes(data_source_type) && (+ {canShowSyncAction && (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={() => handleMenuOperation('sync')}><span aria-hidden className="i-ri-loop-left-line size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.sync', { ns: 'datasetDocuments' })}</span></button>)}- <Divider className="my-1" />- </>- )}- {archived && (- <>- {settingsMenuItem}- {data_source_type === DataSourceType.FILE && (- <button type="button" className={cn(menuActionClassName, 'text-left')} onClick={handleDownloadClick}>- <span aria-hidden className="i-ri-download-2-line size-4 text-text-tertiary" />- <span className={s.actionName}>{t('list.action.download', { ns: 'datasetDocuments' })}</span>- </button>- )}- <Divider className="my-1" />+ {(canShowStatusSection || canShowDeleteAction) && <Divider className="my-1" />}</>)}- {!archived && display_status?.toLowerCase() === 'indexing' && (+ {canShowPauseAction && (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={() => handleMenuOperation('pause')}><span aria-hidden className="i-ri-pause-circle-line size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.pause', { ns: 'datasetDocuments' })}</span></button>)}- {!archived && display_status?.toLowerCase() === 'paused' && (+ {canShowResumeAction && (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={() => handleMenuOperation('resume')}><span aria-hidden className="i-ri-play-circle-line size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.resume', { ns: 'datasetDocuments' })}</span></button>)}- {!archived && (+ {canShowArchiveAction && (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={() => handleMenuOperation('archive')}><span aria-hidden className="i-ri-archive-2-line size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.archive', { ns: 'datasetDocuments' })}</span></button>)}- {archived && (+ {canShowUnarchiveAction && (<button type="button" className={cn(menuActionClassName, 'text-left')} onClick={() => handleMenuOperation('un_archive')}><span aria-hidden className="i-ri-archive-2-line size-4 text-text-tertiary" /><span className={s.actionName}>{t('list.action.unarchive', { ns: 'datasetDocuments' })}</span></button>)}- <button type="button" className={cn(menuDeleteActionClassName, 'text-left')} onClick={handleDeleteClick}>- <span aria-hidden className="i-ri-delete-bin-line size-4 text-text-tertiary group-hover:text-text-destructive" />- <span className={cn(s.actionName, 'group-hover:text-text-destructive')}>{t('list.action.delete', { ns: 'datasetDocuments' })}</span>- </button>+ {canShowDeleteAction && (+ <button type="button" className={cn(menuDeleteActionClassName, 'text-left')} onClick={handleDeleteClick}>+ <span aria-hidden className="i-ri-delete-bin-line size-4 text-text-tertiary group-hover:text-text-destructive" />+ <span className={cn(s.actionName, 'group-hover:text-text-destructive')}>{t('list.action.delete', { ns: 'datasetDocuments' })}</span>+ </button>+ )}</div></DropdownMenuContent></DropdownMenu>diff --git a/web/app/components/datasets/documents/create-from-pipeline/__tests__/index.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/__tests__/index.spec.tsxindex ae1eb817b4c..b6ec26b923c 100644--- a/web/app/components/datasets/documents/create-from-pipeline/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/create-from-pipeline/__tests__/index.spec.tsx@@ -4,7 +4,7 @@ import type { Node } from '@/app/components/workflow/types'import type { NotionPage } from '@/models/common'import type { CrawlResultItem, CustomFile, DocumentItem, FileItem } from '@/models/datasets'import type { InitialDocumentDetail, OnlineDriveFile } from '@/models/pipeline'-import { act, fireEvent, render, renderHook, screen } from '@testing-library/react'+import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { BlockEnum } from '@/app/components/workflow/types'import { DatasourceType } from '@/models/pipeline'@@ -19,6 +19,7 @@ import {useOnlineDrive,useWebsiteCrawl,} from '../hooks'+import CreateFromPipeline from '../index'import { StepOneContent, StepThreeContent, StepTwoContent } from '../steps'import { StepOnePreview, StepTwoPreview } from '../steps/preview-panel'import {@@ -37,11 +38,31 @@ const mockPlan = {type: 'professional',}+let mockDatasetPermissionKeys = ['dataset.acl.use']+const mockRouterReplace = vi.fn()+vi.mock('@/context/provider-context', () => ({useProviderContextSelector: (selector: (state: { plan: typeof mockPlan, enableBilling: boolean }) => unknown) =>selector({ plan: mockPlan, enableBilling: true }),}))+let mockCurrentUserId = 'user-1'+let mockWorkspacePermissionKeys = ['dataset.create_and_management']+let mockIsLoadingWorkspacePermissionKeys = false+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: {+ userProfile: { id: string }+ workspacePermissionKeys: string[]+ isLoadingWorkspacePermissionKeys: boolean+ }) => unknown) => {+ return selector({+ userProfile: { id: mockCurrentUserId },+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ isLoadingWorkspacePermissionKeys: mockIsLoadingWorkspacePermissionKeys,+ })+ },+}))+vi.mock('@/service/use-billing', () => ({useCurrentPlanVectorSpace: () => ({data: {@@ -53,8 +74,8 @@ vi.mock('@/service/use-billing', () => ({}))vi.mock('@/context/dataset-detail', () => ({- useDatasetDetailContextWithSelector: (selector: (state: { dataset: { pipeline_id: string } }) => unknown) =>- selector({ dataset: { pipeline_id: 'test-pipeline-id' } }),+ useDatasetDetailContextWithSelector: (selector: (state: { dataset: { id: string, pipeline_id: string, permission_keys: string[] } }) => unknown) =>+ selector({ dataset: { id: 'test-dataset-id', pipeline_id: 'test-pipeline-id', permission_keys: mockDatasetPermissionKeys } }),}))// Mock API services@@ -104,7 +125,7 @@ vi.mock('@/next/navigation', () => ({useParams: () => ({ datasetId: 'test-dataset-id' }),useRouter: () => ({push: vi.fn(),- replace: vi.fn(),+ replace: mockRouterReplace,back: vi.fn(),}),usePathname: () => '/datasets/test-dataset-id/documents/create-from-pipeline',@@ -233,6 +254,26 @@ const createMockOnlineDriveFile = (overrides?: Partial<OnlineDriveFile>): Online...overrides,} as OnlineDriveFile)+beforeEach(() => {+ mockDatasetPermissionKeys = ['dataset.acl.use']+ mockCurrentUserId = 'user-1'+ mockWorkspacePermissionKeys = ['dataset.create_and_management']+ mockIsLoadingWorkspacePermissionKeys = false+ mockRouterReplace.mockClear()+})++describe('CreateFromPipeline permission guard', () => {+ it('should redirect when existing dataset cannot add documents', async () => {+ mockDatasetPermissionKeys = ['dataset.acl.edit']++ render(<CreateFromPipeline />)++ await waitFor(() => {+ expect(mockRouterReplace).toHaveBeenCalledWith('/datasets/test-dataset-id/documents')+ })+ })+})+// Hook Tests - useAddDocumentsStepsdescribe('useAddDocumentsSteps', () => {it('should initialize with step 1', () => {diff --git a/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-actions.spec.ts b/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-actions.spec.tsindex 2328541cd1a..a1c38c683d3 100644--- a/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-actions.spec.ts+++ b/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-actions.spec.ts@@ -201,4 +201,35 @@ describe('useDatasourceActions', () => {expect.anything(),)})++ it('should not submit process form when processing is not allowed', () => {+ const params = {+ ...defaultParams(),+ canProcess: false,+ }+ const submit = vi.fn()+ const { result } = renderHook(() => useDatasourceActions(params))+ result.current.formRef.current = { submit }++ act(() => {+ result.current.onClickProcess()+ })++ expect(submit).not.toHaveBeenCalled()+ })++ it('should not run published pipeline when processing is not allowed', () => {+ const params = {+ ...defaultParams(),+ canProcess: false,+ }+ const { result } = renderHook(() => useDatasourceActions(params))++ act(() => {+ result.current.handleSubmit({ query: 'test' })+ })++ expect(mockRunPublishedPipeline).not.toHaveBeenCalled()+ expect(params.handleNextStep).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-actions.ts b/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-actions.tsindex ae6472118c7..a0ac69bd1ab 100644--- a/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-actions.ts+++ b/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-actions.ts@@ -34,6 +34,7 @@ type DatasourceActionsParams = {clearWebsiteCrawlData: () => voidclearOnlineDriveData: () => voidsetDatasource: (ds: Datasource) => void+ canProcess?: boolean}/**@@ -54,6 +55,7 @@ export const useDatasourceActions = ({clearWebsiteCrawlData,clearOnlineDriveData,setDatasource,+ canProcess = true,}: DatasourceActionsParams) => {const isPreview = useRef(false)const formRef = useRef<{ submit: () => void } | null>(null)@@ -170,6 +172,9 @@ export const useDatasourceActions = ({// Handle document processingconst handleProcess = useCallback(async (data: Record<string, unknown>) => {+ if (!canProcess)+ return+if (!datasource || !pipelineId)return@@ -192,13 +197,16 @@ export const useDatasourceActions = ({})},})- }, [datasource, pipelineId, datasourceType, buildProcessDatasourceInfo, runPublishedPipeline, setBatchId, setDocuments, handleNextStep])+ }, [canProcess, datasource, pipelineId, datasourceType, buildProcessDatasourceInfo, runPublishedPipeline, setBatchId, setDocuments, handleNextStep])// Form submission handlersconst onClickProcess = useCallback(() => {+ if (!canProcess)+ return+isPreview.current = falseformRef.current?.submit()- }, [])+ }, [canProcess])const onClickPreview = useCallback(() => {isPreview.current = truediff --git a/web/app/components/datasets/documents/create-from-pipeline/index.tsx b/web/app/components/datasets/documents/create-from-pipeline/index.tsxindex 07843217eff..d83e9ae501d 100644--- a/web/app/components/datasets/documents/create-from-pipeline/index.tsx+++ b/web/app/components/datasets/documents/create-from-pipeline/index.tsx@@ -5,16 +5,19 @@ import type { Node } from '@/app/components/workflow/types'import type { FileIndexingEstimateResponse } from '@/models/datasets'import type { InitialDocumentDetail } from '@/models/pipeline'import { useBoolean } from 'ahooks'-import { useCallback, useMemo, useState } from 'react'+import { useCallback, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useProviderContextSelector } from '@/context/provider-context'import { DatasourceType } from '@/models/pipeline'+import { useRouter } from '@/next/navigation'import { useCurrentPlanVectorSpace } from '@/service/use-billing'import { useFileUploadConfig } from '@/service/use-common'import { usePublishedPipelineInfo } from '@/service/use-pipeline'+import { getDatasetACLCapabilities } from '@/utils/permission'import { useDataSourceStore } from './data-source/store'import DataSourceProvider from './data-source/store/provider'import {@@ -32,10 +35,23 @@ import { StepOnePreview, StepTwoPreview } from './steps/preview-panel'const CreateFormPipeline = () => {const { t } = useTranslation()+ const router = useRouter()const plan = useProviderContextSelector(state => state.plan)const enableBilling = useProviderContextSelector(state => state.enableBilling)- const pipelineId = useDatasetDetailContextWithSelector(s => s.dataset?.pipeline_id)+ const dataset = useDatasetDetailContextWithSelector(s => s.dataset)+ const pipelineId = dataset?.pipeline_id+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const isLoadingWorkspacePermissionKeys = useAppContextWithSelector(state => state.isLoadingWorkspacePermissionKeys)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const dataSourceStore = useDataSourceStore()+ const canAddDocumentsToDataset = getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }).canUse+ const shouldRedirectToDocuments = !!dataset+ && !isLoadingWorkspacePermissionKeys+ && !canAddDocumentsToDataset// Core stateconst [datasource, setDatasource] = useState<Datasource>()@@ -187,11 +203,20 @@ const CreateFormPipeline = () => {clearWebsiteCrawlData,clearOnlineDriveData,setDatasource,+ canProcess: canAddDocumentsToDataset,})+ useEffect(() => {+ if (shouldRedirectToDocuments && dataset?.id)+ router.replace(`/datasets/${dataset.id}/documents`)+ }, [dataset, router, shouldRedirectToDocuments])+if (isFetchingPipelineInfo)return <Loading type="app" />+ if (isLoadingWorkspacePermissionKeys || shouldRedirectToDocuments)+ return <Loading type="app" />+return (<div className="relative flex h-[calc(100vh-56px)] w-full min-w-[1024px] overflow-x-auto rounded-t-2xl border-t border-effects-highlight bg-background-default-subtle"><div className="h-full min-w-0 flex-1">diff --git a/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/__tests__/index.spec.tsxindex e8946ce5842..ebbd6ef4a2a 100644--- a/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx@@ -1,10 +1,11 @@import { act, fireEvent, render, screen } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { DatasetACLPermission } from '@/utils/permission'// --- All hoisted mock fns and state (accessible inside vi.mock factories) ---const mocks = vi.hoisted(() => {const state = {- dataset: { embedding_available: true } as Record<string, unknown> | null,+ dataset: { embedding_available: true, permission_keys: ['dataset.acl.edit'] } as Record<string, unknown> | null,documentDetail: null as Record<string, unknown> | null,documentError: null as Error | null,documentMetadata: null as Record<string, unknown> | null,@@ -156,8 +157,8 @@ vi.mock('../../status-item', () => ({}))vi.mock('@/app/components/datasets/metadata/metadata-document', () => ({- default: ({ datasetId, documentId }: { datasetId?: string, documentId?: string }) => (- <div data-testid="metadata" data-dataset-id={datasetId} data-document-id={documentId}>Metadata</div>+ default: ({ datasetId, documentId, canEdit }: { datasetId?: string, documentId?: string, canEdit?: boolean }) => (+ <div data-testid="metadata" data-dataset-id={datasetId} data-document-id={documentId} data-can-edit={String(canEdit)}>Metadata</div>),}))@@ -195,7 +196,7 @@ describe('DocumentDetail', () => {beforeEach(() => {vi.clearAllMocks()vi.useFakeTimers()- mocks.state.dataset = { embedding_available: true }+ mocks.state.dataset = { embedding_available: true, permission_keys: [DatasetACLPermission.Edit] }mocks.state.documentDetail = createDocumentDetail()mocks.state.documentError = nullmocks.state.documentMetadata = null@@ -284,6 +285,12 @@ describe('DocumentDetail', () => {render(<DocumentDetail datasetId="ds-1" documentId="doc-1" />)expect(screen.queryByTestId('segment-add')).not.toBeInTheDocument()})++ it('should hide SegmentAdd when dataset only has readonly ACL permission', () => {+ mocks.state.dataset = { embedding_available: true, permission_keys: [DatasetACLPermission.Readonly] }+ render(<DocumentDetail datasetId="ds-1" documentId="doc-1" />)+ expect(screen.queryByTestId('segment-add')).not.toBeInTheDocument()+ })})describe('Metadata Panel', () => {@@ -316,6 +323,14 @@ describe('DocumentDetail', () => {const metadata = screen.getByTestId('metadata')expect(metadata).toHaveAttribute('data-dataset-id', 'ds-1')expect(metadata).toHaveAttribute('data-document-id', 'doc-1')+ expect(metadata).toHaveAttribute('data-can-edit', 'true')+ })++ it('should pass readonly ACL state to Metadata', () => {+ mocks.state.dataset = { embedding_available: true, permission_keys: [DatasetACLPermission.Readonly] }+ render(<DocumentDetail datasetId="ds-1" documentId="doc-1" />)++ expect(screen.getByTestId('metadata')).toHaveAttribute('data-can-edit', 'false')})})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 f0913405c42..9d1354d045d 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@@ -22,10 +22,10 @@ const i18nPrefix = 'batchAction'type IBatchActionProps = {className?: stringselectedIds: string[]- onBatchEnable: () => void- onBatchDisable: () => void+ onBatchEnable?: () => void+ onBatchDisable?: () => voidonBatchDownload?: () => void- onBatchDelete: () => Promise<void>+ onBatchDelete?: () => Promise<void>onBatchSummary?: () => voidonArchive?: () => voidonEditMetadata?: () => void@@ -56,6 +56,9 @@ const BatchAction: FC<IBatchActionProps> = ({}] = useBoolean(false)const handleBatchDelete = async () => {+ if (!onBatchDelete)+ return+setIsDeleting()await onBatchDelete()hideDeleteConfirm()@@ -70,22 +73,26 @@ const BatchAction: FC<IBatchActionProps> = ({<span className="system-sm-semibold text-text-accent">{t(`${i18nPrefix}.selected`, { ns: 'dataset' })}</span></div><Divider type="vertical" className="mx-0.5 h-3.5 bg-divider-regular" />- <Button- variant="ghost"- className="gap-x-0.5 px-3"- onClick={onBatchEnable}- >- <RiCheckboxCircleLine className="size-4" />- <span className="px-0.5">{t(`${i18nPrefix}.enable`, { ns: 'dataset' })}</span>- </Button>- <Button- variant="ghost"- className="gap-x-0.5 px-3"- onClick={onBatchDisable}- >- <RiCloseCircleLine className="size-4" />- <span className="px-0.5">{t(`${i18nPrefix}.disable`, { ns: 'dataset' })}</span>- </Button>+ {onBatchEnable && (+ <Button+ variant="ghost"+ className="gap-x-0.5 px-3"+ onClick={onBatchEnable}+ >+ <RiCheckboxCircleLine className="size-4" />+ <span className="px-0.5">{t(`${i18nPrefix}.enable`, { ns: 'dataset' })}</span>+ </Button>+ )}+ {onBatchDisable && (+ <Button+ variant="ghost"+ className="gap-x-0.5 px-3"+ onClick={onBatchDisable}+ >+ <RiCloseCircleLine className="size-4" />+ <span className="px-0.5">{t(`${i18nPrefix}.disable`, { ns: 'dataset' })}</span>+ </Button>+ )}{onEditMetadata && (<Buttonvariant="ghost"@@ -136,15 +143,17 @@ const BatchAction: FC<IBatchActionProps> = ({<span className="px-0.5">{t(`${i18nPrefix}.download`, { ns: 'dataset' })}</span></Button>)}- <Button- variant="ghost"- tone="destructive"- className="gap-x-0.5 px-3"- onClick={showDeleteConfirm}- >- <RiDeleteBinLine className="size-4" />- <span className="px-0.5">{t(`${i18nPrefix}.delete`, { ns: 'dataset' })}</span>- </Button>+ {onBatchDelete && (+ <Button+ variant="ghost"+ tone="destructive"+ className="gap-x-0.5 px-3"+ onClick={showDeleteConfirm}+ >+ <RiDeleteBinLine className="size-4" />+ <span className="px-0.5">{t(`${i18nPrefix}.delete`, { ns: 'dataset' })}</span>+ </Button>+ )}<Divider type="vertical" className="mx-0.5 h-3.5 bg-divider-regular" /><Button@@ -155,24 +164,26 @@ const BatchAction: FC<IBatchActionProps> = ({<span className="px-0.5">{t(`${i18nPrefix}.cancel`, { ns: 'dataset' })}</span></Button></div>- <AlertDialog open={isShowDeleteConfirm} onOpenChange={open => !open && hideDeleteConfirm()}>- <AlertDialogContent>- <div className="flex flex-col gap-2 px-6 pt-6 pb-4">- <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">- {t('list.delete.title', { ns: 'datasetDocuments' })}- </AlertDialogTitle>- <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">- {t('list.delete.content', { ns: 'datasetDocuments' })}- </AlertDialogDescription>- </div>- <AlertDialogActions>- <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>- <AlertDialogConfirmButton loading={isDeleting} disabled={isDeleting} onClick={handleBatchDelete}>- {t('operation.sure', { ns: 'common' })}- </AlertDialogConfirmButton>- </AlertDialogActions>- </AlertDialogContent>- </AlertDialog>+ {onBatchDelete && (+ <AlertDialog open={isShowDeleteConfirm} onOpenChange={open => !open && hideDeleteConfirm()}>+ <AlertDialogContent>+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">+ {t('list.delete.title', { ns: 'datasetDocuments' })}+ </AlertDialogTitle>+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">+ {t('list.delete.content', { ns: 'datasetDocuments' })}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions>+ <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>+ <AlertDialogConfirmButton loading={isDeleting} disabled={isDeleting} onClick={handleBatchDelete}>+ {t('operation.sure', { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )}</div>)}diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsxindex c0c9629bfd6..1d7ad17d07e 100644--- a/web/app/components/datasets/documents/detail/index.tsx+++ b/web/app/components/datasets/documents/detail/index.tsx@@ -11,6 +11,7 @@ import Divider from '@/app/components/base/divider'import FloatRightContainer from '@/app/components/base/float-right-container'import Loading from '@/app/components/base/loading'import Metadata from '@/app/components/datasets/metadata/metadata-document'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { ChunkingMode, DisplayStatusList } from '@/models/datasets'@@ -19,6 +20,7 @@ import { useDocumentDetail, useDocumentMetadata, useInvalidDocumentList } from 'import { useCheckSegmentBatchImportProgress, useChildSegmentListKey, useSegmentBatchImport, useSegmentListKey } from '@/service/knowledge/use-segment'import { useInvalid } from '@/service/use-base'import { segmentImportStatus } from '@/types/dataset'+import { getDatasetACLCapabilities } from '@/utils/permission'import Operations from '../components/operations'import StatusItem from '../status-item'import BatchModal from './batch-modal'@@ -47,7 +49,18 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {const isMobile = media === MediaType.mobileconst dataset = useDatasetDetailContextWithSelector(s => s.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const embeddingAvailable = !!dataset?.embedding_available+ const datasetACLCapabilities = useMemo(+ () => getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }),+ [dataset?.maintainer, dataset?.permission_keys, currentUserId, workspacePermissionKeys],+ )+ const canEditDocument = datasetACLCapabilities.canEditconst [showMetadata, setShowMetadata] = useState(!isMobile)const [newSegmentModalVisible, setNewSegmentModalVisible] = useState(false)const [batchModalVisible, setBatchModalVisible] = useState(false)@@ -205,7 +218,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {parentMode={parentMode}/><div className="flex flex-wrap items-center">- {embeddingAvailable && documentDetail && !documentDetail.archived && !isFullDocMode && (+ {embeddingAvailable && canEditDocument && documentDetail && !documentDetail.archived && !isFullDocMode && (<><SegmentAddimportStatus={importStatus}@@ -226,6 +239,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {detail={statusDetail}datasetId={datasetId}onUpdate={handleOperate}+ canEdit={canEditDocument}/>)}<Operations@@ -235,6 +249,10 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {datasetId={datasetId}onUpdate={handleOperate}className="w-[200px]!"+ canEdit={canEditDocument}+ canDownload={datasetACLCapabilities.canDocumentDownload}+ canDelete={datasetACLCapabilities.canDeleteFile}+ canViewSettings={canEditDocument}/><buttontype="button"@@ -283,6 +301,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {datasetId={datasetId}documentId={documentId}docDetail={docDetail}+ canEdit={canEditDocument}/></FloatRightContainer></div>diff --git a/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsxindex ae06f1bb282..65725e62cde 100644--- a/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsx@@ -175,6 +175,7 @@ describe('Metadata', () => {docDetail: createMockDocDetail(),loading: false,onUpdate: vi.fn(),+ canEdit: true,}describe('Rendering', () => {@@ -196,6 +197,20 @@ describe('Metadata', () => {expect(screen.getByText(/operation\.edit/i))!.toBeInTheDocument()})+ it('should hide edit button when canEdit is false', () => {+ render(<Metadata {...defaultProps} canEdit={false} />)++ expect(screen.queryByText(/operation\.edit/i)).not.toBeInTheDocument()+ })++ it('should hide edit button by default when canEdit is omitted', () => {+ const { canEdit: _canEdit, ...propsWithoutCanEdit } = defaultProps++ render(<Metadata {...propsWithoutCanEdit} />)++ expect(screen.queryByText(/operation\.edit/i)).not.toBeInTheDocument()+ })+it('should show loading state', () => {render(<Metadata {...defaultProps} loading={true} />)@@ -334,6 +349,17 @@ describe('Metadata', () => {expect(screen.getByText(/metadata\.docTypeSelectTitle/i))!.toBeInTheDocument()})+ it('should keep doc type selection read-only when canEdit is false', () => {+ const docDetail = createMockDocDetail({ doc_type: '' })++ render(<Metadata {...defaultProps} docDetail={docDetail} canEdit={false} />)++ expect(screen.queryByText(/metadata\.docTypeSelectTitle/i)).not.toBeInTheDocument()+ expect(screen.queryByText(/metadata\.firstMetaAction/i)).not.toBeInTheDocument()+ expect(screen.queryByText(/operation\.save/i)).not.toBeInTheDocument()+ expect(mockModifyDocMetadata).not.toHaveBeenCalled()+ })+it('should show description when no doc_type exists', () => {const docDetail = createMockDocDetail({ doc_type: '' })@@ -535,6 +561,7 @@ describe('useMetadataState coverage', () => {docDetail: createMockDocDetail(),loading: false,onUpdate: vi.fn(),+ canEdit: true,}describe('cancelDocType', () => {diff --git a/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.ts b/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.tsindex 2d5afcc3a99..9444095ba07 100644--- a/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.ts+++ b/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.ts@@ -63,7 +63,7 @@ describe('useMetadataState', () => {const stableDocDetail = makeDoc()const { result } = renderHook(() =>- useMetadataState({ docDetail: stableDocDetail, onUpdate }), { wrapper })+ useMetadataState({ docDetail: stableDocDetail, onUpdate, canEdit: true }), { wrapper })// --- Initialization ---expect(result.current.docType).toBe('book')@@ -150,7 +150,7 @@ describe('useMetadataState', () => {// Verify empty doc type starts in editing modeit('should initialize in editing mode when no doc type exists', () => {const stableDocDetail = makeDoc({ doc_type: '' as FullDocumentDetail['doc_type'], doc_metadata: {} as FullDocumentDetail['doc_metadata'] })- const { result } = renderHook(() => useMetadataState({ docDetail: stableDocDetail }), { wrapper })+ const { result } = renderHook(() => useMetadataState({ docDetail: stableDocDetail, canEdit: true }), { wrapper })expect(result.current.docType).toBe('')expect(result.current.editStatus).toBe(true)@@ -167,7 +167,7 @@ describe('useMetadataState', () => {// Verify undefined docDetail handlingit('should handle undefined docDetail gracefully', () => {- const { result } = renderHook(() => useMetadataState({ docDetail: undefined }), { wrapper })+ const { result } = renderHook(() => useMetadataState({ docDetail: undefined, canEdit: true }), { wrapper })expect(result.current.docType).toBe('')expect(result.current.editStatus).toBe(true)diff --git a/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts b/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.tsindex 7fc0c17cb05..2f45d0144e7 100644--- a/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts+++ b/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts@@ -21,41 +21,62 @@ const normalizeDocType = (rawDocType: string): DocType | '' => {type UseMetadataStateOptions = {docDetail?: FullDocumentDetailonUpdate?: () => void+ canEdit?: boolean}-export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOptions) {+export function useMetadataState({ docDetail, onUpdate, canEdit = false }: UseMetadataStateOptions) {const { doc_metadata = {} } = docDetail || {}const rawDocType = docDetail?.doc_type ?? ''const docType = normalizeDocType(rawDocType)+ const shouldSelectDocType = canEdit && !rawDocTypeconst { t } = useTranslation()const datasetId = useDocumentContext(s => s.datasetId)const documentId = useDocumentContext(s => s.documentId)// If no documentType yet, start in editing + showDocTypes mode- const [editStatus, setEditStatus] = useState(!docType)- const [metadataParams, setMetadataParams] = useState<MetadataState>(docType+ const [editStatus, setEditStatus] = useState(shouldSelectDocType)+ const [metadataParams, setMetadataParams] = useState<MetadataState>(rawDocType? { documentType: docType, metadata: (doc_metadata || {}) as Record<string, string> }: { metadata: {} })- const [showDocTypes, setShowDocTypes] = useState(!docType)+ const [showDocTypes, setShowDocTypes] = useState(shouldSelectDocType)const [tempDocType, setTempDocType] = useState<DocType | ''>('')const [saveLoading, setSaveLoading] = useState(false)// Sync local state when the upstream docDetail changes (e.g. after save or navigation).// These setters are intentionally called together to batch-reset multiple pieces// of derived editing state that cannot be expressed as pure derived values.useEffect(() => {- if (docDetail?.doc_type) {- // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect- setEditStatus(false)- // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect- setShowDocTypes(false)- // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect- setTempDocType(docType)- // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect- setMetadataParams({- documentType: docType,- metadata: (docDetail?.doc_metadata || {}) as Record<string, string>,- })- }- }, [docDetail?.doc_type, docDetail?.doc_metadata, docType])+ if (!rawDocType)+ return++ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ setEditStatus(false)+ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ setShowDocTypes(false)+ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ setTempDocType(docType)+ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ setMetadataParams({+ documentType: docType,+ metadata: (docDetail?.doc_metadata || {}) as Record<string, string>,+ })+ }, [docDetail?.doc_metadata, docType, rawDocType])+ useEffect(() => {+ if (rawDocType && canEdit)+ return++ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ setEditStatus(canEdit && !rawDocType)+ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ setShowDocTypes(canEdit && !rawDocType)+ }, [canEdit, rawDocType])+ const updateShowDocTypes = (show: boolean) => {+ if (!canEdit)+ return++ setShowDocTypes(show)+ }const confirmDocType = () => {+ if (!canEdit)+ return+if (!tempDocType)returnsetMetadataParams({@@ -67,20 +88,32 @@ export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOptionsetShowDocTypes(false)}const cancelDocType = () => {+ if (!canEdit)+ return+setTempDocType(metadataParams.documentType ?? '')setEditStatus(true)setShowDocTypes(false)}const enableEdit = () => {+ if (!canEdit)+ return+setEditStatus(true)}const cancelEdit = () => {+ if (!canEdit)+ return+setMetadataParams({ documentType: docType || '', metadata: { ...docDetail?.doc_metadata } })setEditStatus(!docType)if (!docType)setShowDocTypes(true)}const saveMetadata = async () => {+ if (!canEdit)+ return+setSaveLoading(true)const [e] = await asyncRunSafe<CommonResponse>(modifyDocMetadata({datasetId,@@ -99,6 +132,9 @@ export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOptionsetSaveLoading(false)}const updateMetadataField = (field: string, value: string) => {+ if (!canEdit)+ return+setMetadataParams(prev => ({ ...prev, metadata: { ...prev.metadata, [field]: value } }))}return {@@ -109,7 +145,7 @@ export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOptionsaveLoading,metadataParams,setTempDocType,- setShowDocTypes,+ setShowDocTypes: updateShowDocTypes,confirmDocType,cancelDocType,enableEdit,diff --git a/web/app/components/datasets/documents/detail/metadata/index.tsx b/web/app/components/datasets/documents/detail/metadata/index.tsxindex 762f1ff3e41..5fc65f53c52 100644--- a/web/app/components/datasets/documents/detail/metadata/index.tsx+++ b/web/app/components/datasets/documents/detail/metadata/index.tsx@@ -18,9 +18,10 @@ type MetadataProps = {docDetail?: FullDocumentDetailloading: booleanonUpdate: () => void+ canEdit?: boolean}-const Metadata: FC<MetadataProps> = ({ docDetail, loading, onUpdate }) => {+const Metadata: FC<MetadataProps> = ({ docDetail, loading, onUpdate, canEdit = false }) => {const { t } = useTranslation()const metadataMap = useMetadataMap()@@ -39,7 +40,7 @@ const Metadata: FC<MetadataProps> = ({ docDetail, loading, onUpdate }) => {cancelEdit,saveMetadata,updateMetadataField,- } = useMetadataState({ docDetail, onUpdate })+ } = useMetadataState({ docDetail, onUpdate, canEdit })if (loading) {return (@@ -56,21 +57,23 @@ const Metadata: FC<MetadataProps> = ({ docDetail, loading, onUpdate }) => {<span className={s.title}>{t('metadata.title', { ns: 'datasetDocuments' })}</span>{!editStatus? (- <Button onClick={enableEdit} className={`${s.opBtn} ${s.opEditBtn}`}>- <PencilIcon className={s.opIcon} />- {t('operation.edit', { ns: 'common' })}- </Button>- )- : !showDocTypes && (- <div className={s.opBtnWrapper}>- <Button onClick={cancelEdit} className={`${s.opBtn} ${s.opCancelBtn}`}>- {t('operation.cancel', { ns: 'common' })}+ canEdit && (+ <Button onClick={enableEdit} className={`${s.opBtn} ${s.opEditBtn}`}>+ <PencilIcon className={s.opIcon} />+ {t('operation.edit', { ns: 'common' })}</Button>- <Button onClick={saveMetadata} className={`${s.opBtn} ${s.opSaveBtn}`} variant="primary" loading={saveLoading}>- {t('operation.save', { ns: 'common' })}- </Button>- </div>- )}+ )+ )+ : canEdit && !showDocTypes && (+ <div className={s.opBtnWrapper}>+ <Button onClick={cancelEdit} className={`${s.opBtn} ${s.opCancelBtn}`}>+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ <Button onClick={saveMetadata} className={`${s.opBtn} ${s.opSaveBtn}`} variant="primary" loading={saveLoading}>+ {t('operation.save', { ns: 'common' })}+ </Button>+ </div>+ )}</div>{/* Document type display / selector */}@@ -81,7 +84,7 @@ const Metadata: FC<MetadataProps> = ({ docDetail, loading, onUpdate }) => {: (<DocumentTypeDisplaydisplayType={metadataParams.documentType || ''}- showChangeLink={editStatus}+ showChangeLink={canEdit && editStatus}onChangeClick={() => setShowDocTypes(true)}/>)}@@ -90,7 +93,7 @@ const Metadata: FC<MetadataProps> = ({ docDetail, loading, onUpdate }) => {{(!docType && showDocTypes) ? null : <Divider />}{/* Doc type selector or editable metadata fields */}- {showDocTypes+ {canEdit && showDocTypes? (<DocTypeSelectordocType={docType}@@ -104,7 +107,7 @@ const Metadata: FC<MetadataProps> = ({ docDetail, loading, onUpdate }) => {: (<MetadataFieldListmainField={metadataParams.documentType || ''}- canEdit={editStatus}+ canEdit={canEdit && editStatus}metadata={metadataParams.metadata}docDetail={docDetail}onFieldUpdate={updateMetadataField}diff --git a/web/app/components/datasets/documents/index.tsx b/web/app/components/datasets/documents/index.tsxindex 29d9c01f714..33b27c1c46e 100644--- a/web/app/components/datasets/documents/index.tsx+++ b/web/app/components/datasets/documents/index.tsx@@ -2,6 +2,7 @@import type { FC } from 'react'import { useCallback } from 'react'import Loading from '@/app/components/base/loading'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useProviderContext } from '@/context/provider-context'import { DataSourceType } from '@/models/datasets'@@ -9,6 +10,7 @@ import { useRouter } from '@/next/navigation'import { useDocumentList, useInvalidDocumentDetail, useInvalidDocumentList } from '@/service/knowledge/use-document'import { useChildSegmentListKey, useSegmentListKey } from '@/service/knowledge/use-segment'import { useInvalid } from '@/service/use-base'+import { getDatasetACLCapabilities } from '@/utils/permission'import useEditDocumentMetadata from '../metadata/hooks/use-edit-dataset-metadata'import DocumentsHeader from './components/documents-header'import EmptyElement from './components/empty-element'@@ -29,7 +31,14 @@ const Documents: FC<IDocumentsProps> = ({ datasetId }) => {const isFreePlan = plan.type === 'sandbox'const dataset = useDatasetDetailContextWithSelector(s => s.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const embeddingAvailable = !!dataset?.embedding_available+ const datasetACLCapabilities = getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ })// Use custom hook for page state managementconst {@@ -106,12 +115,14 @@ const Documents: FC<IDocumentsProps> = ({ datasetId }) => {// Route to document creation pageconst routeToDocCreate = useCallback(() => {+ if (!datasetACLCapabilities.canUse)+ returnif (dataset?.runtime_mode === 'rag_pipeline') {router.push(`/datasets/${datasetId}/documents/create-from-pipeline`)return}router.push(`/datasets/${datasetId}/documents/create`)- }, [dataset?.runtime_mode, datasetId, router])+ }, [dataset?.runtime_mode, datasetACLCapabilities.canUse, datasetId, router])const total = documentsRes?.total || 0const documentsList = documentsRes?.data@@ -147,7 +158,7 @@ const Documents: FC<IDocumentsProps> = ({ datasetId }) => {const isDataSourceNotion = dataset?.data_source_type === DataSourceType.NOTIONreturn (<EmptyElement- canAdd={embeddingAvailable}+ canAdd={embeddingAvailable && datasetACLCapabilities.canUse}onClick={routeToDocCreate}type={isDataSourceNotion ? 'sync' : 'upload'}/>@@ -160,6 +171,9 @@ const Documents: FC<IDocumentsProps> = ({ datasetId }) => {datasetId={datasetId}dataSourceType={dataset?.data_source_type}embeddingAvailable={embeddingAvailable}+ canManageMetadata={datasetACLCapabilities.canEdit}+ canAddDocument={datasetACLCapabilities.canUse}+ canEditDocument={datasetACLCapabilities.canEdit}isFreePlan={isFreePlan}statusFilterValue={statusFilterValue}sortValue={sortValue}diff --git a/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsx b/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsxindex 324e7142427..490dbed6378 100644--- a/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsx@@ -161,6 +161,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEdit/>,)// Switch component should be present in detail scene@@ -186,6 +187,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEdit/>,)const switchElement = screen.getByRole('switch')@@ -203,6 +205,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEdit/>,)const switchElement = screen.getByRole('switch')@@ -220,6 +223,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEdit/>,)const switchElement = screen.getByRole('switch')@@ -242,6 +246,24 @@ describe('StatusItem', () => {const switchElement = screen.getByRole('switch')expect(switchElement).toHaveAttribute('aria-disabled', 'true')})++ it('should render switch as disabled when canEdit is false', () => {+ render(+ <StatusItem+ status="available"+ scene="detail"+ detail={{+ enabled: true,+ archived: false,+ id: 'doc-1',+ }}+ datasetId="dataset-1"+ canEdit={false}+ />,+ )+ const switchElement = screen.getByRole('switch')+ expect(switchElement).toHaveAttribute('aria-disabled', 'true')+ })})describe('switch operations', () => {@@ -257,6 +279,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEditonUpdate={mockOnUpdate}/>,)@@ -284,6 +307,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEditonUpdate={mockOnUpdate}/>,)@@ -325,6 +349,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEditonUpdate={mockOnUpdate}/>,)@@ -353,6 +378,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEditonUpdate={mockOnUpdate}/>,)@@ -384,6 +410,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEditonUpdate={mockOnUpdate}/>,)@@ -413,6 +440,7 @@ describe('StatusItem', () => {id: 'doc-1',}}datasetId="dataset-1"+ canEditonUpdate={mockOnUpdate}/>,)diff --git a/web/app/components/datasets/documents/status-item/index.tsx b/web/app/components/datasets/documents/status-item/index.tsxindex fb875fee571..f225b9fd378 100644--- a/web/app/components/datasets/documents/status-item/index.tsx+++ b/web/app/components/datasets/documents/status-item/index.tsx@@ -37,8 +37,9 @@ type StatusItemProps = {}datasetId?: stringonUpdate?: (operationName?: string) => void+ canEdit?: boolean}-const StatusItem = ({ status, reverse = false, scene = 'list', textCls = '', errorMessage, datasetId = '', detail, onUpdate }: StatusItemProps) => {+const StatusItem = ({ status, reverse = false, scene = 'list', textCls = '', errorMessage, datasetId = '', detail, onUpdate, canEdit = false }: StatusItemProps) => {const { t } = useTranslation()const DOC_INDEX_STATUS_MAP = useIndexStatus()const localStatus = status.toLowerCase() as keyof typeof DOC_INDEX_STATUS_MAP@@ -48,6 +49,9 @@ const StatusItem = ({ status, reverse = false, scene = 'list', textCls = '', errconst { mutateAsync: disableDocument } = useDocumentDisable()const { mutateAsync: deleteDocument } = useDocumentDelete()const onOperate = async (operationName: OperationName) => {+ if (!canEdit)+ return+let opApi = deleteDocumentswitch (operationName) {case 'enable':@@ -67,6 +71,8 @@ const StatusItem = ({ status, reverse = false, scene = 'list', textCls = '', err}}const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {+ if (!canEdit)+ returnif (operationName === 'enable' && enabled)returnif (operationName === 'disable' && !enabled)@@ -99,8 +105,8 @@ const StatusItem = ({ status, reverse = false, scene = 'list', textCls = '', err<span className="flex"><Switchchecked={archived ? false : enabled}- onCheckedChange={v => !archived && handleSwitch(v ? 'enable' : 'disable')}- disabled={embedding || archived}+ onCheckedChange={v => !archived && canEdit && handleSwitch(v ? 'enable' : 'disable')}+ disabled={embedding || archived || !canEdit}size="md"/></span>diff --git a/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsx b/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsxindex 964b8fe3443..573a9c16b73 100644--- a/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsx+++ b/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsx@@ -29,8 +29,8 @@ vi.mock('@/context/i18n', () => ({// Mock the ExternalKnowledgeAPICard to avoid mocking its internal dependenciesvi.mock('../../external-knowledge-api-card', () => ({- default: ({ api }: { api: ExternalAPIItem }) => (- <div data-testid={`api-card-${api.id}`}>{api.name}</div>+ default: ({ api, canManageExternalKnowledgeApi }: { api: ExternalAPIItem, canManageExternalKnowledgeApi: boolean }) => (+ <div data-testid={`api-card-${api.id}`} data-can-manage-external-knowledge-api={canManageExternalKnowledgeApi}>{api.name}</div>),}))@@ -38,6 +38,7 @@ vi.mock('../../external-knowledge-api-card', () => ({describe('ExternalAPIPanel', () => {const defaultProps = {+ canManageExternalKnowledgeApi: true,onClose: vi.fn(),}@@ -71,6 +72,11 @@ describe('ExternalAPIPanel', () => {expect(screen.getByText('dataset.createExternalAPI'))!.toBeInTheDocument()})+ it('should hide create button when external knowledge API management is unavailable', () => {+ render(<ExternalAPIPanel {...defaultProps} canManageExternalKnowledgeApi={false} />)+ expect(screen.queryByText('dataset.createExternalAPI')).not.toBeInTheDocument()+ })+it('should render close button', () => {const { container } = render(<ExternalAPIPanel {...defaultProps} />)const closeButton = container.querySelector('[class*="action-button"]') || screen.getAllByRole('button')[0]@@ -123,6 +129,7 @@ describe('ExternalAPIPanel', () => {render(<ExternalAPIPanel {...defaultProps} />)expect(screen.getByTestId('api-card-api-1'))!.toBeInTheDocument()expect(screen.getByTestId('api-card-api-2'))!.toBeInTheDocument()+ expect(screen.getByTestId('api-card-api-1')).toHaveAttribute('data-can-manage-external-knowledge-api', 'true')expect(screen.getByText('Test API 1'))!.toBeInTheDocument()expect(screen.getByText('Test API 2'))!.toBeInTheDocument()})@@ -131,7 +138,7 @@ describe('ExternalAPIPanel', () => {describe('User Interactions', () => {it('should call onClose when close button is clicked', () => {const onClose = vi.fn()- render(<ExternalAPIPanel onClose={onClose} />)+ render(<ExternalAPIPanel canManageExternalKnowledgeApi={true} onClose={onClose} />)// Find the close button (ActionButton with close icon)const buttons = screen.getAllByRole('button')const closeButton = buttons.find(btn => btn.querySelector('svg[class*="ri-close"]'))diff --git a/web/app/components/datasets/external-api/external-api-panel/index.tsx b/web/app/components/datasets/external-api/external-api-panel/index.tsxindex 32f7def506c..1255391c1ec 100644--- a/web/app/components/datasets/external-api/external-api-panel/index.tsx+++ b/web/app/components/datasets/external-api/external-api-panel/index.tsx@@ -15,16 +15,20 @@ import { useModalContext } from '@/context/modal-context'import ExternalKnowledgeAPICard from '../external-knowledge-api-card'type ExternalAPIPanelProps = {+ canManageExternalKnowledgeApi: booleanonClose: () => void}-const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({ onClose }) => {+const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({ canManageExternalKnowledgeApi, onClose }) => {const { t } = useTranslation()const docLink = useDocLink()const { setShowExternalKnowledgeAPIModal } = useModalContext()const { externalKnowledgeApiList, mutateExternalKnowledgeApis, isLoading } = useExternalKnowledgeApi()const handleOpenExternalAPIModal = () => {+ if (!canManageExternalKnowledgeApi)+ return+setShowExternalKnowledgeAPIModal({payload: { name: '', settings: { endpoint: '', api_key: '' } },datasetBindings: [],@@ -67,16 +71,18 @@ const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({ onClose }) => {</ActionButton></div></div>- <div className="flex flex-col items-start justify-center gap-2 self-stretch px-4 py-3">- <Button- variant="primary"- className="flex items-center justify-center gap-0.5 px-3 py-2"- onClick={handleOpenExternalAPIModal}- >- <RiAddLine className="size-4 text-components-button-primary-text" />- <div className="system-sm-medium text-components-button-primary-text">{t('createExternalAPI', { ns: 'dataset' })}</div>- </Button>- </div>+ {canManageExternalKnowledgeApi && (+ <div className="flex flex-col items-start justify-center gap-2 self-stretch px-4 py-3">+ <Button+ variant="primary"+ className="flex items-center justify-center gap-0.5 px-3 py-2"+ onClick={handleOpenExternalAPIModal}+ >+ <RiAddLine className="size-4 text-components-button-primary-text" />+ <div className="system-sm-medium text-components-button-primary-text">{t('createExternalAPI', { ns: 'dataset' })}</div>+ </Button>+ </div>+ )}<div className="flex grow flex-col items-start gap-1 self-stretch px-4 py-0">{isLoading? (@@ -84,7 +90,11 @@ const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({ onClose }) => {): (externalKnowledgeApiList.map(api => (- <ExternalKnowledgeAPICard key={api.id} api={api} />+ <ExternalKnowledgeAPICard+ key={api.id}+ api={api}+ canManageExternalKnowledgeApi={canManageExternalKnowledgeApi}+ />)))}</div>diff --git a/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsx b/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsxindex 6dfd8ff13d1..93edb4e898d 100644--- a/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsx+++ b/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsx@@ -47,6 +47,7 @@ describe('ExternalKnowledgeAPICard', () => {const defaultProps = {api: mockApi,+ canManageExternalKnowledgeApi: true,}beforeEach(() => {@@ -75,6 +76,17 @@ describe('ExternalKnowledgeAPICard', () => {expect(buttons.length).toBe(2)})+ it('should hide edit and delete buttons when external knowledge API management is unavailable', () => {+ const { container } = render((+ <ExternalKnowledgeAPICard+ {...defaultProps}+ canManageExternalKnowledgeApi={false}+ />+ ))++ expect(container.querySelectorAll('button').length).toBe(0)+ })+it('should render API connection icon', () => {const { container } = render(<ExternalKnowledgeAPICard {...defaultProps} />)const icon = container.querySelector('svg')@@ -351,7 +363,7 @@ describe('ExternalKnowledgeAPICard', () => {...mockApi,settings: { endpoint: '', api_key: 'key' },}- render(<ExternalKnowledgeAPICard api={apiWithEmptyEndpoint} />)+ render(<ExternalKnowledgeAPICard api={apiWithEmptyEndpoint} canManageExternalKnowledgeApi={true} />)expect(screen.getByText('Test External API'))!.toBeInTheDocument()})diff --git a/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsx b/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsxindex 3d2e839198a..f1c53e44bba 100644--- a/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsx+++ b/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsx@@ -24,9 +24,10 @@ import { checkUsageExternalAPI, deleteExternalAPI, fetchExternalAPI, updateExtertype ExternalKnowledgeAPICardProps = {api: ExternalAPIItem+ canManageExternalKnowledgeApi: boolean}-const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({ api }) => {+const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({ api, canManageExternalKnowledgeApi }) => {const { setShowExternalKnowledgeAPIModal } = useModalContext()const [showConfirm, setShowConfirm] = useState(false)const [isHovered, setIsHovered] = useState(false)@@ -36,6 +37,9 @@ const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({ apiconst { t } = useTranslation()const handleEditClick = async () => {+ if (!canManageExternalKnowledgeApi)+ return+try {const response = await fetchExternalAPI({ apiTemplateId: api.id })const formValue: CreateExternalAPIReq = {@@ -84,6 +88,9 @@ const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({ api}const handleDeleteClick = async () => {+ if (!canManageExternalKnowledgeApi)+ return+try {const usage = await checkUsageExternalAPI({ apiTemplateId: api.id })if (usage.is_using)@@ -97,6 +104,9 @@ const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({ api}const handleConfirmDelete = async () => {+ if (!canManageExternalKnowledgeApi)+ return+try {const response = await deleteExternalAPI({ apiTemplateId: api.id })if (response && response.result === 'success') {@@ -125,19 +135,21 @@ const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({ api</div><div className="self-stretch system-xs-regular text-text-tertiary">{api.settings.endpoint}</div></div>- <div className="flex items-start gap-1">- <ActionButton onClick={handleEditClick}>- <RiEditLine className="size-4 text-text-tertiary hover:text-text-secondary" />- </ActionButton>- <ActionButton- className="hover:bg-state-destructive-hover"- onClick={handleDeleteClick}- onMouseEnter={() => setIsHovered(true)}- onMouseLeave={() => setIsHovered(false)}- >- <RiDeleteBinLine className="size-4 text-text-tertiary hover:text-text-destructive" />- </ActionButton>- </div>+ {canManageExternalKnowledgeApi && (+ <div className="flex items-start gap-1">+ <ActionButton onClick={handleEditClick}>+ <RiEditLine className="size-4 text-text-tertiary hover:text-text-secondary" />+ </ActionButton>+ <ActionButton+ className="hover:bg-state-destructive-hover"+ onClick={handleDeleteClick}+ onMouseEnter={() => setIsHovered(true)}+ onMouseLeave={() => setIsHovered(false)}+ >+ <RiDeleteBinLine className="size-4 text-text-tertiary hover:text-text-destructive" />+ </ActionButton>+ </div>+ )}</div><AlertDialog open={showConfirm} onOpenChange={open => !open && setShowConfirm(false)}><AlertDialogContent>diff --git a/web/app/components/datasets/external-knowledge-base/create/RetrievalSettings.tsx b/web/app/components/datasets/external-knowledge-base/create/RetrievalSettings.tsxindex 35d61720286..93be9dc1cb3 100644--- a/web/app/components/datasets/external-knowledge-base/create/RetrievalSettings.tsx+++ b/web/app/components/datasets/external-knowledge-base/create/RetrievalSettings.tsx@@ -11,6 +11,7 @@ type RetrievalSettingsProps = {scoreThresholdEnabled: booleanisInHitTesting?: booleanisInRetrievalSetting?: boolean+ readonly?: booleanonChange: (data: { top_k?: number, score_threshold?: number, score_threshold_enabled?: boolean }) => void}@@ -21,6 +22,7 @@ const RetrievalSettings: FC<RetrievalSettingsProps> = ({onChange,isInHitTesting = false,isInRetrievalSetting = false,+ readonly = false,}) => {const { t } = useTranslation()@@ -50,6 +52,7 @@ const RetrievalSettings: FC<RetrievalSettingsProps> = ({value={topK}onChange={(_key, v) => onChange({ top_k: v })}enable={true}+ disabled={readonly}/></div><div className="flex grow flex-col gap-1">@@ -60,6 +63,7 @@ const RetrievalSettings: FC<RetrievalSettingsProps> = ({enable={scoreThresholdEnabled}hasSwitch={true}onSwitchChange={(_key, v) => handleScoreThresholdChange(v)}+ disabled={readonly}/></div></div>diff --git a/web/app/components/datasets/extra-info/__tests__/index.spec.tsx b/web/app/components/datasets/extra-info/__tests__/index.spec.tsxindex de61894a11a..beccaa66600 100644--- a/web/app/components/datasets/extra-info/__tests__/index.spec.tsx+++ b/web/app/components/datasets/extra-info/__tests__/index.spec.tsx@@ -3,6 +3,7 @@ import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { describe, expect, it, vi } from 'vitest'import { AppModeEnum } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'// Component Imports (after mocks)@@ -34,6 +35,7 @@ const mockDataset: Partial<DataSet> = {id: 'dataset-123',name: 'Test Dataset',enable_api: true,+ permission_keys: [DatasetACLPermission.Edit],}// Mock use-context-selector@@ -56,14 +58,6 @@ vi.mock('@/context/dataset-detail', () => ({),}))-// Mock app context for workspace permissions-let mockIsCurrentWorkspaceManager = true-vi.mock('@/context/app-context', () => ({- useSelector: vi.fn((selector: (state: { isCurrentWorkspaceManager: boolean }) => unknown) =>- selector({ isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager }),- ),-}))-const mockEnableDatasetServiceApi = vi.fn(() => Promise.resolve({ result: 'success' }))const mockDisableDatasetServiceApi = vi.fn(() => Promise.resolve({ result: 'success' }))@@ -521,7 +515,7 @@ describe('ApiAccess', () => {describe('ApiAccessCard', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCurrentWorkspaceManager = true+ mockDataset.permission_keys = [DatasetACLPermission.Edit]mockEnableDatasetServiceApi.mockResolvedValue({ result: 'success' })mockDisableDatasetServiceApi.mockResolvedValue({ result: 'success' })})@@ -664,8 +658,8 @@ describe('ApiAccessCard', () => {})describe('Permission Handling', () => {- it('should disable switch when user is not workspace manager', () => {- mockIsCurrentWorkspaceManager = false+ it('should disable switch when dataset lacks edit ACL permission', () => {+ mockDataset.permission_keys = []render(<ApiAccessCard@@ -677,8 +671,8 @@ describe('ApiAccessCard', () => {expect(switchButton).toHaveAttribute('aria-disabled', 'true')})- it('should enable switch when user is workspace manager', () => {- mockIsCurrentWorkspaceManager = true+ it('should enable switch when dataset has edit ACL permission', () => {+ mockDataset.permission_keys = [DatasetACLPermission.Edit]render(<ApiAccessCarddiff --git a/web/app/components/datasets/extra-info/api-access/__tests__/card.spec.tsx b/web/app/components/datasets/extra-info/api-access/__tests__/card.spec.tsxindex 3f9eadc7050..fe2ce21986d 100644--- a/web/app/components/datasets/extra-info/api-access/__tests__/card.spec.tsx+++ b/web/app/components/datasets/extra-info/api-access/__tests__/card.spec.tsx@@ -1,25 +1,21 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { DatasetACLPermission } from '@/utils/permission'import Card from '../card'// Shared mock state for context selectorslet mockDatasetId: string | undefined = 'dataset-123'let mockMutateDatasetRes: ReturnType<typeof vi.fn> = vi.fn()-let mockIsCurrentWorkspaceManager = true+let mockDatasetPermissionKeys: string[] = [DatasetACLPermission.Edit]vi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: (selector: (state: Record<string, unknown>) => unknown) =>selector({- dataset: { id: mockDatasetId },+ dataset: { id: mockDatasetId, permission_keys: mockDatasetPermissionKeys },mutateDatasetRes: mockMutateDatasetRes,}),}))-vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: Record<string, unknown>) => unknown) =>- selector({ isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager }),-}))-const mockEnableApi = vi.fn()const mockDisableApi = vi.fn()@@ -41,7 +37,7 @@ describe('Card (API Access)', () => {vi.clearAllMocks()mockDatasetId = 'dataset-123'mockMutateDatasetRes = vi.fn()- mockIsCurrentWorkspaceManager = true+ mockDatasetPermissionKeys = [DatasetACLPermission.Edit]})// Rendering: verifies enabled/disabled states render correctly@@ -149,8 +145,8 @@ describe('Card (API Access)', () => {// Switch disabled statedescribe('Switch State', () => {- it('should disable switch when user is not workspace manager', () => {- mockIsCurrentWorkspaceManager = false+ it('should disable switch when dataset lacks edit ACL permission', () => {+ mockDatasetPermissionKeys = []render(<Card apiEnabled={true} />)const switchButton = screen.getByRole('switch')@@ -158,8 +154,8 @@ describe('Card (API Access)', () => {expect(switchButton).toHaveAttribute('aria-disabled', 'true')})- it('should enable switch when user is workspace manager', () => {- mockIsCurrentWorkspaceManager = true+ it('should enable switch when dataset has edit ACL permission', () => {+ mockDatasetPermissionKeys = [DatasetACLPermission.Edit]render(<Card apiEnabled={true} />)const switchButton = screen.getByRole('switch')diff --git a/web/app/components/datasets/extra-info/api-access/card.tsx b/web/app/components/datasets/extra-info/api-access/card.tsxindex 0b7a5778538..3a5685e8fbb 100644--- a/web/app/components/datasets/extra-info/api-access/card.tsx+++ b/web/app/components/datasets/extra-info/api-access/card.tsx@@ -1,15 +1,15 @@import { cn } from '@langgenius/dify-ui/cn'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'-import { RiArrowRightUpLine, RiBookOpenLine } from '@remixicon/react'import * as React from 'react'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { useSelector as useAppContextSelector } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'import Link from '@/next/link'import { useDisableDatasetServiceApi, useEnableDatasetServiceApi } from '@/service/knowledge/use-dataset'+import { getDatasetACLCapabilities } from '@/utils/permission'type CardProps = {apiEnabled: boolean@@ -20,11 +20,22 @@ const Card = ({}: CardProps) => {const { t } = useTranslation()const datasetId = useDatasetDetailContextWithSelector(state => state.dataset?.id)+ const dataset = useDatasetDetailContextWithSelector(state => state.dataset)const mutateDatasetRes = useDatasetDetailContextWithSelector(state => state.mutateDatasetRes)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const { mutateAsync: enableDatasetServiceApi } = useEnableDatasetServiceApi()const { mutateAsync: disableDatasetServiceApi } = useDisableDatasetServiceApi()- const isCurrentWorkspaceManager = useAppContextSelector(state => state.isCurrentWorkspaceManager)+ const datasetACLCapabilities = React.useMemo(+ () => getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }),+ [dataset?.maintainer, dataset?.permission_keys, currentUserId, workspacePermissionKeys],+ )+ const canManageApiAccess = datasetACLCapabilities.canEditconst apiReferenceUrl = useDatasetApiAccessUrl()@@ -62,7 +73,7 @@ const Card = ({<Switchchecked={apiEnabled}onCheckedChange={onToggle}- disabled={!isCurrentWorkspaceManager}+ disabled={!canManageApiAccess}/></div><div className="system-xs-regular text-text-tertiary">@@ -78,11 +89,11 @@ const Card = ({rel="noopener noreferrer"className="flex h-8 items-center space-x-[7px] rounded-lg px-2 text-text-tertiary hover:bg-state-base-hover">- <RiBookOpenLine className="size-3.5 shrink-0" />+ <span className="i-ri-book-open-line size-3.5 shrink-0" /><div className="grow truncate system-sm-regular">{t('overview.apiInfo.doc', { ns: 'appOverview' })}</div>- <RiArrowRightUpLine className="size-3.5 shrink-0" />+ <span className="i-ri-arrow-right-up-line size-3.5 shrink-0" /></Link></div></div>diff --git a/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsx b/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsxindex 678434b8c08..fdbebc3d8a7 100644--- a/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsx+++ b/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsx@@ -98,7 +98,7 @@ describe('Card (Service API)', () => {// User Interactions: tests button clicksdescribe('User Interactions', () => {it('should call onOpenSecretKeyModal when API key button is clicked', () => {- renderWithProviders(<Card {...defaultProps} />)+ renderWithProviders(<Card {...defaultProps} canManageSecretKey />)const apiKeyButton = screen.getByText(/serviceApi\.card\.apiKey/).closest('button')fireEvent.click(apiKeyButton!)@@ -106,6 +106,13 @@ describe('Card (Service API)', () => {expect(onOpenSecretKeyModal).toHaveBeenCalledTimes(1)})+ it('should disable API key button when secret key management is not allowed', () => {+ renderWithProviders(<Card {...defaultProps} canManageSecretKey={false} />)++ const apiKeyButton = screen.getByText(/serviceApi\.card\.apiKey/).closest('button')+ expect(apiKeyButton).toBeDisabled()+ })+it('should render API reference as a link', () => {renderWithProviders(<Card {...defaultProps} />)const link = screen.getByRole('link')diff --git a/web/app/components/datasets/extra-info/service-api/__tests__/index.spec.tsx b/web/app/components/datasets/extra-info/service-api/__tests__/index.spec.tsxindex e48e57bd202..06bb88e91ef 100644--- a/web/app/components/datasets/extra-info/service-api/__tests__/index.spec.tsx+++ b/web/app/components/datasets/extra-info/service-api/__tests__/index.spec.tsx@@ -8,6 +8,13 @@ import ServiceApi from '../index'// Mock Setup+let mockWorkspacePermissionKeys: string[] = ['dataset.api_key.manage']++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({ workspacePermissionKeys: mockWorkspacePermissionKeys }),+}))+vi.mock('@/next/navigation', () => ({useRouter: () => ({push: vi.fn(),@@ -31,10 +38,11 @@ vi.mock('@/hooks/use-api-access-url', () => ({// Mock SecretKeyModal to avoid complex modal renderingvi.mock('@/app/components/develop/secret-key/secret-key-modal', () => ({- default: ({ isShow, onClose }: { isShow: boolean, onClose: () => void }) => (+ default: ({ isShow, onClose, canManage }: { isShow: boolean, onClose: () => void, canManage: boolean }) => (isShow? (<div data-testid="secret-key-modal">+ <span data-testid="secret-key-modal-can-manage">{String(canManage)}</span><button onClick={onClose} data-testid="close-modal-btn">Close</button></div>)@@ -48,6 +56,7 @@ const renderCard = (ui: React.ReactElement) =>describe('ServiceApi', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys = ['dataset.api_key.manage']})describe('Rendering', () => {@@ -191,7 +200,7 @@ describe('Card (service-api)', () => {it('should call onOpenSecretKeyModal when API Key button is clicked', async () => {const user = userEvent.setup()- renderCard(<Card apiBaseUrl="https://api.example.com" onOpenSecretKeyModal={onOpenSecretKeyModal} />)+ renderCard(<Card apiBaseUrl="https://api.example.com" onOpenSecretKeyModal={onOpenSecretKeyModal} canManageSecretKey />)const apiKeyButton = screen.getByText(/serviceApi\.card\.apiKey/i).closest('button')if (apiKeyButton)@@ -200,6 +209,13 @@ describe('Card (service-api)', () => {expect(onOpenSecretKeyModal).toHaveBeenCalledTimes(1)})+ it('should disable API Key button when secret key management is not allowed', () => {+ renderCard(<Card apiBaseUrl="https://api.example.com" onOpenSecretKeyModal={onOpenSecretKeyModal} canManageSecretKey={false} />)++ const apiKeyButton = screen.getByText(/serviceApi\.card\.apiKey/i).closest('button')+ expect(apiKeyButton).toBeDisabled()+ })+it('should have correct href for API Reference link', () => {renderCard(<Card apiBaseUrl="https://api.example.com" onOpenSecretKeyModal={onOpenSecretKeyModal} />)@@ -243,4 +259,48 @@ describe('ServiceApi Integration', () => {expect(screen.queryByText(/serviceApi\.card\.title/i)).not.toBeInTheDocument()})})++ it('should pass workspace API key management permission to secret key modal', async () => {+ const user = userEvent.setup()++ render(<ServiceApi apiBaseUrl="https://api.example.com" />)++ const trigger = screen.getByText(/serviceApi\.title/i).closest('[class*="cursor-pointer"]')+ if (trigger)+ await user.click(trigger)++ await waitFor(() => {+ expect(screen.getByText(/serviceApi\.card\.apiKey/i)).toBeInTheDocument()+ })++ const apiKeyButton = screen.getByText(/serviceApi\.card\.apiKey/i).closest('button')+ if (apiKeyButton)+ await user.click(apiKeyButton)++ await waitFor(() => {+ expect(screen.getByTestId('secret-key-modal-can-manage')).toHaveTextContent('true')+ })+ })++ it('should keep API key button disabled without workspace API key management permission', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys = []++ render(<ServiceApi apiBaseUrl="https://api.example.com" />)++ const trigger = screen.getByText(/serviceApi\.title/i).closest('[class*="cursor-pointer"]')+ if (trigger)+ await user.click(trigger)++ await waitFor(() => {+ expect(screen.getByText(/serviceApi\.card\.apiKey/i)).toBeInTheDocument()+ })++ const apiKeyButton = screen.getByText(/serviceApi\.card\.apiKey/i).closest('button')+ expect(apiKeyButton).toBeDisabled()+ if (apiKeyButton)+ await user.click(apiKeyButton)++ expect(screen.queryByTestId('secret-key-modal')).not.toBeInTheDocument()+ })})diff --git a/web/app/components/datasets/extra-info/service-api/card.tsx b/web/app/components/datasets/extra-info/service-api/card.tsxindex c178f875fd5..7a9f1aa8159 100644--- a/web/app/components/datasets/extra-info/service-api/card.tsx+++ b/web/app/components/datasets/extra-info/service-api/card.tsx@@ -1,22 +1,22 @@import { Button } from '@langgenius/dify-ui/button'import { PopoverClose } from '@langgenius/dify-ui/popover'import { StatusDot } from '@langgenius/dify-ui/status-dot'-import { RiBookOpenLine, RiKey2Line } from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'import CopyFeedback from '@/app/components/base/copy-feedback'-import { ApiAggregate } from '@/app/components/base/icons/src/vender/knowledge'import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'import Link from '@/next/link'type CardProps = {apiBaseUrl: stringonOpenSecretKeyModal: () => void+ canManageSecretKey?: boolean}const Card = ({apiBaseUrl,onOpenSecretKeyModal,+ canManageSecretKey = false,}: CardProps) => {const { t } = useTranslation()@@ -28,7 +28,7 @@ const Card = ({<div className="flex items-center gap-x-3"><div className="flex grow items-center gap-x-2"><div className="flex size-6 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-blue-brand-blue-brand-500 shadow-md shadow-shadow-shadow-5">- <ApiAggregate className="size-4 text-text-primary-on-surface" />+ <span className="i-custom-vender-knowledge-api-aggregate size-4 text-text-primary-on-surface" /></div><div className="grow truncate system-sm-semibold text-text-secondary">{t('serviceApi.card.title', { ns: 'dataset' })}@@ -72,9 +72,10 @@ const Card = ({variant="ghost"size="small"className="gap-x-px text-text-tertiary"+ disabled={!canManageSecretKey}onClick={onOpenSecretKeyModal}>- <RiKey2Line className="size-3.5 shrink-0" />+ <span className="i-ri-key-2-line size-3.5 shrink-0" /><span className="px-[3px] system-xs-medium">{t('serviceApi.card.apiKey', { ns: 'dataset' })}</span>@@ -91,7 +92,7 @@ const Card = ({size="small"className="gap-x-px text-text-tertiary">- <RiBookOpenLine className="size-3.5 shrink-0" />+ <span className="i-ri-book-open-line size-3.5 shrink-0" /><span className="px-[3px] system-xs-medium">{t('serviceApi.card.apiReference', { ns: 'dataset' })}</span>diff --git a/web/app/components/datasets/extra-info/service-api/index.tsx b/web/app/components/datasets/extra-info/service-api/index.tsxindex 0b42717b6eb..8d1ca6e4d16 100644--- a/web/app/components/datasets/extra-info/service-api/index.tsx+++ b/web/app/components/datasets/extra-info/service-api/index.tsx@@ -5,6 +5,8 @@ import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import SecretKeyModal from '@/app/components/develop/secret-key/secret-key-modal'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'import Card from './card'type ServiceApiProps = {@@ -17,6 +19,8 @@ const ServiceApi = ({const { t } = useTranslation()const [open, setOpen] = useState(false)const [isSecretKeyModalVisible, setIsSecretKeyModalVisible] = useState(false)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canManageSecretKey = hasPermission(workspacePermissionKeys, 'dataset.api_key.manage')const handleOpenSecretKeyModal = useCallback(() => {setIsSecretKeyModalVisible(true)@@ -60,12 +64,14 @@ const ServiceApi = ({<CardapiBaseUrl={apiBaseUrl}onOpenSecretKeyModal={handleOpenSecretKeyModal}+ canManageSecretKey={canManageSecretKey}/></PopoverContent></Popover><SecretKeyModalisShow={isSecretKeyModalVisible}onClose={handleCloseSecretKeyModal}+ canManage={canManageSecretKey}/></div>)diff --git a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsxindex df0e39554a8..50ba6fc7d6e 100644--- a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx+++ b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx@@ -56,8 +56,14 @@ const mockDataset = {score_threshold: 0.5,},is_multimodal: false,+ permission_keys: ['dataset.acl.retrieval_recall'],} as Partial<DataSet>+let mockAppContextState = {+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [] as string[],+}+vi.mock('use-context-selector', () => ({useContext: vi.fn(() => ({ dataset: mockDataset })),useContextSelector: vi.fn((_, selector) => selector({ dataset: mockDataset })),@@ -73,6 +79,10 @@ vi.mock('@/context/dataset-detail', () => ({),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector(mockAppContextState),+}))+const mockRecordsRefetch = vi.fn()const mockHitTestingMutateAsync = vi.fn()const mockExternalHitTestingMutateAsync = vi.fn()@@ -304,6 +314,11 @@ const _createMockRetrievalConfig = (overrides = {}): RetrievalConfig => ({describe('HitTestingPage', () => {beforeEach(() => {vi.clearAllMocks()+ mockDataset.permission_keys = ['dataset.acl.retrieval_recall']+ mockAppContextState = {+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],+ }})describe('Rendering', () => {@@ -330,6 +345,16 @@ describe('HitTestingPage', () => {renderWithProviders(<HitTestingPage datasetId="dataset-1" />)expect(screen.getByRole('textbox'))!.toBeInTheDocument()})++ it('should disable testing-record queries and hide query input when retrieval recall permission is missing', async () => {+ const { useDatasetTestingRecords } = await import('@/service/knowledge/use-dataset')+ mockDataset.permission_keys = []++ renderWithProviders(<HitTestingPage datasetId="dataset-1" />)++ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()+ expect(vi.mocked(useDatasetTestingRecords)).toHaveBeenCalledWith('dataset-1', { limit: 10, page: 1 }, { enabled: false })+ })})describe('Loading States', () => {@@ -589,6 +614,7 @@ describe('HitTestingPage', () => {describe('Integration: Hit Testing Flow', () => {beforeEach(async () => {vi.clearAllMocks()+ mockDataset.permission_keys = ['dataset.acl.retrieval_recall']mockHitTestingMutateAsync.mockReset()mockExternalHitTestingMutateAsync.mockReset()diff --git a/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsxindex 271db6bf127..51f2150d457 100644--- a/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx+++ b/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx@@ -64,6 +64,7 @@ describe('QueryInput', () => {onClickRetrievalMethod: vi.fn(),retrievalConfig: { search_method: 'semantic_search' } as RetrievalConfig,isEconomy: false,+ canRunRetrievalRecall: true,hitTestingMutation: vi.fn(),externalKnowledgeBaseHitTestingMutation: vi.fn(),})@@ -102,6 +103,12 @@ describe('QueryInput', () => {expect(screen.getByRole('button', { name: /input\.testing/ }))!.toBeDisabled()})+ it('should disable submit button when retrieval recall permission is missing', () => {+ render(<QueryInput {...defaultProps} canRunRetrievalRecall={false} />)++ expect(screen.getByRole('button', { name: /input\.testing/ }))!.toBeDisabled()+ })+it('should render retrieval method for non-external mode', () => {render(<QueryInput {...defaultProps} />)expect(screen.getByText('dataset.retrieval.semantic_search.title'))!.toBeInTheDocument()@@ -233,6 +240,16 @@ describe('QueryInput', () => {})})+ describe('Permission Guarding', () => {+ it('should not run hit testing mutation when retrieval recall permission is missing', () => {+ render(<QueryInput {...defaultProps} canRunRetrievalRecall={false} />)++ fireEvent.click(screen.getByRole('button', { name: /input\.testing/ }))++ expect(defaultProps.hitTestingMutation).not.toHaveBeenCalled()+ })+ })+// Cover lines 127-143: handleImageChangedescribe('Image Change Handling', () => {it('should update queries when images change', () => {diff --git a/web/app/components/datasets/hit-testing/components/query-input/index.tsx b/web/app/components/datasets/hit-testing/components/query-input/index.tsxindex 9f3b489cd9f..73edb09c39e 100644--- a/web/app/components/datasets/hit-testing/components/query-input/index.tsx+++ b/web/app/components/datasets/hit-testing/components/query-input/index.tsx@@ -38,6 +38,7 @@ type QueryInputProps = {onClickRetrievalMethod: () => voidretrievalConfig: RetrievalConfigisEconomy: boolean+ canRunRetrievalRecall?: booleanonSubmit?: () => voidhitTestingMutation: UseMutateAsyncFunction<HitTestingResponse, Error, HitTestingRequest, unknown>externalKnowledgeBaseHitTestingMutation: UseMutateAsyncFunction<@@ -59,6 +60,7 @@ const QueryInput = ({onClickRetrievalMethod,retrievalConfig,isEconomy,+ canRunRetrievalRecall = true,onSubmit: _onSubmit,hitTestingMutation,externalKnowledgeBaseHitTestingMutation,@@ -143,6 +145,9 @@ const QueryInput = ({}, [queries, setQueries])const onSubmit = useCallback(async () => {+ if (!canRunRetrievalRecall)+ return+await hitTestingMutation({query: text,attachment_ids: images.map(image => image.uploadedId),@@ -158,9 +163,12 @@ const QueryInput = ({_onSubmit()},})- }, [text, retrievalConfig, isEconomy, hitTestingMutation, onUpdateList, _onSubmit, images, setHitResult])+ }, [canRunRetrievalRecall, text, retrievalConfig, isEconomy, hitTestingMutation, onUpdateList, _onSubmit, images, setHitResult])const externalRetrievalTestingOnSubmit = useCallback(async () => {+ if (!canRunRetrievalRecall)+ return+await externalKnowledgeBaseHitTestingMutation({query: text,external_retrieval_model: {@@ -174,7 +182,7 @@ const QueryInput = ({onUpdateList?.()},})- }, [text, externalRetrievalSettings, externalKnowledgeBaseHitTestingMutation, onUpdateList, setExternalHitResult])+ }, [canRunRetrievalRecall, text, externalRetrievalSettings, externalKnowledgeBaseHitTestingMutation, onUpdateList, setExternalHitResult])const retrievalMethod = isEconomy ? RETRIEVE_METHOD.keywordSearch : retrievalConfig.search_methodconst icon = <img className="size-3.5 text-util-colors-purple-purple-600" src={getIcon(retrievalMethod)} alt="" />@@ -192,14 +200,14 @@ const QueryInput = ({onClick={isExternal ? externalRetrievalTestingOnSubmit : onSubmit}variant="primary"loading={loading}- disabled={(text.length === 0 && images.length === 0) || text.length > 200 || (images.length > 0 && !isAllUploaded)}+ disabled={!canRunRetrievalRecall || (text.length === 0 && images.length === 0) || text.length > 200 || (images.length > 0 && !isAllUploaded)}className="w-[88px]"><RiPlayCircleLine className="mr-1 size-4" />{t('input.testing', { ns: 'datasetHitTesting' })}</Button>)- }, [isExternal, externalRetrievalTestingOnSubmit, onSubmit, text, loading, t, images, isAllUploaded])+ }, [isExternal, externalRetrievalTestingOnSubmit, onSubmit, canRunRetrievalRecall, text, loading, t, images, isAllUploaded])return (<div className={cn('relative flex h-80 shrink-0 flex-col overflow-hidden rounded-xl bg-linear-to-r from-components-input-border-active-prompt-1 to-components-input-border-active-prompt-2 p-0.5 shadow-xs')}>diff --git a/web/app/components/datasets/hit-testing/index.tsx b/web/app/components/datasets/hit-testing/index.tsxindex 161748104e1..3324a497838 100644--- a/web/app/components/datasets/hit-testing/index.tsx+++ b/web/app/components/datasets/hit-testing/index.tsx@@ -27,6 +27,7 @@ import { useContext } from 'use-context-selector'import FloatRightContainer from '@/app/components/base/float-right-container'import Loading from '@/app/components/base/loading'import docStyle from '@/app/components/datasets/documents/detail/completed/style.module.css'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import DatasetDetailContext from '@/context/dataset-detail'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { useDatasetTestingRecords } from '@/service/knowledge/use-dataset'@@ -34,6 +35,7 @@ import {useExternalKnowledgeBaseHitTesting,useHitTesting,} from '@/service/knowledge/use-hit-testing'+import { getDatasetACLCapabilities } from '@/utils/permission'import { CardSkelton } from '../documents/detail/completed/skeleton/general-list-skeleton'import EmptyRecords from './components/empty-records'import QueryInput from './components/query-input'@@ -60,12 +62,19 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {const [queryInputKey, setQueryInputKey] = useState(Date.now())const [currPage, setCurrPage] = useState<number>(0)- const { data: recordsRes, refetch: recordsRefetch, isLoading: isRecordsLoading } = useDatasetTestingRecords(datasetId, { limit, page: currPage + 1 })+ const { dataset: currentDataset } = useContext(DatasetDetailContext)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canRunRetrievalRecall = React.useMemo(() => getDatasetACLCapabilities(currentDataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: currentDataset?.maintainer,+ workspacePermissionKeys,+ }).canRetrievalRecall, [currentDataset?.maintainer, currentDataset?.permission_keys, currentUserId, workspacePermissionKeys])+ const { data: recordsRes, refetch: recordsRefetch, isLoading: isRecordsLoading } = useDatasetTestingRecords(datasetId, { limit, page: currPage + 1 }, { enabled: canRunRetrievalRecall })const total = recordsRes?.total || 0const totalPages = total ? Math.max(Math.ceil(total / limit), 1) : 1- const { dataset: currentDataset } = useContext(DatasetDetailContext)const isExternal = currentDataset?.provider === 'external'const [retrievalConfig, setRetrievalConfig] = useState(currentDataset?.retrieval_model_dict as RetrievalConfig)@@ -121,6 +130,9 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {setShowRightPanel(!isMobile)}, [isMobile, setShowRightPanel])+ if (!canRunRetrievalRecall)+ return <Loading type="app" />+return (<div className="relative flex size-full gap-x-6 overflow-y-auto pl-6"><div className="flex min-w-0 flex-1 flex-col py-3">@@ -143,6 +155,7 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {isEconomy={currentDataset?.indexing_technique === 'economy'}hitTestingMutation={hitTestingMutation}externalKnowledgeBaseHitTestingMutation={externalKnowledgeBaseHitTestingMutation}+ canRunRetrievalRecall={canRunRetrievalRecall}/><div className="mt-6 mb-3 text-base font-semibold text-text-primary">{t('records', { ns: 'datasetHitTesting' })}</div>{isRecordsLoading && (diff --git a/web/app/components/datasets/list/__tests__/header.spec.tsx b/web/app/components/datasets/list/__tests__/header.spec.tsxindex 49883a543c5..04ae8513d06 100644--- a/web/app/components/datasets/list/__tests__/header.spec.tsx+++ b/web/app/components/datasets/list/__tests__/header.spec.tsx@@ -22,7 +22,7 @@ vi.mock('@/features/tag-management/components/tag-filter', () => ({}))vi.mock('@/app/components/datasets/create/website/base/checkbox-with-label', () => ({- default: () => <label>include all</label>,+ default: () => <span>include all</span>,}))vi.mock('../../extra-info/service-api', () => ({@@ -31,9 +31,9 @@ vi.mock('../../extra-info/service-api', () => ({const defaultProps = {apiBaseUrl: 'https://api.example.com',+ canConnectExternalDataset: true,+ canCreateDataset: true,includeAll: false,- isCurrentWorkspaceEditor: true,- isCurrentWorkspaceManager: true,isCurrentWorkspaceOwner: true,keywords: '',tagFilterValue: [],@@ -61,4 +61,30 @@ describe('DatasetListHeader', () => {expect(menuItem.querySelector('.i-custom-vender-pipeline-pipeline-line')).toBeInTheDocument()})++ it('should hide dataset creation actions when dataset.create_and_management is unavailable', () => {+ render(<DatasetListHeader {...defaultProps} canCreateDataset={false} />)++ expect(screen.queryByRole('button', { name: /dataset\.firstEmpty\.createTitle/ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /dataset\.firstEmpty\.pipelineTitle/ })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: /dataset\.connectDataset/ })).toBeInTheDocument()+ })++ it('should hide external API panel entry when dataset.external.connect is unavailable', () => {+ render(<DatasetListHeader {...defaultProps} canConnectExternalDataset={false} />)++ expect(screen.queryByRole('button', { name: /dataset\.externalAPIPanelTitle/ })).not.toBeInTheDocument()+ })++ it('should hide the create menu when no creation or connection action is available', () => {+ render((+ <DatasetListHeader+ {...defaultProps}+ canConnectExternalDataset={false}+ canCreateDataset={false}+ />+ ))++ expect(screen.queryByRole('button', { name: /common\.operation\.create/ })).not.toBeInTheDocument()+ })})diff --git a/web/app/components/datasets/list/__tests__/index.spec.tsx b/web/app/components/datasets/list/__tests__/index.spec.tsxindex 5fcf57a6b2c..76dfb03a9ed 100644--- a/web/app/components/datasets/list/__tests__/index.spec.tsx+++ b/web/app/components/datasets/list/__tests__/index.spec.tsx@@ -5,6 +5,12 @@ import List from '../index'const mockPush = vi.fn()const mockReplace = vi.fn()+let mockAppContextState = {+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'],+}+let mockIsCurrentWorkspaceOwner = truevi.mock('@/next/navigation', () => ({useRouter: () => ({push: mockPush,@@ -16,9 +22,9 @@ vi.mock('@/next/navigation', () => ({vi.mock('@/context/app-context', () => ({useAppContext: () => ({currentWorkspace: { role: 'admin' },- isCurrentWorkspaceOwner: true,+ isCurrentWorkspaceOwner: mockIsCurrentWorkspaceOwner,}),- useSelector: () => true,+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector(mockAppContextState),}))// Mock external api panel context@@ -75,8 +81,8 @@ vi.mock('../datasets', () => ({// Mock ExternalAPIPanel componentvi.mock('../../external-api/external-api-panel', () => ({- default: ({ onClose }: { onClose: () => void }) => (- <div data-testid="external-api-panel">+ default: ({ canManageExternalKnowledgeApi, onClose }: { canManageExternalKnowledgeApi: boolean, onClose: () => void }) => (+ <div data-testid="external-api-panel" data-can-manage-external-knowledge-api={canManageExternalKnowledgeApi}><button onClick={onClose}>Close Panel</button></div>),@@ -123,6 +129,12 @@ vi.mock('@/app/components/datasets/create/website/base/checkbox-with-label', ()describe('List', () => {beforeEach(async () => {vi.clearAllMocks()+ mockAppContextState = {+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'],+ }+ mockIsCurrentWorkspaceOwner = trueconst { useDatasetList } = await import('@/service/knowledge/use-dataset')vi.mocked(useDatasetList).mockReturnValue({data: { pages: [{ data: [], total: 1 }] },@@ -153,6 +165,18 @@ describe('List', () => {render(<List />)expect(screen.getByText(/externalAPIPanelTitle/)).toBeInTheDocument()})++ it('should hide external API panel button without dataset.external.connect', () => {+ mockAppContextState = {+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['dataset.create_and_management'],+ }++ render(<List />)++ expect(screen.queryByText(/externalAPIPanelTitle/)).not.toBeInTheDocument()+ })})describe('Props', () => {@@ -254,6 +278,48 @@ describe('List', () => {expect(screen.queryByTestId('datasets-component')).not.toBeInTheDocument()})+ it('should render first empty state when dataset.create_and_management is available without the legacy editor role', async () => {+ mockAppContextState = {+ isCurrentWorkspaceEditor: false,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['dataset.create_and_management'],+ }+ const { useDatasetList } = await import('@/service/knowledge/use-dataset')+ vi.mocked(useDatasetList).mockReturnValue({+ data: { pages: [{ data: [], total: 0 }] },+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetching: false,+ isFetchingNextPage: false,+ } as unknown as ReturnType<typeof useDatasetList>)++ render(<List />)++ expect(screen.getByText('dataset.firstEmpty.title')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: /dataset\.firstEmpty\.pipelineTitle/ })).toHaveAttribute('href', '/datasets/create-from-pipeline')+ })++ it('should not render first empty state for legacy editors without dataset creation permissions', async () => {+ mockAppContextState = {+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: [],+ }+ const { useDatasetList } = await import('@/service/knowledge/use-dataset')+ vi.mocked(useDatasetList).mockReturnValue({+ data: { pages: [{ data: [], total: 0 }] },+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetching: false,+ isFetchingNextPage: false,+ } as unknown as ReturnType<typeof useDatasetList>)++ render(<List />)++ expect(screen.queryByText('dataset.firstEmpty.title')).not.toBeInTheDocument()+ expect(screen.getByTestId('datasets-component')).toBeInTheDocument()+ })+it('should not render first empty state before the first dataset page resolves', async () => {const { useDatasetList } = await import('@/service/knowledge/use-dataset')vi.mocked(useDatasetList).mockReturnValue({@@ -298,7 +364,11 @@ describe('List', () => {currentWorkspace: { role: 'normal' },isCurrentWorkspaceOwner: false,}),- useSelector: () => true,+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector({+ isCurrentWorkspaceEditor: false,+ isCurrentWorkspaceManager: false,+ workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'],+ }),}))// Clear module cache and re-import@@ -343,9 +413,48 @@ describe('List', () => {render(<ListComponent />)expect(screen.getByTestId('external-api-panel')).toBeInTheDocument()+ expect(screen.getByTestId('external-api-panel')).toHaveAttribute('data-can-manage-external-knowledge-api', 'true')+ })++ it('should not show ExternalAPIPanel without dataset.external.connect even when panel state is open', async () => {+ vi.doMock('@/context/app-context', () => ({+ useAppContext: () => ({+ currentWorkspace: { role: 'admin' },+ isCurrentWorkspaceOwner: true,+ }),+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector({+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['dataset.create_and_management'],+ }),+ }))+ vi.doMock('@/context/external-api-panel-context', () => ({+ useExternalApiPanel: () => ({+ showExternalApiPanel: true,+ setShowExternalApiPanel: mockSetShowExternalApiPanel,+ }),+ }))++ vi.resetModules()+ const { default: ListComponent } = await import('../index')++ render(<ListComponent />)++ expect(screen.queryByTestId('external-api-panel')).not.toBeInTheDocument()})it('should close ExternalAPIPanel when onClose is called', async () => {+ vi.doMock('@/context/app-context', () => ({+ useAppContext: () => ({+ currentWorkspace: { role: 'admin' },+ isCurrentWorkspaceOwner: true,+ }),+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector({+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'],+ }),+ }))vi.doMock('@/context/external-api-panel-context', () => ({useExternalApiPanel: () => ({showExternalApiPanel: true,@@ -377,7 +486,11 @@ describe('List', () => {currentWorkspace: { role: 'editor' },isCurrentWorkspaceOwner: false,}),- useSelector: () => true,+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector({+ isCurrentWorkspaceEditor: true,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'],+ }),}))vi.resetModules()diff --git a/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx b/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsxindex 00828d382cf..4f85e926ea7 100644--- a/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx+++ b/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx@@ -19,13 +19,20 @@ vi.mock('@/hooks/use-format-time-from-now', () => ({}))const mockPush = vi.fn()+const mockOpenAccessConfig = vi.fn()+const mockCloseAccessConfig = vi.fn()vi.mock('@/next/navigation', () => ({useRouter: () => ({ push: mockPush }),}))+let mockAppContextState = {+ isCurrentWorkspaceDatasetOperator: false,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [] as string[],+}vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: { isCurrentWorkspaceDatasetOperator: boolean }) => boolean) => selector({ isCurrentWorkspaceDatasetOperator: false }),+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector(mockAppContextState),}))vi.mock('../hooks/use-dataset-card-state', () => ({@@ -33,11 +40,14 @@ vi.mock('../hooks/use-dataset-card-state', () => ({modalState: {showRenameModal: false,showConfirmDelete: false,+ showAccessConfig: false,confirmMessage: '',},openRenameModal: vi.fn(),closeRenameModal: vi.fn(),closeConfirmDelete: vi.fn(),+ openAccessConfig: mockOpenAccessConfig,+ closeAccessConfig: mockCloseAccessConfig,handleExportPipeline: vi.fn(),detectIsUsedByApp: vi.fn(),onConfirmDelete: vi.fn(),@@ -51,15 +61,29 @@ vi.mock('../components/dataset-card-header', () => ({default: ({ dataset }: { dataset: DataSet }) => <div data-testid="card-header">{dataset.name}</div>,}))vi.mock('../components/dataset-card-modals', () => ({- default: () => <div data-testid="card-modals" />,+ default: ({ onCloseAccessConfig }: { onCloseAccessConfig?: () => void }) => (+ <div data-testid="card-modals" data-has-close-access-config={typeof onCloseAccessConfig === 'function'} />+ ),}))vi.mock('@/features/tag-management/components/dataset-card-tags', () => ({- DatasetCardTags: ({ onClick }: { onClick: (e: React.MouseEvent) => void }) => (- <div data-testid="tag-area" onClick={onClick} />+ DatasetCardTags: ({+ onClick,+ canBindOrUnbindTags,+ }: {+ onClick: (e: React.MouseEvent) => void+ canBindOrUnbindTags?: boolean+ }) => (+ <div+ data-testid="tag-area"+ data-can-bind-or-unbind-tags={String(Boolean(canBindOrUnbindTags))}+ onClick={onClick}+ />),}))vi.mock('../components/operations-dropdown', () => ({- default: () => <div data-testid="operations-dropdown" />,+ default: ({ openAccessConfig }: { openAccessConfig?: () => void }) => (+ <div data-testid="operations-dropdown" data-has-open-access-config={typeof openAccessConfig === 'function'} />+ ),}))// Factory function for DataSet mock data@@ -90,6 +114,11 @@ const createMockDataset = (overrides: Partial<DataSet> = {}): DataSet => ({describe('DatasetCard Integration', () => {beforeEach(() => {vi.clearAllMocks()+ mockAppContextState = {+ isCurrentWorkspaceDatasetOperator: false,+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],+ }})// Integration tests for Description component@@ -253,14 +282,36 @@ describe('DatasetCard Component', () => {expect(card).toHaveClass('hover:bg-components-card-bg-alt')})+ it('should pass access config handlers to operations and modals', () => {+ const dataset = createMockDataset()+ render(<DatasetCard dataset={dataset} />)++ expect(screen.getByTestId('operations-dropdown')).toHaveAttribute('data-has-open-access-config', 'true')+ expect(screen.getByTestId('card-modals')).toHaveAttribute('data-has-close-access-config', 'true')+ })+it('should navigate to hitTesting for external provider', () => {- const dataset = createMockDataset({ provider: 'external' })+ const dataset = createMockDataset({+ provider: 'external',+ permission_keys: ['dataset.acl.retrieval_recall'],+ })render(<DatasetCard dataset={dataset} />)fireEvent.click(screen.getByText('Test Dataset'))expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-1/hitTesting')})+ it('should navigate to settings for external provider when retrieval recall permission is missing', () => {+ const dataset = createMockDataset({+ provider: 'external',+ permission_keys: [],+ })+ render(<DatasetCard dataset={dataset} />)++ fireEvent.click(screen.getByText('Test Dataset'))+ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-1/settings')+ })+it('should navigate to pipeline for unpublished pipeline', () => {const dataset = createMockDataset({ runtime_mode: 'rag_pipeline', is_published: false })render(<DatasetCard dataset={dataset} />)@@ -278,4 +329,20 @@ describe('DatasetCard Component', () => {// Tag area click should not trigger card navigationexpect(mockPush).not.toHaveBeenCalled()})++ it('should allow tag binding when dataset has edit ACL', () => {+ const dataset = createMockDataset({ permission_keys: ['dataset.acl.edit'] })++ render(<DatasetCard dataset={dataset} />)++ expect(screen.getByTestId('tag-area')).toHaveAttribute('data-can-bind-or-unbind-tags', 'true')+ })++ it('should not allow tag binding when dataset lacks edit ACL', () => {+ const dataset = createMockDataset({ permission_keys: ['dataset.acl.readonly'] })++ render(<DatasetCard dataset={dataset} />)++ expect(screen.getByTestId('tag-area')).toHaveAttribute('data-can-bind-or-unbind-tags', 'false')+ })})diff --git a/web/app/components/datasets/list/dataset-card/__tests__/operations.spec.tsx b/web/app/components/datasets/list/dataset-card/__tests__/operations.spec.tsxindex 41c0b2749ba..015f7f1cbb5 100644--- a/web/app/components/datasets/list/dataset-card/__tests__/operations.spec.tsx+++ b/web/app/components/datasets/list/dataset-card/__tests__/operations.spec.tsx@@ -18,6 +18,7 @@ describe('Operations', () => {openRenameModal: vi.fn(),handleExportPipeline: vi.fn(),detectIsUsedByApp: vi.fn(),+ openAccessConfig: vi.fn(),}beforeEach(() => {@@ -80,6 +81,14 @@ describe('Operations', () => {fireEvent.click(screen.getByText(/operation\.delete/))expect(detectIsUsedByApp).toHaveBeenCalledTimes(1)})++ it('should call openAccessConfig when access config is clicked', () => {+ const openAccessConfig = vi.fn()+ renderInMenu(<Operations {...defaultProps} showAccessConfig openAccessConfig={openAccessConfig} />)++ fireEvent.click(screen.getByText(/settings\.resourceAccess/))+ expect(openAccessConfig).toHaveBeenCalledTimes(1)+ })})describe('Edge Cases', () => {diff --git a/web/app/components/datasets/list/dataset-card/components/__tests__/dataset-card-modals.spec.tsx b/web/app/components/datasets/list/dataset-card/components/__tests__/dataset-card-modals.spec.tsxindex 8cc10ae5ae0..fd6ac86eedb 100644--- a/web/app/components/datasets/list/dataset-card/components/__tests__/dataset-card-modals.spec.tsx+++ b/web/app/components/datasets/list/dataset-card/components/__tests__/dataset-card-modals.spec.tsx@@ -71,10 +71,12 @@ describe('DatasetCardModals', () => {modalState: {showRenameModal: false,showConfirmDelete: false,+ showAccessConfig: false,confirmMessage: '',},onCloseRename: vi.fn(),onCloseConfirm: vi.fn(),+ onCloseAccessConfig: vi.fn(),onConfirmDelete: vi.fn(),onSuccess: vi.fn(),}@@ -209,6 +211,7 @@ describe('DatasetCardModals', () => {modalState={{showRenameModal: true,showConfirmDelete: true,+ showAccessConfig: false,confirmMessage: 'Delete this dataset?',}}/>,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 6f7faf51ce5..5a6303d83e9 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@@ -3,6 +3,7 @@ import { fireEvent, render, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { IndexingType } from '@/app/components/datasets/create/step-two'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'+import { DatasetACLPermission } from '@/utils/permission'import OperationsDropdown from '../operations-dropdown'describe('OperationsDropdown', () => {@@ -25,15 +26,21 @@ describe('OperationsDropdown', () => {created_by: 'user-1',doc_form: ChunkingMode.text,runtime_mode: 'general',+ permission_keys: [+ DatasetACLPermission.Edit,+ DatasetACLPermission.Delete,+ DatasetACLPermission.ImportExportDSL,+ DatasetACLPermission.AccessConfig,+ ],...overrides,} as DataSet)const defaultProps = {dataset: createMockDataset(),- isCurrentWorkspaceDatasetOperator: false,openRenameModal: vi.fn(),handleExportPipeline: vi.fn(),detectIsUsedByApp: vi.fn(),+ openAccessConfig: vi.fn(),}beforeEach(() => {@@ -65,38 +72,52 @@ describe('OperationsDropdown', () => {})describe('Props', () => {- it('should show delete option when not workspace dataset operator', () => {- render(<OperationsDropdown {...defaultProps} isCurrentWorkspaceDatasetOperator={false} />)+ it('should show delete option when dataset has delete ACL permission', () => {+ render(<OperationsDropdown {...defaultProps} />)- const triggerButton = document.querySelector('[class*="cursor-pointer"]')- if (triggerButton)- fireEvent.click(triggerButton)+ fireEvent.click(screen.getByLabelText('Dataset operations'))++ expect(screen.getByText('common.operation.delete')).toBeInTheDocument()})- it('should hide delete option when is workspace dataset operator', () => {- render(<OperationsDropdown {...defaultProps} isCurrentWorkspaceDatasetOperator={true} />)+ it('should hide delete option when dataset lacks delete ACL permission', () => {+ const dataset = createMockDataset({+ permission_keys: [DatasetACLPermission.Edit],+ })+ render(<OperationsDropdown {...defaultProps} dataset={dataset} />)++ fireEvent.click(screen.getByLabelText('Dataset operations'))- const triggerButton = document.querySelector('[class*="cursor-pointer"]')- if (triggerButton)- fireEvent.click(triggerButton)+ expect(screen.queryByText('common.operation.delete')).not.toBeInTheDocument()})it('should show export pipeline when runtime_mode is rag_pipeline', () => {const dataset = createMockDataset({ runtime_mode: 'rag_pipeline' })render(<OperationsDropdown {...defaultProps} dataset={dataset} />)- const triggerButton = document.querySelector('[class*="cursor-pointer"]')- if (triggerButton)- fireEvent.click(triggerButton)+ fireEvent.click(screen.getByLabelText('Dataset operations'))++ expect(screen.getByText('datasetPipeline.operations.exportPipeline')).toBeInTheDocument()})it('should hide export pipeline when runtime_mode is not rag_pipeline', () => {const dataset = createMockDataset({ runtime_mode: 'general' })render(<OperationsDropdown {...defaultProps} dataset={dataset} />)- const triggerButton = document.querySelector('[class*="cursor-pointer"]')- if (triggerButton)- fireEvent.click(triggerButton)+ fireEvent.click(screen.getByLabelText('Dataset operations'))++ expect(screen.queryByText('datasetPipeline.operations.exportPipeline')).not.toBeInTheDocument()+ })++ it('should show resource access option when dataset has access config ACL permission', () => {+ const dataset = createMockDataset({+ permission_keys: [DatasetACLPermission.AccessConfig],+ })+ render(<OperationsDropdown {...defaultProps} dataset={dataset} />)++ fireEvent.click(screen.getByLabelText('Dataset operations'))++ expect(screen.getByText('common.settings.resourceAccess')).toBeInTheDocument()})})@@ -181,6 +202,19 @@ describe('OperationsDropdown', () => {render(<OperationsDropdown {...defaultProps} detectIsUsedByApp={detectIsUsedByApp} />)expect(detectIsUsedByApp).not.toHaveBeenCalled()})++ it('should call openAccessConfig when resource access is clicked', () => {+ const openAccessConfig = vi.fn()+ const dataset = createMockDataset({+ permission_keys: [DatasetACLPermission.AccessConfig],+ })+ render(<OperationsDropdown {...defaultProps} dataset={dataset} openAccessConfig={openAccessConfig} />)++ fireEvent.click(screen.getByLabelText('Dataset operations'))+ fireEvent.click(screen.getByText('common.settings.resourceAccess'))++ expect(openAccessConfig).toHaveBeenCalledTimes(1)+ })})describe('Edge Cases', () => {diff --git a/web/app/components/datasets/list/dataset-card/components/dataset-card-modals.tsx b/web/app/components/datasets/list/dataset-card/components/dataset-card-modals.tsxindex 47a195943b4..14f0f3c79b0 100644--- a/web/app/components/datasets/list/dataset-card/components/dataset-card-modals.tsx+++ b/web/app/components/datasets/list/dataset-card/components/dataset-card-modals.tsx@@ -15,6 +15,7 @@ import RenameDatasetModal from '../../../rename-modal'type ModalState = {showRenameModal: booleanshowConfirmDelete: boolean+ showAccessConfig: booleanconfirmMessage: string}@@ -23,6 +24,7 @@ type DatasetCardModalsProps = {modalState: ModalStateonCloseRename: () => voidonCloseConfirm: () => void+ onCloseAccessConfig: () => voidonConfirmDelete: () => voidonSuccess?: () => void}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 481819599e0..4032810a07a 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@@ -6,24 +6,40 @@ import {DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'import * as React from 'react'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { getDatasetACLCapabilities } from '@/utils/permission'import Operations from '../operations'type OperationsDropdownProps = {dataset: DataSet- isCurrentWorkspaceDatasetOperator: booleanopenRenameModal: () => voidhandleExportPipeline: (include?: boolean) => voiddetectIsUsedByApp: () => void+ openAccessConfig: () => void}const OperationsDropdown = ({dataset,- isCurrentWorkspaceDatasetOperator,openRenameModal,handleExportPipeline,detectIsUsedByApp,+ openAccessConfig,}: OperationsDropdownProps) => {const [open, setOpen] = React.useState(false)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const datasetACLCapabilities = React.useMemo(() => getDatasetACLCapabilities(dataset.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset.maintainer,+ workspacePermissionKeys,+ }), [dataset.maintainer, dataset.permission_keys, currentUserId, workspacePermissionKeys])+ const canShowOperations = datasetACLCapabilities.canEdit+ || datasetACLCapabilities.canImportExportDSL+ || datasetACLCapabilities.canAccessConfig+ || datasetACLCapabilities.canDelete++ if (!canShowOperations)+ return nullreturn (<div@@ -53,11 +69,14 @@ const OperationsDropdown = ({popupClassName="min-w-[186px]"><Operations- showDelete={!isCurrentWorkspaceDatasetOperator}- showExportPipeline={dataset.runtime_mode === 'rag_pipeline'}+ showEdit={datasetACLCapabilities.canEdit}+ showDelete={datasetACLCapabilities.canDelete}+ showExportPipeline={dataset.runtime_mode === 'rag_pipeline' && datasetACLCapabilities.canImportExportDSL}+ showAccessConfig={datasetACLCapabilities.canAccessConfig}openRenameModal={openRenameModal}handleExportPipeline={handleExportPipeline}detectIsUsedByApp={detectIsUsedByApp}+ openAccessConfig={openAccessConfig}/></DropdownMenuContent></DropdownMenu>diff --git a/web/app/components/datasets/list/dataset-card/hooks/__tests__/use-dataset-card-state.spec.ts b/web/app/components/datasets/list/dataset-card/hooks/__tests__/use-dataset-card-state.spec.tsindex fa4868f3911..6229fafac2c 100644--- a/web/app/components/datasets/list/dataset-card/hooks/__tests__/use-dataset-card-state.spec.ts+++ b/web/app/components/datasets/list/dataset-card/hooks/__tests__/use-dataset-card-state.spec.ts@@ -20,6 +20,13 @@ vi.mock('@langgenius/dify-ui/toast', () => ({const mockCheckUsage = vi.fn()const mockDeleteDataset = vi.fn()const mockExportPipeline = vi.fn()+const mockPush = vi.fn()++vi.mock('@/next/navigation', () => ({+ useRouter: () => ({+ push: mockPush,+ }),+}))vi.mock('@/service/use-dataset-card', () => ({useCheckDatasetUsage: () => ({ mutateAsync: mockCheckUsage }),diff --git a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.tsindex 88aa7b50ae9..7a71f2a4df5 100644--- a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts+++ b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts@@ -2,6 +2,7 @@ import type { DataSet } from '@/models/datasets'import { toast } from '@langgenius/dify-ui/toast'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useRouter } from '@/next/navigation'import { useCheckDatasetUsage, useDeleteDataset } from '@/service/use-dataset-card'import { useExportPipelineDSL } from '@/service/use-pipeline'import { downloadBlob } from '@/utils/download'@@ -9,6 +10,7 @@ import { downloadBlob } from '@/utils/download'type ModalState = {showRenameModal: booleanshowConfirmDelete: boolean+ showAccessConfig: booleanconfirmMessage: string}@@ -19,11 +21,13 @@ type UseDatasetCardStateOptions = {export const useDatasetCardState = ({ dataset, onSuccess }: UseDatasetCardStateOptions) => {const { t } = useTranslation()+ const { push } = useRouter()// Modal stateconst [modalState, setModalState] = useState<ModalState>({showRenameModal: false,showConfirmDelete: false,+ showAccessConfig: false,confirmMessage: '',})@@ -43,6 +47,14 @@ export const useDatasetCardState = ({ dataset, onSuccess }: UseDatasetCardStateOsetModalState(prev => ({ ...prev, showConfirmDelete: false }))}, [])+ const openAccessConfig = useCallback(() => {+ push(`/datasets/${dataset.id}/access-config`)+ }, [dataset.id, push])++ const closeAccessConfig = useCallback(() => {+ setModalState(prev => ({ ...prev, showAccessConfig: false }))+ }, [])+// API mutationsconst { mutateAsync: checkUsage } = useCheckDatasetUsage()const { mutateAsync: deleteDatasetMutation } = useDeleteDataset()@@ -112,6 +124,8 @@ export const useDatasetCardState = ({ dataset, onSuccess }: UseDatasetCardStateOopenRenameModal,closeRenameModal,closeConfirmDelete,+ openAccessConfig,+ closeAccessConfig,// Export stateexporting,diff --git a/web/app/components/datasets/list/dataset-card/index.tsx b/web/app/components/datasets/list/dataset-card/index.tsxindex c68e31f0a6c..aee6b54fd93 100644--- a/web/app/components/datasets/list/dataset-card/index.tsx+++ b/web/app/components/datasets/list/dataset-card/index.tsx@@ -4,6 +4,7 @@ import { useMemo } from 'react'import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { DatasetCardTags } from '@/features/tag-management/components/dataset-card-tags'import { useRouter } from '@/next/navigation'+import { getDatasetACLCapabilities } from '@/utils/permission'import CornerLabels from './components/corner-labels'import DatasetCardFooter from './components/dataset-card-footer'import DatasetCardHeader from './components/dataset-card-header'@@ -26,8 +27,8 @@ const DatasetCard = ({onOpenTagManagement = () => {},}: DatasetCardProps) => {const { push } = useRouter()-- const isCurrentWorkspaceDatasetOperator = useAppContextWithSelector(state => state.isCurrentWorkspaceDatasetOperator)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const datasetCard = useDatasetCardController({ dataset, onSuccess })const {@@ -35,6 +36,8 @@ const DatasetCard = ({openRenameModal,closeRenameModal,closeConfirmDelete,+ openAccessConfig,+ closeAccessConfig,handleExportPipeline,detectIsUsedByApp,onConfirmDelete,@@ -44,15 +47,25 @@ const DatasetCard = ({const isPipelineUnpublished = useMemo(() => {return dataset.runtime_mode === 'rag_pipeline' && !dataset.is_published}, [dataset.runtime_mode, dataset.is_published])+ const datasetACLCapabilities = useMemo(() => getDatasetACLCapabilities(dataset.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset.maintainer,+ workspacePermissionKeys,+ }), [dataset.maintainer, dataset.permission_keys, currentUserId, workspacePermissionKeys])const handleCardClick = (e: React.MouseEvent) => {e.preventDefault()- if (isExternalProvider)- push(`/datasets/${dataset.id}/hitTesting`)- else if (isPipelineUnpublished)+ if (isExternalProvider) {+ push(datasetACLCapabilities.canRetrievalRecall+ ? `/datasets/${dataset.id}/hitTesting`+ : `/datasets/${dataset.id}/settings`)+ }+ else if (isPipelineUnpublished) {push(`/datasets/${dataset.id}/pipeline`)- else+ }+ else {push(`/datasets/${dataset.id}/documents`)+ }}const handleTagAreaClick = (e: React.MouseEvent) => {@@ -77,14 +90,15 @@ const DatasetCard = ({onClick={handleTagAreaClick}onOpenTagManagement={onOpenTagManagement}onTagsChange={onSuccess}+ canBindOrUnbindTags={datasetACLCapabilities.canEdit}/><DatasetCardFooter dataset={dataset} /><OperationsDropdowndataset={dataset}- isCurrentWorkspaceDatasetOperator={isCurrentWorkspaceDatasetOperator}openRenameModal={openRenameModal}handleExportPipeline={handleExportPipeline}detectIsUsedByApp={detectIsUsedByApp}+ openAccessConfig={openAccessConfig}/></div><DatasetCardModals@@ -92,6 +106,7 @@ const DatasetCard = ({modalState={modalState}onCloseRename={closeRenameModal}onCloseConfirm={closeConfirmDelete}+ onCloseAccessConfig={closeAccessConfig}onConfirmDelete={onConfirmDelete}onSuccess={onSuccess}/>diff --git a/web/app/components/datasets/list/dataset-card/operations.tsx b/web/app/components/datasets/list/dataset-card/operations.tsxindex 1349ae05e72..70fffa97693 100644--- a/web/app/components/datasets/list/dataset-card/operations.tsx+++ b/web/app/components/datasets/list/dataset-card/operations.tsx@@ -6,20 +6,26 @@ import * as React from 'react'import { useTranslation } from 'react-i18next'type OperationsProps = {+ showEdit?: booleanshowDelete: booleanshowExportPipeline: boolean+ showAccessConfig?: booleanopenRenameModal: () => voidhandleExportPipeline: () => voiddetectIsUsedByApp: () => void+ openAccessConfig: () => voidonClose?: () => void}const Operations = ({+ showEdit = true,showDelete,showExportPipeline,+ showAccessConfig = false,openRenameModal,handleExportPipeline,detectIsUsedByApp,+ openAccessConfig,onClose,}: OperationsProps) => {const { t } = useTranslation()@@ -39,23 +45,36 @@ const Operations = ({detectIsUsedByApp()}+ const handleAccessConfig = () => {+ onClose?.()+ openAccessConfig()+ }+return (<>- <DropdownMenuItem onClick={handleRename}>- <span aria-hidden className="i-ri-edit-line size-4 text-text-tertiary" />- {t('operation.edit', { ns: 'common' })}- </DropdownMenuItem>+ {showEdit && (+ <DropdownMenuItem onClick={handleRename}>+ <span aria-hidden className="mr-1 i-ri-edit-line size-4 text-text-tertiary" />+ {t('operation.edit', { ns: 'common' })}+ </DropdownMenuItem>+ )}{showExportPipeline && (<DropdownMenuItem onClick={handleExport}>- <span aria-hidden className="i-ri-file-download-line size-4 text-text-tertiary" />+ <span aria-hidden className="mr-1 i-ri-file-download-line size-4 text-text-tertiary" />{t('operations.exportPipeline', { ns: 'datasetPipeline' })}</DropdownMenuItem>)}+ {showAccessConfig && (+ <DropdownMenuItem onClick={handleAccessConfig}>+ <span aria-hidden className="mr-1 i-ri-lock-line size-4 text-text-tertiary" />+ {t('settings.resourceAccess', { ns: 'common' })}+ </DropdownMenuItem>+ )}{showDelete && (<><DropdownMenuSeparator /><DropdownMenuItem variant="destructive" onClick={handleDelete}>- <span aria-hidden className="i-ri-delete-bin-line size-4" />+ <span aria-hidden className="mr-1 i-ri-delete-bin-line size-4" />{t('operation.delete', { ns: 'common' })}</DropdownMenuItem></>diff --git a/web/app/components/datasets/list/first-empty-state/__tests__/index.spec.tsx b/web/app/components/datasets/list/first-empty-state/__tests__/index.spec.tsxindex 4186027af62..a1e3e7a7b90 100644--- a/web/app/components/datasets/list/first-empty-state/__tests__/index.spec.tsx+++ b/web/app/components/datasets/list/first-empty-state/__tests__/index.spec.tsx@@ -9,11 +9,25 @@ vi.mock('@/next/link', () => ({describe('DatasetFirstEmptyState', () => {it('uses the pipeline icon for the create-from-pipeline action', () => {- render(<DatasetFirstEmptyState />)+ render(<DatasetFirstEmptyState canConnectExternalDataset canCreateDataset />)const pipelineLink = screen.getByRole('link', { name: /dataset\.firstEmpty\.pipelineTitle/ })expect(pipelineLink).toHaveAttribute('href', '/datasets/create-from-pipeline')expect(pipelineLink.querySelector('.i-custom-vender-pipeline-pipeline-line')).toBeInTheDocument()})++ it('should hide dataset creation actions when dataset.create_and_management is unavailable', () => {+ render(<DatasetFirstEmptyState canConnectExternalDataset canCreateDataset={false} />)++ expect(screen.queryByRole('link', { name: /dataset\.firstEmpty\.createTitle/ })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /dataset\.firstEmpty\.pipelineTitle/ })).not.toBeInTheDocument()+ expect(screen.getByRole('link', { name: /dataset\.connectDataset/ })).toHaveAttribute('href', '/datasets/connect')+ })++ it('should render nothing when no empty-state action is available', () => {+ const { container } = render(<DatasetFirstEmptyState canConnectExternalDataset={false} canCreateDataset={false} />)++ expect(container).toBeEmptyDOMElement()+ })})diff --git a/web/app/components/datasets/list/first-empty-state/index.tsx b/web/app/components/datasets/list/first-empty-state/index.tsxindex 7294fd81273..bdfcabf439f 100644--- a/web/app/components/datasets/list/first-empty-state/index.tsx+++ b/web/app/components/datasets/list/first-empty-state/index.tsx@@ -13,33 +13,49 @@ type EmptyCreateAction = {description: string}-function DatasetFirstEmptyState() {+type DatasetFirstEmptyStateProps = {+ canConnectExternalDataset: boolean+ canCreateDataset: boolean+}++function DatasetFirstEmptyState({+ canConnectExternalDataset,+ canCreateDataset,+}: DatasetFirstEmptyStateProps) {const { t } = useTranslation()- const actions: EmptyCreateAction[] = [- {- badge: t('firstEmpty.recommended', { ns: 'dataset' }),- href: '/datasets/create',- icon: <span aria-hidden className="i-ri-add-line size-4" />,- id: 'create',- title: t('firstEmpty.createTitle', { ns: 'dataset' }),- description: t('firstEmpty.createDescription', { ns: 'dataset' }),- },- {- href: '/datasets/create-from-pipeline',- icon: <span aria-hidden className="i-custom-vender-pipeline-pipeline-line size-4" />,- id: 'pipeline',- title: t('firstEmpty.pipelineTitle', { ns: 'dataset' }),- description: t('firstEmpty.pipelineDescription', { ns: 'dataset' }),- },- {- href: '/datasets/connect',- icon: <span aria-hidden className="i-custom-vender-solid-development-api-connection-mod size-4" />,- id: 'connect',- title: t('connectDataset', { ns: 'dataset' }),- description: t('firstEmpty.connectDescription', { ns: 'dataset' }),- },- ]+ const createActions: EmptyCreateAction[] = canCreateDataset+ ? [+ {+ badge: t('firstEmpty.recommended', { ns: 'dataset' }),+ href: '/datasets/create',+ icon: <span aria-hidden className="i-ri-add-line size-4" />,+ id: 'create',+ title: t('firstEmpty.createTitle', { ns: 'dataset' }),+ description: t('firstEmpty.createDescription', { ns: 'dataset' }),+ },+ {+ href: '/datasets/create-from-pipeline',+ icon: <span aria-hidden className="i-custom-vender-pipeline-pipeline-line size-4" />,+ id: 'pipeline',+ title: t('firstEmpty.pipelineTitle', { ns: 'dataset' }),+ description: t('firstEmpty.pipelineDescription', { ns: 'dataset' }),+ },+ ]+ : []+ const connectAction: EmptyCreateAction | undefined = canConnectExternalDataset+ ? {+ href: '/datasets/connect',+ icon: <span aria-hidden className="i-custom-vender-solid-development-api-connection-mod size-4" />,+ id: 'connect',+ title: t('connectDataset', { ns: 'dataset' }),+ description: t('firstEmpty.connectDescription', { ns: 'dataset' }),+ }+ : undefined+ const hasActions = createActions.length > 0 || !!connectAction++ if (!hasActions)+ return nullreturn (<div className="flex grow flex-col overflow-hidden">@@ -63,31 +79,37 @@ function DatasetFirstEmptyState() {</h2></div><div className="flex w-full flex-col gap-2 pb-8">- <div className="flex flex-col gap-2">- {actions.slice(0, 2).map(action => (- <FirstEmptyActionCard- key={action.id}- badge={action.badge}- description={action.description}- href={action.href}- icon={action.icon}- title={action.title}- visualStyle="list"- />- ))}- </div>- <div className="flex items-center gap-2 text-text-tertiary">- <div className="h-px min-w-0 flex-1 bg-linear-to-r from-background-body/0 to-divider-regular" />- <span className="system-xs-medium-uppercase uppercase">{t('firstEmpty.or', { ns: 'dataset' })}</span>- <div className="h-px min-w-0 flex-1 bg-linear-to-r from-divider-regular to-background-body/0" />- </div>- <FirstEmptyActionCard- description={actions[2]!.description}- href={actions[2]!.href}- icon={actions[2]!.icon}- title={actions[2]!.title}- visualStyle="list"- />+ {createActions.length > 0 && (+ <div className="flex flex-col gap-2">+ {createActions.map(action => (+ <FirstEmptyActionCard+ key={action.id}+ badge={action.badge}+ description={action.description}+ href={action.href}+ icon={action.icon}+ title={action.title}+ visualStyle="list"+ />+ ))}+ </div>+ )}+ {createActions.length > 0 && connectAction && (+ <div className="flex items-center gap-2 text-text-tertiary">+ <div className="h-px min-w-0 flex-1 bg-linear-to-r from-background-body/0 to-divider-regular" />+ <span className="system-xs-medium-uppercase uppercase">{t('firstEmpty.or', { ns: 'dataset' })}</span>+ <div className="h-px min-w-0 flex-1 bg-linear-to-r from-divider-regular to-background-body/0" />+ </div>+ )}+ {connectAction && (+ <FirstEmptyActionCard+ description={connectAction.description}+ href={connectAction.href}+ icon={connectAction.icon}+ title={connectAction.title}+ visualStyle="list"+ />+ )}</div></div></section>diff --git a/web/app/components/datasets/list/header.tsx b/web/app/components/datasets/list/header.tsxindex 8ffbe741f66..85508625801 100644--- a/web/app/components/datasets/list/header.tsx+++ b/web/app/components/datasets/list/header.tsx@@ -10,9 +10,9 @@ import ServiceApi from '../extra-info/service-api'type Props = {apiBaseUrl: string+ canConnectExternalDataset: boolean+ canCreateDataset: booleanincludeAll: boolean- isCurrentWorkspaceEditor: boolean- isCurrentWorkspaceManager: booleanisCurrentWorkspaceOwner: booleankeywords: stringtagFilterValue: string[]@@ -28,9 +28,9 @@ type Props = {const DatasetListHeader = ({apiBaseUrl,+ canConnectExternalDataset,+ canCreateDataset,includeAll,- isCurrentWorkspaceEditor,- isCurrentWorkspaceManager,isCurrentWorkspaceOwner,keywords,tagFilterValue,@@ -44,23 +44,24 @@ const DatasetListHeader = ({onTagsChange,}: Props) => {const { t } = useTranslation()+ const showCreateMenu = canCreateDataset || canConnectExternalDatasetreturn (<div className="sticky top-0 z-10 flex flex-col gap-[14px] bg-background-body px-8 pt-4 pb-2"><div className="flex h-6 w-full items-center gap-2"><h1 className="min-w-0 flex-1 text-[18px]/[21.6px] font-semibold text-text-primary">{t('knowledge', { ns: 'dataset' })}</h1><div className="flex shrink-0 items-center gap-2">- <button- type="button"- className="flex items-center justify-center gap-1 overflow-hidden rounded-md px-1.5 py-1 text-text-tertiary hover:bg-state-base-hover"- onClick={onExternalApiClick}- >- <span aria-hidden className="i-custom-vender-solid-development-api-connection-mod size-3.5 shrink-0" />- <span className="px-0.5 system-xs-medium">{t('externalAPIPanelTitle', { ns: 'dataset' })}</span>- </button>- {isCurrentWorkspaceManager && (- <ServiceApi apiBaseUrl={apiBaseUrl} />+ {canConnectExternalDataset && (+ <button+ type="button"+ className="flex items-center justify-center gap-1 overflow-hidden rounded-md px-1.5 py-1 text-text-tertiary hover:bg-state-base-hover"+ onClick={onExternalApiClick}+ >+ <span aria-hidden className="i-custom-vender-solid-development-api-connection-mod size-3.5 shrink-0" />+ <span className="px-0.5 system-xs-medium">{t('externalAPIPanelTitle', { ns: 'dataset' })}</span>+ </button>)}+ <ServiceApi apiBaseUrl={apiBaseUrl} /></div></div><div className="flex flex-wrap items-center justify-between gap-2">@@ -92,7 +93,7 @@ const DatasetListHeader = ({)}</div><div className="flex items-center gap-2">- {isCurrentWorkspaceEditor && (+ {showCreateMenu && (<DropdownMenu modal={false}><DropdownMenuTriggerrender={(@@ -112,28 +113,36 @@ const DatasetListHeader = ({sideOffset={4}popupClassName="w-80">- <DropdownMenuItem- className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"- onClick={onCreateDataset}- >- <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-secondary" />- <span className="min-w-0 flex-1 truncate px-1">{t('firstEmpty.createTitle', { ns: 'dataset' })}</span>- </DropdownMenuItem>- <DropdownMenuItem- className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"- onClick={onCreateFromPipeline}- >- <span aria-hidden className="i-custom-vender-pipeline-pipeline-line size-4 shrink-0 text-text-secondary" />- <span className="min-w-0 flex-1 truncate px-1">{t('firstEmpty.pipelineTitle', { ns: 'dataset' })}</span>- </DropdownMenuItem>- <DropdownMenuSeparator className="my-1" />- <DropdownMenuItem- className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"- onClick={onConnectDataset}- >- <span aria-hidden className="i-custom-vender-solid-development-api-connection-mod size-4 shrink-0 text-text-secondary" />- <span className="min-w-0 flex-1 truncate px-1">{t('connectDataset', { ns: 'dataset' })}</span>- </DropdownMenuItem>+ {canCreateDataset && (+ <>+ <DropdownMenuItem+ className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"+ onClick={onCreateDataset}+ >+ <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-secondary" />+ <span className="min-w-0 flex-1 truncate px-1">{t('firstEmpty.createTitle', { ns: 'dataset' })}</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"+ onClick={onCreateFromPipeline}+ >+ <span aria-hidden className="i-custom-vender-pipeline-pipeline-line size-4 shrink-0 text-text-secondary" />+ <span className="min-w-0 flex-1 truncate px-1">{t('firstEmpty.pipelineTitle', { ns: 'dataset' })}</span>+ </DropdownMenuItem>+ </>+ )}+ {canCreateDataset && canConnectExternalDataset && (+ <DropdownMenuSeparator className="my-1" />+ )}+ {canConnectExternalDataset && (+ <DropdownMenuItem+ className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"+ onClick={onConnectDataset}+ >+ <span aria-hidden className="i-custom-vender-solid-development-api-connection-mod size-4 shrink-0 text-text-secondary" />+ <span className="min-w-0 flex-1 truncate px-1">{t('connectDataset', { ns: 'dataset' })}</span>+ </DropdownMenuItem>+ )}</DropdownMenuContent></DropdownMenu>)}diff --git a/web/app/components/datasets/list/index.tsx b/web/app/components/datasets/list/index.tsxindex a1ebe6649da..ba1d7cb5565 100644--- a/web/app/components/datasets/list/index.tsx+++ b/web/app/components/datasets/list/index.tsx@@ -11,6 +11,7 @@ import { TagManagementModal } from '@/features/tag-management/components/tag-manimport useDocumentTitle from '@/hooks/use-document-title'import { useRouter } from '@/next/navigation'import { useDatasetApiBaseUrl, useDatasetList, useInvalidDatasetList } from '@/service/knowledge/use-dataset'+import { hasPermission } from '@/utils/permission'// Componentsimport FilterEmptyState from '../../base/filter-empty-state'import ExternalAPIPanel from '../external-api/external-api-panel'@@ -47,8 +48,9 @@ const List = () => {handleTagsUpdate()}- const isCurrentWorkspaceManager = useAppContextSelector(state => state.isCurrentWorkspaceManager)- const isCurrentWorkspaceEditor = useAppContextSelector(state => state.isCurrentWorkspaceEditor)+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)+ const canCreateDataset = hasPermission(workspacePermissionKeys, 'dataset.create_and_management')+ const canConnectExternalDataset = hasPermission(workspacePermissionKeys, 'dataset.external.connect')const { data: apiBaseInfo } = useDatasetApiBaseUrl()const datasetListQuery = useDatasetList({initialPage: 1,@@ -61,7 +63,7 @@ const List = () => {const hasResolvedFirstPage = pages.length > 0const hasAnyDataset = (pages[0]?.total ?? 0) > 0const hasActiveFilters = tagIDs.length > 0 || keywords.trim().length > 0 || searchKeywords.trim().length > 0 || includeAll- const showEmptyDataList = !hasAnyDataset && isCurrentWorkspaceEditor && hasResolvedFirstPage && !hasActiveFilters+ const showEmptyDataList = !hasAnyDataset && (canCreateDataset || canConnectExternalDataset) && hasResolvedFirstPage && !hasActiveFiltersconst showFilteredEmptyState = !hasAnyDataset && hasResolvedFirstPage && hasActiveFiltersreturn (@@ -71,9 +73,9 @@ const List = () => {<><DatasetListHeaderapiBaseUrl={apiBaseInfo?.api_base_url ?? ''}+ canConnectExternalDataset={canConnectExternalDataset}+ canCreateDataset={canCreateDataset}includeAll={includeAll}- isCurrentWorkspaceEditor={isCurrentWorkspaceEditor}- isCurrentWorkspaceManager={isCurrentWorkspaceManager}isCurrentWorkspaceOwner={isCurrentWorkspaceOwner}keywords={keywords}tagFilterValue={tagFilterValue}@@ -86,16 +88,19 @@ const List = () => {onOpenTagManagement={() => setShowTagManagementModal(true)}onTagsChange={handleTagsChange}/>- <DatasetFirstEmptyState />+ <DatasetFirstEmptyState+ canConnectExternalDataset={canConnectExternalDataset}+ canCreateDataset={canCreateDataset}+ /></>): (<><DatasetListHeaderapiBaseUrl={apiBaseInfo?.api_base_url ?? ''}+ canConnectExternalDataset={canConnectExternalDataset}+ canCreateDataset={canCreateDataset}includeAll={includeAll}- isCurrentWorkspaceEditor={isCurrentWorkspaceEditor}- isCurrentWorkspaceManager={isCurrentWorkspaceManager}isCurrentWorkspaceOwner={isCurrentWorkspaceOwner}keywords={keywords}tagFilterValue={tagFilterValue}@@ -127,7 +132,12 @@ const List = () => {onClose={() => setShowTagManagementModal(false)}onTagsChange={invalidDatasetList}/>- {showExternalApiPanel && <ExternalAPIPanel onClose={() => setShowExternalApiPanel(false)} />}+ {showExternalApiPanel && canConnectExternalDataset && (+ <ExternalAPIPanel+ canManageExternalKnowledgeApi={canConnectExternalDataset}+ onClose={() => setShowExternalApiPanel(false)}+ />+ )}</div>)}diff --git a/web/app/components/datasets/list/new-dataset-card/__tests__/index.spec.tsx b/web/app/components/datasets/list/new-dataset-card/__tests__/index.spec.tsxindex 4d360eecb91..2b4e22317d9 100644--- a/web/app/components/datasets/list/new-dataset-card/__tests__/index.spec.tsx+++ b/web/app/components/datasets/list/new-dataset-card/__tests__/index.spec.tsx@@ -3,6 +3,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import NewDatasetCard from '../index'import Option from '../option'+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'],+ }),+}))+describe('New Dataset Card Integration', () => {beforeEach(() => {vi.clearAllMocks()diff --git a/web/app/components/datasets/list/new-dataset-card/option.tsx b/web/app/components/datasets/list/new-dataset-card/option.tsxindex 1650b58dd10..8016f5f1a11 100644--- a/web/app/components/datasets/list/new-dataset-card/option.tsx+++ b/web/app/components/datasets/list/new-dataset-card/option.tsx@@ -10,13 +10,28 @@ type OptionProps = {iconClassName: stringtext: stringhref: string+ disabled?: boolean}const Option = ({iconClassName,text,href,+ disabled = false,}: OptionProps) => {+ if (disabled) {+ return (+ <div+ className={cn(+ 'flex w-full cursor-not-allowed items-center gap-x-2 rounded-lg bg-transparent px-4 py-2 text-text-tertiary opacity-50 shadow-shadow-shadow-3',+ )}+ >+ <span aria-hidden="true" className={cn(iconClassName, 'h-4 w-4 shrink-0')} />+ <span className="grow text-left system-sm-medium">{text}</span>+ </div>+ )+ }+return (<Linktype="button"diff --git a/web/app/components/datasets/metadata/metadata-document/__tests__/index.spec.tsx b/web/app/components/datasets/metadata/metadata-document/__tests__/index.spec.tsxindex bf155aa9ace..815bd27c6cd 100644--- a/web/app/components/datasets/metadata/metadata-document/__tests__/index.spec.tsx+++ b/web/app/components/datasets/metadata/metadata-document/__tests__/index.spec.tsx@@ -103,6 +103,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)expect(container.firstChild)!.toBeInTheDocument()@@ -114,6 +115,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)expect(screen.getByText('field_one'))!.toBeInTheDocument()@@ -134,6 +136,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)expect(screen.getAllByText(/metadata/i).length).toBeGreaterThan(0)@@ -150,6 +153,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -169,6 +173,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -187,6 +192,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -205,6 +211,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -222,6 +229,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -242,6 +250,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -253,17 +262,42 @@ describe('MetadataDocument', () => {})describe('Edit Mode', () => {- it('should show edit button when not in edit mode and embedding available', () => {+ it('should show edit button when not in edit mode, embedding available, and canEdit is true', () => {render(<MetadataDocumentdatasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)expect(screen.getByText(/edit/i))!.toBeInTheDocument()})+ it('should hide edit button by default when canEdit is omitted', () => {+ render(+ <MetadataDocument+ datasetId="ds-1"+ documentId="doc-1"+ docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit+ />,+ )+ expect(screen.queryByText(/^edit$/i)).not.toBeInTheDocument()+ })++ it('should hide edit button when canEdit is false', () => {+ render(+ <MetadataDocument+ datasetId="ds-1"+ documentId="doc-1"+ docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit={false}+ />,+ )+ expect(screen.queryByText(/^edit$/i)).not.toBeInTheDocument()+ })+it('should call startToEdit when edit button is clicked', () => {const startToEdit = vi.fn()mockUseMetadataDocument.mockReturnValue({@@ -277,6 +311,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -297,6 +332,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -317,6 +353,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -340,6 +377,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -364,6 +402,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -388,6 +427,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -412,6 +452,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -431,6 +472,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -454,6 +496,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -478,6 +521,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -714,6 +758,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)@@ -731,6 +776,7 @@ describe('MetadataDocument', () => {datasetId="ds-1"documentId="doc-1"docDetail={mockDocDetail as Parameters<typeof MetadataDocument>[0]['docDetail']}+ canEdit/>,)diff --git a/web/app/components/datasets/metadata/metadata-document/index.tsx b/web/app/components/datasets/metadata/metadata-document/index.tsxindex c54b99edbc1..56391acb8ec 100644--- a/web/app/components/datasets/metadata/metadata-document/index.tsx+++ b/web/app/components/datasets/metadata/metadata-document/index.tsx@@ -3,7 +3,6 @@ import type { FC } from 'react'import type { FullDocumentDetail } from '@/models/datasets'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'-import { RiEditLine } from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'@@ -18,12 +17,14 @@ type Props = Readonly<{documentId: stringclassName?: stringdocDetail: FullDocumentDetail+ canEdit?: boolean}>const MetadataDocument: FC<Props> = ({datasetId,documentId,className,docDetail,+ canEdit = false,}) => {const { t } = useTranslation()@@ -57,7 +58,7 @@ const MetadataDocument: FC<Props> = ({titleTooltip={t(`${i18nPrefix}.metadataToolTip`, { ns: 'dataset' })}list={isEdit ? tempList : list}dataSetId={datasetId}- headerRight={embeddingAvailable && (isEdit+ headerRight={embeddingAvailable && canEdit && (isEdit? (<div className="flex space-x-1"><Button variant="ghost" size="small" onClick={handleCancel}>@@ -70,7 +71,7 @@ const MetadataDocument: FC<Props> = ({): (<Button variant="ghost" size="small" onClick={startToEdit}>- <RiEditLine className="mr-1 size-3.5 cursor-pointer text-text-tertiary" />+ <span className="mr-1 i-ri-edit-line size-3.5 cursor-pointer text-text-tertiary" /><div>{t('operation.edit', { ns: 'common' })}</div></Button>))}@@ -90,7 +91,7 @@ const MetadataDocument: FC<Props> = ({</div>): (- embeddingAvailable && <NoData onStart={() => setIsEdit(true)} />+ embeddingAvailable && canEdit && <NoData onStart={() => setIsEdit(true)} />)}{builtInEnabled && (<div className="pl-2">diff --git a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsxindex 1322d4f6e6b..8fde3275112 100644--- a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx+++ b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx@@ -34,6 +34,35 @@ vi.mock('../../../base/app-icon', () => ({),}))+vi.mock('@/app/components/base/app-icon-picker', () => ({+ default: ({+ onOpenChange,+ onSelect,+ }: {+ onOpenChange: (open: boolean) => void+ onSelect: (payload: { type: 'emoji', icon: string, background: string }) => void+ }) => {+ let selectedBackground = '#FFEAD5'+ return (+ <div>+ <input placeholder="Search emojis..." />+ <button type="button" aria-label="#E4FBCC" onClick={() => { selectedBackground = '#E4FBCC' }} />+ <button type="button" aria-label="#E0F2FE" onClick={() => { selectedBackground = '#E0F2FE' }} />+ <button+ type="button"+ onClick={() => {+ onSelect({ type: 'emoji', icon: '📊', background: selectedBackground })+ onOpenChange(false)+ }}+ >+ iconPicker.ok+ </button>+ <button type="button" onClick={() => onOpenChange(false)}>iconPicker.cancel</button>+ </div>+ )+ },+}))+// The mock returns 'ns.key' format, e.g., 'common.operation.cancel'describe('RenameDatasetModal', () => {diff --git a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx b/web/app/components/datasets/settings/form/__tests__/index.spec.tsxindex 3e5ae330a22..b39f4e54706 100644--- a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx+++ b/web/app/components/datasets/settings/form/__tests__/index.spec.tsx@@ -4,6 +4,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'import { expectLoadingButton } from '@/test/button'import { RETRIEVE_METHOD } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'import { IndexingType } from '../../../create/step-two'import Form from '../index'@@ -22,12 +23,25 @@ const mockUserProfile = {avatar_url: '',role: 'owner',}+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/app-context', () => ({useSelector: (selector: (state: unknown) => unknown) => {const state = {- isCurrentWorkspaceDatasetOperator: false,userProfile: mockUserProfile,+ workspacePermissionKeys: mockWorkspacePermissionKeys,}return selector(state)},@@ -99,6 +113,7 @@ const createMockDataset = (overrides: Partial<DataSet> = {}): DataSet => ({runtime_mode: 'general',enable_api: true,is_multimodal: false,+ permission_keys: [DatasetACLPermission.Edit],...overrides,})@@ -177,7 +192,6 @@ vi.mock('@/context/provider-context', () => ({plan: { type: 'free' },enableBilling: false,onPlanInfoChanged: vi.fn(),- isCurrentWorkspaceDatasetOperator: false,supportRetrievalMethods: ['semantic_search', 'full_text_search', 'hybrid_search'],}),}))@@ -237,6 +251,7 @@ describe('Form', () => {beforeEach(() => {vi.clearAllMocks()mockDataset = createMockDataset()+ mockWorkspacePermissionKeys = ['dataset.create_and_management']})describe('Rendering', () => {@@ -460,6 +475,15 @@ describe('Form', () => {const descriptionTextarea = screen.getByDisplayValue('Test description')expect(descriptionTextarea).toBeDisabled()})++ it('should disable save when dataset only has readonly ACL permission', () => {+ mockWorkspacePermissionKeys = []+ mockDataset = createMockDataset({ permission_keys: [DatasetACLPermission.Readonly] })+ render(<Form />)++ const saveButton = screen.getByRole('button', { name: /form\.save/i })+ expect(saveButton).toBeDisabled()+ })})describe('Conditional Rendering', () => {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 7681d35702a..3c0e997ad57 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@@ -7,6 +7,18 @@ 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,+ },+ }),+ }+})+// Mock app-contextvi.mock('@/context/app-context', () => ({useSelector: () => ({@@ -105,8 +117,8 @@ describe('BasicInfoSection', () => {}const mockMemberList: Member[] = [- { id: 'user-1', name: 'User 1', email: '[email protected]', role: 'owner', avatar: '', avatar_url: '', last_login_at: '', created_at: '', status: 'active' },- { id: 'user-2', name: 'User 2', email: '[email protected]', role: 'admin', avatar: '', avatar_url: '', last_login_at: '', created_at: '', status: 'active' },+ { id: 'user-1', name: 'User 1', email: '[email protected]', role: 'owner', roles: [], avatar: '', avatar_url: '', last_login_at: '', created_at: '', status: 'active' },+ { id: 'user-2', name: 'User 2', email: '[email protected]', role: 'admin', roles: [], avatar: '', avatar_url: '', last_login_at: '', created_at: '', status: 'active' },]const mockIconInfo: IconInfo = {@@ -118,7 +130,6 @@ describe('BasicInfoSection', () => {const defaultProps = {currentDataset: mockDataset,- isCurrentWorkspaceDatasetOperator: false,name: 'Test Dataset',setName: vi.fn(),description: 'Test description',@@ -346,9 +357,9 @@ describe('BasicInfoSection', () => {expect(disabledElement)!.toBeInTheDocument()})- it('should be disabled when user is dataset operator', () => {+ it('should be disabled when form is readonly from dataset ACL editability', () => {const { container } = render(- <BasicInfoSection {...defaultProps} isCurrentWorkspaceDatasetOperator={true} />,+ <BasicInfoSection {...defaultProps} readonly />,)const disabledElement = container.querySelector('[class*="cursor-not-allowed"]')diff --git a/web/app/components/datasets/settings/form/components/basic-info-section.tsx b/web/app/components/datasets/settings/form/components/basic-info-section.tsxindex 17d0a3e6d23..b22d3fc5d0d 100644--- a/web/app/components/datasets/settings/form/components/basic-info-section.tsx+++ b/web/app/components/datasets/settings/form/components/basic-info-section.tsx@@ -15,7 +15,6 @@ const labelClass = 'flex items-center shrink-0 w-[180px] h-7 pt-1'type BasicInfoSectionProps = {currentDataset: DataSet | undefined- isCurrentWorkspaceDatasetOperator: booleanname: stringsetName: (value: string) => voiddescription: string@@ -30,11 +29,11 @@ type BasicInfoSectionProps = {selectedMemberIDs: string[]setSelectedMemberIDs: (value: string[]) => voidmemberList: Member[]+ readonly?: boolean}const BasicInfoSection = ({currentDataset,- isCurrentWorkspaceDatasetOperator,name,setName,description,@@ -49,6 +48,7 @@ const BasicInfoSection = ({selectedMemberIDs,setSelectedMemberIDs,memberList,+ readonly = false,}: BasicInfoSectionProps) => {const { t } = useTranslation()@@ -62,16 +62,16 @@ const BasicInfoSection = ({<div className="flex grow items-center gap-x-2"><AppIconsize="small"- onClick={handleOpenAppIconPicker}- className="cursor-pointer"+ onClick={readonly ? undefined : handleOpenAppIconPicker}+ className={readonly ? undefined : 'cursor-pointer'}iconType={iconInfo.icon_type as AppIconType}icon={iconInfo.icon}background={iconInfo.icon_background}imageUrl={iconInfo.icon_url}- showEditIcon+ showEditIcon={!readonly}/><Input- disabled={!currentDataset?.embedding_available}+ disabled={!currentDataset?.embedding_available || readonly}value={name}onChange={e => setName(e.target.value)}/>@@ -86,7 +86,7 @@ const BasicInfoSection = ({<div className="grow"><Textareaaria-label={t('form.desc', { ns: 'datasetSettings' })}- disabled={!currentDataset?.embedding_available}+ disabled={!currentDataset?.embedding_available || readonly}className="resize-none"placeholder={t('form.descPlaceholder', { ns: 'datasetSettings' }) || ''}value={description}@@ -102,7 +102,7 @@ const BasicInfoSection = ({</div><div className="grow"><PermissionSelector- disabled={!currentDataset?.embedding_available || isCurrentWorkspaceDatasetOperator}+ disabled={!currentDataset?.embedding_available || readonly}permission={permission}value={selectedMemberIDs}onChange={v => setPermission(v)}diff --git a/web/app/components/datasets/settings/form/components/external-knowledge-section.tsx b/web/app/components/datasets/settings/form/components/external-knowledge-section.tsxindex fb9c0eed720..0e1891ab6f5 100644--- a/web/app/components/datasets/settings/form/components/external-knowledge-section.tsx+++ b/web/app/components/datasets/settings/form/components/external-knowledge-section.tsx@@ -14,6 +14,7 @@ type ExternalKnowledgeSectionProps = {scoreThreshold: numberscoreThresholdEnabled: booleanhandleSettingsChange: (data: { top_k?: number, score_threshold?: number, score_threshold_enabled?: boolean }) => void+ readonly?: boolean}const ExternalKnowledgeSection = ({@@ -22,6 +23,7 @@ const ExternalKnowledgeSection = ({scoreThreshold,scoreThresholdEnabled,handleSettingsChange,+ readonly = false,}: ExternalKnowledgeSectionProps) => {const { t } = useTranslation()@@ -40,6 +42,7 @@ const ExternalKnowledgeSection = ({scoreThresholdEnabled={scoreThresholdEnabled}onChange={handleSettingsChange}isInRetrievalSetting={true}+ readonly={readonly}/></div>diff --git a/web/app/components/datasets/settings/form/components/indexing-section.tsx b/web/app/components/datasets/settings/form/components/indexing-section.tsxindex 09aceea0f25..c5edcbbbef1 100644--- a/web/app/components/datasets/settings/form/components/indexing-section.tsx+++ b/web/app/components/datasets/settings/form/components/indexing-section.tsx@@ -2,7 +2,6 @@import type { DefaultModel, Model } 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 { RiAlertFill } from '@remixicon/react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/economical-retrieval-method-config'@@ -33,6 +32,7 @@ type IndexingSectionProps = {summaryIndexSetting: SummaryIndexSettingType | undefinedhandleSummaryIndexSettingChange: (payload: SummaryIndexSettingType) => voidshowMultiModalTip: boolean+ readonly?: boolean}const IndexingSection = ({@@ -49,6 +49,7 @@ const IndexingSection = ({summaryIndexSetting,handleSummaryIndexSettingChange,showMultiModalTip,+ readonly = false,}: IndexingSectionProps) => {const { t } = useTranslation()const docLink = useDocLink()@@ -108,7 +109,7 @@ const IndexingSection = ({<div className="grow"><IndexMethodvalue={indexMethod!}- disabled={!currentDataset?.embedding_available}+ disabled={!currentDataset?.embedding_available || readonly}onChange={setIndexMethod}currentValue={currentDataset.indexing_technique}keywordNumber={keywordNumber}@@ -118,7 +119,7 @@ const IndexingSection = ({<div className="relative mt-2 flex h-10 items-center gap-x-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur px-2 shadow-xs shadow-shadow-shadow-3"><div className="absolute top-0 left-0 flex size-full items-center bg-toast-warning-bg opacity-40" /><div className="p-1">- <RiAlertFill className="size-4 text-text-warning-secondary" />+ <span className="i-ri-alert-fill size-4 text-text-warning-secondary" /></div><span className="system-xs-medium text-text-primary">{t('form.upgradeHighQualityTip', { ns: 'datasetSettings' })}@@ -142,6 +143,7 @@ const IndexingSection = ({defaultModel={embeddingModel}modelList={embeddingModelList}onSelect={setEmbeddingModel}+ readonly={readonly}/></div></div>@@ -155,6 +157,7 @@ const IndexingSection = ({entry="dataset-settings"summaryIndexSetting={summaryIndexSetting}onSummaryIndexSettingChange={handleSummaryIndexSettingChange}+ readonly={readonly}/></>)}@@ -189,12 +192,14 @@ const IndexingSection = ({value={retrievalConfig}onChange={setRetrievalConfig}showMultiModalTip={showMultiModalTip}+ disabled={readonly}/>): (<EconomicalRetrievalMethodConfigvalue={retrievalConfig}onChange={setRetrievalConfig}+ disabled={readonly}/>)}</div>diff --git a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.tsindex cefcedafc67..78db31af095 100644--- a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts+++ b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts@@ -3,6 +3,7 @@ import type { RetrievalConfig } from '@/types/app'import { act, renderHook, waitFor } from '@testing-library/react'import { ChunkingMode, DatasetPermission, DataSourceType, WeightedScoreEnum } from '@/models/datasets'import { RETRIEVE_METHOD } from '@/types/app'+import { DatasetACLPermission } from '@/utils/permission'import { IndexingType } from '../../../../create/step-two'import { useFormState } from '../use-form-state'@@ -16,7 +17,10 @@ const mockMutateDatasets = vi.fn()const mockInvalidDatasetList = vi.fn()vi.mock('@/context/app-context', () => ({- useSelector: () => false, // isCurrentWorkspaceDatasetOperator+ useSelector: <T>(selector: (value: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => T) => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],+ }),}))const createDefaultMockDataset = (): DataSet => ({@@ -85,6 +89,7 @@ const createDefaultMockDataset = (): DataSet => ({runtime_mode: 'general',enable_api: true,is_multimodal: false,+ permission_keys: [DatasetACLPermission.Edit],})let mockDataset: DataSet = createDefaultMockDataset()@@ -183,6 +188,17 @@ describe('useFormState', () => {expect(result.current.currentDataset).toBeDefined()expect(result.current.currentDataset?.id).toBe('dataset-1')})++ it('should expose editability from dataset ACL permission keys without legacy role state', () => {+ mockDataset = {+ ...createDefaultMockDataset(),+ permission_keys: [DatasetACLPermission.Readonly],+ }+ const { result } = renderHook(() => useFormState())++ expect(result.current.canEditSettings).toBe(false)+ expect('isCurrentWorkspaceDatasetOperator' in result.current).toBe(false)+ })})describe('State Setters', () => {@@ -471,6 +487,21 @@ describe('useFormState', () => {})})+ it('should not save when dataset only has readonly ACL permission', async () => {+ const { updateDatasetSetting } = await import('@/service/datasets')+ mockDataset = {+ ...createDefaultMockDataset(),+ permission_keys: [DatasetACLPermission.Readonly],+ }+ const { result } = renderHook(() => useFormState())++ await act(async () => {+ await result.current.handleSave()+ })++ expect(updateDatasetSetting).not.toHaveBeenCalled()+ })+it('should show success toast on successful save', async () => {const { toast } = await import('@langgenius/dify-ui/toast')const { result } = renderHook(() => useFormState())diff --git a/web/app/components/datasets/settings/form/hooks/use-form-state.ts b/web/app/components/datasets/settings/form/hooks/use-form-state.tsindex 0ebd60a69a1..8892d982636 100644--- a/web/app/components/datasets/settings/form/hooks/use-form-state.ts+++ b/web/app/components/datasets/settings/form/hooks/use-form-state.ts@@ -16,6 +16,7 @@ import { DatasetPermission } from '@/models/datasets'import { updateDatasetSetting } from '@/service/datasets'import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'import { useMembers } from '@/service/use-common'+import { getDatasetACLCapabilities } from '@/utils/permission'import { checkShowMultiModalTip } from '../../utils'const DEFAULT_APP_ICON: IconInfo = {@@ -27,9 +28,19 @@ const DEFAULT_APP_ICON: IconInfo = {export const useFormState = () => {const { t } = useTranslation()- const isCurrentWorkspaceDatasetOperator = useAppContextWithSelector(state => state.isCurrentWorkspaceDatasetOperator)const currentDataset = useDatasetDetailContextWithSelector(state => state.dataset)const mutateDatasets = useDatasetDetailContextWithSelector(state => state.mutateDatasetRes)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const datasetACLCapabilities = useMemo(+ () => getDatasetACLCapabilities(currentDataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: currentDataset?.maintainer,+ workspacePermissionKeys,+ }),+ [currentDataset?.maintainer, currentDataset?.permission_keys, currentUserId, workspacePermissionKeys],+ )+ const canEditSettings = datasetACLCapabilities.canEdit// Basic form stateconst [loading, setLoading] = useState(false)@@ -111,6 +122,9 @@ export const useFormState = () => {// Save handlerconst handleSave = async () => {+ if (!canEditSettings)+ return+if (loading)return@@ -201,7 +215,7 @@ export const useFormState = () => {return {// Context valuescurrentDataset,- isCurrentWorkspaceDatasetOperator,+ canEditSettings,// Loading stateloading,diff --git a/web/app/components/datasets/settings/form/index.tsx b/web/app/components/datasets/settings/form/index.tsxindex a483c94be38..58b86ff228c 100644--- a/web/app/components/datasets/settings/form/index.tsx+++ b/web/app/components/datasets/settings/form/index.tsx@@ -12,7 +12,7 @@ const Form = () => {const {// Context valuescurrentDataset,- isCurrentWorkspaceDatasetOperator,+ canEditSettings,// Loading stateloading,@@ -66,12 +66,12 @@ const Form = () => {} = useFormState()const isExternalProvider = currentDataset?.provider === 'external'+ const readonly = !canEditSettingsreturn (<div className="flex w-full flex-col gap-y-4 px-20 py-8 sm:w-[960px]"><BasicInfoSectioncurrentDataset={currentDataset}- isCurrentWorkspaceDatasetOperator={isCurrentWorkspaceDatasetOperator}name={name}setName={setName}description={description}@@ -86,6 +86,7 @@ const Form = () => {selectedMemberIDs={selectedMemberIDs}setSelectedMemberIDs={setSelectedMemberIDs}memberList={memberList}+ readonly={readonly}/>{isExternalProvider@@ -96,6 +97,7 @@ const Form = () => {scoreThreshold={scoreThreshold}scoreThresholdEnabled={scoreThresholdEnabled}handleSettingsChange={handleSettingsChange}+ readonly={readonly}/>): (@@ -113,6 +115,7 @@ const Form = () => {summaryIndexSetting={summaryIndexSetting}handleSummaryIndexSettingChange={handleSummaryIndexSettingChange}showMultiModalTip={showMultiModalTip}+ readonly={readonly}/>)}@@ -126,7 +129,7 @@ const Form = () => {className="min-w-24"variant="primary"loading={loading}- disabled={loading}+ disabled={loading || readonly}onClick={handleSave}>{t('form.save', { ns: 'datasetSettings' })}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 84d5ae64551..7793c50acc2 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,5 +1,6 @@import type { Member } from '@/models/common'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'import { DatasetPermission } from '@/models/datasets'import PermissionSelector from '../index'@@ -16,10 +17,10 @@ vi.mock('@/context/app-context', () => ({describe('PermissionSelector', () => {const mockMemberList: Member[] = [- { id: 'user-1', name: 'Current User', email: '[email protected]', avatar: '', avatar_url: '', role: 'owner', last_login_at: '', created_at: '', status: 'active' }!,- { id: 'user-2', name: 'John Doe', email: '[email protected]', avatar: '', avatar_url: '', role: 'admin', last_login_at: '', created_at: '', status: 'active' }!,- { id: 'user-3', name: 'Jane Smith', email: '[email protected]', avatar: '', avatar_url: '', role: 'editor', last_login_at: '', created_at: '', status: 'active' }!,- { id: 'user-4', name: 'Dataset Operator', email: '[email protected]', avatar: '', avatar_url: '', role: 'dataset_operator', last_login_at: '', created_at: '', status: 'active' }!,+ { id: 'user-1', name: 'Current User', email: '[email protected]', avatar: '', avatar_url: '', role: 'owner', roles: [], last_login_at: '', created_at: '', status: 'active' }!,+ { id: 'user-2', name: 'John Doe', email: '[email protected]', avatar: '', avatar_url: '', role: 'admin', roles: [], last_login_at: '', created_at: '', status: 'active' }!,+ { id: 'user-3', name: 'Jane Smith', email: '[email protected]', avatar: '', avatar_url: '', role: 'editor', roles: [], last_login_at: '', created_at: '', status: 'active' }!,+ { id: 'user-4', name: 'Dataset Operator', email: '[email protected]', avatar: '', avatar_url: '', role: 'dataset_operator', roles: [], last_login_at: '', created_at: '', status: 'active' }!,]const defaultProps = {@@ -36,22 +37,22 @@ describe('PermissionSelector', () => {describe('Rendering', () => {it('should render without crashing', () => {- render(<PermissionSelector {...defaultProps} />)+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} />)expect(screen.getByText(/form\.permissionsOnlyMe/))!.toBeInTheDocument()})it('should render Only Me option when permission is onlyMe', () => {- render(<PermissionSelector {...defaultProps} permission={DatasetPermission.onlyMe} />)+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} permission={DatasetPermission.onlyMe} />)expect(screen.getByText(/form\.permissionsOnlyMe/))!.toBeInTheDocument()})it('should render All Team Members option when permission is allTeamMembers', () => {- render(<PermissionSelector {...defaultProps} permission={DatasetPermission.allTeamMembers} />)+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} permission={DatasetPermission.allTeamMembers} />)expect(screen.getByText(/form\.permissionsAllMember/))!.toBeInTheDocument()})it('should render selected member names when permission is partialMembers', () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -66,7 +67,7 @@ describe('PermissionSelector', () => {describe('Dropdown Toggle', () => {it('should open dropdown when clicked', async () => {- render(<PermissionSelector {...defaultProps} />)+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} />)const trigger = screen.getByText(/form\.permissionsOnlyMe/)fireEvent.click(trigger)@@ -78,7 +79,7 @@ describe('PermissionSelector', () => {})it('should not open dropdown when disabled', () => {- render(<PermissionSelector {...defaultProps} disabled={true} />)+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} disabled={true} />)const trigger = screen.getByText(/form\.permissionsOnlyMe/)fireEvent.click(trigger)@@ -91,7 +92,7 @@ describe('PermissionSelector', () => {describe('Permission Selection', () => {it('should call onChange with onlyMe when Only Me is selected', async () => {const handleChange = vi.fn()- render(<PermissionSelector {...defaultProps} onChange={handleChange} permission={DatasetPermission.allTeamMembers} />)+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} onChange={handleChange} permission={DatasetPermission.allTeamMembers} />)const trigger = screen.getByText(/form\.permissionsAllMember/)fireEvent.click(trigger)@@ -106,7 +107,7 @@ describe('PermissionSelector', () => {it('should call onChange with allTeamMembers when All Team Members is selected', async () => {const handleChange = vi.fn()- render(<PermissionSelector {...defaultProps} onChange={handleChange} />)+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} onChange={handleChange} />)const trigger = screen.getByText(/form\.permissionsOnlyMe/)fireEvent.click(trigger)@@ -122,7 +123,7 @@ describe('PermissionSelector', () => {it('should call onChange with partialMembers when Invited Members is selected', async () => {const handleChange = vi.fn()const handleMemberSelect = vi.fn()- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}onChange={handleChange}@@ -145,7 +146,7 @@ describe('PermissionSelector', () => {describe('Member Selection', () => {it('should show member list when partialMembers is selected', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -165,7 +166,7 @@ describe('PermissionSelector', () => {it('should call onMemberSelect when a member is clicked', async () => {const handleMemberSelect = vi.fn()- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -186,7 +187,7 @@ describe('PermissionSelector', () => {it('should deselect member when clicked again', async () => {const handleMemberSelect = vi.fn()- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -209,7 +210,7 @@ describe('PermissionSelector', () => {describe('Search Functionality', () => {it('should allow typing in search input', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -228,7 +229,7 @@ describe('PermissionSelector', () => {})it('should render search input in partial members mode', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -244,7 +245,7 @@ describe('PermissionSelector', () => {})it('should filter members after debounce completes', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -270,7 +271,7 @@ describe('PermissionSelector', () => {})it('should handle clear search functionality', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -297,7 +298,7 @@ describe('PermissionSelector', () => {})it('should filter members by email', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -323,7 +324,7 @@ describe('PermissionSelector', () => {})it('should show no results message when search matches nothing', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -349,7 +350,7 @@ describe('PermissionSelector', () => {})it('should show current user when search matches user name', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -375,7 +376,7 @@ describe('PermissionSelector', () => {})it('should show current user when search matches user email', async () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -401,16 +402,30 @@ describe('PermissionSelector', () => {describe('Disabled State', () => {it('should apply disabled styles when disabled', () => {- const { container } = render(<PermissionSelector {...defaultProps} disabled={true} />)+ const { container } = renderWithSystemFeatures(<PermissionSelector {...defaultProps} disabled={true} />)// When disabled, the component has cursor-not-allowed! class (escaped in Tailwind)const triggerElement = container.querySelector('[class*="cursor-not-allowed"]')expect(triggerElement)!.toBeInTheDocument()})++ it('should show access config hint and remain closed when RBAC is enabled', () => {+ renderWithSystemFeatures(<PermissionSelector {...defaultProps} />, {+ systemFeatures: {+ rbac_enabled: true,+ },+ })++ const trigger = screen.getByText(/form\.permissionsAccessConfig/)+ fireEvent.click(trigger)++ expect(screen.getByText(/form\.permissionsAccessConfig/))!.toBeInTheDocument()+ expect(screen.queryByText(/form\.permissionsOnlyMe/))!.not.toBeInTheDocument()+ })})describe('Display Variations', () => {it('should display single avatar when only one member selected', () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -424,7 +439,7 @@ describe('PermissionSelector', () => {})it('should display two avatars when two or more members selected', () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}permission={DatasetPermission.partialMembers}@@ -440,7 +455,7 @@ describe('PermissionSelector', () => {describe('Edge Cases', () => {it('should handle empty member list', () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}memberList={[]}@@ -451,7 +466,7 @@ describe('PermissionSelector', () => {})it('should handle member list with only current user', () => {- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}memberList={[mockMemberList[0]!]}@@ -467,10 +482,10 @@ describe('PermissionSelector', () => {// This is tested indirectly through the memberList filteringconst memberListWithNormalUser: Member[] = [...mockMemberList,- { id: 'user-5', name: 'Normal User', email: '[email protected]', avatar: '', avatar_url: '', role: 'normal', last_login_at: '', created_at: '', status: 'active' },+ { id: 'user-5', name: 'Normal User', email: '[email protected]', avatar: '', avatar_url: '', role: 'normal', roles: [], last_login_at: '', created_at: '', status: 'active' },]- render(+ renderWithSystemFeatures(<PermissionSelector{...defaultProps}memberList={memberListWithNormalUser}@@ -486,7 +501,7 @@ describe('PermissionSelector', () => {describe('Props', () => {it('should update when permission prop changes', () => {- const { rerender } = render(<PermissionSelector {...defaultProps} permission={DatasetPermission.onlyMe} />)+ const { rerender } = renderWithSystemFeatures(<PermissionSelector {...defaultProps} permission={DatasetPermission.onlyMe} />)expect(screen.getByText(/form\.permissionsOnlyMe/))!.toBeInTheDocument()diff --git a/web/app/components/datasets/settings/permission-selector/index.tsx b/web/app/components/datasets/settings/permission-selector/index.tsxindex 067bf68da4a..afff19320e5 100644--- a/web/app/components/datasets/settings/permission-selector/index.tsx+++ b/web/app/components/datasets/settings/permission-selector/index.tsx@@ -1,18 +1,18 @@import type { Member } from '@/models/common'import { Avatar } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'import {Popover,PopoverContent,PopoverTrigger,} from '@langgenius/dify-ui/popover'-import { RiArrowDownSLine, RiGroup2Line, RiLock2Line } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useDebounceFn } from 'ahooks'-import * as React from 'react'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import Input from '@/app/components/base/input'import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { DatasetPermission } from '@/models/datasets'import MemberItem from './member-item'import Item from './permission-item'@@ -36,6 +36,7 @@ const PermissionSelector = ({}: RoleSelectorProps) => {const { t } = useTranslation()const userProfile = useAppContextWithSelector(state => state.userProfile)+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const [open, setOpen] = useState(false)const [keywords, setKeywords] = useState('')@@ -66,7 +67,7 @@ const PermissionSelector = ({}, [searchKeywords, userProfile])const filteredMemberList = useMemo(() => {- return memberList.filter(member => (member.name.includes(searchKeywords) || member.email.includes(searchKeywords)) && member.id !== userProfile.id && ['owner', 'admin', 'editor', 'dataset_operator'].includes(member.role))+ return memberList.filter(member => (member.name.includes(searchKeywords) || member.email.includes(searchKeywords)) && member.id !== userProfile.id)}, [memberList, searchKeywords, userProfile])const onSelectOnlyMe = useCallback(() => {@@ -88,12 +89,14 @@ const PermissionSelector = ({const isAllTeamMembers = permission === DatasetPermission.allTeamMembersconst isPartialMembers = permission === DatasetPermission.partialMembersconst selectedMemberNames = selectedMembers.map(member => member.name).join(', ')+ const isDisabledByRBAC = systemFeatures.rbac_enabled+ const isDisabled = disabled || isDisabledByRBACreturn (<Popoveropen={open}onOpenChange={(nextOpen) => {- if (disabled)+ if (isDisabled)returnsetOpen(nextOpen)}}@@ -101,9 +104,19 @@ const PermissionSelector = ({<div className="relative"><PopoverTriggerrender={(- <div className={cn('group flex cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal px-2 py-1 hover:bg-state-base-hover-alt data-popup-open:bg-state-base-hover-alt', disabled && 'cursor-not-allowed! bg-components-input-bg-disabled! hover:bg-components-input-bg-disabled!')}>+ <div className={cn('group flex cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal px-2 py-1 hover:bg-state-base-hover-alt data-popup-open:bg-state-base-hover-alt', isDisabled && 'cursor-not-allowed! bg-components-input-bg-disabled! hover:bg-components-input-bg-disabled!')}>+ {isDisabledByRBAC && (+ <>+ <div className="flex size-6 shrink-0 items-center justify-center">+ <span className="i-ri-lock-2-line size-4 text-text-tertiary" />+ </div>+ <div className="grow p-1 system-sm-regular text-components-input-text-placeholder">+ {t('form.permissionsAccessConfig', { ns: 'datasetSettings' })}+ </div>+ </>+ )}{- isOnlyMe && (+ !isDisabledByRBAC && isOnlyMe && (<><div className="flex size-6 shrink-0 items-center justify-center"><Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xs" />@@ -115,10 +128,10 @@ const PermissionSelector = ({)}{- isAllTeamMembers && (+ !isDisabledByRBAC && isAllTeamMembers && (<><div className="flex size-6 shrink-0 items-center justify-center">- <RiGroup2Line className="size-4 text-text-secondary" />+ <span className="i-ri-group-2-line size-4 text-text-secondary" /></div><div className="grow p-1 system-sm-regular text-components-input-text-filled">{t('form.permissionsAllMember', { ns: 'datasetSettings' })}@@ -127,7 +140,7 @@ const PermissionSelector = ({)}{- isPartialMembers && (+ !isDisabledByRBAC && isPartialMembers && (<><div className="relative flex size-6 shrink-0 items-center justify-center">{@@ -167,11 +180,11 @@ const PermissionSelector = ({</>)}- <RiArrowDownSLine- className={cn(- 'size-4 shrink-0 text-text-quaternary group-hover:text-text-secondary group-data-popup-open:text-text-secondary',- disabled && 'text-components-input-text-placeholder!',- )}+ <span className={cn(+ 'i-ri-arrow-down-s-line',+ 'size-4 shrink-0 text-text-quaternary group-hover:text-text-secondary group-data-popup-open:text-text-secondary',+ isDisabled && 'text-components-input-text-placeholder!',+ )}/></div>)}@@ -196,7 +209,7 @@ const PermissionSelector = ({<ItemleftIcon={(<div className="flex size-6 shrink-0 items-center justify-center">- <RiGroup2Line className="size-4 text-text-secondary" />+ <span className="i-ri-group-2-line size-4 text-text-secondary" /></div>)}text={t('form.permissionsAllMember', { ns: 'datasetSettings' })}@@ -207,7 +220,7 @@ const PermissionSelector = ({<ItemleftIcon={(<div className="flex size-6 shrink-0 items-center justify-center">- <RiLock2Line className="size-4 text-text-secondary" />+ <span className="i-ri-lock-2-line size-4 text-text-secondary" /></div>)}text={t('form.permissionsInvitedMembers', { ns: 'datasetSettings' })}@@ -218,13 +231,25 @@ const PermissionSelector = ({{isPartialMembers && (<div className="max-h-[360px] overflow-y-auto border-t border-divider-regular pr-1 pb-1 pl-1"><div className="sticky top-0 left-0 z-10 bg-components-panel-on-panel-item-bg p-2 pb-1">- <Input- showLeftIcon- showClearIcon- value={keywords}- onChange={e => handleKeywordsChange(e.target.value)}- onClear={() => handleKeywordsChange('')}- />+ <div className="relative w-full">+ <span className="absolute top-1/2 left-2 i-ri-search-line size-4 -translate-y-1/2 text-components-input-text-placeholder" />+ <Input+ className={cn('w-full pl-[26px]', keywords && 'pr-[26px]')}+ value={keywords}+ placeholder={t('operation.search', { ns: 'common' }) || ''}+ onChange={e => handleKeywordsChange(e.target.value)}+ />+ {!!keywords && (+ <button+ type="button"+ aria-label={t('operation.clear', { ns: 'common' })}+ className="group absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer border-none bg-transparent p-px"+ onClick={() => handleKeywordsChange('')}+ >+ <span className="i-ri-close-circle-fill size-3.5 cursor-pointer text-text-quaternary group-hover:text-text-tertiary" aria-hidden="true" />+ </button>+ )}+ </div></div><div className="flex flex-col p-1">{showMe && (diff --git a/web/app/components/datasets/settings/summary-index-setting.tsx b/web/app/components/datasets/settings/summary-index-setting.tsxindex 6c2aad20c3a..5e7a1697fd6 100644--- a/web/app/components/datasets/settings/summary-index-setting.tsx+++ b/web/app/components/datasets/settings/summary-index-setting.tsx@@ -75,6 +75,7 @@ const SummaryIndexSetting = ({checked={summaryIndexSetting?.enable ?? false}onCheckedChange={handleSummaryIndexEnableChange}size="md"+ disabled={readonly}/></div>{@@ -123,6 +124,7 @@ const SummaryIndexSetting = ({checked={summaryIndexSetting?.enable ?? false}onCheckedChange={handleSummaryIndexEnableChange}size="md"+ disabled={readonly}/>{summaryIndexSetting?.enable ? t('list.status.enabled', { ns: 'datasetDocuments' }) : t('list.status.disabled', { ns: 'datasetDocuments' })@@ -189,6 +191,7 @@ const SummaryIndexSetting = ({checked={summaryIndexSetting?.enable ?? false}onCheckedChange={handleSummaryIndexEnableChange}size="md"+ disabled={readonly}/><div className="system-sm-semibold text-text-secondary">{t('form.summaryAutoGen', { ns: 'datasetSettings' })}diff --git a/web/app/components/develop/ApiServer.tsx b/web/app/components/develop/ApiServer.tsxindex 24398d1c858..eeb09d5fd41 100644--- a/web/app/components/develop/ApiServer.tsx+++ b/web/app/components/develop/ApiServer.tsx@@ -8,10 +8,12 @@ import SecretKeyButton from '@/app/components/develop/secret-key/secret-key-butttype ApiServerProps = {apiBaseUrl: stringappId?: string+ canManageApiKey?: boolean}const ApiServer: FC<ApiServerProps> = ({apiBaseUrl,appId,+ canManageApiKey = false,}) => {const { t } = useTranslation()@@ -29,6 +31,7 @@ const ApiServer: FC<ApiServerProps> = ({<SecretKeyButtonclassName="h-8! shrink-0"appId={appId}+ canManage={canManageApiKey}/></div>)diff --git a/web/app/components/develop/__tests__/ApiServer.spec.tsx b/web/app/components/develop/__tests__/ApiServer.spec.tsxindex a805a3d2e0d..3d2fe4e53dd 100644--- a/web/app/components/develop/__tests__/ApiServer.spec.tsx+++ b/web/app/components/develop/__tests__/ApiServer.spec.tsx@@ -80,7 +80,7 @@ describe('ApiServer', () => {describe('SecretKeyButton interaction', () => {it('should open modal when API key button is clicked', async () => {const user = userEvent.setup()- render(<ApiServer {...defaultProps} appId="app-123" />)+ render(<ApiServer {...defaultProps} appId="app-123" canManageApiKey />)const apiKeyButton = screen.getByText('appApi.apiKey')await act(async () => {@@ -92,7 +92,7 @@ describe('ApiServer', () => {it('should close modal when close button is clicked', async () => {const user = userEvent.setup()- render(<ApiServer {...defaultProps} appId="app-123" />)+ render(<ApiServer {...defaultProps} appId="app-123" canManageApiKey />)const apiKeyButton = screen.getByText('appApi.apiKey')await act(async () => {@@ -108,6 +108,20 @@ describe('ApiServer', () => {expect(screen.queryByRole('dialog', { name: 'Secret key' })).not.toBeInTheDocument()})++ it('should disable API key button by default', async () => {+ const user = userEvent.setup()+ render(<ApiServer {...defaultProps} appId="app-123" />)++ const apiKeyButton = screen.getByRole('button', { name: /apiKey/i })+ expect(apiKeyButton).toBeDisabled()++ await act(async () => {+ await user.click(apiKeyButton)+ })++ expect(screen.queryByRole('dialog', { name: 'Secret key' })).not.toBeInTheDocument()+ })})describe('styling', () => {diff --git a/web/app/components/develop/index.tsx b/web/app/components/develop/index.tsxindex bf82facb6aa..3e3b52a5a39 100644--- a/web/app/components/develop/index.tsx+++ b/web/app/components/develop/index.tsx@@ -3,6 +3,8 @@ import { useStore as useAppStore } from '@/app/components/app/store'import Loading from '@/app/components/base/loading'import ApiServer from '@/app/components/develop/ApiServer'import Doc from '@/app/components/develop/doc'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { getAppACLCapabilities } from '@/utils/permission'type IDevelopMainProps = {appId: string@@ -10,6 +12,13 @@ type IDevelopMainProps = {const DevelopMain = ({ appId }: IDevelopMainProps) => {const appDetail = useAppStore(state => state.appDetail)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const appACLCapabilities = getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ })if (!appDetail) {return (@@ -23,7 +32,7 @@ const DevelopMain = ({ appId }: IDevelopMainProps) => {<div data-testid="develop-main" className="relative flex h-full flex-col overflow-hidden"><div className="flex shrink-0 items-center justify-between border-b border-solid border-b-divider-regular px-6 py-2"><div className="text-lg font-medium text-text-primary"></div>- <ApiServer apiBaseUrl={appDetail.api_base_url} appId={appId} />+ <ApiServer apiBaseUrl={appDetail.api_base_url} appId={appId} canManageApiKey={appACLCapabilities.canEdit} /></div><div className="grow overflow-auto p-4 sm:px-10"><Doc appDetail={appDetail} />diff --git a/web/app/components/develop/secret-key/__tests__/secret-key-button.spec.tsx b/web/app/components/develop/secret-key/__tests__/secret-key-button.spec.tsxindex 22342b18b50..6e91454fbdb 100644--- a/web/app/components/develop/secret-key/__tests__/secret-key-button.spec.tsx+++ b/web/app/components/develop/secret-key/__tests__/secret-key-button.spec.tsx@@ -3,11 +3,12 @@ import userEvent from '@testing-library/user-event'import SecretKeyButton from '../secret-key-button'vi.mock('@/app/components/develop/secret-key/secret-key-modal', () => ({- default: ({ isShow, onClose, appId }: { isShow: boolean, onClose: () => void, appId?: string }) => (+ default: ({ isShow, onClose, appId, canManage }: { isShow: boolean, onClose: () => void, appId?: string, canManage: boolean }) => (isShow? (<div data-testid="secret-key-modal"><span data-testid="modal-app-id">{`Modal for ${appId || 'no-app'}`}</span>+ <span data-testid="modal-can-manage">{String(canManage)}</span><button onClick={onClose} data-testid="close-modal">Close</button></div>)@@ -29,8 +30,8 @@ describe('SecretKeyButton', () => {it('should render the key icon', () => {const { container } = render(<SecretKeyButton />)- const svg = container.querySelector('svg')- expect(svg)!.toBeInTheDocument()+ const icon = container.querySelector('.i-ri-key-2-line')+ expect(icon)!.toBeInTheDocument()})it('should not show modal initially', () => {@@ -42,7 +43,7 @@ describe('SecretKeyButton', () => {describe('button interaction', () => {it('should open modal when button is clicked', async () => {const user = userEvent.setup()- render(<SecretKeyButton />)+ render(<SecretKeyButton canManage />)const button = screen.getByRole('button')await act(async () => {@@ -54,7 +55,7 @@ describe('SecretKeyButton', () => {it('should close modal when onClose is called', async () => {const user = userEvent.setup()- render(<SecretKeyButton />)+ render(<SecretKeyButton canManage />)const button = screen.getByRole('button')await act(async () => {@@ -73,7 +74,7 @@ describe('SecretKeyButton', () => {it('should toggle modal visibility', async () => {const user = userEvent.setup()- render(<SecretKeyButton />)+ render(<SecretKeyButton canManage />)const button = screen.getByRole('button')@@ -104,7 +105,7 @@ describe('SecretKeyButton', () => {it('should pass appId to modal', async () => {const user = userEvent.setup()- render(<SecretKeyButton appId="app-123" />)+ render(<SecretKeyButton appId="app-123" canManage />)const button = screen.getByRole('button')await act(async () => {@@ -116,7 +117,7 @@ describe('SecretKeyButton', () => {it('should handle undefined appId', async () => {const user = userEvent.setup()- render(<SecretKeyButton />)+ render(<SecretKeyButton canManage />)const button = screen.getByRole('button')await act(async () => {@@ -126,6 +127,38 @@ describe('SecretKeyButton', () => {expect(screen.getByText('Modal for no-app'))!.toBeInTheDocument()})+ it('should pass canManage to modal', async () => {+ const user = userEvent.setup()+ render(<SecretKeyButton appId="app-123" canManage />)++ const button = screen.getByRole('button')+ await act(async () => {+ await user.click(button)+ })++ expect(screen.getByTestId('modal-can-manage')).toHaveTextContent('true')+ })++ it('should disable the button and keep modal closed when canManage is false', async () => {+ const user = userEvent.setup()+ render(<SecretKeyButton appId="app-123" canManage={false} />)++ const button = screen.getByRole('button')+ expect(button).toBeDisabled()++ await act(async () => {+ await user.click(button)+ })++ expect(screen.queryByTestId('secret-key-modal')).not.toBeInTheDocument()+ })++ it('should disable the button by default when canManage is omitted', () => {+ render(<SecretKeyButton appId="app-123" />)++ expect(screen.getByRole('button')).toBeDisabled()+ })+it('should apply custom textCls', () => {render(<SecretKeyButton textCls="custom-text-class" />)const text = screen.getByText('appApi.apiKey')@@ -184,7 +217,7 @@ describe('SecretKeyButton', () => {describe('modal props', () => {it('should pass isShow prop to modal', async () => {const user = userEvent.setup()- render(<SecretKeyButton />)+ render(<SecretKeyButton canManage />)expect(screen.queryByTestId('secret-key-modal')).not.toBeInTheDocument()@@ -198,7 +231,7 @@ describe('SecretKeyButton', () => {it('should pass onClose callback to modal', async () => {const user = userEvent.setup()- render(<SecretKeyButton />)+ render(<SecretKeyButton canManage />)const button = screen.getByRole('button')await act(async () => {@@ -223,7 +256,7 @@ describe('SecretKeyButton', () => {it('should be keyboard accessible', async () => {const user = userEvent.setup()- render(<SecretKeyButton />)+ render(<SecretKeyButton canManage />)const button = screen.getByRole('button')button.focus()@@ -242,8 +275,8 @@ describe('SecretKeyButton', () => {const user = userEvent.setup()render(<>- <SecretKeyButton appId="app-1" />- <SecretKeyButton appId="app-2" />+ <SecretKeyButton appId="app-1" canManage />+ <SecretKeyButton appId="app-2" canManage /></>,)diff --git a/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsx b/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsxindex 00948180eb4..94c215103c6 100644--- a/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsx+++ b/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsx@@ -83,6 +83,7 @@ vi.mock('@/service/knowledge/use-dataset', () => ({describe('SecretKeyModal', () => {const defaultProps = {isShow: true,+ canManage: true,onClose: vi.fn(),}@@ -124,7 +125,7 @@ describe('SecretKeyModal', () => {it('should render the close icon', async () => {await renderModal(<SecretKeyModal {...defaultProps} />)- const closeIcon = document.body.querySelector('svg.cursor-pointer')+ const closeIcon = document.body.querySelector('.i-heroicons-x-mark-20-solid')expect(closeIcon).toBeInTheDocument()})})@@ -186,19 +187,26 @@ describe('SecretKeyModal', () => {expect(screen.getByText('appApi.never')).toBeInTheDocument()})- it('should render delete button for managers', async () => {+ it('should render delete button for permitted users', async () => {await renderModal(<SecretKeyModal {...defaultProps} appId="app-123" />)const buttons = screen.getAllByRole('button')expect(buttons.length).toBeGreaterThanOrEqual(2)- const deleteIcon = document.body.querySelector('svg[class*="size-4"]')+ const deleteIcon = document.body.querySelector('.i-ri-delete-bin-line')expect(deleteIcon).toBeInTheDocument()})- it('should not render delete button for non-managers', async () => {+ it('should render delete button when canManage is true even if the workspace role is not manager', async () => {mockIsCurrentWorkspaceManager.mockReturnValue(false)await renderModal(<SecretKeyModal {...defaultProps} appId="app-123" />)- const actionButtons = screen.getAllByRole('button')- expect(actionButtons.length).toBeGreaterThan(0)+ const deleteIcon = document.body.querySelector('.i-ri-delete-bin-line')+ expect(deleteIcon).toBeInTheDocument()+ })++ it('should not render delete button when canManage is false even if the workspace role is manager', async () => {+ mockIsCurrentWorkspaceManager.mockReturnValue(true)+ await renderModal(<SecretKeyModal {...defaultProps} appId="app-123" canManage={false} />)+ const deleteIcon = document.body.querySelector('.i-ri-delete-bin-line')+ expect(deleteIcon).not.toBeInTheDocument()})it('should render table headers', async () => {@@ -230,7 +238,7 @@ describe('SecretKeyModal', () => {const onClose = vi.fn()await renderModal(<SecretKeyModal {...defaultProps} onClose={onClose} />)- const closeIcon = document.body.querySelector('svg.cursor-pointer')+ const closeIcon = document.body.querySelector('.i-heroicons-x-mark-20-solid')expect(closeIcon).toBeInTheDocument()await act(async () => {@@ -356,10 +364,18 @@ describe('SecretKeyModal', () => {expect(createButton).toBeDisabled()})- it('should disable create button when not editor', async () => {+ it('should keep create button enabled when canManage is true even if the workspace role is not editor', async () => {mockIsCurrentWorkspaceEditor.mockReturnValue(false)await renderModal(<SecretKeyModal {...defaultProps} />)+ const createButton = screen.getByText('appApi.apiKeyModal.createNewSecretKey').closest('button')+ expect(createButton).not.toBeDisabled()+ })++ it('should disable create button when canManage is false even if the workspace role is editor', async () => {+ mockIsCurrentWorkspaceEditor.mockReturnValue(true)+ await renderModal(<SecretKeyModal {...defaultProps} canManage={false} />)+const createButton = screen.getByText('appApi.apiKeyModal.createNewSecretKey').closest('button')expect(createButton).toBeDisabled()})@@ -374,7 +390,7 @@ describe('SecretKeyModal', () => {mockAppApiKeysData.mockReturnValue({ data: apiKeys })})- it('should render delete button for managers', async () => {+ it('should render delete button for permitted users', async () => {await renderModal(<SecretKeyModal {...defaultProps} appId="app-123" />)const actionButtons = screen.getAllByRole('button')@@ -394,10 +410,10 @@ describe('SecretKeyModal', () => {expect(actionContainers.length).toBeGreaterThan(0)})- it('should have delete button visible for managers', async () => {+ it('should have delete button visible for permitted users', async () => {await renderModal(<SecretKeyModal {...defaultProps} appId="app-123" />)- const deleteIcon = document.body.querySelector('svg[class*="size-4"]')+ const deleteIcon = document.body.querySelector('.i-ri-delete-bin-line')const deleteButton = deleteIcon?.closest('button')expect(deleteButton).toBeInTheDocument()})diff --git a/web/app/components/develop/secret-key/secret-key-button.tsx b/web/app/components/develop/secret-key/secret-key-button.tsxindex edeaf531be3..567abb863e0 100644--- a/web/app/components/develop/secret-key/secret-key-button.tsx+++ b/web/app/components/develop/secret-key/secret-key-button.tsx@@ -1,6 +1,5 @@'use client'import { Button } from '@langgenius/dify-ui/button'-import { RiKey2Line } from '@remixicon/react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import SecretKeyModal from '@/app/components/develop/secret-key/secret-key-modal'@@ -9,25 +8,28 @@ type ISecretKeyButtonProps = {className?: stringappId?: stringtextCls?: string+ canManage?: boolean}-const SecretKeyButton = ({ className, appId, textCls }: ISecretKeyButtonProps) => {- const [isVisible, setVisible] = useState(false)+const SecretKeyButton = ({ className, appId, textCls, canManage = false }: ISecretKeyButtonProps) => {+ const [isVisible, setIsVisible] = useState(false)const { t } = useTranslation()+return (<><ButtonclassName={`px-3 ${className}`}- onClick={() => setVisible(true)}+ onClick={() => setIsVisible(true)}size="small"variant="ghost"+ disabled={!canManage}><div className="flex size-3.5 items-center justify-center">- <RiKey2Line className="size-3.5 text-text-tertiary" />+ <span className="i-ri-key-2-line size-3.5 text-text-tertiary" /></div><div className={`px-[3px] system-xs-medium text-text-tertiary ${textCls}`}>{t('apiKey', { ns: 'appApi' })}</div></Button>- <SecretKeyModal isShow={isVisible} onClose={() => setVisible(false)} appId={appId} />+ <SecretKeyModal isShow={isVisible} onClose={() => setIsVisible(false)} appId={appId} canManage={canManage} /></>)}diff --git a/web/app/components/develop/secret-key/secret-key-modal.tsx b/web/app/components/develop/secret-key/secret-key-modal.tsxindex 7d949d7864e..13c16582e61 100644--- a/web/app/components/develop/secret-key/secret-key-modal.tsx+++ b/web/app/components/develop/secret-key/secret-key-modal.tsx@@ -1,6 +1,5 @@'use client'import type { CreateApiKeyResponse } from '@/models/app'-import { PlusIcon, XMarkIcon } from '@heroicons/react/20/solid'import {AlertDialog,AlertDialogActions,@@ -13,7 +12,6 @@ import {import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'-import { RiDeleteBinLine } from '@remixicon/react'import {useState,} from 'react'@@ -39,19 +37,21 @@ import s from './style.module.css'type ISecretKeyModalProps = {isShow: booleanappId?: string+ canManage: booleanonClose: () => void}const SecretKeyModal = ({isShow = false,appId,+ canManage,onClose,}: ISecretKeyModalProps) => {const { t } = useTranslation()const { formatTime } = useTimestamp()- const { currentWorkspace, isCurrentWorkspaceManager, isCurrentWorkspaceEditor } = useAppContext()+ const { currentWorkspace } = useAppContext()const [showConfirmDelete, setShowConfirmDelete] = useState(false)- const [isVisible, setVisible] = useState(false)+ const [isVisible, setIsVisible] = useState(false)const [newKey, setNewKey] = useState<CreateApiKeyResponse | undefined>(undefined)const invalidateAppApiKeys = useInvalidateAppApiKeys()const invalidateDatasetApiKeys = useInvalidateDatasetApiKeys()@@ -64,6 +64,8 @@ const SecretKeyModal = ({const onDel = async () => {setShowConfirmDelete(false)+ if (!canManage)+ returnif (!delKeyID)return@@ -79,12 +81,15 @@ const SecretKeyModal = ({}const onCreate = async () => {+ if (!currentWorkspace || !canManage)+ return+const params = appId? { url: `/apps/${appId}/api-keys`, body: {} }: { url: '/datasets/api-keys', body: {} }const createApikey = appId ? createAppApikey : createDatasetApikeyconst res = await createApikey(params)- setVisible(true)+ setIsVisible(true)setNewKey(res)if (appId)invalidateAppApiKeys(appId)@@ -105,7 +110,7 @@ const SecretKeyModal = ({}const handleClose = () => {- setVisible(false)+ setIsVisible(false)onClose()}@@ -124,7 +129,7 @@ const SecretKeyModal = ({</DialogTitle><div className="-mt-6 -mr-2 mb-4 flex justify-end">- <XMarkIcon className="size-6 cursor-pointer text-text-tertiary" onClick={handleClose} />+ <span className="i-heroicons-x-mark-20-solid size-6 cursor-pointer text-text-tertiary" onClick={handleClose} /></div><p className="mt-1 shrink-0 text-[13px] leading-5 font-normal text-text-tertiary">{t('apiKeyModal.apiSecretKeyTips', { ns: 'appApi' })}</p>{isApiKeysLoading && <div className="mt-4"><Loading /></div>}@@ -145,14 +150,14 @@ const SecretKeyModal = ({<div className="w-[200px] shrink-0 truncate px-3">{api.last_used_at ? formatTime(Number(api.last_used_at), t('dateTimeFormat', { ns: 'appLog' }) as string) : t('never', { ns: 'appApi' })}</div><div className="flex grow space-x-2 px-3"><CopyFeedback content={api.token} />- {isCurrentWorkspaceManager && (+ {canManage && (<ActionButtononClick={() => {setDelKeyId(api.id)setShowConfirmDelete(true)}}>- <RiDeleteBinLine className="size-4" />+ <span className="i-ri-delete-bin-line size-4" /></ActionButton>)}</div>@@ -163,8 +168,8 @@ const SecretKeyModal = ({)}<div className="flex">- <Button className={`mt-4 flex shrink-0 ${s.autoWidth}`} onClick={onCreate} disabled={!currentWorkspace || !isCurrentWorkspaceEditor}>- <PlusIcon className="mr-1 flex size-4 shrink-0" />+ <Button className={`mt-4 flex shrink-0 ${s.autoWidth}`} onClick={onCreate} disabled={!currentWorkspace || !canManage}>+ <span className="mr-1 i-heroicons-plus-20-solid flex size-4 shrink-0" /><div className="text-xs font-medium text-text-secondary">{t('apiKeyModal.createNewSecretKey', { ns: 'appApi' })}</div></Button></div>@@ -194,7 +199,7 @@ const SecretKeyModal = ({</DialogContent></Dialog>{isShow && (- <SecretKeyGenerateModal className="shrink-0" isShow={isVisible} onClose={() => setVisible(false)} newKey={newKey} />+ <SecretKeyGenerateModal className="shrink-0" isShow={isVisible} onClose={() => setIsVisible(false)} newKey={newKey} />)}</>)diff --git a/web/app/components/explore/app-list/__tests__/index.spec.tsx b/web/app/components/explore/app-list/__tests__/index.spec.tsxindex af87312825c..f884e4d2994 100644--- a/web/app/components/explore/app-list/__tests__/index.spec.tsx+++ b/web/app/components/explore/app-list/__tests__/index.spec.tsx@@ -9,12 +9,19 @@ import { createStore, Provider as JotaiProvider } from 'jotai'import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'import { useAppContext } from '@/context/app-context'import { fetchAppDetail, fetchAppList, fetchBanners } from '@/service/explore'-import { useMembers } from '@/service/use-common'import { renderWithNuqs } from '@/test/nuqs-testing'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import { LEARN_DIFY_HIDDEN_STORAGE_KEY } from '../../learn-dify/atoms'import AppList from '../index'+type MockAppContext = {+ userProfile: { id: string }+ workspacePermissionKeys: string[]+}++const mockUseAppContext = vi.hoisted(() => vi.fn<() => MockAppContext>())+let mockExploreData: { categories: string[], allList: App[] } | undefined = { categories: [], allList: [] }let mockLearnDifyApps: App[] = []let mockLearnDifyLoading = false@@ -100,11 +107,8 @@ vi.mock('@/service/client', () => ({}))vi.mock('@/context/app-context', () => ({- useAppContext: vi.fn(),-}))--vi.mock('@/service/use-common', () => ({- useMembers: vi.fn(),+ useAppContext: mockUseAppContext,+ useSelector: <T,>(selector: (state: MockAppContext) => T): T => selector(mockUseAppContext()),}))vi.mock('@/hooks/use-import-dsl', () => ({@@ -239,6 +243,7 @@ const createWorkspaceApp = (overrides: Partial<WorkspaceApp> = {}): WorkspaceAppapi_base_url: overrides.api_base_url ?? '',tags: overrides.tags ?? [],access_mode: overrides.access_mode,+ permission_keys: overrides.permission_keys,} as WorkspaceApp)const createBanner = (overrides: Partial<BannerType> = {}): BannerType => ({@@ -255,15 +260,10 @@ const createBanner = (overrides: Partial<BannerType> = {}): BannerType => ({created_at: overrides.created_at ?? '2024-01-01T00:00:00Z',})-const mockMemberRole = (hasEditPermission: boolean) => {+const mockAppCreatePermission = (hasEditPermission: boolean) => {;(useAppContext as Mock).mockReturnValue({userProfile: { id: 'user-1' },- isCurrentWorkspaceEditor: hasEditPermission,- })- ;(useMembers as Mock).mockReturnValue({- data: {- accounts: [{ id: 'user-1', role: hasEditPermission ? 'admin' : 'normal' }],- },+ workspacePermissionKeys: hasEditPermission ? ['app.create_and_management'] : [],})}@@ -283,7 +283,7 @@ const renderAppList = (options: RenderOptions = {},) => {mockConfig.isCloudEdition = options.isCloudEdition ?? false- mockMemberRole(hasEditPermission)+ mockAppCreatePermission(hasEditPermission)const { wrapper: SystemFeaturesWrapper, queryClient } = createSystemFeaturesWrapper({systemFeatures: { enable_explore_banner: options.enableExploreBanner ?? false },})@@ -436,7 +436,7 @@ describe('AppList', () => {allList: [createApp()],}mockWorkspaceApps = [- createWorkspaceApp({ id: 'app-1', name: 'Email Reply', author_name: 'Evan' }),+ createWorkspaceApp({ id: 'app-1', name: 'Email Reply', author_name: 'Evan', permission_keys: [AppACLPermission.Monitor] }),createWorkspaceApp({ id: 'app-2', name: 'Feature Copilot', author_name: 'Maggie' }),createWorkspaceApp({ id: 'app-3', name: 'Book Translation', author_name: 'Alex' }),createWorkspaceApp({ id: 'app-4', name: 'Logo Design', author_name: 'Taylor' }),diff --git a/web/app/components/explore/app-list/index.tsx b/web/app/components/explore/app-list/index.tsxindex 8bc348935d8..00431c36486 100644--- a/web/app/components/explore/app-list/index.tsx+++ b/web/app/components/explore/app-list/index.tsx@@ -25,8 +25,8 @@ import { DSLImportMode } from '@/models/app'import dynamic from '@/next/dynamic'import { consoleQuery } from '@/service/client'import { fetchAppDetail, fetchAppList, fetchBanners } from '@/service/explore'-import { useMembers } from '@/service/use-common'import { trackCreateApp } from '@/utils/create-app-tracking'+import { hasPermission } from '@/utils/permission'import { ExploreAppListHeader } from './explore-app-list-header'import { ExploreRecommendations } from './explore-recommendations'import { ExploreHomeSkeleton } from './loading-skeletons'@@ -100,7 +100,7 @@ function getDisabledBannersQueryOptions() {const Apps = ({ onSuccess }: { onSuccess?: () => void }) => {const { t } = useTranslation()const locale = useLocale()- const { userProfile } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions(),)@@ -120,12 +120,8 @@ const Apps = ({ onSuccess }: { onSuccess?: () => void }) => {isAppListError: exploreAppListQuery.isError || (!exploreAppListQuery.isPending && !exploreAppListQuery.data),}),})- const { data: membersData } = useMembers()const allCategoriesEn = t('apps.allCategories', { ns: 'explore', lng: 'en' })- const userAccount = membersData?.accounts?.find(- account => account.id === userProfile.id,- )- const hasEditPermission = !!userAccount && userAccount.role !== 'normal'+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const [keywords, setKeywords] = useState('')const [searchKeywords, setSearchKeywords] = useState('')@@ -288,7 +284,7 @@ const Apps = ({ onSuccess }: { onSuccess?: () => void }) => {<Banner banners={homeQueries.banners} />)}<ExploreRecommendations- canCreate={hasEditPermission}+ canCreate={canCreateApp}continueWorkApps={homeQueries.continueWorkApps}onCreate={handleCreateFromLearnDify}onTry={handleTryApp}@@ -314,7 +310,7 @@ const Apps = ({ onSuccess }: { onSuccess?: () => void }) => {<AppCardkey={app.app_id}app={app}- canCreate={hasEditPermission}+ canCreate={canCreateApp}onCreate={() => handleCreateFromAppList(app)}onTry={handleTryApp}/>diff --git a/web/app/components/explore/continue-work/item.tsx b/web/app/components/explore/continue-work/item.tsxindex dc722c1669a..89f09d57a8f 100644--- a/web/app/components/explore/continue-work/item.tsx+++ b/web/app/components/explore/continue-work/item.tsx@@ -5,7 +5,7 @@ import * as React from 'react'import { useTranslation } from 'react-i18next'import { AppTypeIcon } from '@/app/components/app/type-selector'import AppIcon from '@/app/components/base/app-icon'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextSelector } from '@/context/app-context'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'import Link from '@/next/link'import { getRedirectionPath } from '@/utils/app-redirection'@@ -19,9 +19,14 @@ const ContinueWorkItem = ({}: ContinueWorkItemProps) => {const { t } = useTranslation()const { formatTimeFromNow } = useFormatTimeFromNow()- const { isCurrentWorkspaceEditor } = useAppContext()+ const currentUserId = useAppContextSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)const updatedAt = (app.updated_at || app.created_at) * 1000- const href = getRedirectionPath(Boolean(isCurrentWorkspaceEditor), app)+ const href = getRedirectionPath(app, {+ currentUserId,+ resourceMaintainer: app.maintainer,+ workspacePermissionKeys,+ })return (<Link href={href} className="flex min-w-0 items-center gap-3 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg px-4 pt-4 pb-4 shadow-xs shadow-shadow-shadow-3">diff --git a/web/app/components/explore/installed-app/__tests__/index.spec.tsx b/web/app/components/explore/installed-app/__tests__/index.spec.tsxindex 40709b418b4..36268eced8b 100644--- a/web/app/components/explore/installed-app/__tests__/index.spec.tsx+++ b/web/app/components/explore/installed-app/__tests__/index.spec.tsx@@ -4,7 +4,7 @@ import { render, screen, waitFor } from '@testing-library/react'import { useWebAppStore } from '@/context/web-app-context'import { AccessMode } from '@/models/access-control'-import { useGetUserCanAccessApp } from '@/service/access-control'+import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'import { useGetInstalledAppAccessModeByAppId, useGetInstalledAppMeta, useGetInstalledAppParams, useGetInstalledApps } from '@/service/use-explore'import { AppModeEnum } from '@/types/app'import InstalledApp from '../index'@@ -12,7 +12,7 @@ import InstalledApp from '../index'vi.mock('@/context/web-app-context', () => ({useWebAppStore: vi.fn(),}))-vi.mock('@/service/access-control', () => ({+vi.mock('@/service/access-control/use-app-access-control', () => ({useGetUserCanAccessApp: vi.fn(),}))vi.mock('@/service/use-explore', () => ({diff --git a/web/app/components/explore/installed-app/index.tsx b/web/app/components/explore/installed-app/index.tsxindex ff8c5127df1..d28678fd655 100644--- a/web/app/components/explore/installed-app/index.tsx+++ b/web/app/components/explore/installed-app/index.tsx@@ -7,7 +7,7 @@ import Loading from '@/app/components/base/loading'import TextGenerationApp from '@/app/components/share/text-generation'import { useWebAppStore } from '@/context/web-app-context'import dynamic from '@/next/dynamic'-import { useGetUserCanAccessApp } from '@/service/access-control'+import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'import { useGetInstalledAppAccessModeByAppId, useGetInstalledAppMeta, useGetInstalledAppParams, useGetInstalledApps } from '@/service/use-explore'import { AppModeEnum } from '@/types/app'import AppUnavailable from '../../base/app-unavailable'diff --git a/web/app/components/goto-anything/__tests__/index.spec.tsx b/web/app/components/goto-anything/__tests__/index.spec.tsxindex fe577072c59..1eeed9a6a41 100644--- a/web/app/components/goto-anything/__tests__/index.spec.tsx+++ b/web/app/components/goto-anything/__tests__/index.spec.tsx@@ -71,6 +71,13 @@ vi.mock('@/context/i18n', () => ({useGetLanguage: () => 'en_US',}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission', () => ({+ default: () => ({+ canInstallPlugin: true,+ currentDifyVersion: '1.0.0',+ }),+}))+const contextValue = { isWorkflowPage: false, isRagPipelinePage: false }vi.mock('../context', () => ({useGotoAnythingContext: () => contextValue,diff --git a/web/app/components/goto-anything/actions/__tests__/app.spec.ts b/web/app/components/goto-anything/actions/__tests__/app.spec.tsindex 55939b2da88..b8d58512efe 100644--- a/web/app/components/goto-anything/actions/__tests__/app.spec.ts+++ b/web/app/components/goto-anything/actions/__tests__/app.spec.ts@@ -6,7 +6,7 @@ vi.mock('@/service/apps', () => ({}))vi.mock('@/utils/app-redirection', () => ({- getRedirectionPath: vi.fn((_isAdmin: boolean, app: { id: string }) => `/app/${app.id}`),+ getRedirectionPath: vi.fn((app: { id: string }) => `/app/${app.id}`),}))vi.mock('../../../app/type-selector', () => ({diff --git a/web/app/components/goto-anything/actions/app.tsx b/web/app/components/goto-anything/actions/app.tsxindex 4524ba741fa..7b156fba3e6 100644--- a/web/app/components/goto-anything/actions/app.tsx+++ b/web/app/components/goto-anything/actions/app.tsx@@ -52,10 +52,7 @@ const parser = (apps: App[]): AppSearchResult[] => {title: app.name,description: app.description,type: 'app' as const,- path: getRedirectionPath(true, {- id: app.id,- mode: app.mode,- }),+ path: getRedirectionPath(app),icon: appIcon(app),data: app,}))@@ -70,7 +67,7 @@ const parserWithSections = (apps: App[]): SearchResult[] => {title: app.name,description: app.description,type: 'app' as const,- path: getRedirectionPath(true, { id: app.id, mode: app.mode }),+ path: getRedirectionPath(app),icon: appIcon(app),data: app,})diff --git a/web/app/components/goto-anything/index.tsx b/web/app/components/goto-anything/index.tsxindex f56ada5881d..af5b8bd7bde 100644--- a/web/app/components/goto-anything/index.tsx+++ b/web/app/components/goto-anything/index.tsx@@ -5,6 +5,8 @@ import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { Command } from 'cmdk'import { useCallback, useEffect, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'+import { PluginInstallPermissionProvider } from '../plugins/install-plugin/components/plugin-install-permission-provider'+import useWorkspacePluginInstallPermission from '../plugins/install-plugin/hooks/use-workspace-plugin-install-permission'import InstallFromMarketplace from '../plugins/install-plugin/install-from-marketplace'import { slashCommandRegistry } from './actions/commands/registry'import { SlashCommandProvider } from './actions/commands/slash-provider'@@ -25,6 +27,7 @@ const GotoAnythingDialog: FC<Props> = ({}) => {const { t } = useTranslation()const { isWorkflowPage, isRagPipelinePage } = useGotoAnythingContext()+ const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()const prevShowRef = useRef(false)// Search state management (called first so setSearchQuery is available)@@ -216,13 +219,18 @@ const GotoAnythingDialog: FC<Props> = ({</DialogContent></Dialog>- {activePlugin && (- <InstallFromMarketplace- manifest={activePlugin}- uniqueIdentifier={activePlugin.latest_package_identifier}- onClose={() => setActivePlugin(undefined)}- onSuccess={() => setActivePlugin(undefined)}- />+ {activePlugin && canInstallPlugin && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ currentDifyVersion={currentDifyVersion}+ >+ <InstallFromMarketplace+ manifest={activePlugin}+ uniqueIdentifier={activePlugin.latest_package_identifier}+ onClose={() => setActivePlugin(undefined)}+ onSuccess={() => setActivePlugin(undefined)}+ />+ </PluginInstallPermissionProvider>)}</>)diff --git a/web/app/components/header/__tests__/index.spec.tsx b/web/app/components/header/__tests__/index.spec.tsxindex 4368ac2fc4e..73530684b39 100644--- a/web/app/components/header/__tests__/index.spec.tsx+++ b/web/app/components/header/__tests__/index.spec.tsx@@ -56,6 +56,7 @@ vi.mock('@/next/link', () => ({let mockIsWorkspaceEditor = falselet mockIsDatasetOperator = false+let mockWorkspacePermissionKeys: string[] = []let mockMedia = 'desktop'let mockEnableBilling = falselet mockPlanType = 'sandbox'@@ -70,6 +71,9 @@ vi.mock('@/context/app-context', () => ({isCurrentWorkspaceEditor: mockIsWorkspaceEditor,isCurrentWorkspaceDatasetOperator: mockIsDatasetOperator,}),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),}))vi.mock('@/hooks/use-breakpoints', () => ({@@ -107,6 +111,7 @@ describe('Header', () => {vi.clearAllMocks()mockIsWorkspaceEditor = falsemockIsDatasetOperator = false+ mockWorkspacePermissionKeys = ['app_library.access', 'tool.manage']mockMedia = 'desktop'mockEnableBilling = falsemockPlanType = 'sandbox'@@ -122,6 +127,7 @@ describe('Header', () => {expect(screen.queryByRole('heading', { level: 1 })).not.toBeInTheDocument()expect(screen.queryByRole('img', { name: /dify logo/i })).not.toBeInTheDocument()expect(screen.getByTestId('workplace-selector')).toBeInTheDocument()+ expect(screen.getByTestId('explore-nav')).toBeInTheDocument()expect(screen.getByTestId('app-nav')).toBeInTheDocument()expect(screen.getByTestId('account-dropdown')).toBeInTheDocument()})@@ -138,8 +144,8 @@ describe('Header', () => {expect(screen.getByTestId('plan-badge')).toBeInTheDocument()})- it('should hide explore nav when user is dataset operator', () => {- mockIsDatasetOperator = true+ it('should hide explore nav when workspace lacks app library access', () => {+ mockWorkspacePermissionKeys = ['tool.manage']renderHeader()expect(screen.queryByTestId('explore-nav')).not.toBeInTheDocument()@@ -201,38 +207,43 @@ describe('Header', () => {expect(screen.getByRole('link', { name: 'Dify' })).toHaveAttribute('href', '/apps')})- it('should show dataset nav for editor who is not dataset operator', () => {- mockIsWorkspaceEditor = true- mockIsDatasetOperator = false+ it('should show app and dataset nav without page-level permissions', () => {+ mockWorkspacePermissionKeys = []renderHeader()expect(screen.getByTestId('dataset-nav')).toBeInTheDocument()- expect(screen.getByTestId('explore-nav')).toBeInTheDocument()expect(screen.getByTestId('app-nav')).toBeInTheDocument()})- it('should hide dataset nav when neither editor nor dataset operator', () => {- mockIsWorkspaceEditor = false- mockIsDatasetOperator = false+ it('should show dataset nav when workspace only has dataset mutation permissions', () => {+ mockWorkspacePermissionKeys = ['dataset.create_and_management', 'dataset.tag.manage', 'dataset.external.connect']renderHeader()- expect(screen.queryByTestId('dataset-nav')).not.toBeInTheDocument()+ expect(screen.getByTestId('dataset-nav')).toBeInTheDocument()})- it('should render mobile layout with dataset operator nav restrictions', () => {+ it('should render mobile layout with page permission nav restrictions', () => {mockMedia = 'mobile'- mockIsDatasetOperator = true+ mockWorkspacePermissionKeys = []renderHeader()expect(screen.queryByTestId('explore-nav')).not.toBeInTheDocument()- expect(screen.queryByTestId('app-nav')).not.toBeInTheDocument()expect(screen.queryByTestId('tools-nav')).not.toBeInTheDocument()+ expect(screen.getByTestId('app-nav')).toBeInTheDocument()expect(screen.getByTestId('dataset-nav')).toBeInTheDocument()})+ it('should show tools nav when workspace has MCP management access', () => {+ mockWorkspacePermissionKeys = ['mcp.manage']++ renderHeader()++ expect(screen.getByTestId('tools-nav')).toBeInTheDocument()+ })+it('should render mobile layout with billing enabled', () => {mockMedia = 'mobile'mockEnableBilling = truediff --git a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx b/web/app/components/header/account-dropdown/__tests__/index.spec.tsxindex e459ca2317a..81b08046a94 100644--- a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx+++ b/web/app/components/header/account-dropdown/__tests__/index.spec.tsx@@ -147,6 +147,7 @@ const baseAppContextValue: AppContextValue = {useSelector: vi.fn(),isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],}describe('AccountDropdown', () => {diff --git a/web/app/components/header/account-setting/__tests__/constants.spec.ts b/web/app/components/header/account-setting/__tests__/constants.spec.tsindex e99a278f307..04b9db50741 100644--- a/web/app/components/header/account-setting/__tests__/constants.spec.ts+++ b/web/app/components/header/account-setting/__tests__/constants.spec.ts@@ -20,6 +20,8 @@ describe('AccountSetting Constants', () => {it('should have correct ACCOUNT_SETTING_TAB values', () => {expect(ACCOUNT_SETTING_TAB.PROVIDER).toBe('provider')expect(ACCOUNT_SETTING_TAB.MEMBERS).toBe('members')+ expect(ACCOUNT_SETTING_TAB.PERMISSIONS).toBe('permissions')+ expect(ACCOUNT_SETTING_TAB.ACCESS_RULES).toBe('access-rules')expect(ACCOUNT_SETTING_TAB.BILLING).toBe('billing')expect(ACCOUNT_SETTING_TAB.DATA_SOURCE).toBe('data-source')expect(ACCOUNT_SETTING_TAB.API_BASED_EXTENSION).toBe('custom-endpoint')@@ -34,6 +36,8 @@ describe('AccountSetting Constants', () => {it('isValidAccountSettingTab should return true for valid tabs', () => {expect(isValidAccountSettingTab('provider')).toBe(true)expect(isValidAccountSettingTab('members')).toBe(true)+ expect(isValidAccountSettingTab('permissions')).toBe(true)+ expect(isValidAccountSettingTab('access-rules')).toBe(true)expect(isValidAccountSettingTab('billing')).toBe(true)expect(isValidAccountSettingTab('data-source')).toBe(true)expect(isValidAccountSettingTab('custom-endpoint')).toBe(true)@@ -48,6 +52,8 @@ describe('AccountSetting Constants', () => {})it('isValidSettingsTab should include integrations tabs', () => {+ expect(isValidSettingsTab('permissions')).toBe(true)+ expect(isValidSettingsTab('access-rules')).toBe(true)expect(isValidSettingsTab('billing')).toBe(true)expect(isValidSettingsTab('language')).toBe(true)expect(isValidSettingsTab('provider')).toBe(true)diff --git a/web/app/components/header/account-setting/__tests__/index.spec.tsx b/web/app/components/header/account-setting/__tests__/index.spec.tsxindex d273b240b12..d59199769ed 100644--- a/web/app/components/header/account-setting/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/__tests__/index.spec.tsx@@ -10,6 +10,9 @@ import { ACCOUNT_SETTING_TAB } from '../constants'import AccountSetting from '../index'const mockResetModelProviderListExpanded = vi.fn()+const mockAppContextState = vi.hoisted(() => ({+ current: null as unknown,+}))vi.mock('@/context/provider-context', async (importOriginal) => {const actual = await importOriginal<typeof import('@/context/provider-context')>()@@ -24,6 +27,7 @@ vi.mock('@/context/app-context', async (importOriginal) => {return {...actual,useAppContext: vi.fn(),+ useSelector: vi.fn((selector: (state: unknown) => unknown) => selector(mockAppContextState.current)),}})@@ -111,6 +115,16 @@ vi.mock('@/app/components/header/account-setting/data-source-page-new', () => ({default: () => <div data-testid="data-source-page" />,}))+vi.mock('@/app/components/header/account-setting/permissions-page', () => ({+ __esModule: true,+ default: () => <div data-testid="permissions-page" />,+}))++vi.mock('@/app/components/header/account-setting/access-rules-page', () => ({+ __esModule: true,+ default: () => <div data-testid="access-rules-page" />,+}))+const baseAppContextValue: AppContextValue = {userProfile: {id: '1',@@ -150,6 +164,16 @@ const baseAppContextValue: AppContextValue = {useSelector: vi.fn(),isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [+ 'workspace.member.manage',+ 'workspace.role.manage',+ 'data_source.manage',+ 'api_extension.manage',+ 'customization.manage',+ 'billing.view',+ 'billing.manage',+ 'billing.subscription.manage',+ ],}describe('AccountSetting', () => {@@ -199,6 +223,7 @@ describe('AccountSetting', () => {enableReplaceWebAppLogo: true,})vi.mocked(useAppContext).mockReturnValue(baseAppContextValue)+ mockAppContextState.current = baseAppContextValuevi.mocked(useBreakpoints).mockReturnValue(MediaType.pc)})@@ -209,9 +234,11 @@ describe('AccountSetting', () => {// Assertexpect(screen.getByText('common.settings.settings'))!.toBeInTheDocument()- expect(screen.getByText('common.settings.workspace'))!.toBeInTheDocument()+ expect(screen.getAllByText('common.settings.workspace').length).toBeGreaterThan(0)expect(screen.queryByText('common.settings.provider'))!.not.toBeInTheDocument()expect(screen.getAllByText('common.settings.members').length).toBeGreaterThan(0)+ expect(screen.getByRole('button', { name: 'common.settings.rolesAndPermissions' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.settings.resourceAccess' })).toBeInTheDocument()expect(screen.getByText('common.settings.billing'))!.toBeInTheDocument()expect(screen.queryByText('common.settings.dataSource'))!.not.toBeInTheDocument()expect(screen.queryByText('common.settings.customEndpoint'))!.not.toBeInTheDocument()@@ -301,53 +328,82 @@ describe('AccountSetting', () => {expect(screen.queryByText('common.settings.provider')).not.toBeInTheDocument()})- it('should filter items for dataset operator', () => {+ it('should not hide workspace menu items solely for dataset operators', () => {// Arrange- vi.mocked(useAppContext).mockReturnValue({+ const datasetOperatorContext = {...baseAppContextValue,isCurrentWorkspaceDatasetOperator: true,- })+ }+ vi.mocked(useAppContext).mockReturnValue(datasetOperatorContext)+ mockAppContextState.current = datasetOperatorContext// ActrenderAccountSetting()// Assert+ expect(screen.getByRole('button', { name: 'common.settings.members' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.settings.rolesAndPermissions' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.settings.resourceAccess' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.settings.billing' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'custom.custom' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.settings.preferences' })).toBeInTheDocument()+ })++ it('should keep moved integrations hidden when api extension permission is missing', () => {+ // Arrange+ const contextWithoutApiExtensionPermission = {+ ...baseAppContextValue,+ workspacePermissionKeys: baseAppContextValue.workspacePermissionKeys.filter(key => key !== 'api_extension.manage'),+ }+ vi.mocked(useAppContext).mockReturnValue(contextWithoutApiExtensionPermission)+ mockAppContextState.current = contextWithoutApiExtensionPermission++ // Act+ renderAccountSetting()+// Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert- // Assert+ expect(screen.queryByText('common.settings.provider')).not.toBeInTheDocument()+ expect(screen.queryByText('common.settings.dataSource')).not.toBeInTheDocument()+ expect(screen.queryByText('common.settings.customEndpoint')).not.toBeInTheDocument()+ })++ it('should show custom tab when customization permission is missing', () => {+ // Arrange+ const contextWithoutCustomizationPermission = {+ ...baseAppContextValue,+ workspacePermissionKeys: baseAppContextValue.workspacePermissionKeys.filter(key => key !== 'customization.manage'),+ }+ vi.mocked(useAppContext).mockReturnValue(contextWithoutCustomizationPermission)+ mockAppContextState.current = contextWithoutCustomizationPermission++ // Act+ renderAccountSetting()+// Assertexpect(screen.queryByText('common.settings.provider')).not.toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'common.settings.members' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.settings.members' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'custom.custom' })).toBeInTheDocument()expect(screen.getByText('common.settings.preferences'))!.toBeInTheDocument()})+ it('should hide role and resource access entries when role management permission is missing', () => {+ // Arrange+ const contextWithoutRoleManagePermission = {+ ...baseAppContextValue,+ workspacePermissionKeys: baseAppContextValue.workspacePermissionKeys.filter(key => key !== 'workspace.role.manage'),+ }+ vi.mocked(useAppContext).mockReturnValue(contextWithoutRoleManagePermission)+ mockAppContextState.current = contextWithoutRoleManagePermission++ // Act+ renderAccountSetting()++ // Assert+ expect(screen.getByRole('button', { name: 'common.settings.members' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'common.settings.rolesAndPermissions' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'common.settings.resourceAccess' })).not.toBeInTheDocument()+ })+it('should hide billing and custom tabs when disabled', () => {// Arrangevi.mocked(useProviderContext).mockReturnValue({@@ -394,6 +450,38 @@ describe('AccountSetting', () => {expect(screen.queryByText('common.settings.billing')).not.toBeInTheDocument()expect(screen.queryByText('custom.custom')).not.toBeInTheDocument()})++ it('should hide billing entry when billing view permission is missing', () => {+ // Arrange+ const contextWithoutBillingViewPermission = {+ ...baseAppContextValue,+ workspacePermissionKeys: baseAppContextValue.workspacePermissionKeys.filter(key => key !== 'billing.view'),+ }+ vi.mocked(useAppContext).mockReturnValue(contextWithoutBillingViewPermission)+ mockAppContextState.current = contextWithoutBillingViewPermission++ // Act+ renderAccountSetting()++ // Assert+ expect(screen.queryByRole('button', { name: 'common.settings.billing' })).not.toBeInTheDocument()+ })++ it('should not render billing page when active billing tab lacks billing view permission', () => {+ // Arrange+ const contextWithoutBillingViewPermission = {+ ...baseAppContextValue,+ workspacePermissionKeys: baseAppContextValue.workspacePermissionKeys.filter(key => key !== 'billing.view'),+ }+ vi.mocked(useAppContext).mockReturnValue(contextWithoutBillingViewPermission)+ mockAppContextState.current = contextWithoutBillingViewPermission++ // Act+ renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.BILLING })++ // Assert+ expect(screen.queryByTestId('billing-page')).not.toBeInTheDocument()+ })})describe('Tab Navigation', () => {@@ -428,6 +516,15 @@ describe('AccountSetting', () => {fireEvent.click(screen.getAllByText('common.settings.members')[0]!)expect(screen.getAllByText('common.settings.members').length).toBeGreaterThan(1)+ // Roles & Permissions+ fireEvent.click(screen.getByRole('button', { name: 'common.settings.rolesAndPermissions' }))+ expect(screen.getByTestId('permissions-page')).toBeInTheDocument()++ // Resource Access+ fireEvent.click(screen.getByRole('button', { name: 'common.settings.resourceAccess' }))+ expect(screen.getByText('common.settings.resourceAccessDescription')).toBeInTheDocument()+ expect(screen.getByTestId('access-rules-page')).toBeInTheDocument()+// LanguagefireEvent.click(screen.getByText('common.settings.preferences'))expect(screen.getByText('common.account.general')).toBeInTheDocument()diff --git a/web/app/components/header/account-setting/__tests__/permission-group-list.spec.tsx b/web/app/components/header/account-setting/__tests__/permission-group-list.spec.tsxnew file mode 100644index 00000000000..4f6908d6c57--- /dev/null+++ b/web/app/components/header/account-setting/__tests__/permission-group-list.spec.tsx@@ -0,0 +1,255 @@+import type { PermissionGroup } from '@/models/access-control'+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import PermissionGroupList from '../permission-group-list'++const createPermissionGroup = (overrides: Partial<PermissionGroup> = {}): PermissionGroup => ({+ group_key: 'app_management',+ group_name: 'App management',+ description: '',+ permissions: [+ {+ key: 'app.dsl.import',+ name: 'Import DSL',+ description: '',+ },+ {+ key: 'app.dsl.export',+ name: 'Export DSL',+ description: '',+ },+ ],+ ...overrides,+})++const permissionGroups = [+ createPermissionGroup(),+ createPermissionGroup({+ group_key: 'api_access',+ group_name: 'API access',+ permissions: [+ {+ key: 'app.api.view',+ name: 'View API',+ description: '',+ },+ ],+ }),+]++const getPermissionRow = (permissionName: string) => screen.getByText(permissionName).closest('div')!++const getPermissionCheckbox = (permissionName: string) => within(getPermissionRow(permissionName)).getByRole('checkbox')++describe('PermissionGroupList', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ // Rendering keeps the permission catalog visible as grouped collapsible rows.+ describe('Rendering', () => {+ it('should render the list as a flexible scroll region', () => {+ const { container } = render(+ <PermissionGroupList+ groups={permissionGroups}+ value={[]}+ onChange={vi.fn()}+ />,+ )++ expect(container.firstElementChild).toHaveClass('min-h-0', 'flex-1')+ expect(container.querySelector('.h-full.overflow-hidden')).toBeInTheDocument()+ })++ it('should render an empty state when there are no permission groups', () => {+ render(<PermissionGroupList groups={[]} value={[]} onChange={vi.fn()} />)++ expect(screen.getByText('permission.permissionList.noPermissionsFound')).toHaveClass('flex', 'h-full', 'items-center', 'justify-center')+ })++ it('should expand the first selected group by default', () => {+ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={['app.api.view']}+ onChange={vi.fn()}+ />,+ )++ expect(screen.getByRole('button', { name: /API access/ })).toHaveAttribute('aria-expanded', 'true')+ expect(getPermissionCheckbox('View API')).toHaveAttribute('aria-checked', 'true')+ expect(screen.queryByText('Import DSL')).not.toBeInTheDocument()+ })+ })++ // Group rows can be expanded and collapsed without changing selected values.+ describe('Group Interaction', () => {+ it('should toggle a group when clicking its header', async () => {+ const user = userEvent.setup()++ render(<PermissionGroupList groups={permissionGroups} value={[]} onChange={vi.fn()} />)++ const apiGroupButton = screen.getByRole('button', { name: /API access/ })+ expect(apiGroupButton).toHaveAttribute('aria-expanded', 'false')++ await user.click(apiGroupButton)++ expect(apiGroupButton).toHaveAttribute('aria-expanded', 'true')+ expect(getPermissionCheckbox('View API')).toBeInTheDocument()+ })++ it('should toggle a group when clicking its arrow control', async () => {+ const user = userEvent.setup()++ render(<PermissionGroupList groups={permissionGroups} value={[]} onChange={vi.fn()} />)++ const apiGroupButton = screen.getByRole('button', { name: /API access/ })+ expect(apiGroupButton).toHaveAttribute('aria-expanded', 'false')++ await user.click(screen.getByRole('button', { name: 'permission.permissionList.expandGroup' }))++ expect(apiGroupButton).toHaveAttribute('aria-expanded', 'true')+ })+ })++ // Checkbox interactions update only the selected permission key set.+ describe('Permission Interaction', () => {+ it('should add a permission when clicking an unchecked item row', async () => {+ const user = userEvent.setup()+ const handleChange = vi.fn()++ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={['app.dsl.export']}+ onChange={handleChange}+ />,+ )++ await user.click(screen.getByText('Import DSL'))++ expect(handleChange).toHaveBeenCalledTimes(1)+ expect(handleChange).toHaveBeenCalledWith(['app.dsl.export', 'app.dsl.import'])+ })++ it('should remove a selected permission when clicking its item row', async () => {+ const user = userEvent.setup()+ const handleChange = vi.fn()++ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={['app.dsl.export']}+ onChange={handleChange}+ />,+ )++ await user.click(screen.getByText('Export DSL'))++ expect(handleChange).toHaveBeenCalledTimes(1)+ expect(handleChange).toHaveBeenCalledWith([])+ })++ it('should show selected counts on groups with selected permissions', () => {+ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={['app.dsl.export']}+ onChange={vi.fn()}+ />,+ )++ const appManagementRow = screen.getByRole('button', { name: /App management/ }).parentElement!+ expect(within(appManagementRow).getByText('1/2')).toBeInTheDocument()+ })++ it('should select all permissions in a group without toggling expansion', async () => {+ const user = userEvent.setup()+ const handleChange = vi.fn()++ render(<PermissionGroupList groups={permissionGroups} value={[]} onChange={handleChange} />)++ const appManagementButton = screen.getByRole('button', { name: /App management/ })+ const appManagementRow = appManagementButton.parentElement!+ await user.click(within(appManagementRow).getByRole('button', { name: 'permission.permissionList.selectAll' }))++ expect(handleChange).toHaveBeenCalledTimes(1)+ expect(handleChange).toHaveBeenCalledWith(['app.dsl.import', 'app.dsl.export'])+ expect(appManagementButton).toHaveAttribute('aria-expanded', 'true')+ })++ it('should clear all permissions in a fully selected group', async () => {+ const user = userEvent.setup()+ const handleChange = vi.fn()++ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={['app.dsl.import', 'app.dsl.export', 'app.api.view']}+ onChange={handleChange}+ />,+ )++ const appManagementRow = screen.getByRole('button', { name: /App management/ }).parentElement!+ await user.click(within(appManagementRow).getByRole('button', { name: 'permission.permissionList.clearAll' }))++ expect(handleChange).toHaveBeenCalledTimes(1)+ expect(handleChange).toHaveBeenCalledWith(['app.api.view'])+ })+ })++ // Read-only mode still allows browsing groups but blocks permission mutation.+ describe('Read-only Mode', () => {+ it('should hide group bulk actions in read-only mode', () => {+ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={['app.dsl.export']}+ onChange={vi.fn()}+ readonly+ />,+ )++ expect(screen.queryByRole('button', { name: 'permission.permissionList.selectAll' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'permission.permissionList.clearAll' })).not.toBeInTheDocument()+ })++ it('should not change permissions when clicking a row or checkbox in read-only mode', async () => {+ const user = userEvent.setup()+ const handleChange = vi.fn()++ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={['app.dsl.export']}+ onChange={handleChange}+ readonly+ />,+ )++ await user.click(screen.getByText('Import DSL'))+ await user.click(getPermissionCheckbox('Export DSL'))++ expect(handleChange).not.toHaveBeenCalled()+ })++ it('should still allow expanding groups in read-only mode', async () => {+ const user = userEvent.setup()++ render(+ <PermissionGroupList+ groups={permissionGroups}+ value={[]}+ onChange={vi.fn()}+ readonly+ />,+ )++ const apiGroupButton = screen.getByRole('button', { name: /API access/ })+ await user.click(apiGroupButton)++ expect(apiGroupButton).toHaveAttribute('aria-expanded', 'true')+ expect(getPermissionCheckbox('View API')).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/header/account-setting/__tests__/workspace-role-checkbox-list.spec.tsx b/web/app/components/header/account-setting/__tests__/workspace-role-checkbox-list.spec.tsxnew file mode 100644index 00000000000..653e1737790--- /dev/null+++ b/web/app/components/header/account-setting/__tests__/workspace-role-checkbox-list.spec.tsx@@ -0,0 +1,76 @@+import type { Role } from '@/models/access-control'+import { render, screen } from '@testing-library/react'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'+import WorkspaceRoleCheckboxList from '../workspace-role-checkbox-list'++vi.mock('@/service/access-control/use-workspace-roles')++const createRole = (overrides: Partial<Role>): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_custom',+ name: 'Role',+ description: '',+ is_builtin: false,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})++const mockRoles = [+ createRole({ id: 'role-1', name: 'First role' }),+ createRole({ id: 'role-2', name: 'Second role' }),+]++describe('WorkspaceRoleCheckboxList', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(useWorkspaceRoleList).mockReturnValue({+ data: {+ pages: [{+ data: mockRoles,+ pagination: {+ total_count: 2,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+ },+ }],+ pageParams: [1],+ },+ isLoading: false,+ error: null,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ } as unknown as ReturnType<typeof useWorkspaceRoleList>)+ })++ it('should render checkboxes when multiple roles are allowed', () => {+ render(+ <WorkspaceRoleCheckboxList+ selectedRoleIds={['role-1']}+ selectedRoles={[mockRoles[0]!]}+ onSelectedRolesChange={vi.fn()}+ />,+ )++ expect(screen.getByRole('checkbox', { name: /First role/i })).toBeInTheDocument()+ expect(screen.queryByRole('radio', { name: /First role/i })).not.toBeInTheDocument()+ })++ it('should render radios when only one role is allowed', () => {+ render(+ <WorkspaceRoleCheckboxList+ selectedRoleIds={['role-1']}+ selectedRoles={[mockRoles[0]!]}+ allowMultipleRoles={false}+ onSelectedRolesChange={vi.fn()}+ />,+ )++ expect(screen.getByRole('radio', { name: /First role/i })).toBeInTheDocument()+ expect(screen.queryByRole('checkbox', { name: /First role/i })).not.toBeInTheDocument()+ })+})diff --git a/web/app/components/header/account-setting/access-rules-page/__tests__/access-rule-section.spec.tsx b/web/app/components/header/account-setting/access-rules-page/__tests__/access-rule-section.spec.tsxnew file mode 100644index 00000000000..35dd91459b6--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/__tests__/access-rule-section.spec.tsx@@ -0,0 +1,226 @@+import type { ReactNode } from 'react'+import type { AccessPolicyWithBindings } from '@/models/access-control'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import AccessRuleSection from '../access-rule-section'++const mocks = vi.hoisted(() => ({+ workspacePermissionKeys: [] as string[],+}))++vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn((selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mocks.workspacePermissionKeys,+ })),+}))++const rule: AccessPolicyWithBindings = {+ policy: {+ id: 'app-rule-1',+ tenant_id: 'tenant-1',+ resource_type: 'app',+ policy_key: 'app-rule',+ name: 'Full Control',+ description: 'Can edit and publish apps.',+ permission_keys: ['app.edit'],+ is_builtin: true,+ category: 'global_system_default',+ created_at: '2026-01-01',+ updated_at: '2026-01-01',+ },+ roles: [{+ role_id: 'role-1',+ role_name: 'Admin',+ binding_id: 'role-binding-1',+ is_locked: true,+ role_tag: '',+ }],+ accounts: [{+ account_id: 'account-1',+ account_name: 'Levi',+ binding_id: 'account-binding-1',+ is_locked: false,+ }],+}++let intersectionObserverCallback: IntersectionObserverCallback | null = null++class MockIntersectionObserver {+ constructor(callback: IntersectionObserverCallback) {+ intersectionObserverCallback = callback+ }++ observe = vi.fn()+ disconnect = vi.fn()+}++const renderWithQueryClient = (children: ReactNode) => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>,+ )+}++describe('AccessRuleSection', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.workspacePermissionKeys = []+ intersectionObserverCallback = null+ globalThis.IntersectionObserver = MockIntersectionObserver as unknown as typeof IntersectionObserver+ })++ it('should render a collapsed group and expand it when the header is clicked', async () => {+ render(+ <AccessRuleSection+ title="App Access Rules"+ rules={[rule]}+ totalCount={1}+ isLoadingRules={false}+ />,+ )++ expect(screen.queryByText('Full Control')).not.toBeInTheDocument()++ await userEvent.click(screen.getByRole('button', { expanded: false }))++ expect(screen.getByText('Full Control')).toBeInTheDocument()+ })++ it('should summarize total permission sets without binding counts', () => {+ render(+ <AccessRuleSection+ title="App Access Rules"+ rules={[rule]}+ totalCount={2}+ isLoadingRules={false}+ />,+ )++ expect(screen.getByText(/permission\.accessRule\.summary/)).toHaveTextContent('"count":2')+ expect(screen.queryByText(/permission\.accessRule\.lockedSummary/)).not.toBeInTheDocument()+ })++ it('should render a placeholder when a rule has no description', () => {+ render(+ <AccessRuleSection+ title="App Access Rules"+ rules={[{+ ...rule,+ policy: {+ ...rule.policy,+ description: '',+ },+ }]}+ totalCount={1}+ isLoadingRules={false}+ defaultExpanded+ />,+ )++ expect(screen.getByText('permission.accessRule.noDescription')).toBeInTheDocument()+ })++ it('should fetch the next page when the expanded group reaches its list anchor', () => {+ const fetchNextPage = vi.fn()++ render(+ <AccessRuleSection+ title="App Access Rules"+ rules={[rule]}+ totalCount={2}+ isLoadingRules={false}+ hasNextPage+ fetchNextPage={fetchNextPage}+ defaultExpanded+ />,+ )++ intersectionObserverCallback?.(+ [{ isIntersecting: true } as IntersectionObserverEntry],+ {} as IntersectionObserver,+ )++ expect(fetchNextPage).toHaveBeenCalledTimes(1)+ })++ it('should not fetch more while a next page is already loading', () => {+ const fetchNextPage = vi.fn()++ render(+ <AccessRuleSection+ title="App Access Rules"+ rules={[rule]}+ totalCount={2}+ isLoadingRules={false}+ isFetchingNextPage+ hasNextPage+ fetchNextPage={fetchNextPage}+ defaultExpanded+ />,+ )++ intersectionObserverCallback?.(+ [{ isIntersecting: true } as IntersectionObserverEntry],+ {} as IntersectionObserver,+ )++ expect(fetchNextPage).not.toHaveBeenCalled()+ })++ it('should expose create action when workspace role management is allowed', async () => {+ mocks.workspacePermissionKeys = ['workspace.role.manage']+ const onCreate = vi.fn()++ renderWithQueryClient(+ <AccessRuleSection+ title="App Access Rules"+ rules={[rule]}+ totalCount={1}+ isLoadingRules={false}+ onCreate={onCreate}+ />,+ )++ await userEvent.click(screen.getByRole('button', { name: /permission\.accessRule\.newPermissionSet/ }))++ expect(onCreate).toHaveBeenCalledTimes(1)+ })++ it('should keep row actions when workspace role management is allowed', () => {+ mocks.workspacePermissionKeys = ['workspace.role.manage']++ renderWithQueryClient(+ <AccessRuleSection+ title="App Access Rules"+ rules={[rule]}+ totalCount={1}+ isLoadingRules={false}+ defaultExpanded+ />,+ )++ expect(screen.getByRole('button', { name: 'common.operation.moreActions' })).toBeInTheDocument()+ })++ it('should hide create action when workspace role management is missing', () => {+ render(+ <AccessRuleSection+ title="App Access Rules"+ rules={[rule]}+ totalCount={1}+ isLoadingRules={false}+ />,+ )++ expect(screen.queryByRole('button', { name: /permission\.accessRule\.newPermissionSet/ })).not.toBeInTheDocument()+ })+})diff --git a/web/app/components/header/account-setting/access-rules-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/access-rules-page/__tests__/index.spec.tsxnew file mode 100644index 00000000000..1658b851092--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/__tests__/index.spec.tsx@@ -0,0 +1,241 @@+import type { AccessPolicyWithBindings } from '@/models/access-control'+import { toast } from '@langgenius/dify-ui/toast'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import {+ useCreateAccessRule,+ useInfiniteWorkspaceAppAccessRules,+ useInfiniteWorkspaceDatasetAccessRules,+ useUpdateAccessRule,+} from '@/service/access-control/use-workspace-access-rules'+import AccessRulesPage from '../index'++const mocks = vi.hoisted(() => ({+ createAccessRule: vi.fn(),+ updateAccessRule: vi.fn(),+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ success: vi.fn(),+ },+}))++vi.mock('@/service/access-control/use-workspace-access-rules', () => ({+ workspaceAccessRulesQueryKeys: {+ app: () => ['workspace-access-rules', 'app'],+ dataset: () => ['workspace-access-rules', 'dataset'],+ },+ useCreateAccessRule: vi.fn(),+ useInfiniteWorkspaceAppAccessRules: vi.fn(),+ useInfiniteWorkspaceDatasetAccessRules: vi.fn(),+ useUpdateAccessRule: vi.fn(),+}))++vi.mock('../access-rule-section', () => ({+ default: ({+ title,+ rules,+ onCreate,+ onEditRule,+ }: {+ title: string+ rules: AccessPolicyWithBindings[]+ onCreate: () => void+ onEditRule: (rule: AccessPolicyWithBindings) => void+ }) => (+ <section aria-label={title}>+ <h2>{title}</h2>+ <button type="button" aria-label={`create ${title}`} onClick={onCreate}>+ create+ {title}+ </button>+ <button type="button" aria-label={`edit ${title}`} onClick={() => onEditRule(rules[0]!)}>+ edit+ {title}+ </button>+ </section>+ ),+}))++vi.mock('../permission-set-modal', () => ({+ default: ({+ mode,+ resourceType,+ initialValues,+ onSubmit,+ }: {+ mode: string+ resourceType: string+ initialValues?: { name: string, description: string, permissionKeys: string[] }+ onSubmit: (values: { name: string, description: string, permissionKeys: string[] }) => void+ }) => (+ <div role="dialog" aria-label={`${resourceType} ${mode}`}>+ <span>{initialValues?.name}</span>+ <button+ type="button"+ onClick={() => onSubmit({+ name: `${resourceType} permission`,+ description: `${resourceType} description`,+ permissionKeys: [`${resourceType}.acl.edit`],+ })}+ >+ submit permission set+ </button>+ </div>+ ),+}))++const appRule: AccessPolicyWithBindings = {+ policy: {+ id: 'app-rule-1',+ tenant_id: 'tenant-1',+ resource_type: 'app',+ policy_key: 'app-rule',+ name: 'App rule',+ description: 'App rule description',+ permission_keys: ['app.acl.edit'],+ is_builtin: false,+ category: 'global_custom',+ created_at: '2026-01-01',+ updated_at: '2026-01-01',+ },+ roles: [{+ role_id: 'role-1',+ role_name: 'Role 1',+ binding_id: 'role-binding-1',+ is_locked: false,+ role_tag: '',+ }],+ accounts: [{+ account_id: 'member-1',+ account_name: 'Member 1',+ binding_id: 'member-binding-1',+ is_locked: false,+ }],+}++const datasetRule: AccessPolicyWithBindings = {+ policy: {+ ...appRule.policy,+ id: 'dataset-rule-1',+ resource_type: 'dataset',+ policy_key: 'dataset-rule',+ name: 'Dataset rule',+ permission_keys: ['dataset.acl.edit'],+ },+ roles: [{+ role_id: 'dataset-role-1',+ role_name: 'Dataset Role 1',+ binding_id: 'dataset-role-binding-1',+ is_locked: false,+ role_tag: '',+ }],+ accounts: [{+ account_id: 'dataset-member-1',+ account_name: 'Dataset Member 1',+ binding_id: 'dataset-member-binding-1',+ is_locked: false,+ }],+}++const mockMutation = (mock: ReturnType<typeof vi.fn>) => {+ mock.mockImplementation((_payload, options) => {+ options?.onSuccess?.()+ return Promise.resolve()+ })++ return {+ mutate: mock,+ mutateAsync: mock,+ }+}++const pagination = {+ total_count: 1,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+}++const setupHooks = () => {+ vi.mocked(useInfiniteWorkspaceAppAccessRules).mockReturnValue({+ data: { pages: [{ items: [appRule], pagination }], pageParams: [1] },+ isLoading: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ error: null,+ } as unknown as ReturnType<typeof useInfiniteWorkspaceAppAccessRules>)+ vi.mocked(useInfiniteWorkspaceDatasetAccessRules).mockReturnValue({+ data: { pages: [{ items: [datasetRule], pagination }], pageParams: [1] },+ isLoading: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ error: null,+ } as unknown as ReturnType<typeof useInfiniteWorkspaceDatasetAccessRules>)+ vi.mocked(useCreateAccessRule).mockReturnValue(mockMutation(mocks.createAccessRule) as unknown as ReturnType<typeof useCreateAccessRule>)+ vi.mocked(useUpdateAccessRule).mockReturnValue(mockMutation(mocks.updateAccessRule) as unknown as ReturnType<typeof useUpdateAccessRule>)+}++describe('AccessRulesPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ setupHooks()+ })++ it('renders app and dataset access rule sections', () => {+ render(<AccessRulesPage />)++ expect(screen.getByRole('heading', { name: 'permission.accessRule.appTitle' })).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'permission.accessRule.datasetTitle' })).toBeInTheDocument()+ })++ it('creates app permission sets with app resource type', async () => {+ render(<AccessRulesPage />)++ await userEvent.click(screen.getByRole('button', { name: 'create permission.accessRule.appTitle' }))+ await userEvent.click(screen.getByRole('button', { name: 'submit permission set' }))++ expect(mocks.createAccessRule).toHaveBeenCalledWith({+ name: 'app permission',+ description: 'app description',+ permission_keys: ['app.acl.edit'],+ resourceType: 'app',+ }, expect.any(Object))+ expect(toast.success).toHaveBeenCalledWith('permission.accessRule.created')+ })++ it('creates dataset permission sets with dataset resource type', async () => {+ render(<AccessRulesPage />)++ await userEvent.click(screen.getByRole('button', { name: 'create permission.accessRule.datasetTitle' }))+ await userEvent.click(screen.getByRole('button', { name: 'submit permission set' }))++ expect(mocks.createAccessRule).toHaveBeenCalledWith({+ name: 'dataset permission',+ description: 'dataset description',+ permission_keys: ['dataset.acl.edit'],+ resourceType: 'dataset',+ }, expect.any(Object))+ expect(toast.success).toHaveBeenCalledWith('permission.accessRule.created')+ })++ it('updates dataset permission sets with dataset resource type', async () => {+ render(<AccessRulesPage />)++ await userEvent.click(screen.getByRole('button', { name: 'edit permission.accessRule.datasetTitle' }))+ expect(screen.getByText('Dataset rule')).toBeInTheDocument()+ await userEvent.click(screen.getByRole('button', { name: 'submit permission set' }))++ expect(mocks.updateAccessRule).toHaveBeenCalledWith({+ id: 'dataset-rule-1',+ name: 'dataset permission',+ description: 'dataset description',+ permission_keys: ['dataset.acl.edit'],+ resourceType: 'dataset',+ }, expect.any(Object))+ expect(toast.success).toHaveBeenCalledWith('permission.accessRule.updated')+ })+})diff --git a/web/app/components/header/account-setting/access-rules-page/access-rule-row-menu.tsx b/web/app/components/header/account-setting/access-rules-page/access-rule-row-menu.tsxnew file mode 100644index 00000000000..8fd88c1f4fc--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/access-rule-row-menu.tsx@@ -0,0 +1,154 @@+'use client'++import type { AccessPolicy } from '@/models/access-control'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { toast } from '@langgenius/dify-ui/toast'+import { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import ActionButton from '@/app/components/base/action-button'+import { useCopyAccessRule, useDeleteAccessRule } from '@/service/access-control/use-workspace-access-rules'++type AccessRuleRowMenuProps = {+ rule: AccessPolicy+ onView?: () => void+ onEdit?: () => void+}++const AccessRuleRowMenu = ({+ rule,+ onView,+ onEdit,+}: AccessRuleRowMenuProps) => {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)++ const { mutateAsync: copyAccessRule } = useCopyAccessRule(rule.resource_type)+ const { mutateAsync: deleteAccessRule, isPending: isDeletingAccessRule } = useDeleteAccessRule(rule.resource_type)++ const handleView = useCallback(() => {+ onView?.()+ }, [onView])++ const handleCopyRules = useCallback(() => {+ copyAccessRule(rule.id, {+ onSuccess: () => {+ toast.success(t('accessRule.copied', { ns: 'permission' }))+ setOpen(false)+ },+ })+ }, [copyAccessRule, rule.id, t])++ const openDeleteConfirm = useCallback(() => {+ setShowDeleteConfirm(true)+ setOpen(false)+ }, [])++ const handleDelete = useCallback(() => {+ deleteAccessRule(rule.id, {+ onSuccess: () => {+ toast.success(t('accessRule.deleted', { ns: 'permission' }))+ setShowDeleteConfirm(false)+ },+ })+ }, [deleteAccessRule, rule.id, t])++ const isBuiltIn = rule.is_builtin++ return (+ <>+ <DropdownMenu open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger+ render={(+ <ActionButton+ size="l"+ className={open ? 'bg-state-base-hover' : ''}+ aria-label={t('operation.moreActions', { ns: 'common' })}+ />+ )}+ >+ <span aria-hidden className="i-ri-more-fill h-4 w-4 text-text-tertiary" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ placement="bottom-end"+ sideOffset={4}+ popupClassName="min-w-[140px]"+ >+ {isBuiltIn+ ? (+ <DropdownMenuItem+ className="system-sm-semibold text-text-secondary"+ onClick={handleView}+ >+ {t('operation.view', { ns: 'common' })}+ </DropdownMenuItem>+ )+ : (+ <DropdownMenuItem+ className="system-sm-semibold text-text-secondary"+ onClick={onEdit}+ >+ {t('operation.edit', { ns: 'common' })}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ className="system-sm-semibold text-text-secondary"+ onClick={handleCopyRules}+ >+ {t('common.duplicateAction', { ns: 'permission' })}+ </DropdownMenuItem>+ {!isBuiltIn && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ className="system-sm-semibold"+ onClick={openDeleteConfirm}+ >+ {t('operation.delete', { ns: 'common' })}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ <AlertDialog open={showDeleteConfirm} onOpenChange={open => !open && setShowDeleteConfirm(false)}>+ <AlertDialogContent backdropProps={{ forceRender: true }}>+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">+ {t('accessRule.deleteTitle', { ns: 'permission', name: rule.name })}+ </AlertDialogTitle>+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">+ {t('accessRule.deleteDescription', { ns: 'permission' })}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions>+ <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>+ <AlertDialogConfirmButton+ disabled={isDeletingAccessRule}+ onClick={handleDelete}+ >+ {t('operation.delete', { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )+}++export default AccessRuleRowMenudiff --git a/web/app/components/header/account-setting/access-rules-page/access-rule-row.tsx b/web/app/components/header/account-setting/access-rules-page/access-rule-row.tsxnew file mode 100644index 00000000000..89673392658--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/access-rule-row.tsx@@ -0,0 +1,54 @@+'use client'++import type { AccessPolicyWithBindings } from '@/models/access-control'+import { cn } from '@langgenius/dify-ui/cn'+import { memo, useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import AccessRuleRowMenu from './access-rule-row-menu'++type AccessRuleRowProps = {+ rule: AccessPolicyWithBindings+ canManage: boolean+ className?: string+ showMenu?: boolean+ onView?: (rule: AccessPolicyWithBindings) => void+ onEdit?: (rule: AccessPolicyWithBindings) => void+}++const AccessRuleRow = ({+ rule,+ canManage,+ className,+ showMenu = true,+ onView,+ onEdit,+}: AccessRuleRowProps) => {+ const { t } = useTranslation()+ const { policy } = rule+ const description = policy.description.trim() || t('accessRule.noDescription', { ns: 'permission' })++ const handleView = useCallback(() => onView?.(rule), [onView, rule])+ const handleEdit = useCallback(() => onEdit?.(rule), [onEdit, rule])++ return (+ <div className={cn('flex items-start gap-3 px-1 py-3.5', className)}>+ <div className="min-w-0 flex-1">+ <div className="flex h-6 items-center system-sm-semibold text-text-primary">+ {policy.name}+ </div>+ <p className="system-xs-regular leading-4 text-text-tertiary">+ {description}+ </p>+ </div>+ {showMenu && canManage && (+ <AccessRuleRowMenu+ onView={handleView}+ onEdit={handleEdit}+ rule={policy}+ />+ )}+ </div>+ )+}++export default memo(AccessRuleRow)diff --git a/web/app/components/header/account-setting/access-rules-page/access-rule-section.tsx b/web/app/components/header/account-setting/access-rules-page/access-rule-section.tsxnew file mode 100644index 00000000000..fe1498a64f0--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/access-rule-section.tsx@@ -0,0 +1,165 @@+'use client'++import type { AccessPolicyWithBindings } from '@/models/access-control'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { memo, useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import ActionButton from '@/app/components/base/action-button'+import Loading from '@/app/components/base/loading'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'+import AccessRuleRow from './access-rule-row'++type AccessRuleSectionProps = {+ title: string+ rules: AccessPolicyWithBindings[]+ totalCount?: number+ isLoadingRules: boolean+ isFetchingNextPage?: boolean+ hasNextPage?: boolean+ fetchNextPage?: () => unknown+ error?: unknown+ defaultExpanded?: boolean+ onCreate?: () => void+ onViewRule?: (rule: AccessPolicyWithBindings) => void+ onEditRule?: (rule: AccessPolicyWithBindings) => void+ className?: string+}++const AccessRuleSection = ({+ title,+ rules,+ totalCount,+ isLoadingRules,+ isFetchingNextPage = false,+ hasNextPage,+ fetchNextPage,+ error,+ defaultExpanded = false,+ onCreate,+ onViewRule,+ onEditRule,+ className,+}: AccessRuleSectionProps) => {+ const { t } = useTranslation()+ const [expanded, setExpanded] = useState(defaultExpanded)+ const listRef = useRef<HTMLDivElement>(null)+ const anchorRef = useRef<HTMLDivElement>(null)+ const workspacePermissionKeys = useAppContextWithSelector(s => s.workspacePermissionKeys)+ const canManage = hasPermission(workspacePermissionKeys, 'workspace.role.manage')+ const ruleCount = totalCount ?? rules.length++ useEffect(() => {+ const hasMore = hasNextPage ?? true+ let observer: IntersectionObserver | undefined++ if (!expanded || error || !fetchNextPage)+ return++ if (anchorRef.current && listRef.current) {+ const containerHeight = listRef.current.clientHeight+ const dynamicMargin = Math.max(48, Math.min(containerHeight * 0.2, 120))++ observer = new IntersectionObserver((entries) => {+ if (entries[0]!.isIntersecting && !isLoadingRules && !isFetchingNextPage && !error && hasMore)+ fetchNextPage()+ }, {+ root: listRef.current,+ rootMargin: `${dynamicMargin}px`,+ })+ observer.observe(anchorRef.current)+ }++ return () => observer?.disconnect()+ }, [error, expanded, fetchNextPage, hasNextPage, isFetchingNextPage, isLoadingRules])++ return (+ <section className={cn('overflow-hidden rounded-xl border border-components-panel-border bg-components-panel-bg', className)}>+ <div className="flex items-center gap-4 p-4">+ <button+ type="button"+ className="min-w-0 flex-1 text-left"+ onClick={() => setExpanded(expanded => !expanded)}+ aria-expanded={expanded}+ >+ <div className="flex min-w-0 items-center gap-4">+ <span className="truncate system-sm-semibold text-text-primary">+ {title}+ </span>+ <span className="shrink-0 system-xs-regular text-text-tertiary">+ {t('accessRule.summary', { ns: 'permission', count: ruleCount })}+ </span>+ </div>+ </button>+ <div className="flex shrink-0 items-center gap-3">+ {canManage && (+ <Button+ variant="primary"+ size="medium"+ onClick={onCreate}+ disabled={isLoadingRules}+ >+ <span className="mr-0.5 i-ri-add-line size-3.5" />+ <span>{t('accessRule.newPermissionSet', { ns: 'permission' })}</span>+ </Button>+ )}+ <ActionButton+ size="l"+ aria-label={expanded ? t('accessRule.collapseSection', { ns: 'permission', title }) : t('accessRule.expandSection', { ns: 'permission', title })}+ onClick={() => setExpanded(expanded => !expanded)}+ >+ <span+ aria-hidden+ className={cn(+ 'i-ri-arrow-right-s-line size-4 text-text-tertiary transition-transform',+ expanded && 'rotate-90',+ )}+ />+ </ActionButton>+ </div>+ </div>+ {expanded && (+ <div+ ref={listRef}+ className="max-h-105 overflow-y-auto overscroll-contain border-t border-divider-deep px-4"+ >+ {isLoadingRules+ ? (+ <div className="px-1 py-8 text-center">+ <Loading type="app" />+ </div>+ )+ : rules.length === 0+ ? (+ <div className="px-1 py-8 text-center system-sm-regular text-text-tertiary">+ {t('accessRule.noRules', { ns: 'permission' })}+ </div>+ )+ : (+ <>+ {rules.map((rule, index) => (+ <AccessRuleRow+ key={rule.policy.id}+ rule={rule}+ canManage={canManage}+ className={cn(index > 0 && 'border-t border-divider-regular')}+ onView={onViewRule}+ onEdit={onEditRule}+ />+ ))}+ <div ref={anchorRef} className="h-1" />+ {isFetchingNextPage && (+ <div className="px-1 py-3 text-center system-xs-regular text-text-tertiary">+ <Loading type="app" />+ </div>+ )}+ </>+ )}+ </div>+ )}+ </section>+ )+}++export default memo(AccessRuleSection)diff --git a/web/app/components/header/account-setting/access-rules-page/app-access-rule-section.tsx b/web/app/components/header/account-setting/access-rules-page/app-access-rule-section.tsxnew file mode 100644index 00000000000..1b83eaf1c5d--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/app-access-rule-section.tsx@@ -0,0 +1,152 @@+import type { PermissionSetFormValues, PermissionSetModalMode } from './permission-set-modal'+import type { AccessPolicyWithBindings } from '@/models/access-control'+import { toast } from '@langgenius/dify-ui/toast'+import { useCallback, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import {+ useCreateAccessRule,+ useInfiniteWorkspaceAppAccessRules,+ useUpdateAccessRule,+} from '@/service/access-control/use-workspace-access-rules'+import AccessRuleSection from './access-rule-section'+import PermissionSetModal from './permission-set-modal'++type AppAccessRuleSectionProps = {+ className?: string+}++type PermissionSetModalState = {+ mode: PermissionSetModalMode+ ruleId?: string+ initialValues?: PermissionSetFormValues+}++const RULES_PER_PAGE = 20++const AppAccessRuleSection = ({+ className,+}: AppAccessRuleSectionProps) => {+ const { t } = useTranslation()+ const locale = useLocale()+ const [permissionSetModalState, setPermissionSetModalState] = useState<PermissionSetModalState | null>(null)+ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])++ const {+ data: appAccessRulesResponse,+ isLoading,+ isFetchingNextPage,+ fetchNextPage,+ hasNextPage,+ error,+ } = useInfiniteWorkspaceAppAccessRules({+ page: 1,+ limit: RULES_PER_PAGE,+ language,+ })+ const { mutateAsync: createAccessRule } = useCreateAccessRule()+ const { mutateAsync: updateAccessRule } = useUpdateAccessRule()++ const appAccessRules = useMemo(() => appAccessRulesResponse?.pages.flatMap(page => page.items) || [], [appAccessRulesResponse?.pages])+ const totalCount = appAccessRulesResponse?.pages[0]?.pagination.total_count || 0++ const closePermissionSetModal = useCallback(() => {+ setPermissionSetModalState(null)+ }, [])++ const handleCreate = useCallback(() => {+ setPermissionSetModalState({ mode: 'create' })+ }, [])++ const handleView = useCallback((rule: AccessPolicyWithBindings) => {+ const { policy } = rule+ setPermissionSetModalState({+ mode: 'view',+ initialValues: {+ name: policy.name,+ description: policy.description,+ permissionKeys: policy.permission_keys,+ },+ })+ }, [])++ const handleEdit = useCallback((rule: AccessPolicyWithBindings) => {+ const { policy } = rule+ setPermissionSetModalState({+ mode: 'edit',+ ruleId: policy.id,+ initialValues: {+ name: policy.name,+ description: policy.description,+ permissionKeys: policy.permission_keys,+ },+ })+ }, [])++ const handlePermissionSetSubmit = useCallback((values: PermissionSetFormValues) => {+ if (!permissionSetModalState)+ return++ const { name, description, permissionKeys } = values+ if (permissionSetModalState.mode === 'create') {+ createAccessRule({+ name,+ description,+ permission_keys: permissionKeys,+ resourceType: 'app',+ }, {+ onSuccess: () => {+ toast.success(t('accessRule.created', { ns: 'permission' }))+ closePermissionSetModal()+ },+ })+ }+ else if (permissionSetModalState.mode === 'edit') {+ updateAccessRule({+ id: permissionSetModalState.ruleId!,+ name,+ description,+ permission_keys: permissionKeys,+ resourceType: 'app',+ }, {+ onSuccess: () => {+ toast.success(t('accessRule.updated', { ns: 'permission' }))+ closePermissionSetModal()+ },+ })+ }+ }, [closePermissionSetModal, createAccessRule, permissionSetModalState, t, updateAccessRule])++ return (+ <>+ <AccessRuleSection+ title={t('accessRule.appTitle', { ns: 'permission' })}+ rules={appAccessRules}+ totalCount={totalCount}+ isLoadingRules={isLoading}+ isFetchingNextPage={isFetchingNextPage}+ hasNextPage={hasNextPage}+ fetchNextPage={fetchNextPage}+ error={error}+ defaultExpanded+ onCreate={handleCreate}+ onViewRule={handleView}+ onEditRule={handleEdit}+ className={className}+ />+ {permissionSetModalState && (+ <PermissionSetModal+ open+ mode={permissionSetModalState.mode}+ resourceType="app"+ initialValues={permissionSetModalState.initialValues}+ onClose={closePermissionSetModal}+ onSubmit={handlePermissionSetSubmit}+ />+ )}+ </>+ )+}++export default AppAccessRuleSectiondiff --git a/web/app/components/header/account-setting/access-rules-page/dataset-access-rule-section.tsx b/web/app/components/header/account-setting/access-rules-page/dataset-access-rule-section.tsxnew file mode 100644index 00000000000..ef21c673333--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/dataset-access-rule-section.tsx@@ -0,0 +1,151 @@+import type { PermissionSetFormValues, PermissionSetModalMode } from './permission-set-modal'+import type { AccessPolicyWithBindings } from '@/models/access-control'+import { toast } from '@langgenius/dify-ui/toast'+import { useCallback, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import {+ useCreateAccessRule,+ useInfiniteWorkspaceDatasetAccessRules,+ useUpdateAccessRule,+} from '@/service/access-control/use-workspace-access-rules'+import AccessRuleSection from './access-rule-section'+import PermissionSetModal from './permission-set-modal'++type DatasetAccessRuleSectionProps = {+ className?: string+}++type PermissionSetModalState = {+ mode: PermissionSetModalMode+ ruleId?: string+ initialValues?: PermissionSetFormValues+}++const RULES_PER_PAGE = 20++const DatasetAccessRuleSection = ({+ className,+}: DatasetAccessRuleSectionProps) => {+ const { t } = useTranslation()+ const locale = useLocale()+ const [permissionSetModalState, setPermissionSetModalState] = useState<PermissionSetModalState | null>(null)+ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])++ const {+ data: datasetAccessRulesResponse,+ isLoading,+ isFetchingNextPage,+ fetchNextPage,+ hasNextPage,+ error,+ } = useInfiniteWorkspaceDatasetAccessRules({+ page: 1,+ limit: RULES_PER_PAGE,+ language,+ })+ const { mutateAsync: createAccessRule } = useCreateAccessRule()+ const { mutateAsync: updateAccessRule } = useUpdateAccessRule()++ const datasetAccessRules = useMemo(() => datasetAccessRulesResponse?.pages.flatMap(page => page.items) || [], [datasetAccessRulesResponse?.pages])+ const totalCount = datasetAccessRulesResponse?.pages[0]?.pagination.total_count || 0++ const closePermissionSetModal = useCallback(() => {+ setPermissionSetModalState(null)+ }, [])++ const handleCreate = useCallback(() => {+ setPermissionSetModalState({ mode: 'create' })+ }, [])++ const handleView = useCallback((rule: AccessPolicyWithBindings) => {+ const { policy } = rule+ setPermissionSetModalState({+ mode: 'view',+ initialValues: {+ name: policy.name,+ description: policy.description,+ permissionKeys: policy.permission_keys,+ },+ })+ }, [])++ const handleEdit = useCallback((rule: AccessPolicyWithBindings) => {+ const { policy } = rule+ setPermissionSetModalState({+ mode: 'edit',+ ruleId: policy.id,+ initialValues: {+ name: policy.name,+ description: policy.description,+ permissionKeys: policy.permission_keys,+ },+ })+ }, [])++ const handlePermissionSetSubmit = useCallback((values: PermissionSetFormValues) => {+ if (!permissionSetModalState)+ return++ const { name, description, permissionKeys } = values+ if (permissionSetModalState.mode === 'create') {+ createAccessRule({+ name,+ description,+ permission_keys: permissionKeys,+ resourceType: 'dataset',+ }, {+ onSuccess: () => {+ toast.success(t('accessRule.created', { ns: 'permission' }))+ closePermissionSetModal()+ },+ })+ }+ else if (permissionSetModalState.mode === 'edit') {+ updateAccessRule({+ id: permissionSetModalState.ruleId!,+ name,+ description,+ permission_keys: permissionKeys,+ resourceType: 'dataset',+ }, {+ onSuccess: () => {+ toast.success(t('accessRule.updated', { ns: 'permission' }))+ closePermissionSetModal()+ },+ })+ }+ }, [closePermissionSetModal, createAccessRule, permissionSetModalState, t, updateAccessRule])++ return (+ <>+ <AccessRuleSection+ title={t('accessRule.datasetTitle', { ns: 'permission' })}+ rules={datasetAccessRules}+ totalCount={totalCount}+ isLoadingRules={isLoading}+ isFetchingNextPage={isFetchingNextPage}+ hasNextPage={hasNextPage}+ fetchNextPage={fetchNextPage}+ error={error}+ onCreate={handleCreate}+ onViewRule={handleView}+ onEditRule={handleEdit}+ className={className}+ />+ {permissionSetModalState && (+ <PermissionSetModal+ open+ mode={permissionSetModalState.mode}+ resourceType="dataset"+ initialValues={permissionSetModalState.initialValues}+ onClose={closePermissionSetModal}+ onSubmit={handlePermissionSetSubmit}+ />+ )}+ </>+ )+}++export default DatasetAccessRuleSectiondiff --git a/web/app/components/header/account-setting/access-rules-page/index.tsx b/web/app/components/header/account-setting/access-rules-page/index.tsxnew file mode 100644index 00000000000..bd8569adc20--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/index.tsx@@ -0,0 +1,15 @@+'use client'++import AppAccessRuleSection from './app-access-rule-section'+import DatasetAccessRuleSection from './dataset-access-rule-section'++const AccessRulesPage = () => {+ return (+ <div className="flex flex-col gap-4">+ <AppAccessRuleSection />+ <DatasetAccessRuleSection />+ </div>+ )+}++export default AccessRulesPagediff --git a/web/app/components/header/account-setting/access-rules-page/permission-set-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/__tests__/index.spec.tsxnew file mode 100644index 00000000000..b28a95a78ee--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/__tests__/index.spec.tsx@@ -0,0 +1,209 @@+import type { PermissionGroup } from '@/models/access-control'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import PermissionSetModal from '../index'++const expectedAppACLPermissionKeys = [+ 'app.acl.view_layout',+ 'app.acl.test_and_run',+ 'app.acl.edit',+ 'app.acl.import_export_dsl',+ 'app.acl.delete',+ 'app.acl.release_and_version',+ 'app.acl.monitor',+ 'app.acl.access_config',+]++const getPermissionKeyMatcher = (permissionKey: string) => new RegExp(permissionKey.replaceAll('.', '\\.'))++const mockCatalogs = vi.hoisted(() => ({+ app: {+ groups: [] as PermissionGroup[],+ },+ dataset: {+ groups: [] as PermissionGroup[],+ },+}))++vi.mock('@/service/access-control/use-permission-catalog', () => ({+ useAppPermissionCatalog: () => ({+ data: { groups: mockCatalogs.app.groups },+ }),+ useDatasetPermissionCatalog: () => ({+ data: { groups: mockCatalogs.dataset.groups },+ }),+}))++const createPermissionGroup = (overrides: Partial<PermissionGroup> = {}): PermissionGroup => ({+ group_key: 'app_management',+ group_name: 'App management',+ description: '',+ permissions: expectedAppACLPermissionKeys.map(permissionKey => ({+ key: permissionKey,+ name: permissionKey,+ description: '',+ })),+ ...overrides,+})++describe('PermissionSetModal', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockCatalogs.app.groups = [createPermissionGroup()]+ mockCatalogs.dataset.groups = [+ createPermissionGroup({+ group_key: 'dataset_management',+ group_name: 'Dataset management',+ permissions: [+ {+ key: 'dataset.acl.edit',+ name: 'Edit dataset',+ description: '',+ },+ ],+ }),+ ]+ })++ // Rendering keeps the form fields and permission picker available inside the modal.+ describe('Rendering', () => {+ it('should render create mode with app permission catalog', () => {+ render(+ <PermissionSetModal+ open+ mode="create"+ resourceType="app"+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ expect(screen.getByText('permission.permissionSet.modal.create.app.title')).toBeInTheDocument()+ expect(screen.getByLabelText(/permission\.permissionSet\.nameLabel/)).toBeInTheDocument()+ expect(screen.getByLabelText('permission.permissionSet.descriptionLabel')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /App management/ })).toHaveAttribute('aria-expanded', 'true')+ expect(screen.getByText(/app\.acl\.edit/)).toBeInTheDocument()+ })++ it('should render the complete app ACL permission catalog', async () => {+ render(+ <PermissionSetModal+ open+ mode="create"+ resourceType="app"+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ for (const permissionKey of expectedAppACLPermissionKeys)+ expect(await screen.findByText(getPermissionKeyMatcher(permissionKey))).toBeInTheDocument()+ })++ it('should render dataset permission catalog when resource type is dataset', () => {+ render(+ <PermissionSetModal+ open+ mode="create"+ resourceType="dataset"+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ expect(screen.getByText('permission.permissionSet.modal.create.dataset.title')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Dataset management/ })).toBeInTheDocument()+ expect(screen.getByText(/dataset\.acl\.edit/)).toBeInTheDocument()+ })+ })++ // Form submission trims text fields and sends the selected permission keys.+ describe('User Interactions', () => {+ it('should submit trimmed values and selected permissions when confirming create mode', async () => {+ const user = userEvent.setup()+ const handleClose = vi.fn()+ const handleSubmit = vi.fn()++ render(+ <PermissionSetModal+ open+ mode="create"+ resourceType="app"+ onClose={handleClose}+ onSubmit={handleSubmit}+ />,+ )++ await user.type(screen.getByLabelText(/permission\.permissionSet\.nameLabel/), ' Custom app rule ')+ await user.type(screen.getByLabelText('permission.permissionSet.descriptionLabel'), ' Can edit apps ')+ await user.click(screen.getByText(/app\.acl\.release_and_version/))+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))++ expect(handleSubmit).toHaveBeenCalledTimes(1)+ expect(handleSubmit).toHaveBeenCalledWith({+ name: 'Custom app rule',+ description: 'Can edit apps',+ permissionKeys: ['app.acl.release_and_version'],+ })+ expect(handleClose).toHaveBeenCalledTimes(1)+ })++ it('should submit an updated description when editing an existing permission set', async () => {+ const user = userEvent.setup()+ const handleSubmit = vi.fn()++ render(+ <PermissionSetModal+ open+ mode="edit"+ resourceType="app"+ initialValues={{+ name: 'Existing app rule',+ description: 'Original description',+ permissionKeys: ['app.acl.edit'],+ }}+ onClose={vi.fn()}+ onSubmit={handleSubmit}+ />,+ )++ const descriptionInput = screen.getByLabelText('permission.permissionSet.descriptionLabel')+ await user.clear(descriptionInput)+ await user.type(descriptionInput, ' Updated rule description ')+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))++ expect(handleSubmit).toHaveBeenCalledTimes(1)+ expect(handleSubmit).toHaveBeenCalledWith({+ name: 'Existing app rule',+ description: 'Updated rule description',+ permissionKeys: ['app.acl.edit'],+ })+ })+ })++ // View mode is read-only and uses close-only footer actions.+ describe('Read-only Mode', () => {+ it('should disable editing and hide confirm action in view mode', () => {+ render(+ <PermissionSetModal+ open+ mode="view"+ resourceType="app"+ initialValues={{+ name: 'Viewer',+ description: 'Read only rule',+ permissionKeys: ['app.acl.edit'],+ }}+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ expect(screen.getByLabelText(/permission\.permissionSet\.nameLabel/)).toBeDisabled()+ expect(screen.getByLabelText('permission.permissionSet.descriptionLabel')).toBeDisabled()+ expect(screen.queryByRole('button', { name: 'common.operation.confirm' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'permission.permissionList.clearAll' })).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/header/account-setting/access-rules-page/permission-set-modal/hooks.ts b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/hooks.tsnew file mode 100644index 00000000000..de29b2a61e0--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/hooks.ts@@ -0,0 +1,40 @@+import type { AccessPolicyResourceType } from '@/models/access-control'+import { useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { useAppPermissionCatalog, useDatasetPermissionCatalog } from '@/service/access-control/use-permission-catalog'++export const usePermissionsGroups = (resourceType: AccessPolicyResourceType) => {+ const { t } = useTranslation()+ const { data: appPermissionCatalog } = useAppPermissionCatalog(resourceType === 'app')+ const { data: datasetPermissionCatalog } = useDatasetPermissionCatalog(resourceType === 'dataset')++ const permissionCatalog = resourceType === 'app' ? appPermissionCatalog : datasetPermissionCatalog++ const groups = useMemo(() => {+ return (permissionCatalog?.groups || []).map(group => ({+ ...group,+ group_name: t(`group.${resourceType}_acl`, {+ ns: 'permission',+ defaultValue: group.group_name,+ }),+ permissions: group.permissions.map(permission => ({+ ...permission,+ name: t(permission.key, {+ ns: 'permissionKeys',+ defaultValue: permission.name,+ }),+ })),+ }))+ }, [permissionCatalog?.groups, resourceType, t])++ const allPermissions = groups.flatMap(g => g.permissions) || []++ const permissionMap = Object.fromEntries(+ allPermissions.map(p => [p.key, p]),+ )++ return {+ groups,+ permissionMap,+ }+}diff --git a/web/app/components/header/account-setting/access-rules-page/permission-set-modal/index.tsx b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/index.tsxnew file mode 100644index 00000000000..d77f3f9ef68--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/index.tsx@@ -0,0 +1,179 @@+'use client'++import type { AccessPolicyResourceType } from '@/models/access-control'+import { Button } from '@langgenius/dify-ui/button'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { Input } from '@langgenius/dify-ui/input'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import PermissionPicker from './permission-picker'++export type PermissionSetModalMode = 'create' | 'edit' | 'view'++export type PermissionSetFormValues = {+ name: string+ description: string+ permissionKeys: string[]+}++type PermissionSetModalProps = {+ open: boolean+ mode: PermissionSetModalMode+ resourceType: AccessPolicyResourceType+ initialValues?: Partial<PermissionSetFormValues>+ onClose: () => void+ onSubmit: (values: PermissionSetFormValues) => void+}++type PermissionSetModalBodyProps = Omit<PermissionSetModalProps, 'open'>++const PermissionSetModalBody = ({+ mode,+ resourceType,+ initialValues,+ onClose,+ onSubmit,+}: PermissionSetModalBodyProps) => {+ const { t } = useTranslation()+ const [name, setName] = useState(initialValues?.name ?? '')+ const [description, setDescription] = useState(initialValues?.description ?? '')+ const [permissionKeys, setPermissionKeys] = useState<string[]>(initialValues?.permissionKeys ?? [])++ const trimmedName = name.trim()+ const readonly = mode === 'view'+ const canSubmit = trimmedName.length > 0++ const handleConfirm = () => {+ if (readonly || !canSubmit)+ return+ onSubmit({+ name: trimmedName,+ description: description.trim(),+ permissionKeys,+ })+ onClose()+ }++ return (+ <DialogContent+ className="flex h-[85vh] w-140 flex-col overflow-hidden p-0"+ backdropProps={{ forceRender: true }}+ >+ <div className="relative shrink-0 px-6 pt-6 pb-4">+ <DialogCloseButton />+ <div className="pr-8">+ <DialogTitle className="system-xl-semibold text-text-primary">+ {t(`permissionSet.modal.${mode}.${resourceType}.title`, { ns: 'permission' })}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t(`permissionSet.modal.${mode}.${resourceType}.description`, { ns: 'permission' })}+ </DialogDescription>+ </div>+ </div>++ <div className="border-t border-divider-subtle" />++ <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-hidden px-6 py-5">+ <div className="flex shrink-0 flex-col gap-1">+ <label htmlFor="permission-set-name" className="system-sm-medium text-text-secondary">+ {t('permissionSet.nameLabel', { ns: 'permission' })}+ <span aria-hidden className="ml-0.5 text-text-destructive">*</span>+ </label>+ <Input+ id="permission-set-name"+ value={name}+ onChange={e => setName(e.target.value)}+ placeholder={t('permissionSet.namePlaceholder', { ns: 'permission' })}+ disabled={readonly}+ />+ </div>++ <div className="flex shrink-0 flex-col gap-1">+ <label htmlFor="permission-set-description" className="system-sm-medium text-text-secondary">+ {t('permissionSet.descriptionLabel', { ns: 'permission' })}+ </label>+ <Textarea+ id="permission-set-description"+ value={description}+ onValueChange={value => setDescription(value)}+ placeholder={t('permissionSet.descriptionPlaceholder', { ns: 'permission' })}+ className="min-h-20 resize-none"+ disabled={readonly}+ />+ </div>++ <div className="flex min-h-0 flex-1 flex-col gap-2">+ <div className="system-sm-medium text-text-secondary">{t('permissionSet.permissions', { ns: 'permission' })}</div>+ <PermissionPicker+ resourceType={resourceType}+ value={permissionKeys}+ onChange={setPermissionKeys}+ readonly={readonly}+ />+ </div>+ </div>++ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-divider-subtle px-6 py-4">+ <a+ href="https://docs.dify.ai/"+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 system-xs-medium text-text-accent hover:underline"+ >+ <span>{t('permissionSet.learnMore', { ns: 'permission' })}</span>+ <span aria-hidden className="i-ri-external-link-line h-3.5 w-3.5" />+ </a>+ <div className="flex items-center gap-2">+ <Button variant="secondary" onClick={onClose}>+ {readonly ? t('operation.close', { ns: 'common' }) : t('operation.cancel', { ns: 'common' })}+ </Button>+ {!readonly && (+ <Button+ variant="primary"+ disabled={!canSubmit}+ onClick={handleConfirm}+ >+ {t('operation.confirm', { ns: 'common' })}+ </Button>+ )}+ </div>+ </div>+ </DialogContent>+ )+}++const PermissionSetModal = ({+ open,+ mode,+ resourceType,+ initialValues,+ onClose,+ onSubmit,+}: PermissionSetModalProps) => {+ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen)+ onClose()+ }}+ >+ <PermissionSetModalBody+ mode={mode}+ resourceType={resourceType}+ initialValues={initialValues}+ onClose={onClose}+ onSubmit={onSubmit}+ />+ </Dialog>+ )+}++export default PermissionSetModaldiff --git a/web/app/components/header/account-setting/access-rules-page/permission-set-modal/permission-picker.tsx b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/permission-picker.tsxnew file mode 100644index 00000000000..6a816408a3e--- /dev/null+++ b/web/app/components/header/account-setting/access-rules-page/permission-set-modal/permission-picker.tsx@@ -0,0 +1,35 @@+'use client'++import type { AccessPolicyResourceType } from '@/models/access-control'+import PermissionGroupList from '../../permission-group-list'+import { usePermissionsGroups } from './hooks'++type PermissionPickerProps = {+ resourceType: AccessPolicyResourceType+ value: string[]+ onChange: (next: string[]) => void+ className?: string+ readonly?: boolean+}++const PermissionPicker = ({+ resourceType,+ value,+ onChange,+ className,+ readonly = false,+}: PermissionPickerProps) => {+ const { groups } = usePermissionsGroups(resourceType)++ return (+ <PermissionGroupList+ groups={groups}+ value={value}+ onChange={onChange}+ className={className}+ readonly={readonly}+ />+ )+}++export default PermissionPickerdiff --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 de131a2491d..af0536fd282 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@@ -7,11 +7,21 @@ const {mockCreateApiBasedExtension,mockUpdateApiBasedExtension,mockDeleteApiBasedExtension,+ mockWorkspacePermissionKeys,} = vi.hoisted(() => ({mockApiBasedExtensionsQuery: vi.fn(),mockCreateApiBasedExtension: vi.fn(),mockUpdateApiBasedExtension: vi.fn(),mockDeleteApiBasedExtension: vi.fn(),+ mockWorkspacePermissionKeys: {+ current: ['api_extension.manage'] as string[],+ },+}))++vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn((selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.current,+ })),}))vi.mock('@/service/client', () => ({@@ -48,6 +58,7 @@ vi.mock('@tanstack/react-query', () => ({describe('ApiBasedExtensionPage', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys.current = ['api_extension.manage']mockApiBasedExtensionsQuery.mockReturnValue({data: [],isPending: false,@@ -175,6 +186,24 @@ describe('ApiBasedExtensionPage', () => {expect(screen.queryByText('common.apiBasedExtension.title')).not.toBeInTheDocument()expect(screen.getByText('common.apiBasedExtension.add'))!.toBeInTheDocument()})++ it('should disable management actions when api extension permission is missing', () => {+ // Arrange+ mockWorkspacePermissionKeys.current = []+ const extension: ApiBasedExtensionResponse = { id: '1', name: 'Extension 1', api_endpoint: 'url1', api_key: 'key1' }+ mockApiBasedExtensionsQuery.mockReturnValue({+ data: [extension],+ isPending: false,+ })++ // Act+ render(<ApiBasedExtensionPage />)++ // Assert+ expect(screen.getByRole('button', { name: 'common.apiBasedExtension.add' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'common.operation.edit' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'common.operation.delete' })).toBeDisabled()+ })})describe('User Interactions', () => {diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsxindex 9643b81ae48..0077f66a565 100644--- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsx+++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsx@@ -81,6 +81,26 @@ describe('Item Component', () => {// Assertexpect(mockOnEdit).toHaveBeenCalledWith(mockData)})++ it('should disable edit and delete actions when management is not allowed', () => {+ // Act+ render(<Item apiBasedExtension={mockData} onEdit={mockOnEdit} canManage={false} />)++ // Assert+ expect(screen.getByRole('button', { name: 'common.operation.edit' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'common.operation.delete' })).toBeDisabled()+ })++ it('should not open edit or delete flows when management is not allowed', () => {+ // Act+ render(<Item apiBasedExtension={mockData} onEdit={mockOnEdit} canManage={false} />)+ fireEvent.click(screen.getByText('common.operation.edit'))+ fireEvent.click(screen.getByText('common.operation.delete'))++ // Assert+ expect(mockOnEdit).not.toHaveBeenCalled()+ expect(screen.queryByText(/common\.operation\.delete.*Test Extension.*\?/i)).not.toBeInTheDocument()+ })})describe('Deletion', () => {diff --git a/web/app/components/header/account-setting/api-based-extension-page/index.tsx b/web/app/components/header/account-setting/api-based-extension-page/index.tsxindex 5bf385345b9..78faacf711f 100644--- a/web/app/components/header/account-setting/api-based-extension-page/index.tsx+++ b/web/app/components/header/account-setting/api-based-extension-page/index.tsx@@ -6,7 +6,9 @@ import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { SearchInput } from '@/app/components/base/search-input'import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { consoleQuery } from '@/service/client'+import { hasPermission } from '@/utils/permission'import { Empty } from './empty'import { Item } from './item'import { ApiBasedExtensionModal } from './modal'@@ -49,6 +51,8 @@ export function ApiBasedExtensionPage({layout,}: ApiBasedExtensionPageProps = {}) {const { t } = useTranslation()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canManage = hasPermission(workspacePermissionKeys, 'api_extension.manage')const { data: apiBasedExtensions = [], isPending: isLoading } = useQuery(consoleQuery.apiBasedExtension.get.queryOptions())const [dialogState, setDialogState] = useState<ApiBasedExtensionDialogState>(null)const [keywords, setKeywords] = useState('')@@ -67,11 +71,17 @@ export function ApiBasedExtensionPage({const hasSearchKeywords = keywords.trim().length > 0const handleOpenApiBasedExtensionModal = () => {+ if (!canManage)+ return+setDialogState({mode: 'create',})}const handleEditApiBasedExtension = (apiBasedExtension: ApiBasedExtensionResponse) => {+ if (!canManage)+ return+setDialogState({mode: 'edit',apiBasedExtension,@@ -94,6 +104,7 @@ export function ApiBasedExtensionPage({/><Buttonvariant="secondary"+ disabled={!canManage}onClick={handleOpenApiBasedExtensionModal}><span className="mr-1 i-ri-add-line size-4" aria-hidden="true" />@@ -128,6 +139,7 @@ export function ApiBasedExtensionPage({key={item.id}apiBasedExtension={item}onEdit={handleEditApiBasedExtension}+ canManage={canManage}/>)))diff --git a/web/app/components/header/account-setting/api-based-extension-page/item.tsx b/web/app/components/header/account-setting/api-based-extension-page/item.tsxindex 25485226b24..3972a88fef8 100644--- a/web/app/components/header/account-setting/api-based-extension-page/item.tsx+++ b/web/app/components/header/account-setting/api-based-extension-page/item.tsx@@ -16,19 +16,27 @@ import { consoleQuery } from '@/service/client'type ItemProps = {apiBasedExtension: ApiBasedExtensionResponseonEdit: (apiBasedExtension: ApiBasedExtensionResponse) => void+ canManage?: boolean}export function Item({apiBasedExtension,onEdit,+ canManage = true,}: ItemProps) {const { t } = useTranslation()const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)const deleteApiBasedExtensionMutation = useMutation(consoleQuery.apiBasedExtension.byId.delete.mutationOptions())const handleOpenApiBasedExtensionModal = () => {+ if (!canManage)+ return+onEdit(apiBasedExtension)}const handleDeleteApiBasedExtension = () => {+ if (!canManage)+ return+deleteApiBasedExtensionMutation.mutate({params: {id: apiBasedExtension.id,@@ -48,13 +56,15 @@ export function Item({</div><div className="pointer-events-none flex shrink-0 items-center gap-1 opacity-0 transition-opacity group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100"><Button+ disabled={!canManage}onClick={handleOpenApiBasedExtensionModal}><span className="mr-1 i-ri-edit-line size-4" aria-hidden="true" />{t('operation.edit', { ns: 'common' })}</Button><Button- onClick={() => setShowDeleteConfirm(true)}+ disabled={!canManage}+ onClick={() => canManage && setShowDeleteConfirm(true)}><span className="mr-1 i-ri-delete-bin-line size-4" aria-hidden="true" />{t('operation.delete', { ns: 'common' })}@@ -70,7 +80,7 @@ export function Item({<AlertDialogActions><AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton><AlertDialogConfirmButton- disabled={deleteApiBasedExtensionMutation.isPending}+ disabled={!canManage || deleteApiBasedExtensionMutation.isPending}onClick={handleDeleteApiBasedExtension}>{t('operation.delete', { ns: 'common' }) || ''}diff --git a/web/app/components/header/account-setting/constants.ts b/web/app/components/header/account-setting/constants.tsindex 191c5b4cab5..d8128631306 100644--- a/web/app/components/header/account-setting/constants.ts+++ b/web/app/components/header/account-setting/constants.ts@@ -6,6 +6,8 @@ export const ACCOUNT_SETTING_MODAL_ACTION = 'showSettings'export const ACCOUNT_SETTING_TAB = {PROVIDER: 'provider',MEMBERS: 'members',+ PERMISSIONS: 'permissions',+ ACCESS_RULES: 'access-rules',BILLING: 'billing',DATA_SOURCE: 'data-source',API_BASED_EXTENSION: 'custom-endpoint',@@ -19,6 +21,8 @@ export const DEFAULT_ACCOUNT_SETTING_TAB = ACCOUNT_SETTING_TAB.MEMBERSconst WORKSPACE_SETTING_TAB_VALUES = [ACCOUNT_SETTING_TAB.MEMBERS,+ ACCOUNT_SETTING_TAB.PERMISSIONS,+ ACCOUNT_SETTING_TAB.ACCESS_RULES,ACCOUNT_SETTING_TAB.BILLING,ACCOUNT_SETTING_TAB.CUSTOM,] as constdiff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsxindex d11d7d166a2..5ce1c8f72c1 100644--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx@@ -11,6 +11,14 @@ import { useInvalidDataSourceList } from '@/service/use-pipeline'import Card from '../card'import { useDataSourceAuthUpdate } from '../hooks'+let mockWorkspacePermissionKeys: string[] = ['credential.manage', 'credential.use']++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+vi.mock('@/app/components/plugins/plugin-auth', () => ({ApiKeyModal: vi.fn(({ onClose, onUpdate, onRemove, disabled, editValues }: { onClose: () => void, onUpdate: () => void, onRemove: () => void, disabled: boolean, editValues: Record<string, unknown> }) => (<div data-testid="mock-api-key-modal" data-disabled={disabled}>@@ -24,8 +32,8 @@ vi.mock('@/app/components/plugins/plugin-auth', () => ({AuthCategory: {datasource: 'datasource',},- AddApiKeyButton: ({ onUpdate }: { onUpdate: () => void }) => <button onClick={onUpdate}>Add API Key</button>,- AddOAuthButton: ({ onUpdate }: { onUpdate: () => void }) => <button onClick={onUpdate}>Add OAuth</button>,+ AddApiKeyButton: ({ onUpdate, disabled }: { onUpdate: () => void, disabled?: boolean }) => <button disabled={disabled} onClick={onUpdate}>Add API Key</button>,+ AddOAuthButton: ({ onUpdate, disabled }: { onUpdate: () => void, disabled?: boolean }) => <button disabled={disabled} onClick={onUpdate}>Add OAuth</button>,}))vi.mock('@/hooks/use-i18n', () => ({@@ -118,6 +126,7 @@ describe('Card Component', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys = ['credential.manage', 'credential.use']mockPluginAuthActionReturn = createMockPluginAuthActionReturn()vi.mocked(useDataSourceAuthUpdate).mockReturnValue({ handleAuthUpdate: mockHandleAuthUpdate })@@ -297,6 +306,60 @@ describe('Card Component', () => {})expect(openOAuthPopup).not.toHaveBeenCalled()})++ it('should allow credential.use to set default without allowing credential management actions', async () => {+ // Arrange+ mockWorkspacePermissionKeys = ['credential.use']++ const oAuthItem = {+ ...mockItem,+ credentials_list: [{+ ...mockItem.credentials_list[0]!,+ type: CredentialTypeEnum.OAUTH2,+ }],+ }+ render(<Card item={oAuthItem} />)++ // Act: setting the default is a credential-use action.+ openDropdown('Credential 1')+ fireEvent.click(screen.getByText(/auth.setDefault/))++ // Assert+ await waitFor(() => {+ expect(mockPluginAuthActionReturn.handleSetDefault).toHaveBeenCalledWith('c1')+ })++ // Act: management actions remain blocked without credential.manage.+ openDropdown('Credential 1')+ fireEvent.click(screen.getByText(/operation.rename/))+ expect(screen.queryByPlaceholderText(/placeholder.input/)).not.toBeInTheDocument()++ fireEvent.click(screen.getByText(/dataSource.notion.changeAuthorizedPages/))++ // Assert+ expect(mockGetPluginOAuthUrl).not.toHaveBeenCalled()+ expect(mockPluginAuthActionReturn.handleRename).not.toHaveBeenCalled()+ })++ it('should block credential actions when neither credential.use nor credential.manage is granted', async () => {+ // Arrange+ mockWorkspacePermissionKeys = []++ render(<Card item={mockItem} />)++ // Act+ openDropdown('Credential 1')+ fireEvent.click(screen.getByText(/auth.setDefault/))+ fireEvent.click(screen.getByText(/operation.edit/))+ fireEvent.click(screen.getByText(/operation.remove/))++ // Assert+ await waitFor(() => {+ expect(mockPluginAuthActionReturn.handleSetDefault).not.toHaveBeenCalled()+ expect(mockPluginAuthActionReturn.handleEdit).not.toHaveBeenCalled()+ expect(mockPluginAuthActionReturn.openConfirm).not.toHaveBeenCalled()+ })+ })})describe('Modals', () => {@@ -354,6 +417,19 @@ describe('Card Component', () => {// Assertexpect(screen.getByTestId('mock-api-key-modal'))!.toHaveAttribute('data-disabled', 'true')})++ it('should disable ApiKeyModal when user lacks credential.manage', () => {+ // Arrange+ mockWorkspacePermissionKeys = ['credential.use']+ const mockReturn = createMockPluginAuthActionReturn({ editValues: { some: 'value' }, doingAction: false })+ vi.mocked(usePluginAuthAction).mockReturnValue(mockReturn)++ // Act+ render(<Card item={mockItem} disabled={false} />)++ // Assert+ expect(screen.getByTestId('mock-api-key-modal'))!.toHaveAttribute('data-disabled', 'true')+ })})describe('Integration', () => {@@ -374,5 +450,29 @@ describe('Card Component', () => {// AssertexpectAuthUpdated()})++ it('should disable configure credential actions when user lacks credential.manage', () => {+ // Arrange+ mockWorkspacePermissionKeys = ['credential.use']+ const configurableItem: DataSourceAuth = {+ ...mockItem,+ credential_schema: [{ name: 'api_key', type: FormTypeEnum.textInput, label: 'API Key', required: true }],+ oauth_schema: {+ client_schema: [{ name: 'oauth_key', type: FormTypeEnum.textInput, label: 'OAuth Key', required: true }],+ },+ }++ // Act+ render(<Card item={configurableItem} />)+ fireEvent.click(screen.getByText(/dataSource.configure/))++ // Assert+ expect(screen.getByText('Add API Key')).toBeDisabled()+ expect(screen.getByText('Add OAuth')).toBeDisabled()++ fireEvent.click(screen.getByText('Add API Key'))+ fireEvent.click(screen.getByText('Add OAuth'))+ expect(mockInvalidateDataSourceListAuth).toHaveBeenCalledTimes(0)+ })})})diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsxindex 9cdef50105c..871ab0b4321 100644--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx@@ -64,12 +64,16 @@ vi.mock('@/app/components/plugins/plugin-auth', () => ({vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({useCanSetPluginSettings: () => ({canSetPermissions: true,+ canSetPluginPreferences: true,}),usePluginSettingsAccess: () => ({canSetPermissions: true,+ canSetPluginPreferences: true,+ canViewInstalledPlugins: true,}),default: () => ({canSetPermissions: true,+ canSetPluginPreferences: true,}),}))diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/install-from-marketplace.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/install-from-marketplace.spec.tsxindex 128662e7fae..ba73742642f 100644--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/install-from-marketplace.spec.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/install-from-marketplace.spec.tsx@@ -58,6 +58,12 @@ vi.mock('../hooks', () => ({useMarketplaceAllPlugins: vi.fn(),}))+vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({+ usePluginSettingsAccess: () => ({+ canInstallPlugin: true,+ }),+}))+describe('InstallFromMarketplace Component', () => {const mockProviders: DataSourceAuth[] = [{diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/item.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/item.spec.tsxindex ed05018388f..fdcb954c145 100644--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/item.spec.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/item.spec.tsx@@ -67,7 +67,7 @@ describe('Item Component', () => {describe('Rename Mode Interactions', () => {it('should switch to rename mode when Trigger Rename is clicked', async () => {// Arrange- render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} />)+ render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} canManageCredential />)// Actawait triggerRename()@@ -78,7 +78,7 @@ describe('Item Component', () => {it('should update rename input value when changed', async () => {// Arrange- render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} />)+ render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} canManageCredential />)await triggerRename()const input = screen.getByPlaceholderText('common.placeholder.input')@@ -91,7 +91,7 @@ describe('Item Component', () => {it('should call onAction with "rename" and correct payload when Save is clicked', async () => {// Arrange- render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} />)+ render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} canManageCredential />)await triggerRename()const input = screen.getByPlaceholderText('common.placeholder.input')fireEvent.change(input, { target: { value: 'New Name' } })@@ -115,7 +115,7 @@ describe('Item Component', () => {it('should exit rename mode without calling onAction when Cancel is clicked', async () => {// Arrange- render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} />)+ render(<Item credentialItem={mockCredentialItem} onAction={mockOnAction} canManageCredential />)await triggerRename()const input = screen.getByPlaceholderText('common.placeholder.input')fireEvent.change(input, { target: { value: 'Cancelled Name' } })@@ -137,7 +137,7 @@ describe('Item Component', () => {const parentClick = vi.fn()render(<div onClick={parentClick}>- <Item credentialItem={mockCredentialItem} onAction={mockOnAction} />+ <Item credentialItem={mockCredentialItem} onAction={mockOnAction} canManageCredential /></div>,)// Act & Assert@@ -164,7 +164,7 @@ describe('Item Component', () => {it('should not throw if onAction is missing', async () => {// Arrange & Act// @ts-expect-error - Testing runtime tolerance for missing prop- render(<Item credentialItem={mockCredentialItem} onAction={undefined} />)+ render(<Item credentialItem={mockCredentialItem} onAction={undefined} canManageCredential />)await triggerRename()// Assertdiff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/operator.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/operator.spec.tsxindex 12042acfa1f..1cbe3717b0d 100644--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/operator.spec.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/operator.spec.tsx@@ -65,7 +65,7 @@ describe('Operator Component', () => {it('should call onRename when "rename" action is selected', async () => {// Arrangeconst credential = createMockCredential(CredentialTypeEnum.OAUTH2)- render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} />)+ render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} canManageCredential />)// Actawait userEvent.setup().click(screen.getByRole('button'))@@ -81,7 +81,7 @@ describe('Operator Component', () => {it('should handle missing onRename gracefully when "rename" action is selected', async () => {// Arrangeconst credential = createMockCredential(CredentialTypeEnum.OAUTH2)- render(<Operator credentialItem={credential} onAction={mockOnAction} />)+ render(<Operator credentialItem={credential} onAction={mockOnAction} canManageCredential />)// Act & Assertawait userEvent.setup().click(screen.getByRole('button'))@@ -92,7 +92,7 @@ describe('Operator Component', () => {it('should call onAction for "setDefault" action', async () => {// Arrangeconst credential = createMockCredential(CredentialTypeEnum.API_KEY)- render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} />)+ render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} canUseCredential />)// Actawait userEvent.setup().click(screen.getByRole('button'))@@ -107,7 +107,7 @@ describe('Operator Component', () => {it('should call onAction for "edit" action', async () => {// Arrangeconst credential = createMockCredential(CredentialTypeEnum.API_KEY)- render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} />)+ render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} canManageCredential />)// Actawait userEvent.setup().click(screen.getByRole('button'))@@ -122,7 +122,7 @@ describe('Operator Component', () => {it('should call onAction for "change" action', async () => {// Arrangeconst credential = createMockCredential(CredentialTypeEnum.OAUTH2)- render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} />)+ render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} canManageCredential />)// Actawait userEvent.setup().click(screen.getByRole('button'))@@ -137,7 +137,7 @@ describe('Operator Component', () => {it('should call onAction for "delete" action', async () => {// Arrangeconst credential = createMockCredential(CredentialTypeEnum.API_KEY)- render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} />)+ render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} canManageCredential />)// Actawait userEvent.setup().click(screen.getByRole('button'))@@ -148,5 +148,20 @@ describe('Operator Component', () => {expect(mockOnAction).toHaveBeenCalledWith('delete', credential)})})++ it('should not call actions by default when credential permissions are omitted', async () => {+ const credential = createMockCredential(CredentialTypeEnum.API_KEY)+ render(<Operator credentialItem={credential} onAction={mockOnAction} onRename={mockOnRename} />)++ await userEvent.setup().click(screen.getByRole('button'))+ fireEvent.click(await screen.findByText('plugin.auth.setDefault'))+ fireEvent.click(screen.getByText('common.operation.edit'))+ fireEvent.click(screen.getByText('common.operation.remove'))++ await waitFor(() => {+ expect(mockOnAction).not.toHaveBeenCalled()+ expect(mockOnRename).not.toHaveBeenCalled()+ })+ })})})diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsxindex c03998eadae..792dc0b3f75 100644--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsx@@ -94,6 +94,13 @@ vi.mock('@/utils/var', () => ({getMarketplaceUrl: (path: string) => `https://marketplace.example.com${path}`,}))+vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({+ usePluginSettingsAccess: () => ({+ canManagePlugin: true,+ canUpdatePlugin: true,+ }),+}))+const createPluginDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({id: 'plugin-installation-id',created_at: '2024-01-01',diff --git a/web/app/components/header/account-setting/data-source-page-new/card.tsx b/web/app/components/header/account-setting/data-source-page-new/card.tsxindex 57d217ad985..0eddcb5d394 100644--- a/web/app/components/header/account-setting/data-source-page-new/card.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/card.tsx@@ -24,6 +24,7 @@ import {} from '@/app/components/plugins/plugin-auth'import { AuthCategory } from '@/app/components/plugins/plugin-auth/types'import { CollectionType } from '@/app/components/tools/types'+import { useCredentialPermissions } from '@/hooks/use-credential-permissions'import { useRenderI18nObject } from '@/hooks/use-i18n'import { openOAuthPopup } from '@/hooks/use-oauth'import { useGetDataSourceOAuthUrl } from '@/service/use-datasource'@@ -49,6 +50,7 @@ const Card = ({onPluginUpdate,}: CardProps) => {const { t } = useTranslation()+ const { canUseCredential, canManageCredential } = useCredentialPermissions()const renderI18nObject = useRenderI18nObject()const {icon,@@ -176,6 +178,7 @@ const Card = ({pluginPayload={pluginPayload}item={item}onUpdate={handleAuthUpdate}+ disabled={disabled || !canManageCredential}/></div></div>@@ -192,6 +195,8 @@ const Card = ({key={credentialItem.id}credentialItem={credentialItem}onAction={handleAction}+ canUseCredential={canUseCredential}+ canManageCredential={canManageCredential}/>))}@@ -216,7 +221,7 @@ const Card = ({</div><AlertDialogActions><AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>- <AlertDialogConfirmButton disabled={doingAction} onClick={handleConfirm}>+ <AlertDialogConfirmButton disabled={doingAction || !canManageCredential} onClick={handleConfirm}>{t('operation.confirm', { ns: 'common' })}</AlertDialogConfirmButton></AlertDialogActions>@@ -234,7 +239,7 @@ const Card = ({formSchemas={credential_schema}editValues={editValues}onRemove={handleRemove}- disabled={disabled || doingAction}+ disabled={disabled || doingAction || !canManageCredential}/>)}diff --git a/web/app/components/header/account-setting/data-source-page-new/index.tsx b/web/app/components/header/account-setting/data-source-page-new/index.tsxindex 691a0cca838..5200a4df097 100644--- a/web/app/components/header/account-setting/data-source-page-new/index.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/index.tsx@@ -5,7 +5,7 @@ import { Trans, useTranslation } from 'react-i18next'import { SearchInput } from '@/app/components/base/search-input'import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'import { usePluginsWithLatestVersion } from '@/app/components/plugins/hooks'-import { useCanSetPluginSettings } from '@/app/components/plugins/plugin-page/use-reference-setting'+import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import { PluginCategoryEnum } from '@/app/components/plugins/types'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useRenderI18nObject } from '@/hooks/use-i18n'@@ -59,14 +59,15 @@ const DataSourcePage = ({const renderI18nObject = useRenderI18nObject()const [searchText, setSearchText] = useState('')const {- canSetPermissions,- } = useCanSetPluginSettings()+ canSetPluginPreferences,+ canViewInstalledPlugins,+ } = usePluginSettingsAccess()const { data: enable_marketplace } = useSuspenseQuery({...systemFeaturesQueryOptions(),select: s => s.enable_marketplace,})const { data, isLoading: isDataSourceListLoading } = useGetDataSourceListAuth()- const { data: installedPluginList } = useInstalledPluginList()+ const { data: installedPluginList } = useInstalledPluginList(!canViewInstalledPlugins)const pluginListWithLatestVersion = usePluginsWithLatestVersion(installedPluginList?.plugins)const invalidateInstalledPluginList = useInvalidateInstalledPluginList()const invalidateDataSourceListAuth = useInvalidDataSourceListAuth()@@ -111,7 +112,7 @@ const DataSourcePage = ({value={searchText}onValueChange={setSearchText}/>- {canSetPermissions && (+ {canSetPluginPreferences && (<UpdateSettingDialogcategory={PluginCategoryEnum.datasource}/>diff --git a/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsx b/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsxindex 7be959e52cb..15e1bfeb1d5 100644--- a/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsx@@ -16,6 +16,7 @@ import Divider from '@/app/components/base/divider'import Loading from '@/app/components/base/loading'import List from '@/app/components/plugins/marketplace/list'import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'+import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import ProviderCard from '@/app/components/plugins/provider-card'import { PluginCategoryEnum } from '@/app/components/plugins/types'import Link from '@/next/link'@@ -33,6 +34,7 @@ const InstallFromMarketplace = ({}: InstallFromMarketplaceProps) => {const { t } = useTranslation()const { theme } = useTheme()+ const { canInstallPlugin } = usePluginSettingsAccess()const [collapse, setCollapse] = useState(false)const {plugins: allPlugins,@@ -74,7 +76,7 @@ const InstallFromMarketplace = ({marketplaceCollections={[]}marketplaceCollectionPluginsMap={{}}plugins={allPlugins}- showInstallButton+ showInstallButton={canInstallPlugin}cardContainerClassName="grid grid-cols-3 gap-2"cardRender={cardRender}emptyClassName="h-auto"diff --git a/web/app/components/header/account-setting/data-source-page-new/item.tsx b/web/app/components/header/account-setting/data-source-page-new/item.tsxindex cb4520a3a2c..fe46af7c6b8 100644--- a/web/app/components/header/account-setting/data-source-page-new/item.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/item.tsx@@ -14,10 +14,14 @@ import Operator from './operator'type ItemProps = {credentialItem: DataSourceCredentialonAction: (action: string, credentialItem: DataSourceCredential, renamePayload?: { credential_id: string, name: string }) => void+ canUseCredential?: boolean+ canManageCredential?: boolean}const Item = ({credentialItem,onAction,+ canUseCredential = false,+ canManageCredential = false,}: ItemProps) => {const { t } = useTranslation()const [renaming, setRenaming] = useState(false)@@ -97,6 +101,8 @@ const Item = ({credentialItem={credentialItem}onAction={onAction}onRename={() => setRenaming(true)}+ canUseCredential={canUseCredential}+ canManageCredential={canManageCredential}/></>)diff --git a/web/app/components/header/account-setting/data-source-page-new/operator.tsx b/web/app/components/header/account-setting/data-source-page-new/operator.tsxindex 4e1148aae2b..1a1b243d8c2 100644--- a/web/app/components/header/account-setting/data-source-page-new/operator.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/operator.tsx@@ -20,17 +20,24 @@ type OperatorProps = {credentialItem: DataSourceCredentialonAction: (action: string, credentialItem: DataSourceCredential) => voidonRename?: () => void+ canUseCredential?: boolean+ canManageCredential?: boolean}const Operator = ({credentialItem,onAction,onRename,+ canUseCredential = false,+ canManageCredential = false,}: OperatorProps) => {const { t } = useTranslation()const {type,} = credentialItem- const handleAction = useCallback((action: string) => {+ const handleAction = useCallback((action: string, allowed: boolean) => {+ if (!allowed)+ return+queueMicrotask(() => {if (action === 'rename') {onRename?.()@@ -54,30 +61,30 @@ const Operator = ({)}/><DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="min-w-[200px]">- <DropdownMenuItem className="h-auto gap-2 py-2" onClick={() => handleAction('setDefault')}>+ <DropdownMenuItem disabled={!canUseCredential} className="h-auto gap-2 py-2" onClick={() => handleAction('setDefault', canUseCredential)}><span aria-hidden className="i-ri-home-9-line size-4 text-text-tertiary" /><div className="system-sm-semibold text-text-secondary">{t('auth.setDefault', { ns: 'plugin' })}</div></DropdownMenuItem>{type === CredentialTypeEnum.OAUTH2 && (- <DropdownMenuItem className="h-auto gap-2 py-2" onClick={() => handleAction('rename')}>+ <DropdownMenuItem disabled={!canManageCredential} className="h-auto gap-2 py-2" onClick={() => handleAction('rename', canManageCredential)}><span aria-hidden className="i-ri-edit-line size-4 text-text-tertiary" /><div className="system-sm-semibold text-text-secondary">{t('operation.rename', { ns: 'common' })}</div></DropdownMenuItem>)}{type === CredentialTypeEnum.API_KEY && (- <DropdownMenuItem className="h-auto gap-2 py-2" onClick={() => handleAction('edit')}>+ <DropdownMenuItem disabled={!canManageCredential} className="h-auto gap-2 py-2" onClick={() => handleAction('edit', canManageCredential)}><span aria-hidden className="i-ri-equalizer-2-line size-4 text-text-tertiary" /><div className="system-sm-semibold text-text-secondary">{t('operation.edit', { ns: 'common' })}</div></DropdownMenuItem>)}{type === CredentialTypeEnum.OAUTH2 && (- <DropdownMenuItem className="h-auto gap-2 py-2" onClick={() => handleAction('change')}>+ <DropdownMenuItem disabled={!canManageCredential} className="h-auto gap-2 py-2" onClick={() => handleAction('change', canManageCredential)}><span aria-hidden className="i-ri-sticky-note-add-line size-4 text-text-tertiary" /><div className="mb-1 system-sm-semibold text-text-secondary">{t('dataSource.notion.changeAuthorizedPages', { ns: 'common' })}</div></DropdownMenuItem>)}<DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" className="h-auto gap-2 py-2" onClick={() => handleAction('delete')}>+ <DropdownMenuItem disabled={!canManageCredential} variant="destructive" className="h-auto gap-2 py-2" onClick={() => handleAction('delete', canManageCredential)}><span aria-hidden className="i-ri-delete-bin-line size-4" /><div className="system-sm-semibold">{t('operation.remove', { ns: 'common' })}diff --git a/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx b/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsxindex bf72eb2afe2..5e9c1db9d89 100644--- a/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx@@ -9,6 +9,7 @@ import Badge from '@/app/components/base/badge'import { HeaderModals } from '@/app/components/plugins/plugin-detail-panel/detail-header/components'import { useDetailHeaderState, usePluginOperations } from '@/app/components/plugins/plugin-detail-panel/detail-header/hooks'import OperationDropdown from '@/app/components/plugins/plugin-detail-panel/operation-dropdown'+import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import { useReadmePanelStore } from '@/app/components/plugins/readme-panel/store'import { PluginSource } from '@/app/components/plugins/types'import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'@@ -49,6 +50,7 @@ const DataSourcePluginActions = ({const locale = useLocale()const readmeTriggerId = useId()const openReadmePanel = useReadmePanelStore(s => s.openReadmePanel)+ const { canManagePlugin, canUpdatePlugin } = usePluginSettingsAccess()const detailHeaderState = usePluginDetailHeader(detail)const {modalStates,@@ -67,6 +69,8 @@ const DataSourcePluginActions = ({modalStates,versionPicker,isFromMarketplace,+ canManagePlugin,+ canUpdatePlugin,onUpdate,})const displayVersion = isFromGitHub ? (detail.meta?.version ?? detail.version) : detail.version@@ -96,7 +100,7 @@ const DataSourcePluginActions = ({<div className="flex shrink-0 items-center gap-1" onClick={e => e.stopPropagation()}>{!!displayVersion && (<PluginVersionPicker- disabled={!isFromMarketplace}+ disabled={!canUpdatePlugin || !isFromMarketplace}isShow={versionPicker.isShow}onShowChange={versionPicker.setIsShow}pluginID={detail.plugin_id}@@ -108,7 +112,7 @@ const DataSourcePluginActions = ({text={(<><div>{displayVersion}</div>- {isFromMarketplace && <span aria-hidden className="ml-1 i-ri-arrow-left-right-line h-3 w-3 shrink-0 text-text-tertiary" />}+ {canUpdatePlugin && isFromMarketplace && <span aria-hidden className="ml-1 i-ri-arrow-left-right-line h-3 w-3 shrink-0 text-text-tertiary" />}</>)}hasRedCornerMark={hasNewVersion}@@ -117,7 +121,7 @@ const DataSourcePluginActions = ({)}/>)}- {(hasNewVersion || isFromGitHub) && (+ {canUpdatePlugin && (hasNewVersion || isFromGitHub) && (<Tooltip><TooltipTriggerdelay={300}@@ -145,6 +149,8 @@ const DataSourcePluginActions = ({onViewReadme={detail.plugin_unique_identifier ? handleViewReadme : undefined}detailUrl={getDetailUrl(detail, locale, theme || 'light')}triggerSize="xs"+ showCheckVersion={canUpdatePlugin}+ showRemove={canManagePlugin}/><HeaderModalsdetail={detail}diff --git a/web/app/components/header/account-setting/index.tsx b/web/app/components/header/account-setting/index.tsxindex 41c8573b17a..3d9b0b1a8c9 100644--- a/web/app/components/header/account-setting/index.tsx+++ b/web/app/components/header/account-setting/index.tsx@@ -3,24 +3,26 @@ import type { AccountSettingTab } from '@/app/components/header/account-setting/import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { ScrollArea } from '@langgenius/dify-ui/scroll-area'-import { useCallback, useState } from 'react'+import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'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 { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'+import { BillingPermission, hasPermission } from '@/utils/permission'+import AccessRulesPage from './access-rules-page'import { ApiBasedExtensionPage } from './api-based-extension-page'import DataSourcePage from './data-source-page-new'import LanguagePage from './language-page'import MembersPage from './members-page'import ModelProviderPage from './model-provider-page'import { useResetModelProviderListExpanded } from './model-provider-page/atoms'+import PermissionsPage from './permissions-page'const iconClassName = `w-4 h-4 mr-2@@ -47,10 +49,15 @@ export default function AccountSetting({onTabChangeAction,}: IAccountSettingProps) {const resetModelProviderListExpanded = useResetModelProviderListExpanded()- const activeMenu = activeTabconst { t } = useTranslation()const { enableBilling, enableReplaceWebAppLogo } = useProviderContext()- const { isCurrentWorkspaceDatasetOperator } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()+ const canManageWorkspaceRoles = hasPermission(workspacePermissionKeys, 'workspace.role.manage')+ const canViewBilling = enableBilling && hasPermission(workspacePermissionKeys, BillingPermission.View)+ const activeMenu = activeTab === ACCOUNT_SETTING_TAB.BILLING && !canViewBilling+ ? ACCOUNT_SETTING_TAB.LANGUAGE+ : activeTab+ const scrollContainerRef = useRef<HTMLDivElement>(null)const settingItems: GroupItem[] = [{@@ -65,6 +72,19 @@ export default function AccountSetting({icon: <span className={cn('i-ri-group-2-line', iconClassName)} />,activeIcon: <span className={cn('i-ri-group-2-fill', iconClassName)} />,},+ {+ key: ACCOUNT_SETTING_TAB.PERMISSIONS,+ name: t('settings.rolesAndPermissions', { ns: 'common' }),+ icon: <span className={cn('i-ri-shield-user-line', iconClassName)} />,+ activeIcon: <span className={cn('i-ri-shield-user-fill', iconClassName)} />,+ },+ {+ key: ACCOUNT_SETTING_TAB.ACCESS_RULES,+ name: t('settings.resourceAccess', { ns: 'common' }),+ description: t('settings.resourceAccessDescription', { ns: 'common' }),+ icon: <span className={cn('i-ri-lock-2-line', iconClassName)} />,+ activeIcon: <span className={cn('i-ri-lock-2-fill', iconClassName)} />,+ },{key: ACCOUNT_SETTING_TAB.BILLING,name: t('settings.billing', { ns: 'common' }),@@ -101,14 +121,16 @@ export default function AccountSetting({const activeItem = settingItems.find(item => item.key === activeMenu)const visibleSettingItems: GroupItem[] = (() => {- if (isCurrentWorkspaceDatasetOperator)- return []-const visibleTabs: AccountSettingTab[] = []visibleTabs.push(ACCOUNT_SETTING_TAB.MEMBERS)- if (enableBilling)+ if (canManageWorkspaceRoles) {+ visibleTabs.push(ACCOUNT_SETTING_TAB.PERMISSIONS)+ visibleTabs.push(ACCOUNT_SETTING_TAB.ACCESS_RULES)+ }++ if (canViewBilling)visibleTabs.push(ACCOUNT_SETTING_TAB.BILLING)if (enableReplaceWebAppLogo || enableBilling)@@ -207,6 +229,7 @@ export default function AccountSetting({<div className="mt-1 system-2xs-medium-uppercase text-text-tertiary">ESC</div></div><ScrollArea+ ref={scrollContainerRef}className="h-full min-h-0 flex-1 bg-components-panel-bg"slotClassNames={{viewport: 'overscroll-contain',@@ -214,10 +237,10 @@ export default function AccountSetting({}}><div className="sticky top-0 z-20 mx-8 flex min-h-[60px] items-end bg-components-panel-bg pt-8 pb-2">- <div className="shrink-0 title-2xl-semi-bold text-text-primary">+ <div className="min-w-0 flex-1 title-2xl-semi-bold text-text-primary">{activeItem?.title ?? activeItem?.name}{activeItem?.description && (- <div className="mt-1 system-sm-regular text-text-tertiary">{activeItem?.description}</div>+ <div className="mt-1 system-sm-regular wrap-break-word whitespace-normal text-text-tertiary">{activeItem?.description}</div>)}</div></div>@@ -229,6 +252,8 @@ export default function AccountSetting({/>)}{activeMenu === ACCOUNT_SETTING_TAB.MEMBERS && <MembersPage />}+ {activeMenu === ACCOUNT_SETTING_TAB.PERMISSIONS && <PermissionsPage containerRef={scrollContainerRef} />}+ {activeMenu === ACCOUNT_SETTING_TAB.ACCESS_RULES && <AccessRulesPage />}{activeMenu === ACCOUNT_SETTING_TAB.BILLING && <BillingPage />}{activeMenu === ACCOUNT_SETTING_TAB.DATA_SOURCE && <DataSourcePage />}{activeMenu === ACCOUNT_SETTING_TAB.API_BASED_EXTENSION && <ApiBasedExtensionPage />}diff --git a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsxindex e1298004879..d618b70cfbb 100644--- a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx@@ -1,4 +1,5 @@import type { AppContextValue } from '@/context/app-context'+import type { Role } from '@/models/access-control'import type { ICurrentWorkspace, Member } from '@/models/common'import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -9,18 +10,33 @@ import { Plan } from '@/app/components/billing/type'import { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import { useUpdateRolesOfMember } from '@/service/access-control/use-member-roles'import { useMembers } from '@/service/use-common'import MembersPage from '../index'vi.mock('@/context/app-context')vi.mock('@/context/provider-context')vi.mock('@/hooks/use-format-time-from-now')+vi.mock('@/service/access-control/use-member-roles')vi.mock('@/service/use-common')const renderMembersPage = () => renderWithSystemFeatures(<MembersPage />, {systemFeatures: { is_email_setup: true },})+const createRole = (overrides: Partial<Role>): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_custom',+ name: 'Role',+ description: '',+ is_builtin: false,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})+vi.mock('../edit-workspace-modal', () => ({default: ({ onCancel }: { onCancel: () => void }) => (<div>@@ -51,17 +67,39 @@ vi.mock('../invited-modal', () => ({</div>),}))-vi.mock('../operation', () => ({- default: ({ member }: { member: Member }) => (- <div>- Member Operation- {' '}- {member.role}- </div>+vi.mock('../role-badges', () => ({+ default: ({ roleNames }: { roleNames: string[] }) => (+ <div data-testid="role-badges">{roleNames.join(',')}</div>),}))-vi.mock('../operation/transfer-ownership', () => ({- default: ({ onOperate }: { onOperate: () => void }) => <button onClick={onOperate}>Transfer ownership</button>,+vi.mock('../member-menu', () => ({+ default: ({+ member,+ isCurrentUser,+ onTransferOwnership,+ canTransferOwnership,+ }: {+ member: Member+ isCurrentUser?: boolean+ onTransferOwnership?: () => void+ canTransferOwnership?: boolean+ }) => (+ <div data-testid="member-menu">+ {member.role !== 'owner' && !isCurrentUser && (+ <div>{`Member Operation ${member.role}`}</div>+ )}+ {canTransferOwnership && member.role === 'owner' && onTransferOwnership && (+ <button+ onClick={(e) => {+ e.stopPropagation()+ onTransferOwnership()+ }}+ >+ Transfer ownership+ </button>+ )}+ </div>+ ),}))vi.mock('../transfer-ownership-modal', () => ({default: ({ onClose }: { onClose: () => void }) => (@@ -71,6 +109,33 @@ vi.mock('../transfer-ownership-modal', () => ({</div>),}))+vi.mock('../member-details-modal', () => ({+ default: ({+ member,+ onClose,+ canAssignRoles,+ onAssignSubmit,+ }: {+ member: Member+ onClose: () => void+ canAssignRoles?: boolean+ onAssignSubmit?: (roles: Role[]) => void+ }) => (+ <div>+ <div>Member Details Modal</div>+ <div data-testid="details-member-name">{member.name}</div>+ <div data-testid="details-can-assign">{String(canAssignRoles)}</div>+ <button onClick={() => onAssignSubmit?.([+ createRole({ id: 'role-next', name: 'Next role' }),+ createRole({ id: 'role-extra', name: 'Extra role' }),+ ])}+ >+ Submit Member Roles+ </button>+ <button onClick={onClose}>Close Member Details Modal</button>+ </div>+ ),+}))vi.mock('@/app/components/billing/upgrade-btn', () => ({default: () => <div>Upgrade Button</div>,}))@@ -78,6 +143,7 @@ vi.mock('@/app/components/billing/upgrade-btn', () => ({describe('MembersPage', () => {const mockRefetch = vi.fn()const mockFormatTimeFromNow = vi.fn(() => 'just now')+ const mockUpdateRolesOfMember = vi.fn()const mockAccounts: Member[] = [{@@ -91,6 +157,7 @@ describe('MembersPage', () => {last_login_at: '1731000000',created_at: '1731000000',status: 'active',+ roles: [createRole({ id: 'owner-role', name: 'Owner', is_builtin: true, role_tag: 'owner' })],},{id: '2',@@ -103,6 +170,7 @@ describe('MembersPage', () => {last_login_at: '1731000000',created_at: '1731000000',status: 'active',+ roles: [createRole({ id: 'admin-role', name: 'Admin', is_builtin: true })],},]@@ -114,12 +182,20 @@ describe('MembersPage', () => {currentWorkspace: { name: 'Test Workspace', role: 'owner' } as ICurrentWorkspace,isCurrentWorkspaceOwner: true,isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['workspace.member.manage'],} as unknown as AppContextValue)vi.mocked(useMembers).mockReturnValue({data: { accounts: mockAccounts },refetch: mockRefetch,} as unknown as ReturnType<typeof useMembers>)+ mockUpdateRolesOfMember.mockImplementation((_payload, options) => {+ options?.onSuccess?.()+ return Promise.resolve()+ })+ vi.mocked(useUpdateRolesOfMember).mockReturnValue({+ mutateAsync: mockUpdateRolesOfMember,+ } as unknown as ReturnType<typeof useUpdateRolesOfMember>)vi.mocked(useProviderContext).mockReturnValue(createMockProviderContextValue({enableBilling: false,@@ -139,6 +215,15 @@ describe('MembersPage', () => {expect(screen.getByText('Admin User'))!.toBeInTheDocument()})+ it('should render fixed name column and flexible role column layout', () => {+ renderMembersPage()++ expect(screen.getByText('common.members.name', { selector: '.system-xs-medium-uppercase' }))!.toHaveClass('w-65', 'shrink-0')+ expect(screen.getByText('common.members.role', { selector: '.system-xs-medium-uppercase' }))!.toHaveClass('min-w-0', 'grow')+ expect(screen.getByTestId('member-row-1').children[0])!.toHaveClass('w-65', 'shrink-0')+ expect(screen.getByTestId('member-row-1').children[2])!.toHaveClass('min-w-0', 'grow')+ })+it('should open and close invite modal', async () => {const user = userEvent.setup()@@ -183,7 +268,7 @@ describe('MembersPage', () => {renderMembersPage()- expect(screen.getByText('common.members.owner'))!.toBeInTheDocument()+ expect(screen.getByText('Owner'))!.toBeInTheDocument()expect(screen.queryByRole('button', { name: /transfer ownership/i })).not.toBeInTheDocument()})@@ -294,6 +379,7 @@ describe('MembersPage', () => {currentWorkspace: { name: 'Test Workspace', role: 'admin' } as ICurrentWorkspace,isCurrentWorkspaceOwner: false,isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['workspace.member.manage'],} as unknown as AppContextValue)renderMembersPage()@@ -308,6 +394,7 @@ describe('MembersPage', () => {currentWorkspace: { name: 'Test Workspace', role: 'admin' } as ICurrentWorkspace,isCurrentWorkspaceOwner: false,isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['workspace.member.manage'],} as unknown as AppContextValue)vi.mocked(useMembers).mockReturnValue({data: {@@ -329,7 +416,6 @@ describe('MembersPage', () => {expect(screen.getByText('Member Operation normal'))!.toBeInTheDocument()expect(screen.getByText('Member Operation dataset_operator'))!.toBeInTheDocument()expect(screen.getByText('Member Operation admin'))!.toBeInTheDocument()- expect(screen.getAllByText('common.members.admin')).toHaveLength(1)expect(screen.queryByText('Member Operation owner')).not.toBeInTheDocument()})@@ -380,7 +466,7 @@ describe('MembersPage', () => {expect(screen.getByText('1'))!.toBeInTheDocument()})- it('should show normal role as fallback for unknown role', () => {+ it('should render role badge names from account roles', () => {vi.mocked(useAppContext).mockReturnValue({userProfile: { email: '[email protected]' },currentWorkspace: { name: 'Test Workspace', role: 'admin' } as ICurrentWorkspace,@@ -394,7 +480,106 @@ describe('MembersPage', () => {renderMembersPage()- expect(screen.getByText('common.members.normal'))!.toBeInTheDocument()+ expect(screen.getByText('Admin'))!.toBeInTheDocument()+ })++ it('should open member details modal when a member row is clicked', async () => {+ const user = userEvent.setup()++ renderMembersPage()++ await user.click(screen.getByTestId('member-row-2'))++ expect(screen.getByText('Member Details Modal'))!.toBeInTheDocument()+ expect(screen.getByTestId('details-member-name'))!.toHaveTextContent('Admin User')++ await user.click(screen.getByRole('button', { name: 'Close Member Details Modal' }))+ expect(screen.queryByText('Member Details Modal')).not.toBeInTheDocument()+ })++ it('should open member details modal via keyboard Enter', async () => {+ const user = userEvent.setup()++ renderMembersPage()++ const row = screen.getByTestId('member-row-2')+ row.focus()+ await user.keyboard('{Enter}')++ expect(screen.getByText('Member Details Modal'))!.toBeInTheDocument()+ })++ it('should not allow assigning roles from member details when target is owner', async () => {+ const user = userEvent.setup()++ renderMembersPage()++ await user.click(screen.getByTestId('member-row-1'))++ expect(screen.getByTestId('details-can-assign'))!.toHaveTextContent('false')+ })++ it('should not allow assigning roles from member details when target is current user', async () => {+ const user = userEvent.setup()+ vi.mocked(useAppContext).mockReturnValue({+ userProfile: { email: '[email protected]' },+ currentWorkspace: { name: 'Test Workspace', role: 'admin' } as ICurrentWorkspace,+ isCurrentWorkspaceOwner: false,+ isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['workspace.member.manage'],+ } as unknown as AppContextValue)++ renderMembersPage()++ await user.click(screen.getByTestId('member-row-2'))++ expect(screen.getByTestId('details-can-assign'))!.toHaveTextContent('false')+ })++ it('should submit only one member role when RBAC is disabled', async () => {+ const user = userEvent.setup()++ renderMembersPage()++ await user.click(screen.getByTestId('member-row-2'))+ await user.click(screen.getByRole('button', { name: 'Submit Member Roles' }))++ expect(mockUpdateRolesOfMember).toHaveBeenCalledWith({+ memberId: '2',+ roleIds: ['role-next'],+ }, expect.any(Object))+ expect(mockRefetch).toHaveBeenCalled()+ expect(screen.getByText('Member Details Modal')).toBeInTheDocument()+ expect(screen.getByTestId('details-member-name')).toHaveTextContent('Admin User')+ })++ it('should submit multiple member roles when RBAC is enabled', async () => {+ const user = userEvent.setup()++ renderWithSystemFeatures(<MembersPage />, {+ systemFeatures: {+ is_email_setup: true,+ rbac_enabled: true,+ },+ })++ await user.click(screen.getByTestId('member-row-2'))+ await user.click(screen.getByRole('button', { name: 'Submit Member Roles' }))++ expect(mockUpdateRolesOfMember).toHaveBeenCalledWith({+ memberId: '2',+ roleIds: ['role-next', 'role-extra'],+ }, expect.any(Object))+ })++ it('should not open member details when clicking the member menu area', async () => {+ const user = userEvent.setup()++ renderMembersPage()++ await user.click(screen.getByRole('button', { name: /transfer ownership/i }))++ expect(screen.queryByText('Member Details Modal')).not.toBeInTheDocument()})it('should show upgrade button when member limit is full', () => {diff --git a/web/app/components/header/account-setting/members-page/__tests__/member-menu.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/member-menu.spec.tsxnew file mode 100644index 00000000000..a780e46ff4e--- /dev/null+++ b/web/app/components/header/account-setting/members-page/__tests__/member-menu.spec.tsx@@ -0,0 +1,152 @@+import type { Role } from '@/models/access-control'+import type { Member } from '@/models/common'+import { toast } from '@langgenius/dify-ui/toast'+import { QueryClient } from '@tanstack/react-query'+import { screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'+import { useUpdateRolesOfMember } from '@/service/access-control/use-member-roles'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'+import { deleteMemberOrCancelInvitation } from '@/service/common'+import { commonQueryKeys } from '@/service/use-common'+import MemberMenu from '../member-menu'++vi.mock('@/service/access-control/use-member-roles')+vi.mock('@/service/access-control/use-workspace-roles')+vi.mock('@/service/common', () => ({+ deleteMemberOrCancelInvitation: vi.fn(),+}))+vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ success: vi.fn(),+ },+}))++const createRole = (overrides: Partial<Role>): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_custom',+ name: 'Role',+ description: '',+ is_builtin: false,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})++const roles = [+ createRole({ id: 'role-1', name: 'First role' }),+ createRole({ id: 'role-2', name: 'Second role' }),+]++const member: Member = {+ id: 'member-1',+ name: 'Member User',+ email: '[email protected]',+ avatar: '',+ avatar_url: '',+ role: 'normal',+ roles: [roles[0]!],+ last_active_at: '1731000000',+ last_login_at: '1731000000',+ created_at: '1731000000',+ status: 'active',+}++describe('MemberMenu', () => {+ const mockUpdateRolesOfMember = vi.fn()++ const createQueryClient = () => new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ staleTime: Infinity,+ },+ mutations: {+ retry: false,+ },+ },+ })++ beforeEach(() => {+ vi.clearAllMocks()+ mockUpdateRolesOfMember.mockResolvedValue(undefined)+ vi.mocked(deleteMemberOrCancelInvitation).mockResolvedValue({ result: 'success' })+ vi.mocked(useUpdateRolesOfMember).mockReturnValue({+ mutateAsync: mockUpdateRolesOfMember,+ } as unknown as ReturnType<typeof useUpdateRolesOfMember>)+ vi.mocked(useWorkspaceRoleList).mockReturnValue({+ data: {+ pages: [{+ data: roles,+ pagination: {+ total_count: 2,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+ },+ }],+ pageParams: [1],+ },+ isLoading: false,+ error: null,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ } as unknown as ReturnType<typeof useWorkspaceRoleList>)+ })++ it('should submit only one selected role from the assign modal when RBAC is disabled', async () => {+ const user = userEvent.setup()++ renderWithSystemFeatures(+ <MemberMenu+ member={member}+ isCurrentUser={false}+ allowMultipleRoles={false}+ />,+ {+ systemFeatures: {+ rbac_enabled: false,+ },+ },+ )++ await user.click(screen.getByRole('button', { name: /members\.memberActions/i }))+ await user.click(screen.getByRole('menuitem', { name: /members\.assignRoles/i }))+ await user.click(screen.getByRole('radio', { name: /Second role/i }))+ await user.click(screen.getByRole('button', { name: /common\.operation\.confirm/i }))++ expect(mockUpdateRolesOfMember).toHaveBeenCalledWith({+ memberId: 'member-1',+ roleIds: ['role-2'],+ }, expect.any(Object))+ })++ it('should refresh and invalidate members after removing a member', async () => {+ const user = userEvent.setup()+ const queryClient = createQueryClient()+ const membersQueryKey = [...commonQueryKeys.members, 'en-US']+ queryClient.setQueryData(membersQueryKey, { accounts: [member] })++ renderWithSystemFeatures(+ <MemberMenu+ member={member}+ isCurrentUser={false}+ />,+ {+ queryClient,+ },+ )++ await user.click(screen.getByRole('button', { name: /members\.memberActions/i }))+ await user.click(screen.getByRole('menuitem', { name: /members\.removeFromTeam/i }))++ expect(deleteMemberOrCancelInvitation).toHaveBeenCalledWith({+ url: '/workspaces/current/members/member-1',+ })+ expect(queryClient.getQueryState(membersQueryKey)?.isInvalidated).toBe(true)+ expect(toast.success).toHaveBeenCalledWith('common.actionMsg.modifiedSuccessfully')+ })+})diff --git a/web/app/components/header/account-setting/members-page/__tests__/role-badges.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/role-badges.spec.tsxnew file mode 100644index 00000000000..3135bc4256f--- /dev/null+++ b/web/app/components/header/account-setting/members-page/__tests__/role-badges.spec.tsx@@ -0,0 +1,22 @@+import { render, screen } from '@testing-library/react'+import RoleBadges from '../role-badges'++describe('RoleBadges', () => {+ describe('Rendering', () => {+ it('should expose visible role names as badge titles', () => {+ render(<RoleBadges roleNames={['Very long custom role name', 'Admin']} />)++ expect(screen.getByTitle('Very long custom role name'))!.toHaveTextContent('Very long custom role name')+ expect(screen.getByTitle('Admin'))!.toHaveTextContent('Admin')+ })++ it('should render overflow count for hidden roles', () => {+ render(<RoleBadges roleNames={['Owner', 'Admin', 'Editor']} max={2} />)++ expect(screen.getByTitle('Owner'))!.toBeInTheDocument()+ expect(screen.getByTitle('Admin'))!.toBeInTheDocument()+ expect(screen.getByText('+1'))!.toBeInTheDocument()+ expect(screen.queryByTitle('Editor')).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/header/account-setting/members-page/assign-roles-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/assign-roles-modal/__tests__/index.spec.tsxnew file mode 100644index 00000000000..4e6113f9828--- /dev/null+++ b/web/app/components/header/account-setting/members-page/assign-roles-modal/__tests__/index.spec.tsx@@ -0,0 +1,72 @@+import type { Role } from '@/models/access-control'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'+import AssignRolesModal from '../index'++vi.mock('@/service/access-control/use-workspace-roles')++const createRole = (overrides: Partial<Role>): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_custom',+ name: 'Role',+ description: '',+ is_builtin: false,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})++const roles = [+ createRole({ id: 'role-1', name: 'First role' }),+ createRole({ id: 'role-2', name: 'Second role' }),+]++describe('AssignRolesModal', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(useWorkspaceRoleList).mockReturnValue({+ data: {+ pages: [{+ data: roles,+ pagination: {+ total_count: 2,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+ },+ }],+ pageParams: [1],+ },+ isLoading: false,+ error: null,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ } as unknown as ReturnType<typeof useWorkspaceRoleList>)+ })++ describe('Role selection', () => {+ it('should disable confirm when the last selected role is unchecked', async () => {+ const user = userEvent.setup()++ render(+ <AssignRolesModal+ selectedRoles={[roles[0]!]}+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ const confirmButton = screen.getByRole('button', { name: /common\.operation\.confirm/i })++ expect(confirmButton).toBeEnabled()++ await user.click(screen.getByRole('checkbox', { name: /First role/i }))++ expect(confirmButton).toBeDisabled()+ })+ })+})diff --git a/web/app/components/header/account-setting/members-page/assign-roles-modal/index.tsx b/web/app/components/header/account-setting/members-page/assign-roles-modal/index.tsxnew file mode 100644index 00000000000..e679b630e87--- /dev/null+++ b/web/app/components/header/account-setting/members-page/assign-roles-modal/index.tsx@@ -0,0 +1,116 @@+'use client'++import type { Role } from '@/models/access-control'+import { Button } from '@langgenius/dify-ui/button'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import WorkspaceRoleCheckboxList from '../../workspace-role-checkbox-list'++type AssignRolesModalProps = {+ selectedRoles: Role[]+ allowMultipleRoles?: boolean+ onClose: () => void+ onSubmit: (roles: Role[]) => void+}++type AssignRolesModalBodyProps = AssignRolesModalProps++const AssignRolesModalBody = ({+ selectedRoles,+ allowMultipleRoles = true,+ onClose,+ onSubmit,+}: AssignRolesModalBodyProps) => {+ const { t } = useTranslation()+ const [selected, setSelected] = useState(selectedRoles)+ const selectedRoleIds = selected.map(role => role.id)+ const isConfirmDisabled = selected.length === 0++ const handleConfirm = () => {+ if (isConfirmDisabled)+ return++ onSubmit(selected)+ onClose()+ }++ return (+ <DialogContent+ className="flex h-121 w-120 flex-col overflow-hidden p-0"+ backdropProps={{ forceRender: true }}+ >+ <div className="relative shrink-0 px-6 pt-6 pb-4">+ <DialogCloseButton />+ <div className="pr-8">+ <DialogTitle className="system-xl-semibold text-text-primary">+ {t('members.assignRolesModal.title', { ns: 'common', defaultValue: 'Assign Roles' })}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('members.assignRolesModal.description', {+ ns: 'common',+ defaultValue:+ 'Select roles to assign to this member. All permissions from selected roles will be combined.',+ })}+ </DialogDescription>+ </div>+ </div>++ <WorkspaceRoleCheckboxList+ selectedRoleIds={selectedRoleIds}+ selectedRoles={selected}+ allowMultipleRoles={allowMultipleRoles}+ onSelectedRolesChange={setSelected}+ />++ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-divider-subtle px-6 py-4">+ <div className="system-xs-regular text-text-tertiary">+ {t('members.assignRolesModal.selectedCount', {+ ns: 'common',+ count: selected.length,+ })}+ </div>+ <div className="flex items-center gap-2">+ <Button variant="secondary" onClick={onClose}>+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ <Button variant="primary" disabled={isConfirmDisabled} onClick={handleConfirm}>+ {t('operation.confirm', { ns: 'common' })}+ </Button>+ </div>+ </div>+ </DialogContent>+ )+}++const AssignRolesModal = ({+ selectedRoles,+ allowMultipleRoles = true,+ onClose,+ onSubmit,+}: AssignRolesModalProps) => {+ return (+ <Dialog+ open+ onOpenChange={(nextOpen) => {+ if (!nextOpen)+ onClose()+ }}+ >+ <AssignRolesModalBody+ selectedRoles={selectedRoles}+ allowMultipleRoles={allowMultipleRoles}+ onClose={onClose}+ onSubmit={onSubmit}+ />+ </Dialog>+ )+}++export default AssignRolesModaldiff --git a/web/app/components/header/account-setting/members-page/index.tsx b/web/app/components/header/account-setting/members-page/index.tsxindex 568413780ae..b9f42d4f1cc 100644--- a/web/app/components/header/account-setting/members-page/index.tsx+++ b/web/app/components/header/account-setting/members-page/index.tsx@@ -1,9 +1,10 @@'use client'+import type { Role } from '@/models/access-control'import type { InvitationResult, Member } from '@/models/common'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { toast } from '@langgenius/dify-ui/toast'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useSuspenseQuery } from '@tanstack/react-query'-import { useState } from 'react'+import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { NUM_INFINITE } from '@/app/components/billing/config'import { Plan } from '@/app/components/billing/type'@@ -12,32 +13,26 @@ import { useAppContext } from '@/context/app-context'import { useLocale } from '@/context/i18n'import { useProviderContext } from '@/context/provider-context'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'-import { LanguagesSupported } from '@/i18n-config/language'+import { getAccessControlTemplateLanguage, LanguagesSupported } from '@/i18n-config/language'+import { useUpdateRolesOfMember } from '@/service/access-control/use-member-roles'import { useMembers } from '@/service/use-common'+import { hasPermission } from '@/utils/permission'import EditWorkspaceModal from './edit-workspace-modal'import InviteButton from './invite-button'import InviteModal from './invite-modal'import InvitedModal from './invited-modal'-import Operation from './operation'-import TransferOwnership from './operation/transfer-ownership'+import MemberDetailsModal from './member-details-modal'+import MemberRow from './member-row'import TransferOwnershipModal from './transfer-ownership-modal'const MembersPage = () => {const { t } = useTranslation()- const RoleMap = {- owner: t('members.owner', { ns: 'common' }),- admin: t('members.admin', { ns: 'common' }),- editor: t('members.editor', { ns: 'common' }),- dataset_operator: t('members.datasetOperator', { ns: 'common' }),- normal: t('members.normal', { ns: 'common' }),- }const locale = useLocale()+ const language = getAccessControlTemplateLanguage(locale)- const { userProfile, currentWorkspace, isCurrentWorkspaceOwner, isCurrentWorkspaceManager } = useAppContext()- const { data, refetch } = useMembers()+ const { userProfile, currentWorkspace, isCurrentWorkspaceOwner, workspacePermissionKeys } = useAppContext()+ const { data, refetch } = useMembers(language)const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const { formatTimeFromNow } = useFormatTimeFromNow()const [inviteModalVisible, setInviteModalVisible] = useState(false)const [invitationResults, setInvitationResults] = useState<InvitationResult[]>([])const [invitedModalVisible, setInvitedModalVisible] = useState(false)@@ -47,19 +42,48 @@ const MembersPage = () => {const isMemberFull = enableBilling && isNotUnlimitedMemberPlan && accounts.length >= plan.total.teamMembersconst [editWorkspaceModalVisible, setEditWorkspaceModalVisible] = useState(false)const [showTransferOwnershipModal, setShowTransferOwnershipModal] = useState(false)- const canOperateMember = (account: Member) => {- if (isCurrentWorkspaceOwner)- return account.role !== 'owner'+ const [detailsMember, setDetailsMember] = useState<Member | null>(null)++ const canManageMembers = hasPermission(workspacePermissionKeys, 'workspace.member.manage')++ const handleOpenDetails = useCallback((member: Member) => {+ setDetailsMember(member)+ }, [])++ const handleCloseDetails = useCallback(() => {+ setDetailsMember(null)+ }, [])++ const { mutateAsync: updateRolesOfMember } = useUpdateRolesOfMember()++ const handleAssignRolesSubmit = (roles: Role[]) => {+ const roleIds = systemFeatures.rbac_enabled+ ? roles.map(role => role.id)+ : roles.slice(0, 1).map(role => role.id)- return currentWorkspace.role === 'admin' && account.role !== 'owner' && account.email !== userProfile.email+ updateRolesOfMember({+ memberId: detailsMember!.id,+ roleIds,+ }, {+ onSuccess: () => {+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))+ refetch()+ },+ })}+ const handleTransferOwnership = useCallback(() => {+ setShowTransferOwnershipModal(true)+ }, [])+return (<><div className="flex flex-col"><div className="mb-6 flex items-center gap-3 rounded-xl border-t-[0.5px] border-l-[0.5px] border-divider-subtle bg-linear-to-r from-background-gradient-bg-fill-chat-bg-2 to-background-gradient-bg-fill-chat-bg-1 py-2 pr-5 pl-2"><div className="flex h-12 w-12 items-center justify-center rounded-xl bg-components-icon-bg-blue-solid text-[20px]">- <span className="bg-linear-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text font-semibold text-shadow-shadow-1 uppercase opacity-90">{currentWorkspace?.name[0]?.toLocaleUpperCase()}</span>+ <span className="bg-linear-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text font-semibold text-shadow-shadow-1 uppercase opacity-90">+ {currentWorkspace?.name[0]?.toLocaleUpperCase()}+ </span></div><div className="grow"><div className="flex items-center gap-1 system-md-semibold text-text-secondary">@@ -120,48 +144,29 @@ const MembersPage = () => {<UpgradeBtn className="mr-2" loc="member-invite" />)}<div className="shrink-0">- {isCurrentWorkspaceManager && <InviteButton disabled={isMemberFull} onClick={() => setInviteModalVisible(true)} />}+ {canManageMembers && <InviteButton disabled={isMemberFull} onClick={() => setInviteModalVisible(true)} />}</div></div><div className="overflow-visible lg:overflow-visible">- <div className="flex min-w-[480px] items-center border-b border-divider-regular py-[7px]">- <div className="grow px-3 system-xs-medium-uppercase text-text-tertiary">{t('members.name', { ns: 'common' })}</div>- <div className="w-[120px] shrink-0 px-2 system-xs-medium-uppercase text-text-tertiary">{t('members.lastActive', { ns: 'common' })}</div>- <div className="w-[96px] shrink-0 px-2 system-xs-medium-uppercase text-text-tertiary">{t('members.role', { ns: 'common' })}</div>+ <div className="flex min-w-120 items-center border-b border-divider-regular py-1.75">+ <div className="w-65 shrink-0 px-3 system-xs-medium-uppercase text-text-tertiary">{t('members.name', { ns: 'common' })}</div>+ <div className="w-30 shrink-0 system-xs-medium-uppercase text-text-tertiary">{t('members.lastActive', { ns: 'common' })}</div>+ <div className="min-w-0 grow px-3 system-xs-medium-uppercase text-text-tertiary">{t('members.role', { ns: 'common' })}</div></div>- <div className="relative min-w-[480px]">- {- accounts.map(account => (- <div key={account.id} className="flex border-b border-divider-subtle">- <div className="flex grow items-center px-3 py-2">- <Avatar avatar={account.avatar_url} size="sm" className="mr-2" name={account.name} />- <div className="">- <div className="system-sm-medium text-text-secondary">- {account.name}- {account.status === 'pending' && <span className="ml-1 system-xs-medium text-text-warning">{t('members.pending', { ns: 'common' })}</span>}- {userProfile.email === account.email && <span className="system-xs-regular text-text-tertiary">{t('members.you', { ns: 'common' })}</span>}- </div>- <div className="system-xs-regular text-text-tertiary">{account.email}</div>- </div>- </div>- <div className="flex w-[120px] shrink-0 items-center px-2 py-2 system-sm-regular text-text-secondary">{formatTimeFromNow(Number((account.last_active_at || account.created_at)) * 1000)}</div>- <div className="flex w-[96px] shrink-0 items-center">- {isCurrentWorkspaceOwner && account.role === 'owner' && isAllowTransferWorkspace && (- <TransferOwnership onOperate={() => setShowTransferOwnershipModal(true)}></TransferOwnership>- )}- {isCurrentWorkspaceOwner && account.role === 'owner' && !isAllowTransferWorkspace && (- <div className="px-3 system-sm-regular text-text-secondary">{RoleMap[account.role] || RoleMap.normal}</div>- )}- {account.role !== 'owner' && canOperateMember(account) && (- <Operation member={account} operatorRole={currentWorkspace.role} onOperate={refetch} />- )}- {account.role !== 'owner' && !canOperateMember(account) && (- <div className="px-3 system-sm-regular text-text-secondary">{RoleMap[account.role] || RoleMap.normal}</div>- )}- </div>- </div>- ))- }+ <div className="relative min-w-120">+ {accounts.map(account => (+ <MemberRow+ key={account.id}+ member={account}+ roles={account.roles}+ isCurrentUser={userProfile.email === account.email}+ canManage={canManageMembers}+ canTransferOwnership={isCurrentWorkspaceOwner && isAllowTransferWorkspace}+ allowMultipleRoles={systemFeatures.rbac_enabled}+ onOpenDetails={handleOpenDetails}+ onTransferOwnership={handleTransferOwnership}+ />+ ))}</div></div></div>@@ -199,6 +204,19 @@ const MembersPage = () => {onClose={() => setShowTransferOwnershipModal(false)}/>)}+ {detailsMember && (+ <MemberDetailsModal+ member={detailsMember}+ canAssignRoles={+ canManageMembers+ && detailsMember.role !== 'owner'+ && userProfile.email !== detailsMember.email+ }+ allowMultipleRoles={systemFeatures.rbac_enabled}+ onClose={handleCloseDetails}+ onAssignSubmit={handleAssignRolesSubmit}+ />+ )}</>)}diff --git a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsxindex 9b262a3f31c..40f5c84a93e 100644--- a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx@@ -1,10 +1,13 @@import type { InvitationResponse } from '@/models/common'import { toast } from '@langgenius/dify-ui/toast'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { vi } from 'vitest'import { useProviderContextSelector } from '@/context/provider-context'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'import { inviteMember } from '@/service/common'+import { commonQueryKeys } from '@/service/use-common'import InviteModal from '../index'const { mockToastError } = vi.hoisted(() => ({@@ -18,6 +21,7 @@ vi.mock('@/context/provider-context', () => ({})),}))vi.mock('@/service/common')+vi.mock('@/service/access-control/use-workspace-roles')vi.mock('@langgenius/dify-ui/toast', () => ({toast: {error: mockToastError,@@ -47,21 +51,85 @@ describe('InviteModal', () => {const mockOnSend = vi.fn()const mockRefreshLicenseLimit = vi.fn()+ const createQueryClient = () => new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ staleTime: Infinity,+ },+ mutations: {+ retry: false,+ },+ },+ })+beforeEach(() => {vi.clearAllMocks()+ vi.mocked(useWorkspaceRoleList).mockReturnValue({+ data: {+ pages: [{+ data: [+ {+ id: 'admin',+ tenant_id: 'tenant-id',+ type: 'workspace',+ category: 'global_system_default',+ name: 'Admin',+ description: 'Can manage workspace settings',+ is_builtin: true,+ permission_keys: [],+ role_tag: '',+ },+ {+ id: 'normal',+ tenant_id: 'tenant-id',+ type: 'workspace',+ category: 'global_system_default',+ name: 'Normal',+ description: 'Can use apps',+ is_builtin: true,+ permission_keys: [],+ role_tag: '',+ },+ ],+ pagination: {+ total_count: 2,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+ },+ }],+ pageParams: [1],+ },+ isLoading: false,+ error: null,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ } as unknown as ReturnType<typeof useWorkspaceRoleList>)+vi.mocked(useProviderContextSelector).mockImplementation(selector => selector({licenseLimit: { workspace_members: { size: 5, limit: 10 } },refreshLicenseLimit: mockRefreshLicenseLimit,} as unknown as Parameters<typeof selector>[0]))})- const renderModal = (isEmailSetup = true) => render(- <InviteModal isEmailSetup={isEmailSetup} onCancel={mockOnCancel} onSend={mockOnSend} />,- )+ const renderModal = (isEmailSetup = true, queryClient = createQueryClient()) => ({+ queryClient,+ ...render(+ <QueryClientProvider client={queryClient}>+ <InviteModal isEmailSetup={isEmailSetup} onCancel={mockOnCancel} onSend={mockOnSend} />+ </QueryClientProvider>,+ ),+ })const fillEmails = (value: string) => {fireEvent.change(screen.getByTestId('mock-email-input'), { target: { value } })}+ const selectAdminRole = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(screen.getByRole('button', { name: /members\.selectRole/i }))+ await user.click(screen.getByRole('menuitemradio', { name: /Admin/i }))+ }it('should render invite modal content', async () => {renderModal()@@ -76,10 +144,15 @@ describe('InviteModal', () => {expect(await screen.findByText(/members\.emailNotSetup$/i)).toBeInTheDocument()})- it('should enable send button after entering an email', async () => {+ it('should enable send button after entering an email and selecting a role', async () => {renderModal()fillEmails('[email protected]')+ expect(screen.getByRole('button', { name: /members\.sendInvite/i })).toBeDisabled()++ const user = userEvent.setup()+ await selectAdminRole(user)+expect(screen.getByRole('button', { name: /members\.sendInvite/i })).toBeEnabled()})@@ -90,6 +163,7 @@ describe('InviteModal', () => {renderModal()fillEmails('[email protected]')+ await selectAdminRole(user)await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))await waitFor(() => {@@ -109,6 +183,7 @@ describe('InviteModal', () => {renderModal()fillEmails('[email protected]')+ await selectAdminRole(user)await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))await waitFor(() => {@@ -119,6 +194,52 @@ describe('InviteModal', () => {})})+ it('should submit the selected workspace role id', async () => {+ const user = userEvent.setup()+ vi.mocked(inviteMember).mockResolvedValue({+ result: 'success',+ invitation_results: [],+ } as InvitationResponse)++ renderModal()++ fillEmails('[email protected]')+ await selectAdminRole(user)+ await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))++ await waitFor(() => {+ expect(inviteMember).toHaveBeenCalledWith({+ url: '/workspaces/current/members/invite-email',+ body: {+ emails: ['[email protected]'],+ role: 'admin',+ language: 'en-US',+ },+ })+ })+ })++ it('should invalidate members after successful submission', async () => {+ const user = userEvent.setup()+ const queryClient = createQueryClient()+ const membersQueryKey = [...commonQueryKeys.members, 'en-US']+ queryClient.setQueryData(membersQueryKey, { accounts: [] })+ vi.mocked(inviteMember).mockResolvedValue({+ result: 'success',+ invitation_results: [],+ } as InvitationResponse)++ renderModal(true, queryClient)++ fillEmails('[email protected]')+ await selectAdminRole(user)+ await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))++ await waitFor(() => {+ expect(queryClient.getQueryState(membersQueryKey)?.isInvalidated).toBe(true)+ })+ })+it('should keep send button disabled when license limit is exceeded', async () => {vi.mocked(useProviderContextSelector).mockImplementation(selector => selector({licenseLimit: { workspace_members: { size: 10, limit: 10 } },@@ -147,6 +268,7 @@ describe('InviteModal', () => {// Use an email that passes basic validation but fails our strict regex (needs 2+ char TLD)fillEmails('[email protected]')+ await selectAdminRole(user)await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))expect(toast.error).toHaveBeenCalledWith('common.members.emailInvalid')@@ -200,6 +322,7 @@ describe('InviteModal', () => {renderModal()fillEmails('[email protected]')+ await selectAdminRole(user)await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))await waitFor(() => {@@ -235,6 +358,7 @@ describe('InviteModal', () => {renderModal()fillEmails('[email protected]')+ await selectAdminRole(user)const sendBtn = screen.getByRole('button', { name: /members\.sendInvite/i })@@ -283,6 +407,7 @@ describe('InviteModal', () => {renderModal()fillEmails('[email protected]')+ await selectAdminRole(user)const sendBtn = screen.getByRole('button', { name: /members\.sendInvite/i })diff --git a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/role-selector.spec.tsx b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/role-selector.spec.tsxindex 1284a7abb19..2fd8e2a91d7 100644--- a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/role-selector.spec.tsx+++ b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/role-selector.spec.tsx@@ -1,101 +1,192 @@-import { render, screen, waitFor, within } from '@testing-library/react'+import type { Role, RoleListResponse } from '@/models/access-control'+import { act, render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'import { vi } from 'vitest'-import { createMockProviderContextValue } from '@/__mocks__/provider-context'-import { useProviderContext } from '@/context/provider-context'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'import RoleSelector from '../role-selector'-vi.mock('@/context/provider-context')+vi.mock('@/service/access-control/use-workspace-roles')++const createRole = (overrides: Partial<Role>): Role => ({+ id: overrides.id ?? overrides.name ?? 'role-id',+ tenant_id: 'tenant-id',+ type: 'workspace',+ category: 'global_system_default',+ name: overrides.name ?? 'Role',+ description: overrides.description ?? '',+ is_builtin: overrides.is_builtin ?? true,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})++const rolePages: RoleListResponse[] = [+ {+ data: [+ createRole({ id: 'admin', name: 'Admin', description: 'Can manage workspace settings' }),+ createRole({ id: 'editor', name: 'Editor', description: 'Can build and edit apps' }),+ createRole({ id: 'normal', name: 'Normal', description: 'Can use apps' }),+ ],+ pagination: {+ total_count: 3,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+ },+ },+]++const mockUseWorkspaceRoleList = ({+ pages = rolePages,+ isLoading = false,+ hasNextPage = false,+ isFetchingNextPage = false,+ fetchNextPage = vi.fn(),+}: {+ pages?: RoleListResponse[]+ isLoading?: boolean+ hasNextPage?: boolean+ isFetchingNextPage?: boolean+ fetchNextPage?: () => void+} = {}) => {+ vi.mocked(useWorkspaceRoleList).mockReturnValue({+ data: { pages, pageParams: [1] },+ isLoading,+ error: null,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ } as unknown as ReturnType<typeof useWorkspaceRoleList>)+}type WrapperProps = {- initialRole?: 'normal' | 'editor' | 'admin' | 'dataset_operator'+ initialRole?: string}const RoleSelectorWrapper = ({ initialRole = 'normal' }: WrapperProps) => {- const [role, setRole] = useState<'normal' | 'editor' | 'admin' | 'dataset_operator'>(initialRole)+ const [role, setRole] = useState(initialRole)return <RoleSelector value={role} onChange={setRole} />}-const getTrigger = () => screen.getByRole('button', { name: /members\.invitedAsRole/i })-const getRoleDialog = () => screen.getByRole('dialog')-const getRoleOption = (role: string) => within(getRoleDialog()).getByRole('button', { name: new RegExp(`common\\.members\\.${role}`, 'i') })+const getTrigger = () => screen.getByRole('button', { name: /members\.(invitedAsRole|selectRole)/i })+const getRoleMenu = () => screen.getByRole('menu')+const getRoleOption = (role: string) => within(getRoleMenu()).getByRole('menuitemradio', { name: new RegExp(role, 'i') })describe('RoleSelector', () => {beforeEach(() => {vi.clearAllMocks()- vi.mocked(useProviderContext).mockReturnValue(createMockProviderContextValue({- datasetOperatorEnabled: true,- }))+ mockUseWorkspaceRoleList()})- it('should show current role in trigger text', () => {+ it('should show current role name in trigger text', () => {render(<RoleSelectorWrapper initialRole="admin" />)- // members.invitedAsRole is the translation key- expect(screen.getByText(/members\.invitedAsRole/i)).toBeInTheDocument()+ expect(screen.getByText(/members\.invitedAsRole:\{"role":"Admin"\}/i)).toBeInTheDocument()+ })++ it('should ask users to select a role when no role is selected', () => {+ render(<RoleSelectorWrapper initialRole="" />)++ expect(screen.getByText(/members\.selectRole/i)).toBeInTheDocument()+ expect(screen.queryByText(/members\.invitedAsRole:\{"role":""\}/i)).not.toBeInTheDocument()})it('should toggle dropdown when trigger is clicked', async () => {const user = userEvent.setup()render(<RoleSelectorWrapper />)- const trigger = getTrigger()-- // Open- await user.click(trigger)- expect(getRoleOption('normal')).toBeInTheDocument()+ await user.click(getTrigger())+ expect(getRoleOption('Normal')).toBeInTheDocument()- // Close- await user.click(trigger)+ await user.click(getTrigger())await waitFor(() => {- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()})})- it('should show checkmark for selected role', async () => {+ it('should show checkmark state for selected role', async () => {const user = userEvent.setup()render(<RoleSelectorWrapper initialRole="editor" />)await user.click(getTrigger())- expect(getRoleOption('editor')).toHaveAttribute('aria-pressed', 'true')+ expect(getRoleOption('Editor')).toHaveAttribute('aria-checked', 'true')})- it.each([- ['normal'],- ['editor'],- ['admin'],- ['datasetOperator'],- ])('should update selected role after user chooses %s', async (roleKey) => {+ it('should update selected role name after user chooses a role', async () => {const user = userEvent.setup()- render(<RoleSelectorWrapper initialRole="normal" />)+ render(<RoleSelectorWrapper initialRole="Normal" />)await user.click(getTrigger())- await user.click(getRoleOption(roleKey))+ await user.click(getRoleOption('Admin'))- // Verify dropdown closedawait waitFor(() => {- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()})- // Verify trigger text updated (using translation key pattern from global mock)- expect(screen.getByText(/members\.invitedAsRole/i)).toBeInTheDocument()+ expect(screen.getByText(/members\.invitedAsRole:\{"role":"Admin"\}/i)).toBeInTheDocument()})- it('should hide dataset operator option when feature is disabled', async () => {+ it('should load more roles when scrolling reaches the list anchor', async () => {const user = userEvent.setup()+ const fetchNextPage = vi.fn()+ const callbacks: IntersectionObserverCallback[] = []+ const originalIntersectionObserver = globalThis.IntersectionObserver++ globalThis.IntersectionObserver = class {+ readonly root: Element | Document | null = null+ readonly rootMargin: string = ''+ readonly scrollMargin: string = ''+ readonly thresholds: ReadonlyArray<number> = []- vi.mocked(useProviderContext).mockReturnValue(createMockProviderContextValue({- datasetOperatorEnabled: false,- }))+ constructor(callback: IntersectionObserverCallback) {+ callbacks.push(callback)+ }++ observe() { /* noop */ }+ unobserve() { /* noop */ }+ disconnect() { /* noop */ }+ takeRecords(): IntersectionObserverEntry[] { return [] }+ }++ mockUseWorkspaceRoleList({ hasNextPage: true, fetchNextPage })render(<RoleSelectorWrapper />)+ await user.click(getTrigger())+ await waitFor(() => {+ expect(callbacks).toHaveLength(1)+ })++ await act(async () => {+ callbacks[0]!([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver)+ })++ expect(fetchNextPage).toHaveBeenCalledTimes(1)++ globalThis.IntersectionObserver = originalIntersectionObserver+ })++ it('should render an empty state when there are no roles', async () => {+ const user = userEvent.setup()+ mockUseWorkspaceRoleList({+ pages: [{+ data: [],+ pagination: {+ total_count: 0,+ per_page: 20,+ current_page: 1,+ total_pages: 0,+ },+ }],+ })++ render(<RoleSelectorWrapper initialRole="" />)+await user.click(getTrigger())- expect(within(getRoleDialog()).queryByRole('button', { name: /common\.members\.datasetOperator/i })).not.toBeInTheDocument()- expect(getRoleOption('normal')).toBeInTheDocument()+ expect(within(getRoleMenu()).getByText(/dynamicSelect\.noData/i)).toBeInTheDocument()})})diff --git a/web/app/components/header/account-setting/members-page/invite-modal/index.tsx b/web/app/components/header/account-setting/members-page/invite-modal/index.tsxindex d80b93cdb33..d6fd5adf31a 100644--- a/web/app/components/header/account-setting/members-page/invite-modal/index.tsx+++ b/web/app/components/header/account-setting/members-page/invite-modal/index.tsx@@ -1,10 +1,10 @@'use client'-import type { RoleKey } from './role-selector'import type { InvitationResult } from '@/models/common'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'import { toast } from '@langgenius/dify-ui/toast'+import { useQueryClient } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -13,6 +13,7 @@ import { emailRegex } from '@/config'import { useLocale } from '@/context/i18n'import { useProviderContextSelector } from '@/context/provider-context'import { inviteMember } from '@/service/common'+import { commonQueryKeys } from '@/service/use-common'import RoleSelector from './role-selector'import 'react-multi-email/dist/style.css'@@ -28,6 +29,7 @@ const InviteModal = ({onSend,}: IInviteModalProps) => {const { t } = useTranslation()+ const queryClient = useQueryClient()const licenseLimit = useProviderContextSelector(s => s.licenseLimit)const refreshLicenseLimit = useProviderContextSelector(s => s.refreshLicenseLimit)const [emails, setEmails] = useState<string[]>([])@@ -36,7 +38,7 @@ const InviteModal = ({const isLimitExceeded = isLimited && (usedSize > licenseLimit.workspace_members.limit)const locale = useLocale()- const [role, setRole] = useState<RoleKey>('normal')+ const [role, setRole] = useState<string>('')const [isSubmitting, {setTrue: setIsSubmitting,@@ -56,6 +58,7 @@ const InviteModal = ({if (result === 'success') {refreshLicenseLimit()+ void queryClient.invalidateQueries({ queryKey: commonQueryKeys.members })onCancel()onSend(invitation_results)}@@ -66,7 +69,7 @@ const InviteModal = ({toast.error(t('members.emailInvalid', { ns: 'common' }))}setIsSubmitted()- }, [isLimitExceeded, emails, role, locale, onCancel, onSend, t, isSubmitting, refreshLicenseLimit, setIsSubmitted, setIsSubmitting])+ }, [isLimitExceeded, emails, role, locale, onCancel, onSend, t, isSubmitting, refreshLicenseLimit, queryClient, setIsSubmitted, setIsSubmitting])return (<Dialog@@ -78,7 +81,7 @@ const InviteModal = ({><DialogContentbackdropProps={{ forceRender: true }}- className="w-[400px] px-8 py-6"+ className="w-100 overflow-visible px-8 py-6"><DialogCloseButton className="top-6 right-8" /><div className="mb-2 pr-8">@@ -144,7 +147,7 @@ const InviteModal = ({tabIndex={0}className="w-full"onClick={handleSend}- disabled={!emails.length || isLimitExceeded || isSubmitting}+ disabled={!emails.length || !role || isLimitExceeded || isSubmitting}variant="primary">{t('members.sendInvite', { ns: 'common' })}diff --git a/web/app/components/header/account-setting/members-page/invite-modal/role-selector.tsx b/web/app/components/header/account-setting/members-page/invite-modal/role-selector.tsxindex af821e3bdef..36cf845acb8 100644--- a/web/app/components/header/account-setting/members-page/invite-modal/role-selector.tsx+++ b/web/app/components/header/account-setting/members-page/invite-modal/role-selector.tsx@@ -1,138 +1,164 @@import { cn } from '@langgenius/dify-ui/cn'import {- Popover,- PopoverContent,- PopoverTrigger,-} from '@langgenius/dify-ui/popover'-import * as React from 'react'+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useProviderContext } from '@/context/provider-context'--const roleI18nKeyMap = {- normal: 'members.normal',- editor: 'members.editor',- admin: 'members.admin',- dataset_operator: 'members.datasetOperator',-} as const--export type RoleKey = keyof typeof roleI18nKeyMap+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'type RoleSelectorProps = {- value: RoleKey- onChange: (role: RoleKey) => void+ value: string+ onChange: (role: string) => void}+const PAGE_SIZE = 20+const RoleSelector = ({ value, onChange }: RoleSelectorProps) => {const { t } = useTranslation()- const { datasetOperatorEnabled } = useProviderContext()- const [open, setOpen] = React.useState(false)+ const locale = useLocale()+ const [open, setOpen] = useState(false)+ const containerRef = useRef<HTMLDivElement>(null)+ const anchorRef = useRef<HTMLDivElement>(null)+ const [observerReadyKey, setObserverReadyKey] = useState(0)+ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])++ const {+ data: rolesData,+ isLoading: rolesLoading,+ error,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ } = useWorkspaceRoleList({+ page: 1,+ limit: PAGE_SIZE,+ language,+ })++ useEffect(() => {+ const hasMore = hasNextPage ?? true+ let observer: IntersectionObserver | undefined++ if (error || !open)+ return++ if (anchorRef.current && containerRef.current) {+ const containerHeight = containerRef.current.clientHeight+ const dynamicMargin = Math.max(100, Math.min(containerHeight * 0.2, 200))++ observer = new IntersectionObserver((entries) => {+ if (entries[0]!.isIntersecting && !rolesLoading && !isFetchingNextPage && !error && hasMore)+ fetchNextPage()+ }, {+ root: containerRef.current,+ rootMargin: `${dynamicMargin}px`,+ })+ observer.observe(anchorRef.current)+ }++ return () => observer?.disconnect()+ }, [rolesLoading, isFetchingNextPage, fetchNextPage, error, hasNextPage, open, observerReadyKey])++ const roles = useMemo(() => rolesData?.pages.flatMap(page => page.data) ?? [], [rolesData])+ const selectedRole = roles.find(role => role.id === value)+ const selectedRoleName = selectedRole?.name || value+ const triggerLabel = selectedRoleName+ ? t('members.invitedAsRole', { ns: 'common', role: selectedRoleName })+ : t('members.selectRole', { ns: 'common' })++ const setContainerElement = useCallback((node: HTMLDivElement | null) => {+ containerRef.current = node+ setObserverReadyKey(key => key + 1)+ }, [])++ const setAnchorElement = useCallback((node: HTMLDivElement | null) => {+ anchorRef.current = node+ setObserverReadyKey(key => key + 1)+ }, [])++ const handleRoleChange = (roleId: string) => {+ onChange(roleId)+ setOpen(false)+ }return (- <Popover+ <DropdownMenuopen={open}onOpenChange={setOpen}+ modal={false}>- <PopoverTrigger+ <DropdownMenuTriggerdata-testid="role-selector-trigger"className={cn('flex w-full cursor-pointer items-center rounded-lg bg-components-input-bg-normal px-3 py-2 hover:bg-state-base-hover',open && 'bg-state-base-hover',)}>- <div className="mr-2 grow text-sm/5 text-text-primary">{t('members.invitedAsRole', { ns: 'common', role: t(roleI18nKeyMap[value], { ns: 'common' }) })}</div>- <div className="i-ri-arrow-down-s-line size-4 shrink-0 text-text-secondary" />- </PopoverTrigger>- <PopoverContent+ <div className="mr-2 grow text-sm/5 text-text-primary">{triggerLabel}</div>+ <div className={cn('size-4 shrink-0 text-text-secondary', open ? 'i-ri-arrow-up-s-line' : 'i-ri-arrow-down-s-line')} />+ </DropdownMenuTrigger>+ <DropdownMenuContentplacement="bottom-start"sideOffset={4}- popupClassName="w-[336px] rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg"+ popupClassName="w-[336px] rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg p-0 shadow-lg">- <div className="p-1">- <button- type="button"- aria-pressed={value === 'normal'}- className="w-full cursor-pointer rounded-lg border-none bg-transparent p-2 text-left hover:bg-state-base-hover"- onClick={() => {- onChange('normal')- setOpen(false)- }}- >- <div className="relative pl-5">- <div className="text-sm/5 text-text-secondary">{t('members.normal', { ns: 'common' })}</div>- <div className="text-xs leading-[18px] text-text-tertiary">{t('members.normalTip', { ns: 'common' })}</div>- {value === 'normal' && (- <div- aria-hidden="true"- className="absolute top-0.5 left-0 i-custom-vender-line-general-check size-4 text-text-accent"- />- )}- </div>- </button>- <button- type="button"- aria-pressed={value === 'editor'}- className="w-full cursor-pointer rounded-lg border-none bg-transparent p-2 text-left hover:bg-state-base-hover"- onClick={() => {- onChange('editor')- setOpen(false)- }}- >- <div className="relative pl-5">- <div className="text-sm/5 text-text-secondary">{t('members.editor', { ns: 'common' })}</div>- <div className="text-xs leading-[18px] text-text-tertiary">{t('members.editorTip', { ns: 'common' })}</div>- {value === 'editor' && (- <div- aria-hidden="true"- className="absolute top-0.5 left-0 i-custom-vender-line-general-check size-4 text-text-accent"- />- )}- </div>- </button>- <button- type="button"- aria-pressed={value === 'admin'}- className="w-full cursor-pointer rounded-lg border-none bg-transparent p-2 text-left hover:bg-state-base-hover"- onClick={() => {- onChange('admin')- setOpen(false)- }}- >- <div className="relative pl-5">- <div className="text-sm/5 text-text-secondary">{t('members.admin', { ns: 'common' })}</div>- <div className="text-xs leading-[18px] text-text-tertiary">{t('members.adminTip', { ns: 'common' })}</div>- {value === 'admin' && (- <div- aria-hidden="true"- className="absolute top-0.5 left-0 i-custom-vender-line-general-check size-4 text-text-accent"- />- )}- </div>- </button>- {datasetOperatorEnabled && (- <button- type="button"- aria-pressed={value === 'dataset_operator'}- className="w-full cursor-pointer rounded-lg border-none bg-transparent p-2 text-left hover:bg-state-base-hover"- onClick={() => {- onChange('dataset_operator')- setOpen(false)- }}- >- <div className="relative pl-5">- <div className="text-sm/5 text-text-secondary">{t('members.datasetOperator', { ns: 'common' })}</div>- <div className="text-xs leading-[18px] text-text-tertiary">{t('members.datasetOperatorTip', { ns: 'common' })}</div>- {value === 'dataset_operator' && (- <div- aria-hidden="true"- className="absolute top-0.5 left-0 i-custom-vender-line-general-check size-4 text-text-accent"- />- )}- </div>- </button>- )}- </div>- </PopoverContent>- </Popover>+ <ScrollArea+ ref={setContainerElement}+ className="h-70"+ slotClassNames={{ viewport: 'overscroll-contain' }}+ >+ <div className="p-1">+ {rolesLoading+ ? (+ <div className="px-3 py-6 text-center system-sm-regular text-text-tertiary">+ {t('loading', { ns: 'common' })}+ </div>+ )+ : roles.length === 0+ ? (+ <div className="px-3 py-6 text-center system-sm-regular text-text-tertiary">+ {t('dynamicSelect.noData', { ns: 'common' })}+ </div>+ )+ : (+ <>+ <DropdownMenuRadioGroup+ value={value}+ onValueChange={handleRoleChange}+ >+ {roles.map(role => (+ <DropdownMenuRadioItem+ key={role.id}+ value={role.id}+ className="mx-0 h-auto w-full cursor-pointer items-start gap-0 rounded-lg border-none bg-transparent p-2 text-left hover:bg-state-base-hover data-highlighted:bg-state-base-hover"+ >+ <div className="relative min-w-0 pl-5">+ <div className="truncate text-sm leading-5 text-text-secondary">{role.name}</div>+ <div className="line-clamp-2 text-xs leading-4.5 text-text-tertiary">{role.description || t('role.noDescription', { ns: 'permission' })}</div>+ {value === role.id && (+ <div+ aria-hidden="true"+ className="absolute top-0.5 left-0 i-custom-vender-line-general-check h-4 w-4 text-text-accent"+ />+ )}+ </div>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ <div ref={setAnchorElement} className="h-0" />+ </>+ )}+ </div>+ </ScrollArea>+ </DropdownMenuContent>+ </DropdownMenu>)}diff --git a/web/app/components/header/account-setting/members-page/member-details-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/member-details-modal/__tests__/index.spec.tsxnew file mode 100644index 00000000000..1508a5b6eb7--- /dev/null+++ b/web/app/components/header/account-setting/members-page/member-details-modal/__tests__/index.spec.tsx@@ -0,0 +1,203 @@+import type { Role } from '@/models/access-control'+import type { Member } from '@/models/common'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { vi } from 'vitest'+import { useRolesOfMember } from '@/service/access-control/use-member-roles'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'+import MemberDetailsModal from '../index'++vi.mock('@/service/access-control/use-member-roles')+vi.mock('@/service/access-control/use-workspace-roles')++const createRole = (overrides: Partial<Role>): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_custom',+ name: 'Custom role',+ description: '',+ is_builtin: false,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})++const member: Member = {+ id: 'member-1',+ name: 'Admin User',+ email: '[email protected]',+ avatar: '',+ avatar_url: '',+ role: 'admin',+ roles: [+ createRole({ id: 'role-1', name: 'Custom role' }),+ ],+ last_active_at: '1731000000',+ last_login_at: '1731000000',+ created_at: '1731000000',+ status: 'active',+}++describe('MemberDetailsModal', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(useRolesOfMember).mockReturnValue({+ data: {+ account_id: member.id,+ roles: [+ createRole({ id: 'role-1', name: 'Custom role' }),+ ],+ },+ isLoading: false,+ } as unknown as ReturnType<typeof useRolesOfMember>)+ vi.mocked(useWorkspaceRoleList).mockReturnValue({+ data: {+ pages: [{+ data: [+ createRole({ id: 'role-1', name: 'Custom role' }),+ createRole({ id: 'role-2', name: 'Second role' }),+ ],+ pagination: {+ total_count: 2,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+ },+ }],+ pageParams: [1],+ },+ isLoading: false,+ error: null,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ } as unknown as ReturnType<typeof useWorkspaceRoleList>)+ })++ describe('Rendering', () => {+ it('should render role loading state without assigned role chips or count', () => {+ vi.mocked(useRolesOfMember).mockReturnValue({+ data: undefined,+ isLoading: true,+ } as unknown as ReturnType<typeof useRolesOfMember>)++ render(+ <MemberDetailsModal+ member={member}+ canAssignRoles+ onClose={vi.fn()}+ onAssignSubmit={vi.fn()}+ />,+ )++ expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /members\.memberDetails\.assign/i })).toBeInTheDocument()+ expect(screen.queryByText('Custom role')).not.toBeInTheDocument()+ expect(screen.queryByText('1')).not.toBeInTheDocument()+ })+ })++ describe('Role actions', () => {+ it('should not show role removal controls when role assignment is not allowed', () => {+ render(+ <MemberDetailsModal+ member={member}+ canAssignRoles={false}+ onClose={vi.fn()}+ onAssignSubmit={vi.fn()}+ />,+ )++ expect(screen.queryByRole('button', { name: /members\.memberDetails\.assign/i })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /members\.memberDetails\.removeRoleAria/i })).not.toBeInTheDocument()+ })++ it('should submit pending role changes only after save is clicked', async () => {+ const user = userEvent.setup()+ const handleAssignSubmit = vi.fn()++ vi.mocked(useRolesOfMember).mockReturnValue({+ data: {+ account_id: member.id,+ roles: [+ createRole({ id: 'role-1', name: 'Custom role' }),+ createRole({ id: 'role-2', name: 'Second role' }),+ ],+ },+ } as unknown as ReturnType<typeof useRolesOfMember>)++ render(+ <MemberDetailsModal+ member={member}+ canAssignRoles+ onClose={vi.fn()}+ onAssignSubmit={handleAssignSubmit}+ />,+ )++ await user.click(screen.getByRole('button', { name: /Custom role/i }))++ await user.click(screen.getByRole('menuitem', { name: /common\.operation\.remove/i }))++ expect(handleAssignSubmit).not.toHaveBeenCalled()++ await user.click(screen.getByRole('button', { name: /common\.operation\.save/i }))++ expect(handleAssignSubmit).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'role-2', name: 'Second role' }),+ ])+ })++ it('should keep assigned role selections pending until save is clicked', async () => {+ const user = userEvent.setup()+ const handleAssignSubmit = vi.fn()++ render(+ <MemberDetailsModal+ member={member}+ canAssignRoles+ onClose={vi.fn()}+ onAssignSubmit={handleAssignSubmit}+ />,+ )++ await user.click(screen.getByRole('button', { name: /members\.memberDetails\.assign/i }))+ await user.click(screen.getByRole('checkbox', { name: /Second role/i }))+ await user.click(screen.getByRole('button', { name: /common\.operation\.confirm/i }))++ expect(handleAssignSubmit).not.toHaveBeenCalled()++ await user.click(screen.getByRole('button', { name: /common\.operation\.save/i }))++ expect(handleAssignSubmit).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'role-1', name: 'Custom role' }),+ expect.objectContaining({ id: 'role-2', name: 'Second role' }),+ ])+ })++ it('should replace the selected role when multiple roles are not allowed', async () => {+ const user = userEvent.setup()+ const handleAssignSubmit = vi.fn()++ render(+ <MemberDetailsModal+ member={member}+ canAssignRoles+ allowMultipleRoles={false}+ onClose={vi.fn()}+ onAssignSubmit={handleAssignSubmit}+ />,+ )++ await user.click(screen.getByRole('button', { name: /members\.memberDetails\.assign/i }))+ await user.click(screen.getByRole('radio', { name: /Second role/i }))+ await user.click(screen.getByRole('button', { name: /common\.operation\.confirm/i }))+ await user.click(screen.getByRole('button', { name: /common\.operation\.save/i }))++ expect(handleAssignSubmit).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'role-2', name: 'Second role' }),+ ])+ })+ })+})diff --git a/web/app/components/header/account-setting/members-page/member-details-modal/index.tsx b/web/app/components/header/account-setting/members-page/member-details-modal/index.tsxnew file mode 100644index 00000000000..269a4c03ddd--- /dev/null+++ b/web/app/components/header/account-setting/members-page/member-details-modal/index.tsx@@ -0,0 +1,225 @@+'use client'++import type { Role } from '@/models/access-control'+import type { Member } from '@/models/common'+import { Avatar } from '@langgenius/dify-ui/avatar'+import { Button } from '@langgenius/dify-ui/button'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { memo, useCallback, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import { useRolesOfMember } from '@/service/access-control/use-member-roles'+import AssignRolesModal from '../assign-roles-modal'+import PermissionRoleChip from './permission-role-chip'++type MemberDetailsModalProps = {+ member: Member+ canAssignRoles?: boolean+ allowMultipleRoles?: boolean+ onClose: () => void+ onAssignSubmit?: (roles: Role[]) => void+}++const MemberDetailsModal = ({+ member,+ canAssignRoles = false,+ allowMultipleRoles = true,+ onClose,+ onAssignSubmit,+}: MemberDetailsModalProps) => {+ const { t } = useTranslation()+ const locale = useLocale()+ const [assignOpen, setAssignOpen] = useState(false)+ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])++ const { data: rolesOfMember, isLoading: isLoadingRolesOfMember } = useRolesOfMember(member.id, language)+ const [pendingRoles, setPendingRoles] = useState<Role[]>()++ const roles = useMemo(() => rolesOfMember?.roles ?? [], [rolesOfMember?.roles])+ const selectedRoles = pendingRoles ?? roles+ const selectedRoleIds = useMemo(() => selectedRoles.map(role => role.id), [selectedRoles])++ const builtinRoles = useMemo(() => selectedRoles.filter(role => role.is_builtin), [selectedRoles])+ const customRoles = useMemo(() => selectedRoles.filter(role => !role.is_builtin), [selectedRoles])++ const handleClose = useCallback(() => {+ setAssignOpen(false)+ }, [])++ const handleAssignSubmit = useCallback((roles: Role[]) => {+ setPendingRoles(allowMultipleRoles ? roles : roles.slice(0, 1))+ setAssignOpen(false)+ }, [allowMultipleRoles])++ const handleRemove = useCallback((roleId: string) => {+ if (!allowMultipleRoles && selectedRoles.length <= 1)+ return++ setPendingRoles(selectedRoles.filter(selectedRole => selectedRole.id !== roleId))+ }, [allowMultipleRoles, selectedRoles])++ const handleSave = useCallback(() => {+ onAssignSubmit?.(allowMultipleRoles ? selectedRoles : selectedRoles.slice(0, 1))+ onClose()+ }, [allowMultipleRoles, onAssignSubmit, onClose, selectedRoles])++ return (+ <>+ <Dialog+ open+ onOpenChange={(next) => {+ if (!next)+ onClose()+ }}+ >+ <DialogContent className="w-110 overflow-visible p-0" backdropProps={{ forceRender: true }}>+ <div className="relative px-6 pt-6 pb-5">+ <DialogCloseButton />+ <DialogTitle className="pr-8 system-xl-semibold text-text-primary">+ {t('members.memberDetails.title', {+ ns: 'common',+ defaultValue: 'Member Details',+ })}+ </DialogTitle>++ <div className="mt-5 flex items-center gap-3">+ <Avatar+ avatar={member.avatar_url}+ name={member.name}+ size="2xl"+ />+ <div className="min-w-0 flex-1">+ <div className="truncate system-md-semibold text-text-primary">+ {member.name}+ </div>+ <div className="truncate system-xs-regular text-text-tertiary">+ {member.email}+ </div>+ </div>+ </div>+ </div>++ <div className="border-t border-divider-subtle px-6 py-4">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-1.5 system-sm-semibold text-text-secondary">+ <span>+ {t('members.memberDetails.assignedRoles', {+ ns: 'common',+ defaultValue: 'Assigned Roles',+ })}+ </span>+ {!isLoadingRolesOfMember && (+ <span className="system-xs-medium text-text-tertiary">+ {selectedRoleIds.length}+ </span>+ )}+ </div>+ {canAssignRoles && (+ <Button+ variant="ghost"+ size="small"+ onClick={() => setAssignOpen(true)}+ >+ <span+ aria-hidden+ className="mr-0.5 i-ri-add-line h-3.5 w-3.5"+ />+ {t('members.memberDetails.assign', {+ ns: 'common',+ defaultValue: 'Assign',+ })}+ </Button>+ )}+ </div>++ {isLoadingRolesOfMember+ ? (+ <div className="mt-4">+ <Loading />+ </div>+ )+ : (+ <>+ {builtinRoles.length > 0 && (+ <div className="mt-4">+ <div className="mb-2 system-2xs-medium-uppercase text-text-tertiary">+ {t('members.memberDetails.generalGroup', {+ ns: 'common',+ })}+ </div>+ <div className="flex flex-wrap gap-1.5">+ {builtinRoles.map(role => (+ <PermissionRoleChip+ key={role.id}+ roleId={role.id}+ label={role.name}+ isOwner={role.role_tag === 'owner'}+ permissionKeys={role.permission_keys}+ onRemove={canAssignRoles ? handleRemove : undefined}+ />+ ))}+ </div>+ </div>+ )}+ {customRoles.length > 0 && (+ <div className="mt-4">+ <div className="mb-2 system-2xs-medium-uppercase text-text-tertiary">+ {t('members.memberDetails.customGroup', {+ ns: 'common',+ })}+ </div>+ <div className="flex flex-wrap gap-1.5">+ {customRoles.map(role => (+ <PermissionRoleChip+ key={role.id}+ roleId={role.id}+ label={role.name}+ isOwner={role.role_tag === 'owner'}+ permissionKeys={role.permission_keys}+ onRemove={canAssignRoles ? handleRemove : undefined}+ />+ ))}+ </div>+ </div>+ )}+ </>+ )}+ </div>++ {canAssignRoles && (+ <div className="flex items-center justify-end gap-2 px-6 pt-2 pb-4">+ <Button variant="secondary" onClick={onClose}>+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ <Button+ variant="primary"+ onClick={handleSave}+ disabled={!onAssignSubmit}+ >+ {t('operation.save', { ns: 'common' })}+ </Button>+ </div>+ )}+ </DialogContent>+ </Dialog>++ {assignOpen && (+ <AssignRolesModal+ selectedRoles={selectedRoles}+ allowMultipleRoles={allowMultipleRoles}+ onClose={handleClose}+ onSubmit={handleAssignSubmit}+ />+ )}+ </>+ )+}++export default memo(MemberDetailsModal)diff --git a/web/app/components/header/account-setting/members-page/member-details-modal/permission-role-chip.tsx b/web/app/components/header/account-setting/members-page/member-details-modal/permission-role-chip.tsxnew file mode 100644index 00000000000..e9456c18f66--- /dev/null+++ b/web/app/components/header/account-setting/members-page/member-details-modal/permission-role-chip.tsx@@ -0,0 +1,162 @@+'use client'++import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import {+ PreviewCard,+ PreviewCardContent,+ PreviewCardTrigger,+} from '@langgenius/dify-ui/preview-card'+import { memo, useState } from 'react'+import { Trans, useTranslation } from 'react-i18next'++type PermissionRoleChipProps = {+ roleId: string+ label: string+ isOwner: boolean+ permissionKeys: string[]+ onRemove?: (roleId: string) => void+ className?: string+}++const PermissionRoleChip = ({+ roleId,+ label,+ isOwner,+ permissionKeys,+ onRemove,+ className,+}: PermissionRoleChipProps) => {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const permissions = permissionKeys+ const canOpenMenu = !isOwner && !!onRemove+ const permissionLabels = permissions+ .map(key => t(key, {+ ns: 'permissionKeys',+ defaultValue: key,+ }))+ .join(', ')+ const hasPermissionLabels = permissionLabels.length > 0++ const chipClassName = cn(+ 'inline-flex h-6 max-w-full items-center rounded-full border-[0.5px] border-components-panel-border-subtle bg-background-body p-1 system-xs-regular text-text-primary shadow-xs transition-colors outline-none',+ canOpenMenu && 'cursor-pointer hover:bg-background-section-burn focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden',+ open && 'bg-background-section-burn',+ className,+ )++ const chipContent = (+ <span className="min-w-0 truncate px-1 leading-4">{label}</span>+ )++ const chip = canOpenMenu+ ? (+ <button+ type="button"+ className={chipClassName}+ aria-label={t('members.memberDetails.roleActionsAria', {+ ns: 'common',+ role: label,+ defaultValue: 'Open actions for {{role}} role',+ })}+ data-testid="permission-role-chip"+ data-role-id={roleId}+ >+ {chipContent}+ </button>+ )+ : (+ <span+ className={chipClassName}+ data-testid="permission-role-chip"+ data-role-id={roleId}+ >+ {chipContent}+ </span>+ )++ const permissionSummary = (+ <div className="flex w-58 flex-col gap-1 px-4 py-3.5">+ <div className="title-xs-semi-bold leading-4 whitespace-nowrap text-text-primary">+ {label}+ </div>+ <div className="body-xs-regular text-text-secondary">+ {hasPermissionLabels+ ? (+ <Trans+ i18nKey="members.memberDetails.rolePermissionSummary"+ ns="common"+ values={{+ role: label,+ permissions: permissionLabels,+ }}+ components={{+ permissionList: <span className="text-text-accent" />,+ }}+ />+ )+ : t('members.memberDetails.roleNoPermissionSummary', {+ ns: 'common',+ defaultValue: 'Current role has no permissions.',+ })}+ </div>+ </div>+ )++ const chipWithPermissions = (+ <PreviewCard>+ <PreviewCardTrigger render={chip} />+ <PreviewCardContent+ placement="bottom-start"+ sideOffset={8}+ popupClassName="overflow-hidden border-components-panel-border bg-components-tooltip-bg p-0 shadow-lg backdrop-blur-[5px]"+ >+ {permissionSummary}+ </PreviewCardContent>+ </PreviewCard>+ )++ if (!canOpenMenu)+ return chipWithPermissions++ const menuTrigger = (+ <PreviewCard>+ <DropdownMenuTrigger render={<PreviewCardTrigger render={chip} />} />+ <PreviewCardContent+ placement="bottom-start"+ sideOffset={8}+ popupClassName="overflow-hidden border-components-panel-border bg-components-tooltip-bg p-0 shadow-lg backdrop-blur-[5px]"+ >+ {permissionSummary}+ </PreviewCardContent>+ </PreviewCard>+ )++ return (+ <DropdownMenu open={open} onOpenChange={setOpen}>+ {menuTrigger}+ <DropdownMenuContent+ placement="bottom-start"+ sideOffset={4}+ popupClassName="w-[236px] rounded-xl p-1"+ >+ <DropdownMenuItem+ variant="destructive"+ className="h-8 gap-2 rounded-lg px-2 py-1 system-sm-regular"+ onClick={() => onRemove?.(roleId)}+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />+ {t('operation.remove', { ns: 'common' })}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}++export default memo(PermissionRoleChip)diff --git a/web/app/components/header/account-setting/members-page/member-menu.tsx b/web/app/components/header/account-setting/members-page/member-menu.tsxnew file mode 100644index 00000000000..d658d09f65f--- /dev/null+++ b/web/app/components/header/account-setting/members-page/member-menu.tsx@@ -0,0 +1,160 @@+'use client'+import type { Role } from '@/models/access-control'+import type { Member } from '@/models/common'+import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { toast } from '@langgenius/dify-ui/toast'+import { useQueryClient } from '@tanstack/react-query'+import { memo, useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import ActionButton from '@/app/components/base/action-button'+import { useUpdateRolesOfMember } from '@/service/access-control/use-member-roles'+import { deleteMemberOrCancelInvitation } from '@/service/common'+import { commonQueryKeys } from '@/service/use-common'+import AssignRolesModal from './assign-roles-modal'++type MemberMenuProps = {+ member: Member+ isCurrentUser: boolean+ canTransferOwnership?: boolean+ allowMultipleRoles?: boolean+ onTransferOwnership?: () => void+}++const MemberMenu = ({+ member,+ isCurrentUser,+ canTransferOwnership = false,+ allowMultipleRoles = true,+ onTransferOwnership,+}: MemberMenuProps) => {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const [open, setOpen] = useState(false)+ const [assignModalOpen, setAssignModalOpen] = useState(false)++ const isOwner = member.role === 'owner'+ const canAssignRoles = !isOwner && !isCurrentUser+ const canRemove = !isOwner && !isCurrentUser+ const showTransferOwnership = isOwner && canTransferOwnership++ const selectedRoles = member.roles || []++ const handleOpenAssignRoles = useCallback(() => {+ setOpen(false)+ setAssignModalOpen(true)+ }, [])++ const { mutateAsync: updateRolesOfMember } = useUpdateRolesOfMember()++ const handleAssignRolesSubmit = useCallback((roles: Role[]) => {+ const roleIds = allowMultipleRoles+ ? roles.map(role => role.id)+ : roles.slice(0, 1).map(role => role.id)++ updateRolesOfMember({+ memberId: member.id,+ roleIds,+ }, {+ onSuccess: () => {+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))+ },+ })+ }, [allowMultipleRoles, member.id, t, updateRolesOfMember])++ const handleRemove = useCallback(async () => {+ setOpen(false)+ try {+ await deleteMemberOrCancelInvitation({ url: `/workspaces/current/members/${member.id}` })+ void queryClient.invalidateQueries({ queryKey: commonQueryKeys.members })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))+ }+ catch {+ }+ }, [member.id, queryClient, t])++ const handleTransferOwnership = useCallback(() => {+ setOpen(false)+ onTransferOwnership?.()+ }, [onTransferOwnership])++ const stopPropagationOnClick = useCallback((e: React.MouseEvent) => {+ e.stopPropagation()+ }, [])++ const stopPropagationOnKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {+ if (e.key === 'Enter' || e.key === ' ')+ e.stopPropagation()+ }, [])++ if (!canAssignRoles && !canRemove && !showTransferOwnership)+ return null++ return (+ <div role="presentation" onClick={stopPropagationOnClick} onKeyDown={stopPropagationOnKeyDown}>+ <DropdownMenu open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger+ render={(+ <ActionButton+ size="l"+ className={cn(open && 'bg-state-base-hover')}+ aria-label={t('members.memberActions', { ns: 'common', defaultValue: 'Member actions' })}+ />+ )}+ >+ <span aria-hidden className="i-ri-more-fill h-4 w-4 text-text-tertiary" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ placement="bottom-end"+ sideOffset={4}+ popupClassName="min-w-[180px] rounded-xl p-1"+ >+ {canAssignRoles && (+ <DropdownMenuItem+ className="system-sm-medium text-text-secondary"+ onClick={handleOpenAssignRoles}+ >+ {t('members.assignRoles', { ns: 'common', defaultValue: 'Assign Roles' })}+ </DropdownMenuItem>+ )}+ {showTransferOwnership && (+ <DropdownMenuItem+ className="system-sm-medium text-text-secondary"+ onClick={handleTransferOwnership}+ >+ {t('members.transferOwnership', { ns: 'common' })}+ </DropdownMenuItem>+ )}+ {(canAssignRoles || showTransferOwnership) && canRemove && (+ <DropdownMenuSeparator />+ )}+ {canRemove && (+ <DropdownMenuItem+ variant="destructive"+ className="system-sm-medium"+ onClick={handleRemove}+ >+ {t('members.removeFromTeam', { ns: 'common' })}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ {assignModalOpen && (+ <AssignRolesModal+ selectedRoles={selectedRoles}+ allowMultipleRoles={allowMultipleRoles}+ onClose={() => setAssignModalOpen(false)}+ onSubmit={handleAssignRolesSubmit}+ />+ )}+ </div>+ )+}++export default memo(MemberMenu)diff --git a/web/app/components/header/account-setting/members-page/member-row.tsx b/web/app/components/header/account-setting/members-page/member-row.tsxnew file mode 100644index 00000000000..2886a45700e--- /dev/null+++ b/web/app/components/header/account-setting/members-page/member-row.tsx@@ -0,0 +1,109 @@+'use client'+import type { KeyboardEvent } from 'react'+import type { Member } from '@/models/common'+import { Avatar } from '@langgenius/dify-ui/avatar'+import { memo, useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import MemberMenu from './member-menu'+import RoleBadges from './role-badges'++type MemberRowProps = {+ member: Member+ roles: Array<{+ id: string+ name: string+ }>+ isCurrentUser: boolean+ canManage: boolean+ canTransferOwnership: boolean+ allowMultipleRoles: boolean+ onOpenDetails: (member: Member) => void+ onTransferOwnership: () => void+}++const MemberRow = ({+ member,+ roles,+ isCurrentUser,+ canManage,+ canTransferOwnership,+ allowMultipleRoles,+ onOpenDetails,+ onTransferOwnership,+}: MemberRowProps) => {+ const { t } = useTranslation()+ const { formatTimeFromNow } = useFormatTimeFromNow()++ const roleNames = roles.map(role => role.name)++ const openDetails = useCallback(() => {+ onOpenDetails(member)+ }, [member, onOpenDetails])++ const handleRowKeyDown = useCallback((e: KeyboardEvent<HTMLDivElement>) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ openDetails()+ }+ }, [openDetails])++ return (+ <div+ role="button"+ tabIndex={0}+ data-testid={`member-row-${member.id}`}+ aria-label={t('members.memberDetails.openAria', {+ ns: 'common',+ name: member.name,+ defaultValue: 'Open member details for {{name}}',+ })}+ className="flex cursor-pointer border-b border-divider-subtle hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={openDetails}+ onKeyDown={handleRowKeyDown}+ >+ <div className="flex w-65 shrink-0 items-center px-3 py-2">+ <Avatar avatar={member.avatar_url} size="sm" className="mr-2" name={member.name} />+ <div className="">+ <div className="system-sm-medium text-text-secondary">+ {member.name}+ {member.status === 'pending' && (+ <span className="ml-1 system-xs-medium text-text-warning">+ {t('members.pending', { ns: 'common' })}+ </span>+ )}+ {isCurrentUser && (+ <span className="system-xs-regular text-text-tertiary">+ {t('members.you', { ns: 'common' })}+ </span>+ )}+ </div>+ <div className="system-xs-regular text-text-tertiary">{member.email}</div>+ </div>+ </div>+ <div className="flex w-30 shrink-0 items-center py-2 system-sm-regular text-text-secondary">+ {formatTimeFromNow(Number((member.last_active_at || member.created_at)) * 1000)}+ </div>+ <div+ className="flex min-w-0 grow items-center gap-2 px-3"+ role="presentation"+ >+ <RoleBadges+ className="grow"+ roleNames={roleNames}+ />+ {canManage && (+ <MemberMenu+ member={member}+ isCurrentUser={isCurrentUser}+ canTransferOwnership={canTransferOwnership}+ allowMultipleRoles={allowMultipleRoles}+ onTransferOwnership={onTransferOwnership}+ />+ )}+ </div>+ </div>+ )+}++export default memo(MemberRow)diff --git a/web/app/components/header/account-setting/members-page/operation/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/operation/__tests__/index.spec.tsxdeleted file mode 100644index 728ccf82e18..00000000000--- a/web/app/components/header/account-setting/members-page/operation/__tests__/index.spec.tsx+++ /dev/null@@ -1,142 +0,0 @@-import type { Member } from '@/models/common'-import { render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { vi } from 'vitest'-import Operation from '../index'--const mockUpdateMemberRole = vi.fn()-const mockDeleteMemberOrCancelInvitation = vi.fn()--vi.mock('@/service/common', () => ({- deleteMemberOrCancelInvitation: (args: unknown) => mockDeleteMemberOrCancelInvitation(args),- updateMemberRole: (args: unknown) => mockUpdateMemberRole(args),-}))--const mockUseProviderContext = vi.fn(() => ({- datasetOperatorEnabled: false,-}))--vi.mock('@/context/provider-context', () => ({- useProviderContext: () => mockUseProviderContext(),-}))--const defaultMember: Member = {- id: 'member-id',- name: 'Test Member',- email: '[email protected]',- avatar: '',- avatar_url: null,- status: 'active',- role: 'editor',- last_login_at: '',- last_active_at: '',- created_at: '',-}--const renderOperation = (propsOverride: Partial<Member> = {}, operatorRole = 'owner', onOperate?: () => void) => {- const mergedMember = { ...defaultMember, ...propsOverride }- return render(- <>- <Operation member={mergedMember} operatorRole={operatorRole} onOperate={onOperate ?? vi.fn()} />- </>,- )-}--describe('Operation', () => {- beforeEach(() => {- vi.clearAllMocks()- mockUseProviderContext.mockReturnValue({ datasetOperatorEnabled: false })- })-- it('should render the current role label when member has editor role', () => {- renderOperation()-- expect(screen.getByText('common.members.editor')).toBeInTheDocument()- })-- it('should show dataset operator option when feature flag is enabled', async () => {- const user = userEvent.setup()-- mockUseProviderContext.mockReturnValue({ datasetOperatorEnabled: true })- renderOperation()-- await user.click(screen.getByText('common.members.editor'))-- expect(await screen.findByText('common.members.datasetOperator')).toBeInTheDocument()- })-- it('should show admin-allowed role options when operator role is admin', async () => {- const user = userEvent.setup()-- renderOperation({}, 'admin')-- await user.click(screen.getByText('common.members.editor'))-- expect(screen.getByText('common.members.admin')).toBeInTheDocument()- expect(screen.getAllByText('common.members.editor')).toHaveLength(2)- expect(screen.getByText('common.members.normal')).toBeInTheDocument()- expect(screen.queryByText('common.members.datasetOperator')).not.toBeInTheDocument()- expect(screen.getByText('common.members.removeFromTeam')).toBeInTheDocument()- })-- it('should not show role options or remove action when operator role is unsupported', async () => {- const user = userEvent.setup()-- renderOperation({}, 'normal')-- await user.click(screen.getByText('common.members.editor'))-- expect(screen.queryByText('common.members.normal')).not.toBeInTheDocument()- expect(screen.queryByText('common.members.removeFromTeam')).not.toBeInTheDocument()- })-- it('should call updateMemberRole and onOperate when selecting another role', async () => {- const user = userEvent.setup()- const onOperate = vi.fn()- renderOperation({}, 'owner', onOperate)-- await user.click(screen.getByText('common.members.editor'))- await user.click(await screen.findByText('common.members.normal'))-- await waitFor(() => {- expect(mockUpdateMemberRole).toHaveBeenCalledWith({- url: '/workspaces/current/members/member-id/update-role',- body: { role: 'normal' },- })- expect(onOperate).toHaveBeenCalled()- })- })-- it('should show dataset operator option when operator is admin and feature flag is enabled', async () => {- const user = userEvent.setup()- mockUseProviderContext.mockReturnValue({ datasetOperatorEnabled: true })- renderOperation({}, 'admin')-- await user.click(screen.getByText('common.members.editor'))-- expect(await screen.findByText('common.members.datasetOperator')).toBeInTheDocument()- expect(screen.getByText('common.members.admin')).toBeInTheDocument()- })-- it('should fall back to normal role label when member role is unknown', () => {- renderOperation({ role: 'unknown_role' as Member['role'] })-- expect(screen.getByText('common.members.normal')).toBeInTheDocument()- })-- it('should call deleteMemberOrCancelInvitation when removing the member', async () => {- const user = userEvent.setup()- const onOperate = vi.fn()- renderOperation({}, 'owner', onOperate)-- await user.click(screen.getByText('common.members.editor'))- await user.click(await screen.findByText('common.members.removeFromTeam'))-- await waitFor(() => {- expect(mockDeleteMemberOrCancelInvitation).toHaveBeenCalledWith({- url: '/workspaces/current/members/member-id',- })- expect(onOperate).toHaveBeenCalled()- })- })-})diff --git a/web/app/components/header/account-setting/members-page/operation/__tests__/transfer-ownership.spec.tsx b/web/app/components/header/account-setting/members-page/operation/__tests__/transfer-ownership.spec.tsxdeleted file mode 100644index f7b8f1dd5a2..00000000000--- a/web/app/components/header/account-setting/members-page/operation/__tests__/transfer-ownership.spec.tsx+++ /dev/null@@ -1,91 +0,0 @@-import type { AppContextValue } from '@/context/app-context'-import type { ICurrentWorkspace } from '@/models/common'-import { fireEvent, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { vi } from 'vitest'-import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'-import { useAppContext } from '@/context/app-context'-import { useWorkspacePermissions } from '@/service/use-workspace'-import TransferOwnership from '../transfer-ownership'--vi.mock('@/context/app-context')-vi.mock('@/service/use-workspace')--describe('TransferOwnership', () => {- const setupPermissions = ({- isFetching,- allowOwnerTransfer,- }: {- isFetching: boolean- allowOwnerTransfer?: boolean- }) => {- vi.mocked(useWorkspacePermissions).mockReturnValue({- data: allowOwnerTransfer === undefined ? null : { allow_owner_transfer: allowOwnerTransfer },- isFetching,- } as unknown as ReturnType<typeof useWorkspacePermissions>)- }-- const renderTransferOwnership = (- brandingEnabled: boolean,- onOperate: () => void = vi.fn(),- ) =>- renderWithSystemFeatures(<TransferOwnership onOperate={onOperate} />, {- systemFeatures: { branding: { enabled: brandingEnabled } },- })-- beforeEach(() => {- vi.clearAllMocks()- vi.mocked(useAppContext).mockReturnValue({- currentWorkspace: { id: 'workspace-id' } as ICurrentWorkspace,- } as unknown as AppContextValue)- })-- it('should show loading status while permissions are loading', () => {- setupPermissions({ isFetching: true })-- renderTransferOwnership(true)-- expect(screen.getByRole('status')).toBeInTheDocument()- })-- it('should show owner text without transfer menu when transfer is forbidden', () => {- setupPermissions({ isFetching: false, allowOwnerTransfer: false })-- renderTransferOwnership(true)-- expect(screen.getByText(/members\.owner/i)).toBeInTheDocument()- expect(screen.queryByText(/members\.transferOwnership/i)).toBeNull()- })-- it('should open transfer dialog when transfer option is selected', async () => {- const user = userEvent.setup()- const onOperate = vi.fn()-- setupPermissions({ isFetching: false, allowOwnerTransfer: true })-- renderTransferOwnership(true, onOperate)-- await user.click(screen.getByRole('button', { name: /members\.owner/i }))- const transferOptionText = await screen.findByText(/members\.transferOwnership/i)- const transferOption = transferOptionText.closest('div.cursor-pointer')- if (!transferOption)- throw new Error('Transfer option container not found')- fireEvent.click(transferOption)-- await waitFor(() => {- expect(onOperate).toHaveBeenCalledTimes(1)- })- })-- it('should allow transfer menu when branding is disabled', async () => {- const user = userEvent.setup()-- setupPermissions({ isFetching: false })-- renderTransferOwnership(false)-- await user.click(screen.getByRole('button', { name: /members\.owner/i }))-- expect(screen.getByText(/members\.transferOwnership/i)).toBeInTheDocument()- })-})diff --git a/web/app/components/header/account-setting/members-page/operation/index.tsx b/web/app/components/header/account-setting/members-page/operation/index.tsxdeleted file mode 100644index fe72f972d13..00000000000--- a/web/app/components/header/account-setting/members-page/operation/index.tsx+++ /dev/null@@ -1,131 +0,0 @@-'use client'-import type { Member } from '@/models/common'-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from '@langgenius/dify-ui/dropdown-menu'-import { toast } from '@langgenius/dify-ui/toast'-import { memo, useMemo } from 'react'-import { useTranslation } from 'react-i18next'-import { useProviderContext } from '@/context/provider-context'-import { deleteMemberOrCancelInvitation, updateMemberRole } from '@/service/common'--type IOperationProps = {- member: Member- operatorRole: string- onOperate: () => void-}-const roleI18nKeyMap = {- admin: { label: 'members.admin', tip: 'members.adminTip' },- editor: { label: 'members.editor', tip: 'members.editorTip' },- normal: { label: 'members.normal', tip: 'members.normalTip' },- dataset_operator: { label: 'members.datasetOperator', tip: 'members.datasetOperatorTip' },-} as const-type OperationRoleKey = keyof typeof roleI18nKeyMap-const nonOwnerRoles = ['admin', 'editor', 'normal'] as const-const isNonOwnerRole = (role: Member['role']) => role !== 'owner'--const Operation = ({ member, operatorRole, onOperate }: IOperationProps) => {- const { t } = useTranslation()- const { datasetOperatorEnabled } = useProviderContext()- const RoleMap = {- owner: t('members.owner', { ns: 'common' }),- admin: t('members.admin', { ns: 'common' }),- editor: t('members.editor', { ns: 'common' }),- normal: t('members.normal', { ns: 'common' }),- dataset_operator: t('members.datasetOperator', { ns: 'common' }),- }- const roleList = useMemo((): OperationRoleKey[] => {- if (operatorRole === 'owner') {- return [- 'admin',- 'editor',- 'normal',- ...(datasetOperatorEnabled ? ['dataset_operator'] as const : []),- ]- }- if (operatorRole === 'admin') {- return [- ...nonOwnerRoles,- ...(datasetOperatorEnabled ? ['dataset_operator'] as const : []),- ]- }- return []- }, [operatorRole, datasetOperatorEnabled])- const canRemoveMember = operatorRole === 'owner' || (operatorRole === 'admin' && isNonOwnerRole(member.role))- const handleDeleteMemberOrCancelInvitation = async () => {- try {- await deleteMemberOrCancelInvitation({ url: `/workspaces/current/members/${member.id}` })- onOperate()- toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))- }- catch {- }- }- const handleUpdateMemberRole = async (role: string) => {- try {- await updateMemberRole({- url: `/workspaces/current/members/${member.id}/update-role`,- body: { role },- })- onOperate()- toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))- }- catch {- }- }- return (- <DropdownMenu>- <DropdownMenuTrigger- className="group flex size-full cursor-pointer items-center justify-between border-none bg-transparent px-3 text-left system-sm-regular text-text-secondary hover:bg-state-base-hover data-popup-open:bg-state-base-hover"- >- {RoleMap[member.role] || RoleMap.normal}- <span aria-hidden className="i-ri-arrow-down-s-line hidden size-4 shrink-0 group-hover:block group-data-popup-open:block" />- </DropdownMenuTrigger>- <DropdownMenuContent- placement="bottom-end"- sideOffset={4}- popupClassName="inline-flex flex-col rounded-xl p-0"- >- <div className="p-1">- {roleList.map(role => (- <DropdownMenuItem- key={role}- className="h-auto items-start gap-2 rounded-lg px-3 py-2"- onClick={() => handleUpdateMemberRole(role)}- >- {role === member.role- ? <span aria-hidden className="mt-[2px] i-ri-check-line h-4 w-4 shrink-0 text-text-accent" />- : <span aria-hidden className="mt-[2px] h-4 w-4 shrink-0" />}- <div>- <div className="system-sm-semibold whitespace-nowrap text-text-secondary">{t(roleI18nKeyMap[role].label, { ns: 'common' })}</div>- <div className="system-xs-regular whitespace-nowrap text-text-tertiary">{t(roleI18nKeyMap[role].tip, { ns: 'common' })}</div>- </div>- </DropdownMenuItem>- ))}- </div>- {canRemoveMember && (- <>- <DropdownMenuSeparator className="my-0" />- <div className="p-1">- <DropdownMenuItem- className="h-auto items-start gap-2 rounded-lg px-3 py-2"- onClick={handleDeleteMemberOrCancelInvitation}- >- <span aria-hidden className="mt-[2px] h-4 w-4 shrink-0" />- <div>- <div className="system-sm-semibold whitespace-nowrap text-text-secondary">{t('members.removeFromTeam', { ns: 'common' })}</div>- <div className="system-xs-regular whitespace-nowrap text-text-tertiary">{t('members.removeFromTeamTip', { ns: 'common' })}</div>- </div>- </DropdownMenuItem>- </div>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- )-}-export default memo(Operation)diff --git a/web/app/components/header/account-setting/members-page/operation/transfer-ownership.tsx b/web/app/components/header/account-setting/members-page/operation/transfer-ownership.tsxdeleted file mode 100644index 8a9f07fa0ad..00000000000--- a/web/app/components/header/account-setting/members-page/operation/transfer-ownership.tsx+++ /dev/null@@ -1,64 +0,0 @@-'use client'-import { cn } from '@langgenius/dify-ui/cn'-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@langgenius/dify-ui/dropdown-menu'-import {- RiArrowDownSLine,-} from '@remixicon/react'-import { useSuspenseQuery } from '@tanstack/react-query'-import { useTranslation } from 'react-i18next'-import Loading from '@/app/components/base/loading'-import { useAppContext } from '@/context/app-context'-import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { useWorkspacePermissions } from '@/service/use-workspace'--type Props = Readonly<{- onOperate: () => void-}>--const TransferOwnership = ({ onOperate }: Props) => {- const { t } = useTranslation()- const { currentWorkspace } = useAppContext()- const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const { data: workspacePermissions, isFetching: isFetchingWorkspacePermissions } = useWorkspacePermissions(currentWorkspace!.id, systemFeatures.branding.enabled)- if (systemFeatures.branding.enabled) {- if (isFetchingWorkspacePermissions) {- return <Loading />- }- if (!workspacePermissions || workspacePermissions.allow_owner_transfer !== true) {- return <span className="px-3 system-sm-regular text-text-secondary">{t('members.owner', { ns: 'common' })}</span>- }- }-- return (- <DropdownMenu modal={false}>- <DropdownMenuTrigger- className={cn(- 'group flex size-full cursor-pointer items-center justify-between px-3 system-sm-regular text-text-secondary outline-hidden',- 'hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-components-input-border-hover data-popup-open:bg-state-base-hover',- )}- >- {t('members.owner', { ns: 'common' })}- <RiArrowDownSLine className="hidden size-4 group-hover:block group-data-popup-open:block" />- </DropdownMenuTrigger>- <DropdownMenuContent- placement="bottom-end"- sideOffset={4}- popupClassName="bg-components-panel-bg-blur p-1 backdrop-blur-xs"- >- <DropdownMenuItem- className="h-auto px-3 py-2"- onClick={onOperate}- >- <span className="system-md-regular whitespace-nowrap text-text-secondary">{t('members.transferOwnership', { ns: 'common' })}</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )-}--export default TransferOwnershipdiff --git a/web/app/components/header/account-setting/members-page/role-badges.tsx b/web/app/components/header/account-setting/members-page/role-badges.tsxnew file mode 100644index 00000000000..fc1654f3022--- /dev/null+++ b/web/app/components/header/account-setting/members-page/role-badges.tsx@@ -0,0 +1,54 @@+'use client'++import { cn } from '@langgenius/dify-ui/cn'+import { memo } from 'react'++type RoleBadgeProps = {+ label: string+ className?: string+}++const RoleBadge = memo(({ label, className }: RoleBadgeProps) => {+ return (+ <span+ className={cn(+ 'inline-flex h-5 max-w-full shrink items-center overflow-hidden rounded-md bg-background-body px-1.5 system-xs-medium text-text-secondary shadow-xs',+ className,+ )}+ title={label}+ >+ <span className="truncate">{label}</span>+ </span>+ )+})++type RoleBadgesProps = {+ roleNames: string[]+ max?: number+ className?: string+}++const RoleBadges = ({ roleNames, max = 2, className }: RoleBadgesProps) => {+ if (!roleNames.length)+ return null++ const visible = roleNames.slice(0, max)+ const overflow = roleNames.slice(max)++ return (+ <div className={cn('flex min-w-0 items-center gap-1', className)}>+ {visible.map(role => (+ <RoleBadge key={role} label={role} />+ ))}+ {overflow.length > 0 && (+ <span+ className="inline-flex h-5 shrink-0 cursor-default items-center rounded-md bg-background-body px-1.5 system-xs-medium text-text-tertiary shadow-xs"+ >+ {`+${overflow.length}`}+ </span>+ )}+ </div>+ )+}++export default memo(RoleBadges)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 6ff9664bded..ce2b1c85b4f 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@@ -62,9 +62,12 @@ vi.mock('../install-from-marketplace', () => ({vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({useCanSetPluginSettings: () => ({canSetPermissions: true,+ canSetPluginPreferences: true,}),usePluginSettingsAccess: () => ({canSetPermissions: true,+ canSetPluginPreferences: true,+ canViewInstalledPlugins: true,}),default: () => ({referenceSetting: {diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsxindex 475b3944250..b82929ca04b 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx@@ -146,13 +146,17 @@ vi.mock('../system-model-selector', () => ({vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({useCanSetPluginSettings: () => ({canSetPermissions: true,+ canSetPluginPreferences: true,}),usePluginSettingsAccess: () => ({canSetPermissions: true,+ canSetPluginPreferences: true,+ canViewInstalledPlugins: true,}),default: () => ({referenceSetting: mockReferenceSetting,canSetPermissions: true,+ canSetPluginPreferences: true,}),}))diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsxindex c3753dd602c..7962486504c 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx@@ -59,6 +59,12 @@ vi.mock('../hooks', () => ({})),}))+vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({+ usePluginSettingsAccess: () => ({+ canInstallPlugin: true,+ }),+}))+describe('InstallFromMarketplace', () => {const mockProviders = [] as ModelProvider[]diff --git a/web/app/components/header/account-setting/model-provider-page/index.tsx b/web/app/components/header/account-setting/model-provider-page/index.tsxindex 22b4100db08..5d51f78c1e9 100644--- a/web/app/components/header/account-setting/model-provider-page/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/index.tsx@@ -10,7 +10,7 @@ import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { SearchInput } from '@/app/components/base/search-input'import { usePluginsWithLatestVersion } from '@/app/components/plugins/hooks'-import { useCanSetPluginSettings } from '@/app/components/plugins/plugin-page/use-reference-setting'+import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import { PluginCategoryEnum } from '@/app/components/plugins/types'import { useProviderContext } from '@/context/provider-context'import { systemFeaturesQueryOptions } from '@/features/system-features/client'@@ -49,8 +49,9 @@ const ModelProviderPage = ({const debouncedSearchText = useDebounce(searchText, { wait: 500 })const { t } = useTranslation()const {- canSetPermissions,- } = useCanSetPluginSettings()+ canSetPluginPreferences,+ canViewInstalledPlugins,+ } = usePluginSettingsAccess()const { data: textGenerationDefaultModel, isLoading: isTextGenerationDefaultModelLoading } = useDefaultModel(ModelTypeEnum.textGeneration)const { data: embeddingsDefaultModel, isLoading: isEmbeddingsDefaultModelLoading } = useDefaultModel(ModelTypeEnum.textEmbedding)const { data: rerankDefaultModel, isLoading: isRerankDefaultModelLoading } = useDefaultModel(ModelTypeEnum.rerank)@@ -64,7 +65,7 @@ const ModelProviderPage = ({}, [providers])const { data: installedPlugins } = useQuery(consoleQuery.plugins.checkInstalled.queryOptions({input: { body: { plugin_ids: allPluginIds } },- enabled: allPluginIds.length > 0,+ enabled: canViewInstalledPlugins && allPluginIds.length > 0,staleTime: 0,}))const enrichedPlugins = usePluginsWithLatestVersion(installedPlugins?.plugins)@@ -188,7 +189,7 @@ const ModelProviderPage = ({</div>): systemModelSelector('h-8 px-3 system-sm-medium')}- {canSetPermissions && (+ {canSetPluginPreferences && (<UpdateSettingDialogcategory={PluginCategoryEnum.model}/>diff --git a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsxindex 106fd87bee8..d86d2d14bef 100644--- a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx+++ b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx@@ -10,6 +10,7 @@ import Divider from '@/app/components/base/divider'import Loading from '@/app/components/base/loading'import List from '@/app/components/plugins/marketplace/list'import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'+import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import ProviderCard from '@/app/components/plugins/provider-card'import { PluginCategoryEnum } from '@/app/components/plugins/types'import Link from '@/next/link'@@ -27,6 +28,7 @@ const InstallFromMarketplace = ({}: InstallFromMarketplaceProps) => {const { t } = useTranslation()const { theme } = useTheme()+ const { canInstallPlugin } = usePluginSettingsAccess()const [collapse, setCollapse] = useState(false)const {plugins: allPlugins,@@ -73,7 +75,7 @@ const InstallFromMarketplace = ({marketplaceCollections={[]}marketplaceCollectionPluginsMap={{}}plugins={allPlugins}- showInstallButton+ showInstallButton={canInstallPlugin}cardContainerClassName="grid grid-cols-3 gap-2"cardRender={cardRender}emptyClassName="h-auto"diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsxindex c72264dd7ae..16b3dc3fb54 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsx@@ -3,6 +3,12 @@ import { fireEvent, render, screen } from '@testing-library/react'import { ConfigurationMethodEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import AddCredentialInLoadBalancing from '../add-credential-in-load-balancing'+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: ['credential.use', 'credential.manage'],+ }),+}))+vi.mock('@/app/components/header/account-setting/model-provider-page/model-auth', () => ({Authorized: ({renderTrigger,diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsxindex d0ba140fded..3bfa1029474 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx@@ -24,6 +24,12 @@ vi.mock('../hooks/use-custom-models', () => ({useCanAddedModels: () => mockCanAddedModels,}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: ['credential.manage', 'credential.use'],+ }),+}))+// Mock componentsvi.mock('../../model-icon', () => ({default: () => <div data-testid="model-icon" />,@@ -66,7 +72,6 @@ describe('AddCustomModel', () => {)expect(screen.getByText(/modelProvider.addModel/)).toBeInTheDocument()- expect(screen.getByTestId('add-circle-icon')).toBeInTheDocument()})it('should call handleOpenModal directly when no models available and allowed', () => {diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsxindex e135c23764b..e871b35954f 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsx@@ -4,6 +4,12 @@ import userEvent from '@testing-library/user-event'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import SwitchCredentialInLoadBalancing from '../switch-credential-in-load-balancing'+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: ['credential.use', 'credential.manage'],+ }),+}))+// Mock componentsvi.mock('../authorized', () => ({default: ({ renderTrigger, onItemClick, items }: { renderTrigger: () => React.ReactNode, onItemClick: (c: unknown) => void, items: { credentials: unknown[] }[] }) => (diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/add-credential-in-load-balancing.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/add-credential-in-load-balancing.tsxindex 9d83d1632ad..1f27fc96788 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/add-credential-in-load-balancing.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/add-credential-in-load-balancing.tsx@@ -6,7 +6,6 @@ import type {ModelProvider,} from '@/app/components/header/account-setting/model-provider-page/declarations'import { cn } from '@langgenius/dify-ui/cn'-import { RiAddLine } from '@remixicon/react'import {memo,useCallback,@@ -14,6 +13,8 @@ import {import { useTranslation } from 'react-i18next'import { ConfigurationMethodEnum, ModelModalModeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { Authorized } from '@/app/components/header/account-setting/model-provider-page/model-auth'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'type AddCredentialInLoadBalancingProps = {provider: ModelProvider@@ -22,7 +23,7 @@ type AddCredentialInLoadBalancingProps = {currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFieldsmodelCredential: ModelCredentialonSelectCredential: (credential: Credential) => void- onUpdate?: (payload?: any, formValues?: Record<string, any>) => void+ onUpdate?: (payload?: unknown, formValues?: Record<string, unknown>) => voidonRemove?: (credentialId: string) => void}const AddCredentialInLoadBalancing = ({@@ -35,12 +36,15 @@ const AddCredentialInLoadBalancing = ({onRemove,}: AddCredentialInLoadBalancingProps) => {const { t } = useTranslation()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canUseCredential = hasPermission(workspacePermissionKeys, ['credential.use', 'credential.manage'])+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')const {available_credentials,} = modelCredentialconst isCustomModel = configurationMethod === ConfigurationMethodEnum.customizableModelconst notAllowCustomCredential = provider.allow_custom_token === false- const handleUpdate = useCallback((payload?: any, formValues?: Record<string, any>) => {+ const handleUpdate = useCallback((payload?: unknown, formValues?: Record<string, unknown>) => {onUpdate?.(payload, formValues)}, [onUpdate])@@ -51,13 +55,16 @@ const AddCredentialInLoadBalancing = ({open && 'bg-state-base-hover',)}>- <RiAddLine className="mr-2 size-4" />+ <span className="mr-2 i-ri-add-line size-4" />{t('modelProvider.auth.addCredential', { ns: 'common' })}</div>)return Item- }, [t, isCustomModel])+ }, [t])++ if (!canUseCredential)+ return nullreturn (<Authorized@@ -69,7 +76,7 @@ const AddCredentialInLoadBalancing = ({onUpdate: handleUpdate,onRemove,}}- triggerOnlyOpenModal={!available_credentials?.length && !notAllowCustomCredential}+ triggerOnlyOpenModal={!available_credentials?.length && !notAllowCustomCredential && canManageCredential}items={[{title: isCustomModel ? '' : t('modelProvider.auth.apiKeys', { ns: 'common' }),@@ -86,6 +93,7 @@ const AddCredentialInLoadBalancing = ({}: undefined}onItemClick={onSelectCredential}+ hideAddAction={!canManageCredential}placement="bottom-start"popupTitle={isCustomModel ? t('modelProvider.auth.modelCredentials', { ns: 'common' }) : ''}/>diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/add-custom-model.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/add-custom-model.tsxindex d4b778d415b..d7c677b06c4 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/add-custom-model.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/add-custom-model.tsx@@ -17,10 +17,6 @@ import {TooltipContent,TooltipTrigger,} from '@langgenius/dify-ui/tooltip'-import {- RiAddCircleFill,- RiAddLine,-} from '@remixicon/react'import {memo,useCallback,@@ -28,6 +24,8 @@ import {} from 'react'import { useTranslation } from 'react-i18next'import { ModelModalModeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'import ModelIcon from '../model-icon'import { useAuth } from './hooks/use-auth'import { useCanAddedModels } from './hooks/use-custom-models'@@ -48,6 +46,9 @@ const AddCustomModel = ({const [open, setOpen] = useState(false)const canAddedModels = useCanAddedModels(provider)const noModels = !canAddedModels.length+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canUseCredential = hasPermission(workspacePermissionKeys, ['credential.use', 'credential.manage'])+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')const {handleOpenModal: handleOpenModalForAddNewCustomModel,} = useAuth(@@ -72,6 +73,7 @@ const AddCustomModel = ({)const notAllowCustomCredential = provider.allow_custom_token === falseconst renderTrigger = useCallback((open?: boolean, onClick?: () => void) => {+ const disabled = (noModels && !canManageCredential) || (!noModels && !canUseCredential)const item = (<Buttonvariant="ghost"@@ -81,13 +83,14 @@ const AddCustomModel = ({'text-text-tertiary',open && 'bg-components-button-ghost-bg-hover',notAllowCustomCredential && !!noModels && 'cursor-not-allowed opacity-50',+ disabled && 'cursor-not-allowed opacity-50',)}>- <RiAddCircleFill className="mr-1 size-3.5" />+ <span className="mr-1 i-ri-add-circle-fill size-3.5" />{t('modelProvider.addModel', { ns: 'common' })}</Button>)- if (notAllowCustomCredential && !!noModels) {+ if ((notAllowCustomCredential && !!noModels) || disabled) {return (<Tooltip><TooltipTrigger render={item} />@@ -96,10 +99,10 @@ const AddCustomModel = ({)}return item- }, [t, notAllowCustomCredential, noModels])+ }, [canManageCredential, canUseCredential, t, notAllowCustomCredential, noModels])if (noModels) {- return renderTrigger(false, notAllowCustomCredential ? undefined : handleOpenModalForAddNewCustomModel)+ return renderTrigger(false, notAllowCustomCredential || !canManageCredential ? undefined : handleOpenModalForAddNewCustomModel)}return (@@ -124,6 +127,9 @@ const AddCustomModel = ({key={model.model}className="flex h-8 cursor-pointer items-center rounded-lg px-2 hover:bg-state-base-hover"onClick={() => {+ if (!canUseCredential)+ return+setOpen(false)handleOpenModalForAddCustomModelToModelList(undefined, model)}}@@ -145,7 +151,7 @@ const AddCustomModel = ({}</div>{- !notAllowCustomCredential && (+ !notAllowCustomCredential && canManageCredential && (<divclassName="flex cursor-pointer items-center border-t border-t-divider-subtle p-3 system-xs-medium text-text-accent-light-mode-only"onClick={() => {@@ -153,7 +159,7 @@ const AddCustomModel = ({handleOpenModalForAddNewCustomModel()}}>- <RiAddLine className="mr-1 size-4" />+ <span className="mr-1 i-ri-add-line size-4" />{t('modelProvider.auth.addNewModel', { ns: 'common' })}</div>)diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsxindex f405fb55280..f0058dca99f 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx@@ -11,6 +11,13 @@ const mockHandleConfirmDelete = vi.fn()let mockDeleteCredentialId: string | null = nulllet mockDoingAction = false+let mockWorkspacePermissionKeys = ['credential.manage', 'credential.use']++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))vi.mock('../../hooks', () => ({useAuth: () => ({@@ -25,9 +32,12 @@ vi.mock('../../hooks', () => ({}))vi.mock('../authorized-item', () => ({- default: ({ credentials, model, onEdit, onDelete, onItemClick }: {+ default: ({ credentials, model, disabled, disableEdit, disableDelete, onEdit, onDelete, onItemClick }: {credentials: Credential[]model?: CustomModel+ disabled?: boolean+ disableEdit?: boolean+ disableDelete?: booleanonEdit?: (credential: Credential, model?: CustomModel) => voidonDelete?: (credential: Credential, model?: CustomModel) => voidonItemClick?: (credential: Credential, model?: CustomModel) => void@@ -36,9 +46,9 @@ vi.mock('../authorized-item', () => ({{credentials.map((cred: Credential) => (<div key={cred.credential_id}><span>{cred.credential_name}</span>- <button onClick={() => onEdit?.(cred, model)}>Edit</button>- <button onClick={() => onDelete?.(cred, model)}>Delete</button>- <button onClick={() => onItemClick?.(cred, model)}>Select</button>+ <button disabled={disabled || disableEdit} onClick={() => onEdit?.(cred, model)}>Edit</button>+ <button disabled={disabled || disableDelete} onClick={() => onDelete?.(cred, model)}>Delete</button>+ <button disabled={disabled} onClick={() => onItemClick?.(cred, model)}>Select</button></div>))}</div>@@ -79,6 +89,7 @@ describe('Authorized', () => {vi.clearAllMocks()mockDeleteCredentialId = nullmockDoingAction = false+ mockWorkspacePermissionKeys = ['credential.manage', 'credential.use']})it('should render trigger and open popup when trigger is clicked', () => {@@ -185,6 +196,29 @@ describe('Authorized', () => {expect(screen.queryByRole('button', { name: /addApiKey/i })).not.toBeInTheDocument()})+ it('should allow use-only users to switch credentials but not add, edit, or delete them', () => {+ mockWorkspacePermissionKeys = ['credential.use']++ render(+ <Authorized+ provider={mockProvider}+ configurationMethod={ConfigurationMethodEnum.predefinedModel}+ items={mockItems}+ renderTrigger={mockRenderTrigger}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))+ fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0]!)+ fireEvent.click(screen.getAllByRole('button', { name: 'Delete' })[0]!)+ fireEvent.click(screen.getAllByRole('button', { name: 'Select' })[0]!)++ expect(mockHandleActiveCredential).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)+ expect(mockHandleOpenModal).not.toHaveBeenCalled()+ expect(mockOpenConfirmDelete).not.toHaveBeenCalled()+ expect(screen.queryByRole('button', { name: /addApiKey/i })).not.toBeInTheDocument()+ })+it('should show confirm dialog and call confirm handler when delete is confirmed', () => {mockDeleteCredentialId = 'cred-1'diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/authorized-item.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/authorized-item.tsxindex 7e7bd9b7d81..55c2f2d7cf3 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/authorized-item.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/authorized-item.tsx@@ -27,6 +27,8 @@ type AuthorizedItemProps = {showModelTitle?: booleandisableDeleteButShowAction?: booleandisableDeleteTip?: string+ disableEdit?: boolean+ disableDelete?: boolean}export const AuthorizedItem = ({provider,@@ -42,6 +44,8 @@ export const AuthorizedItem = ({showModelTitle,disableDeleteButShowAction,disableDeleteTip,+ disableEdit,+ disableDelete,}: AuthorizedItemProps) => {const handleEdit = useCallback((credential?: Credential) => {onEdit?.(credential, model)@@ -86,6 +90,8 @@ export const AuthorizedItem = ({disabled={disabled}onDelete={handleDelete}onEdit={handleEdit}+ disableEdit={disableEdit}+ disableDelete={disableDelete}showSelectedIcon={showItemSelectedIcon}selectedCredentialId={selectedCredentialId}onItemClick={handleItemClick}diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/index.tsxindex 903d2205726..042d6771097 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/index.tsx@@ -1,6 +1,3 @@-import type {- OffsetOptions,-} from '@floating-ui/react'import type { Placement } from '@langgenius/dify-ui/popover'import type { MouseEvent } from 'react'import type {@@ -26,9 +23,6 @@ import {PopoverContent,PopoverTrigger,} from '@langgenius/dify-ui/popover'-import {- RiAddLine,-} from '@remixicon/react'import {Fragment,memo,@@ -36,9 +30,17 @@ import {useState,} from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'import { useAuth } from '../hooks'import AuthorizedItem from './authorized-item'+type PopoverOffsetOptions = {+ mainAxis?: number+ crossAxis?: number+ alignmentAxis?: number+}+type AuthorizedProps = {provider: ModelProviderconfigurationMethod: ConfigurationMethodEnum@@ -59,7 +61,7 @@ type AuthorizedProps = {renderTrigger: (open?: boolean) => React.ReactNodeisOpen?: booleanonOpenChange?: (open: boolean) => void- offset?: number | OffsetOptions+ offset?: number | PopoverOffsetOptionsplacement?: PlacementtriggerPopupSameWidth?: booleanpopupClassName?: string@@ -99,6 +101,9 @@ const Authorized = ({disableDeleteTip,}: AuthorizedProps) => {const { t } = useTranslation()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canUseCredential = hasPermission(workspacePermissionKeys, ['credential.use', 'credential.manage'])+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')const [isLocalOpen, setIsLocalOpen] = useState(false)const mergedIsOpen = isOpen ?? isLocalOpenconst setMergedIsOpen = useCallback((open: boolean) => {@@ -134,15 +139,24 @@ const Authorized = ({)const handleEdit = useCallback((credential?: Credential, model?: CustomModel) => {+ if (!canManageCredential)+ return+setMergedIsOpen(false)handleOpenModal(credential, model)- }, [handleOpenModal, setMergedIsOpen])+ }, [canManageCredential, handleOpenModal, setMergedIsOpen])const handleDelete = useCallback((credential?: Credential, model?: CustomModel) => {+ if (!canManageCredential)+ return+setMergedIsOpen(false)openConfirmDelete(credential, model)- }, [openConfirmDelete, setMergedIsOpen])+ }, [canManageCredential, openConfirmDelete, setMergedIsOpen])const handleItemClick = useCallback((credential: Credential, model?: CustomModel) => {+ if (!canUseCredential)+ return+if (disableItemClick)return@@ -152,9 +166,9 @@ const Authorized = ({handleActiveCredential(credential, model)setMergedIsOpen(false)- }, [handleActiveCredential, onItemClick, setMergedIsOpen, disableItemClick])+ }, [canUseCredential, handleActiveCredential, onItemClick, setMergedIsOpen, disableItemClick])const notAllowCustomCredential = provider.allow_custom_token === false- const resolvedOffset = typeof offset === 'number' || typeof offset === 'function' ? undefined : offset+ const resolvedOffset = typeof offset === 'number' ? undefined : offsetconst sideOffset = typeof offset === 'number' ? offset : resolvedOffset?.mainAxis ?? 0const alignOffset = typeof offset === 'number' ? 0 : resolvedOffset?.crossAxis ?? resolvedOffset?.alignmentAxis ?? 0const popupProps = triggerPopupSameWidth@@ -165,8 +179,11 @@ const Authorized = ({returnevent.preventDefault()+ if (!canManageCredential)+ return+handleOpenModal()- }, [handleOpenModal, triggerOnlyOpenModal])+ }, [canManageCredential, handleOpenModal, triggerOnlyOpenModal])return (<>@@ -207,7 +224,9 @@ const Authorized = ({title={item.title}model={item.model}credentials={item.credentials}- disabled={disabled}+ disabled={disabled || !canUseCredential}+ disableEdit={!canManageCredential}+ disableDelete={!canManageCredential}onDelete={handleDelete}disableDeleteButShowAction={disableDeleteButShowAction}disableDeleteTip={disableDeleteTip}@@ -228,7 +247,7 @@ const Authorized = ({</div><div className="h-px bg-divider-subtle"></div>{- isModelCredential && !notAllowCustomCredential && !hideAddAction && (+ isModelCredential && !notAllowCustomCredential && !hideAddAction && canManageCredential && (<divonClick={() => handleEdit(undefined,@@ -241,13 +260,13 @@ const Authorized = ({)}className="flex h-[40px] cursor-pointer items-center px-3 system-xs-medium text-text-accent-light-mode-only">- <RiAddLine className="mr-1 size-4" />+ <span className="mr-1 i-ri-add-line size-4" />{t('modelProvider.auth.addModelCredential', { ns: 'common' })}</div>)}{- !isModelCredential && !notAllowCustomCredential && !hideAddAction && (+ !isModelCredential && !notAllowCustomCredential && !hideAddAction && canManageCredential && (<div className="p-2"><ButtononClick={() => handleEdit()}diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/switch-credential-in-load-balancing.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/switch-credential-in-load-balancing.tsxindex aaaa8f5dfa4..1a9fd752683 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/switch-credential-in-load-balancing.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/switch-credential-in-load-balancing.tsx@@ -9,7 +9,6 @@ import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { RiArrowDownSLine } from '@remixicon/react'import {memo,useCallback,@@ -17,6 +16,8 @@ import {import { useTranslation } from 'react-i18next'import Badge from '@/app/components/base/badge'import { ConfigurationMethodEnum, ModelModalModeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'import Authorized from './authorized'type SwitchCredentialInLoadBalancingProps = {@@ -25,7 +26,7 @@ type SwitchCredentialInLoadBalancingProps = {credentials?: Credential[]customModelCredential?: CredentialsetCustomModelCredential: Dispatch<SetStateAction<Credential | undefined>>- onUpdate?: (payload?: any, formValues?: Record<string, any>) => void+ onUpdate?: (payload?: unknown, formValues?: Record<string, unknown>) => voidonRemove?: (credentialId: string) => void}const SwitchCredentialInLoadBalancing = ({@@ -39,9 +40,15 @@ const SwitchCredentialInLoadBalancing = ({}: SwitchCredentialInLoadBalancingProps) => {const { t } = useTranslation()const notAllowCustomCredential = provider.allow_custom_token === false+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canUseCredential = hasPermission(workspacePermissionKeys, ['credential.use', 'credential.manage'])+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')const handleItemClick = useCallback((credential: Credential) => {+ if (!canUseCredential)+ return+setCustomModelCredential(credential)- }, [setCustomModelCredential])+ }, [canUseCredential, setCustomModelCredential])const renderTrigger = useCallback(() => {const selectedCredentialId = customModelCredential?.credential_id@@ -60,7 +67,7 @@ const SwitchCredentialInLoadBalancing = ({className={cn('shrink-0 space-x-1',(authRemoved || unavailable) && 'text-components-button-destructive-secondary-text',- empty && 'cursor-not-allowed opacity-50',+ (empty || !canUseCredential) && 'cursor-not-allowed opacity-50',)}>{@@ -85,10 +92,10 @@ const SwitchCredentialInLoadBalancing = ({<Badge className="ml-2">Enterprise</Badge>)}- <RiArrowDownSLine className="size-4" />+ <span className="i-ri-arrow-down-s-line size-4" /></Button>)- if (empty && notAllowCustomCredential) {+ if ((empty && notAllowCustomCredential) || !canUseCredential) {return (<Tooltip><TooltipTrigger render={Item} />@@ -99,7 +106,7 @@ const SwitchCredentialInLoadBalancing = ({)}return Item- }, [customModelCredential, t, credentials, notAllowCustomCredential])+ }, [canUseCredential, customModelCredential, t, credentials, notAllowCustomCredential])return (<Authorized@@ -133,8 +140,10 @@ const SwitchCredentialInLoadBalancing = ({onItemClick={handleItemClick}enableAddModelCredentialshowItemSelectedIcon+ disabled={!canUseCredential}+ hideAddAction={!canManageCredential}popupTitle={t('modelProvider.auth.modelCredentials', { ns: 'common' })}- triggerOnlyOpenModal={!credentials?.length}+ triggerOnlyOpenModal={!credentials?.length && canManageCredential}/>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsxindex e2c934bb7cc..cfb241be7d5 100644--- a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsx@@ -78,9 +78,8 @@ vi.mock('../../model-auth/hooks', () => ({}))vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: true,- }),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({ workspacePermissionKeys: ['credential.manage', 'credential.use'] }),}))vi.mock('@/hooks/use-i18n', () => ({diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsxindex a7e85bd9ebf..f1d672299c0 100644--- a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx@@ -29,7 +29,7 @@ const mockState = vi.hoisted(() => ({credentialData: { credentials: {}, available_credentials: [] } as CredentialData,doingAction: false,deleteCredentialId: null as string | null,- isCurrentWorkspaceManager: true,+ workspacePermissionKeys: ['credential.manage', 'credential.use'] as string[],formSchemas: [] as CredentialFormSchema[],formValues: {} as Record<string, unknown>,modelNameAndTypeFormSchemas: [] as CredentialFormSchema[],@@ -76,7 +76,8 @@ vi.mock('../../model-auth/hooks', () => ({}))vi.mock('@/context/app-context', () => ({- useAppContext: () => ({ isCurrentWorkspaceManager: mockState.isCurrentWorkspaceManager }),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({ workspacePermissionKeys: mockState.workspacePermissionKeys }),}))vi.mock('@/hooks/use-i18n', () => ({@@ -183,7 +184,7 @@ describe('ModelModal', () => {mockState.credentialData = { credentials: {}, available_credentials: [] }mockState.doingAction = falsemockState.deleteCredentialId = null- mockState.isCurrentWorkspaceManager = true+ mockState.workspacePermissionKeys = ['credential.manage', 'credential.use']mockState.formSchemas = []mockState.formValues = {}mockState.modelNameAndTypeFormSchemas = []diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsxindex ecc0cf48e4b..0c7f68fb361 100644--- a/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsx@@ -41,8 +41,9 @@ import {useCredentialData,} from '@/app/components/header/account-setting/model-provider-page/model-auth/hooks'import ModelIcon from '@/app/components/header/account-setting/model-provider-page/model-icon'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useRenderI18nObject } from '@/hooks/use-i18n'+import { hasPermission } from '@/utils/permission'import {ConfigurationMethodEnum,FormTypeEnum,@@ -106,7 +107,9 @@ const ModelModal: FC<ModelModalProps> = ({available_credentials,} = credentialData as any- const { isCurrentWorkspaceManager } = useAppContext()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canUseCredential = hasPermission(workspacePermissionKeys, ['credential.use', 'credential.manage'])+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')const { t } = useTranslation()const language = useLanguage()const {@@ -120,15 +123,21 @@ const ModelModal: FC<ModelModalProps> = ({const formRef2 = useRef<FormRefObject>(null)const isEditMode = !!credential && !!Object.keys(formSchemasValue || {}).filter((key) => {return key !== '__model_name' && key !== '__model_type' && !!formValues[key]- }).length && isCurrentWorkspaceManager+ }).length && canManageCredentialconst handleSave = useCallback(async () => {if (mode === ModelModalModeEnum.addCustomModelToModelList && selectedCredential && !selectedCredential?.addNewCredential) {+ if (!canUseCredential)+ return+handleActiveCredential(selectedCredential, model)onCancel()return}+ if (!canManageCredential)+ return+let modelNameAndTypeIsCheckValidated = truelet modelNameAndTypeValues: Record<string, any> = {}@@ -188,7 +197,7 @@ const ModelModal: FC<ModelModalProps> = ({})}onSave(values)- }, [handleSaveCredential, credential?.credential_id, model, onSave, mode, selectedCredential, handleActiveCredential])+ }, [mode, selectedCredential, model, canUseCredential, canManageCredential, onSave, handleActiveCredential, onCancel, handleSaveCredential, credential?.credential_id])const modalTitle = useMemo(() => {let label = t('modelProvider.auth.apiKeyModal.title', { ns: 'common' })@@ -266,11 +275,14 @@ const ModelModal: FC<ModelModalProps> = ({return t('operation.add', { ns: 'common' })return t('operation.save', { ns: 'common' })}, [mode, t])+ const canSaveCredentialChange = mode === ModelModalModeEnum.addCustomModelToModelList && selectedCredential && !selectedCredential.addNewCredential+ ? canUseCredential+ : canManageCredentialconst handleDeleteCredential = useCallback(() => {handleConfirmDelete()onCancel()- }, [handleConfirmDelete])+ }, [handleConfirmDelete, onCancel])const handleModelNameAndTypeChange = useCallback((field: string, value: any) => {const {@@ -327,7 +339,7 @@ const ModelModal: FC<ModelModalProps> = ({onSelect={setSelectedCredential}selectedCredential={selectedCredential}disabled={isLoading}- notAllowAddNewCredential={notAllowCustomCredential}+ notAllowAddNewCredential={notAllowCustomCredential || !canManageCredential}/>)}@@ -402,7 +414,7 @@ const ModelModal: FC<ModelModalProps> = ({<Buttonvariant="primary"onClick={handleSave}- disabled={isLoading || doingAction}+ disabled={isLoading || doingAction || !canSaveCredentialChange}>{saveButtonText}</Button>diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsxindex 1df71b32761..f5f00b93242 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx@@ -4,7 +4,6 @@ import type {ModelProvider,} from '../declarations'import { cn } from '@langgenius/dify-ui/cn'-import { RiEqualizer2Line } from '@remixicon/react'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'@@ -75,7 +74,7 @@ const AgentModelTrigger: FC<AgentModelTriggerProps> = ({return (<divclassName={cn(- 'group relative flex grow cursor-pointer items-center gap-[2px] rounded-lg bg-components-input-bg-normal p-1 hover:bg-state-base-hover-alt',+ 'group relative flex grow cursor-pointer items-center gap-0.5 rounded-lg bg-components-input-bg-normal p-1 hover:bg-state-base-hover-alt',)}>{modelId@@ -131,7 +130,7 @@ const AgentModelTrigger: FC<AgentModelTriggerProps> = ({)}{modelProvider && !disabled && !needsConfiguration && (<div className="flex items-center pr-1">- <RiEqualizer2Line className="size-4 text-text-tertiary group-hover:text-text-secondary" />+ <span className="i-ri-equalizer-2-line size-4 text-text-tertiary group-hover:text-text-secondary" /></div>)}</>@@ -144,7 +143,7 @@ const AgentModelTrigger: FC<AgentModelTriggerProps> = ({</span></div><div className="flex items-center pr-1">- <RiEqualizer2Line className="size-4 text-text-tertiary group-hover:text-text-secondary" />+ <span className="i-ri-equalizer-2-line size-4 text-text-tertiary group-hover:text-text-secondary" /></div></>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsxindex e946ef6348d..f8511a17855 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsx@@ -74,6 +74,9 @@ vi.mock('@/context/provider-context', () => ({const mockUseAppContext = vi.hoisted(() => vi.fn())vi.mock('@/context/app-context', () => ({useAppContext: mockUseAppContext,+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: ['credential.manage', 'credential.use'],+ }),}))const makeModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({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 67edd0ae685..66d66807b2e 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@@ -30,6 +30,10 @@ vi.mock('@/next/navigation', () => ({useSearchParams: () => mockSearchParams.current,}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission', () => ({+ default: () => ({ canInstallPlugin: true }),+}))+const mockSupportFunctionCall = vi.hoisted(() => vi.fn())vi.mock('@/utils/tool-call', () => ({supportFunctionCall: mockSupportFunctionCall,@@ -261,7 +265,7 @@ describe('Popup', () => {expect(input).toHaveFocus()})- it('should show matching models when searching by model name', () => {+ it('should show matching models when searching by model name with direct props', () => {renderPopup(<PopupHarnessmodelList={[@@ -290,7 +294,7 @@ describe('Popup', () => {expect(screen.queryByText(/common\.modelProvider\.selector\.noModelFoundForSearch/)).not.toBeInTheDocument()})- it('should show empty search placeholder when no provider or model name matches', () => {+ it('should show empty search placeholder when direct props have no provider or model match', () => {renderPopup(<PopupHarnessmodelList={[@@ -315,7 +319,7 @@ describe('Popup', () => {expect(screen.queryByText('gpt-4')).not.toBeInTheDocument()})- it('should show all models of a provider when searching by provider label', () => {+ it('should show all models of a provider when searching by provider label with direct props', () => {renderPopup(<PopupHarnessmodelList={[@@ -525,6 +529,151 @@ describe('Popup', () => {expect(screen.queryByText('langgenius/tongyi/tongyi')).not.toBeInTheDocument()})+ it('should match by model provider key when direct props model label does not contain the search text', () => {+ renderPopup(+ <PopupHarness+ modelList={[+ makeModel({+ provider: 'azure_openai',+ label: { en_US: 'Azure', zh_Hans: 'Azure' },+ models: [+ makeModelItem({ model: 'gpt-4', label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' } }),+ ],+ }),+ ]}+ onHide={vi.fn()}+ />,+ )++ fireEvent.change(+ screen.getByPlaceholderText('datasetSettings.form.searchModel'),+ { target: { value: 'openai' } },+ )++ expect(screen.getByText('azure_openai'))!.toBeInTheDocument()+ expect(screen.getByText('gpt-4'))!.toBeInTheDocument()+ })++ it('should still apply scope features when direct props match by provider label', () => {+ mockSupportFunctionCall.mockReturnValue(false)++ renderPopup(+ <PopupHarness+ modelList={[+ makeModel({+ provider: 'openai',+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [+ makeModelItem({ model: 'gpt-4', features: [ModelFeatureEnum.vision] }),+ makeModelItem({ model: 'gpt-4-tool', features: [ModelFeatureEnum.toolCall] }),+ ],+ }),+ ]}+ onHide={vi.fn()}+ scopeFeatures={[ModelFeatureEnum.toolCall]}+ />,+ )++ fireEvent.change(+ screen.getByPlaceholderText('datasetSettings.form.searchModel'),+ { target: { value: 'openai' } },+ )++ expect(screen.getByText(/common\.modelProvider\.selector\.noModelFoundForSearch.*openai/))!.toBeInTheDocument()+ expect(screen.queryByText('gpt-4')).not.toBeInTheDocument()+ expect(screen.queryByText('gpt-4-tool')).not.toBeInTheDocument()+ })++ it('should show matching models when searching by model name', () => {+ renderPopup(+ <PopupHarness+ modelList={[+ makeModel({+ models: [makeModelItem({ model: 'gpt-4', label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' } })],+ }),+ makeModel({+ provider: 'anthropic',+ label: { en_US: 'Anthropic', zh_Hans: 'Anthropic' },+ models: [makeModelItem({ model: 'claude-3', label: { en_US: 'Claude 3', zh_Hans: 'Claude 3' } })],+ }),+ ]}+ onHide={vi.fn()}+ />,+ )++ fireEvent.change(+ screen.getByPlaceholderText('datasetSettings.form.searchModel'),+ { target: { value: 'claude' } },+ )++ expect(screen.queryByText('openai')).not.toBeInTheDocument()+ expect(screen.getByText('anthropic')).toBeInTheDocument()+ expect(screen.getByText('claude-3')).toBeInTheDocument()+ expect(screen.queryByText('gpt-4')).not.toBeInTheDocument()+ expect(screen.queryByText(/common\.modelProvider\.selector\.noModelFoundForSearch.*claude/)).not.toBeInTheDocument()+ })++ it('should show empty search placeholder when no provider or model name matches', () => {+ renderPopup(+ <PopupHarness+ modelList={[+ makeModel({+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [+ makeModelItem({ model: 'gpt-4', label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' } }),+ ],+ }),+ ]}+ onHide={vi.fn()}+ />,+ )++ fireEvent.change(+ screen.getByPlaceholderText('datasetSettings.form.searchModel'),+ { target: { value: 'mistral' } },+ )++ expect(screen.getByText(/common\.modelProvider\.selector\.noModelFoundForSearch.*mistral/))!.toBeInTheDocument()+ expect(screen.queryByText('openai')).not.toBeInTheDocument()+ expect(screen.queryByText('gpt-4')).not.toBeInTheDocument()+ })++ it('should show all models of a provider when searching by provider label', () => {+ renderPopup(+ <PopupHarness+ modelList={[+ makeModel({+ provider: 'openai',+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [+ makeModelItem({ model: 'gpt-4', label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' } }),+ makeModelItem({ model: 'gpt-4o', label: { en_US: 'GPT-4o', zh_Hans: 'GPT-4o' } }),+ ],+ }),+ makeModel({+ provider: 'anthropic',+ label: { en_US: 'Anthropic', zh_Hans: 'Anthropic' },+ models: [+ makeModelItem({ model: 'claude-3', label: { en_US: 'Claude 3', zh_Hans: 'Claude 3' } }),+ ],+ }),+ ]}+ onHide={vi.fn()}+ />,+ )++ fireEvent.change(+ screen.getByPlaceholderText('datasetSettings.form.searchModel'),+ { target: { value: 'openai' } },+ )++ expect(screen.getByText('openai'))!.toBeInTheDocument()+ expect(screen.getByText('gpt-4'))!.toBeInTheDocument()+ expect(screen.getByText('gpt-4o'))!.toBeInTheDocument()+ expect(screen.queryByText('anthropic')).not.toBeInTheDocument()+ expect(screen.queryByText('claude-3')).not.toBeInTheDocument()+ })+it('should match by model provider key when model label does not contain the search text', () => {renderPopup(<PopupHarnessdiff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsxindex 987bae96758..26edfd22eca 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsx@@ -11,6 +11,7 @@ type MarketplaceSectionProps = {marketplaceCollapsed: booleaninstallingProvider: ModelProviderQuotaGetPaid | nullisMarketplacePluginsLoading: boolean+ canInstallPlugin: booleantheme?: stringonMarketplaceCollapsedChange: (collapsed: boolean) => voidonInstallPlugin: (key: ModelProviderQuotaGetPaid) => void | Promise<void>@@ -21,6 +22,7 @@ function MarketplaceSection({marketplaceCollapsed,installingProvider,isMarketplacePluginsLoading,+ canInstallPlugin,theme,onMarketplaceCollapsedChange,onInstallPlugin,@@ -60,21 +62,23 @@ function MarketplaceSection({<Icon className="size-5 shrink-0 rounded-md" /><span className="system-sm-regular text-text-secondary">{modelNameMap[key]}</span></div>- <Button- variant="secondary"- size="small"- className={cn(- 'shrink-0 backdrop-blur-[5px]',- !isInstalling && 'hidden group-hover:flex',- )}- disabled={isInstalling || isMarketplacePluginsLoading}- onClick={() => onInstallPlugin(key)}- >- {isInstalling && <span className="i-ri-loader-2-line size-3.5 animate-spin" />}- {isInstalling- ? t('installModal.installing', { ns: 'plugin' })- : t('modelProvider.selector.install', { ns: 'common' })}- </Button>+ {canInstallPlugin && (+ <Button+ variant="secondary"+ size="small"+ className={cn(+ 'shrink-0 backdrop-blur-[5px]',+ !isInstalling && 'hidden group-hover:flex',+ )}+ disabled={isInstalling || isMarketplacePluginsLoading}+ onClick={() => onInstallPlugin(key)}+ >+ {isInstalling && <span className="i-ri-loader-2-line size-3.5 animate-spin" />}+ {isInstalling+ ? t('installModal.installing', { ns: 'plugin' })+ : t('modelProvider.selector.install', { ns: 'common' })}+ </Button>+ )}</div>)})}diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsxindex 59aa284b339..a957ae16577 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsx@@ -8,8 +8,10 @@ import { StatusDot } from '@langgenius/dify-ui/status-dot'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { CreditsCoin } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { hasPermission } from '@/utils/permission'import { ConfigurationMethodEnum, ModelStatusEnum } from '../declarations'import { useLanguage, useUpdateModelList, useUpdateModelProviders } from '../hooks'import ModelIcon from '../model-icon'@@ -48,7 +50,13 @@ function PopupItem({const updateModelList = useUpdateModelList()const updateModelProviders = useUpdateModelProviders()const currentProvider = modelProviders.find(provider => provider.provider === model.provider)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canUseCredentials = hasPermission(workspacePermissionKeys, ['credential.manage', 'credential.use'])+ const canManageCredentials = hasPermission(workspacePermissionKeys, 'credential.manage')const handleOpenModelModal = () => {+ if (!canManageCredentials)+ return+if (!currentProvider)returnsetShowModelModal({@@ -102,6 +110,7 @@ function PopupItem({</button><Popover open={dropdownOpen} onOpenChange={setDropdownOpen}><PopoverTrigger+ disabled={!canUseCredentials}render={(<button type="button" className="flex max-w-[50%] min-w-0 shrink-0 cursor-pointer items-center rounded-md px-1.5 py-1 system-xs-medium text-text-tertiary hover:bg-components-button-ghost-bg-hover">{isUsingCredits@@ -133,7 +142,7 @@ function PopupItem({<span className="ml-1 truncate text-text-tertiary">{t('modelProvider.selector.configureRequired', { ns: 'common' })}</span></>)}- <span className="i-ri-arrow-down-s-line size-3.5! shrink-0 translate-y-px text-text-tertiary" />+ {canUseCredentials && <span className="i-ri-arrow-down-s-line size-3.5! shrink-0 translate-y-px text-text-tertiary" />}</button>)}/>@@ -184,13 +193,15 @@ function PopupItem({onPointerDown={onPreviewCardClose}>{rowContent}- <button- type="button"- className="hidden cursor-pointer text-xs font-medium text-text-accent group-hover:block"- onClick={handleOpenModelModal}- >- {t('operation.add', { ns: 'common' }).toLocaleUpperCase()}- </button>+ {canManageCredentials && (+ <button+ type="button"+ className="hidden cursor-pointer text-xs font-medium text-text-accent group-hover:block"+ onClick={handleOpenModelModal}+ >+ {t('operation.add', { ns: 'common' }).toLocaleUpperCase()}+ </button>+ )}</div>): (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 7cf543a3568..3b8122f6071 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@@ -11,6 +11,7 @@ import { ACCOUNT_SETTING_MODAL_ACTION, ACCOUNT_SETTING_TAB } from '@/app/componeimport { useIntegrationsSetting } from '@/app/components/header/account-setting/use-integrations-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'@@ -72,6 +73,7 @@ function Popup({} = useMarketplaceAllPlugins(modelProviders, '', enableMarketplace)const { mutateAsync: installPackageFromMarketPlace } = useInstallPackageFromMarketPlace()const { refreshPluginList } = useRefreshPluginList()+ const { canInstallPlugin } = useWorkspacePluginInstallPermission()const [installingProvider, setInstallingProvider] = useState<ModelProviderQuotaGetPaid | null>(null)const { isExhausted: isCreditsExhausted } = useTrialCredits()const { data: trialModels = [] } = useQuery(consoleQuery.trialModels.get.queryOptions({@@ -100,7 +102,7 @@ function Popup({})const handleInstallPlugin = useCallback(async (key: ModelProviderQuotaGetPaid) => {- if (!enableMarketplace || !allPlugins || isMarketplacePluginsLoading || installingProvider)+ if (!enableMarketplace || !canInstallPlugin || !allPlugins || isMarketplacePluginsLoading || installingProvider)returnconst pluginId = providerKeyToPluginId[key]const plugin = allPlugins.find(p => p.plugin_id === pluginId)@@ -121,7 +123,7 @@ function Popup({finally {setInstallingProvider(null)}- }, [allPlugins, enableMarketplace, installPackageFromMarketPlace, installingProvider, isMarketplacePluginsLoading, refreshPluginList])+ }, [allPlugins, enableMarketplace, canInstallPlugin, installPackageFromMarketPlace, installingProvider, isMarketplacePluginsLoading, refreshPluginList])const installedModelList = useMemo(() => {const modelMap = new Map(modelList.map(model => [model.provider, model]))@@ -230,6 +232,7 @@ function Popup({marketplaceCollapsed={marketplaceCollapsed}installingProvider={installingProvider}isMarketplacePluginsLoading={isMarketplacePluginsLoading}+ canInstallPlugin={canInstallPlugin}theme={theme}onMarketplaceCollapsedChange={setMarketplaceCollapsed}onInstallPlugin={handleInstallPlugin}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 0b920008b42..01886f0db8a 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@@ -8,6 +8,7 @@ import { ConfigurationMethodEnum } from '../../declarations'import ProviderAddedCard from '../index'let mockIsCurrentWorkspaceManager = true+let mockWorkspacePermissionKeys: string[] = ['plugin.manage', 'credential.manage', 'credential.use']const mockFetchModelProviderModels = vi.fn()const mockQueryOptions = vi.fn(({ input, ...options }: { input: { params: { provider: string } }, enabled?: boolean }) => ({queryKey: ['console', 'modelProviders', 'models', input.params.provider],@@ -29,6 +30,9 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager,}),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),}))// Mock internal components to simplify testing of the index file@@ -101,6 +105,7 @@ describe('ProviderAddedCard', () => {beforeEach(() => {vi.clearAllMocks()mockIsCurrentWorkspaceManager = true+ mockWorkspacePermissionKeys = ['plugin.manage', 'credential.manage', 'credential.use']})it('should render provider added card component', () => {@@ -196,7 +201,7 @@ describe('ProviderAddedCard', () => {expect(screen.getByText('common.modelProvider.configureTip')).toBeInTheDocument()})- it('should render custom model actions for workspace managers', () => {+ it('should render custom model actions when user can manage plugins', () => {const customConfigProvider = {...mockProvider,configurate_methods: [ConfigurationMethodEnum.customizableModel],@@ -208,7 +213,21 @@ describe('ProviderAddedCard', () => {unmount()mockIsCurrentWorkspaceManager = false+ mockWorkspacePermissionKeys = ['credential.manage', 'credential.use']renderWithQueryClient(<ProviderAddedCard provider={customConfigProvider} />)expect(screen.queryByTestId('manage-custom-model')).not.toBeInTheDocument()})++ it('should render custom model actions when user can manage plugins without credential permissions', () => {+ const customConfigProvider = {+ ...mockProvider,+ configurate_methods: [ConfigurationMethodEnum.customizableModel],+ } as unknown as ModelProvider+ mockWorkspacePermissionKeys = ['plugin.manage']++ renderWithQueryClient(<ProviderAddedCard provider={customConfigProvider} />)++ expect(screen.getByTestId('manage-custom-model')).toBeInTheDocument()+ expect(screen.getByTestId('add-custom-model')).toBeInTheDocument()+ })})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsxindex 1615d86faf1..d21df4c5a89 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsx@@ -14,10 +14,11 @@ function createWrapper() {let mockModelLoadBalancingEnabled = falselet mockPlanType: string = 'pro'+let mockWorkspacePermissionKeys: string[] = ['plugin.manage']vi.mock('@/context/app-context', () => ({useAppContext: () => ({- isCurrentWorkspaceManager: true,+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -70,6 +71,7 @@ describe('ModelListItem', () => {vi.clearAllMocks()mockModelLoadBalancingEnabled = falsemockPlanType = 'pro'+ mockWorkspacePermissionKeys = ['plugin.manage']})it('should render model item with icon and name', () => {@@ -142,6 +144,42 @@ describe('ModelListItem', () => {expect(onModifyLoadBalancing).toHaveBeenCalledWith(mockModel)})+ it('should allow model status and load balancing controls with plugin.manage', () => {+ mockWorkspacePermissionKeys = ['plugin.manage']+ mockModelLoadBalancingEnabled = true++ render(+ <ModelListItem+ model={mockModel}+ provider={mockProvider}+ isConfigurable+ onModifyLoadBalancing={vi.fn()}+ />,+ { wrapper: createWrapper() },+ )++ expect(screen.getByRole('switch')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'modify load balancing' })).toBeInTheDocument()+ })++ it('should hide model status and load balancing controls without plugin.manage', () => {+ mockWorkspacePermissionKeys = []+ mockModelLoadBalancingEnabled = true++ render(+ <ModelListItem+ model={mockModel}+ provider={mockProvider}+ isConfigurable+ onModifyLoadBalancing={vi.fn()}+ />,+ { wrapper: createWrapper() },+ )++ expect(screen.queryByRole('switch')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'modify load balancing' })).not.toBeInTheDocument()+ })+// Deprecated branches: opacity-60, disabled switch, no ConfigModelit('should show deprecated model with opacity and disabled switch', () => {// Arrangediff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list.spec.tsxindex e435835807f..215b349eb0d 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list.spec.tsx@@ -4,12 +4,11 @@ import { ConfigurationMethodEnum } from '../../declarations'import ModelList from '../model-list'const mockSetShowModelLoadBalancingModal = vi.fn()-let mockIsCurrentWorkspaceManager = true+let mockWorkspacePermissionKeys: string[] = ['plugin.manage', 'credential.manage', 'credential.use']vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager,- }),+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({ workspacePermissionKeys: mockWorkspacePermissionKeys }),}))vi.mock('@/context/modal-context', () => ({@@ -46,7 +45,7 @@ describe('ModelList', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCurrentWorkspaceManager = true+ mockWorkspacePermissionKeys = ['plugin.manage', 'credential.manage', 'credential.use']})it('should render model count and model items', () => {@@ -92,8 +91,8 @@ describe('ModelList', () => {expect(mockSetShowModelLoadBalancingModal).toHaveBeenCalled()})- it('should hide custom model actions for non-manager', () => {- mockIsCurrentWorkspaceManager = false+ it('should hide custom model actions without plugin.manage', () => {+ mockWorkspacePermissionKeys = []render(<ModelListprovider={mockProvider}@@ -107,15 +106,12 @@ describe('ModelList', () => {expect(screen.queryByTestId('add-custom-model')).not.toBeInTheDocument()})- // isConfigurable=false: predefinedModel only provider hides custom model actionsit('should hide custom model actions when provider uses predefinedModel only', () => {- // Arrangeconst predefinedProvider = {provider: 'test-provider',configurate_methods: ['predefinedModel'],} as unknown as ModelProvider- // Actrender(<ModelListprovider={predefinedProvider}@@ -183,15 +179,12 @@ describe('ModelList', () => {expect(mockSetShowModelLoadBalancingModal).toHaveBeenCalledWith(null)})- // fetchFromRemote filtered out: provider with only fetchFromRemoteit('should hide custom model actions when provider uses fetchFromRemote only', () => {- // Arrangeconst fetchOnlyProvider = {provider: 'test-provider',configurate_methods: ['fetchFromRemote'],} as unknown as ModelProvider- // Actrender(<ModelListprovider={fetchOnlyProvider}@@ -237,16 +230,14 @@ describe('ModelList', () => {expect(screen.queryByTestId('add-custom-model')).not.toBeInTheDocument()})- it('should show custom model actions when provider is configurable and user is workspace manager', () => {- // Arrange: use ConfigurationMethodEnum.customizableModel ('customizable-model') so isConfigurable=true+ it('should show custom model actions when provider is configurable and user can manage plugins', () => {const configurableProvider = {provider: 'test-provider',configurate_methods: [ConfigurationMethodEnum.customizableModel],} as unknown as ModelProvider- mockIsCurrentWorkspaceManager = true+ mockWorkspacePermissionKeys = ['plugin.manage']- // Actrender(<ModelListprovider={configurableProvider}@@ -256,22 +247,18 @@ describe('ModelList', () => {/>,)- // Assert: custom model actions are shown (isConfigurable=true && isCurrentWorkspaceManager=true)- // Assert: custom model actions are shown (isConfigurable=true && isCurrentWorkspaceManager=true)expect(screen.getByTestId('manage-credentials'))!.toBeInTheDocument()expect(screen.getByTestId('add-custom-model'))!.toBeInTheDocument()})- it('should hide custom model actions when provider is configurable but user is not workspace manager', () => {- // Arrange: use ConfigurationMethodEnum.customizableModel ('customizable-model') so isConfigurable=true, but manager=false+ it('should hide custom model actions when provider is configurable but user cannot manage plugins', () => {const configurableProvider = {provider: 'test-provider',configurate_methods: [ConfigurationMethodEnum.customizableModel],} as unknown as ModelProvider- mockIsCurrentWorkspaceManager = false+ mockWorkspacePermissionKeys = []- // Actrender(<ModelListprovider={configurableProvider}@@ -281,38 +268,6 @@ describe('ModelList', () => {/>,)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)- // Assert: custom model actions are hidden (isCurrentWorkspaceManager=false covers the && short-circuit)expect(screen.queryByTestId('manage-credentials')).not.toBeInTheDocument()expect(screen.queryByTestId('add-custom-model')).not.toBeInTheDocument()})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsxindex 595ad30089a..55a67db72f9 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx@@ -71,6 +71,16 @@ vi.mock('@/app/components/plugins/plugin-detail-panel/operation-dropdown', () =>),}))+vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({+ usePluginSettingsAccess: () => ({+ canManagePlugin: true,+ canUpdatePlugin: true,+ }),+ default: () => ({+ canUpdate: true,+ }),+}))+vi.mock('@/app/components/plugins/update-plugin/plugin-version-picker', () => ({default: ({ trigger, onSelect, disabled }: {trigger: ReactNodediff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsxindex 01627533a2b..daaebf53724 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx@@ -56,6 +56,14 @@ vi.mock('../../hooks', () => ({}),}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission', () => ({+ default: () => ({+ canInstallPlugin: true,+ canUpdatePlugin: true,+ currentDifyVersion: '1.0.0',+ }),+}))+vi.mock('@/hooks/use-timestamp', () => ({default: () => ({formatTime: () => '2024-12-31',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 1f42c5ec7d2..696c9c623d7 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@@ -14,10 +14,11 @@ import {ManageCustomModelCredentials,} from '@/app/components/header/account-setting/model-provider-page/model-auth'import { IS_CE_EDITION } from '@/config'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useProviderContextSelector } from '@/context/provider-context'import { renderI18nObject } from '@/i18n-config'import { consoleQuery } from '@/service/client'+import { hasPermission } from '@/utils/permission'import { useModelProviderListExpanded, useSetModelProviderListExpanded } from '../atoms'import { ConfigurationMethodEnum } from '../declarations'import { useLanguage } from '../hooks'@@ -65,10 +66,12 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({}))const hasModelList = hasFetchedModelList && !!modelList.lengthconst showCollapsedSection = !expanded || !hasFetchedModelList- const { isCurrentWorkspaceManager } = useAppContext()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const showModelProvider = systemConfig.enabled && MODEL_PROVIDER_QUOTA_GET_PAID.includes(currentProviderName as ModelProviderQuotaGetPaid) && !IS_CE_EDITION- const showCredential = supportsPredefinedModel && isCurrentWorkspaceManager- const showCustomModelActions = supportsCustomizableModel && isCurrentWorkspaceManager+ const canManagePlugins = hasPermission(workspacePermissionKeys, 'plugin.manage')+ const canUseCredentials = hasPermission(workspacePermissionKeys, ['credential.manage', 'credential.use'])+ const showCredential = supportsPredefinedModel && canUseCredentials+ const showCustomModelActions = supportsCustomizableModel && canManagePluginsconst refreshModelList = useCallback((targetProviderName: string) => {if (targetProviderName !== currentProviderName)@@ -241,7 +244,7 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({</div>{showCollapsedSection && (- <div className="group flex items-center justify-between border-t border-t-divider-subtle py-1.5 pr-[11px] pl-2 system-xs-medium text-text-tertiary">+ <div className="group flex items-center justify-between border-t border-t-divider-subtle py-1.5 pr-2.75 pl-2 system-xs-medium text-text-tertiary">{(showModelProvider || !notConfigured) && (<buttontype="button"diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/api-key-section.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/api-key-section.spec.tsxindex 942885c617c..03224ac09f3 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/api-key-section.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/api-key-section.spec.tsx@@ -3,6 +3,12 @@ import { fireEvent, render, screen } from '@testing-library/react'import { CustomConfigurationStatusEnum, PreferredProviderTypeEnum } from '../../../declarations'import ApiKeySection from '../api-key-section'+vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: ['credential.manage', 'credential.use'],+ }),+}))+const createCredential = (overrides: Partial<Credential> = {}): Credential => ({credential_id: 'cred-1',credential_name: 'Test API Key',diff --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 424b92c8dd9..5e16edba5e4 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@@ -10,6 +10,7 @@ const mockOpenConfirmDelete = vi.fn()const mockCloseConfirmDelete = vi.fn()const mockHandleConfirmDelete = vi.fn()let mockDeleteCredentialId: string | null = null+let mockWorkspacePermissionKeys = ['credential.manage', 'credential.use']vi.mock('../../use-trial-credits', () => ({useTrialCredits: () => ({ credits: 0, totalCredits: 10_000, isExhausted: true, isLoading: false }),@@ -34,9 +35,18 @@ vi.mock('../../../model-auth/hooks', () => ({}),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+vi.mock('../../../model-auth/authorized/credential-item', () => ({- default: ({ credential, onItemClick, onEdit, onDelete }: {+ default: ({ credential, disabled, disableEdit, disableDelete, onItemClick, onEdit, onDelete }: {credential: { credential_id: string, credential_name: string }+ disabled?: boolean+ disableEdit?: boolean+ disableDelete?: booleanonItemClick?: (c: unknown) => voidonEdit?: (c: unknown) => voidonDelete?: (c: unknown) => void@@ -44,8 +54,8 @@ vi.mock('../../../model-auth/authorized/credential-item', () => ({<div data-testid={`credential-${credential.credential_id}`}><span>{credential.credential_name}</span><button data-testid={`click-${credential.credential_id}`} onClick={() => onItemClick?.(credential)}>select</button>- <button data-testid={`edit-${credential.credential_id}`} onClick={() => onEdit?.(credential)}>edit</button>- <button data-testid={`delete-${credential.credential_id}`} onClick={() => onDelete?.(credential)}>delete</button>+ <button data-testid={`edit-${credential.credential_id}`} disabled={disabled || disableEdit} onClick={() => onEdit?.(credential)}>edit</button>+ <button data-testid={`delete-${credential.credential_id}`} disabled={disabled || disableDelete} onClick={() => onDelete?.(credential)}>delete</button></div>),}))@@ -87,6 +97,7 @@ describe('DropdownContent', () => {beforeEach(() => {vi.clearAllMocks()mockDeleteCredentialId = null+ mockWorkspacePermissionKeys = ['credential.manage', 'credential.use']})describe('UsagePrioritySection visibility', () => {@@ -362,6 +373,30 @@ describe('DropdownContent', () => {expect.objectContaining({ credential_id: 'cred-2' }),)})++ it('should allow use-only users to switch credentials but not edit or delete them', () => {+ mockWorkspacePermissionKeys = ['credential.use']++ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )++ fireEvent.click(screen.getByTestId('click-cred-2'))+ fireEvent.click(screen.getByTestId('edit-cred-2'))+ fireEvent.click(screen.getByTestId('delete-cred-2'))++ expect(mockActivate).toHaveBeenCalledWith(+ expect.objectContaining({ credential_id: 'cred-2' }),+ )+ expect(mockHandleOpenModal).not.toHaveBeenCalled()+ expect(mockOpenConfirmDelete).not.toHaveBeenCalled()+ })})describe('Add API Key', () => {@@ -386,6 +421,27 @@ describe('DropdownContent', () => {expect(mockHandleOpenModal).toHaveBeenCalledWith()expect(onClose).toHaveBeenCalled()})++ it('should hide add action for use-only users', () => {+ mockWorkspacePermissionKeys = ['credential.use']++ render(+ <DropdownContent+ provider={createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ })}+ state={createState({ hasCredentials: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )++ expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()+ })})describe('AlertDialog for delete confirmation', () => {diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.tsxindex 41645677b69..eba042cb48f 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.tsx@@ -2,6 +2,8 @@ import type { Credential, CustomModel, ModelProvider } from '../../declarations'import { Button } from '@langgenius/dify-ui/button'import { memo } from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'import CredentialItem from '../../model-auth/authorized/credential-item'type ApiKeySectionProps = {@@ -27,6 +29,8 @@ function ApiKeySection({}: ApiKeySectionProps) {const { t } = useTranslation()const notAllowCustomCredential = provider.allow_custom_token === false+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')if (!credentials.length) {return (@@ -41,7 +45,7 @@ function ApiKeySection({</div></div></div>- {!notAllowCustomCredential && (+ {!notAllowCustomCredential && canManageCredential && (<ButtononClick={onAdd}className="w-full"@@ -59,7 +63,7 @@ function ApiKeySection({<div className="pt-3 pr-2 pb-1 pl-7 system-xs-medium-uppercase text-text-tertiary">{t('modelProvider.auth.apiKeys', { ns: 'common' })}</div>- <div className="max-h-[200px] overflow-y-auto">+ <div className="max-h-50 overflow-y-auto">{credentials.map(credential => (<CredentialItemkey={credential.credential_id}@@ -70,11 +74,13 @@ function ApiKeySection({onItemClick={onItemClick}onEdit={onEdit}onDelete={onDelete}+ disableEdit={!canManageCredential}+ disableDelete={!canManageCredential}/>))}</div></div>- {!notAllowCustomCredential && (+ {!notAllowCustomCredential && canManageCredential && (<div className="p-2"><ButtononClick={onAdd}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsxindex 66a080015d7..7fda66c8e4f 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx@@ -13,6 +13,7 @@ import { useAppContext } from '@/context/app-context'import { useProviderContext, useProviderContextSelector } from '@/context/provider-context'import { consoleQuery } from '@/service/client'import { disableModel, enableModel } from '@/service/common'+import { hasPermission } from '@/utils/permission'import { ModelStatusEnum } from '../declarations'import { useUpdateModelList } from '../hooks'import { ConfigModel } from '../model-auth'@@ -31,7 +32,8 @@ const ModelListItem = ({ model, provider, isConfigurable, onChange, onModifyLoadconst { t } = useTranslation()const { plan } = useProviderContext()const modelLoadBalancingEnabled = useProviderContextSelector(state => state.modelLoadBalancingEnabled)- const { isCurrentWorkspaceManager } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()+ const canManagePlugin = hasPermission(workspacePermissionKeys, 'plugin.manage')const queryClient = useQueryClient()const updateModelList = useUpdateModelList()const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({@@ -86,12 +88,12 @@ const ModelListItem = ({ model, provider, isConfigurable, onChange, onModifyLoad</ModelName><div className="flex shrink-0 items-center">{modelLoadBalancingEnabled && !model.deprecated && model.load_balancing_enabled && !model.has_invalid_load_balancing_configs && (- <Badge className="mr-1 h-[18px] w-[18px] items-center justify-center border-text-accent-secondary p-0">+ <Badge className="mr-1 h-4.5 w-4.5 items-center justify-center border-text-accent-secondary p-0"><Balance className="size-3 text-text-accent-secondary" /></Badge>)}{- (isCurrentWorkspaceManager && (modelLoadBalancingEnabled || plan.type === Plan.sandbox) && !model.deprecated && [ModelStatusEnum.active, ModelStatusEnum.disabled].includes(model.status)) && (+ (canManagePlugin && (modelLoadBalancingEnabled || plan.type === Plan.sandbox) && !model.deprecated && [ModelStatusEnum.active, ModelStatusEnum.disabled].includes(model.status)) && (<ConfigModelonClick={() => onModifyLoadBalancing?.(model)}loadBalancingEnabled={model.load_balancing_enabled}@@ -110,7 +112,7 @@ const ModelListItem = ({ model, provider, isConfigurable, onChange, onModifyLoad</PopoverContent></Popover>)- : (isCurrentWorkspaceManager && (+ : (canManagePlugin && (<SwitchclassName="ml-2"checked={model?.status === ModelStatusEnum.active}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list.tsxindex 344d3de0f6a..9870950fe3e 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list.tsx@@ -4,17 +4,15 @@ import type {ModelItem,ModelProvider,} from '../declarations'-import {- RiArrowRightSLine,-} from '@remixicon/react'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import {AddCustomModel,ManageCustomModelCredentials,} from '@/app/components/header/account-setting/model-provider-page/model-auth'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useModalContextSelector } from '@/context/modal-context'+import { hasPermission } from '@/utils/permission'import {ConfigurationMethodEnum,} from '../declarations'@@ -35,7 +33,8 @@ const ModelList: FC<ModelListProps> = ({}) => {const { t } = useTranslation()const configurativeMethods = provider.configurate_methods.filter(method => method !== ConfigurationMethodEnum.fetchFromRemote)- const { isCurrentWorkspaceManager } = useAppContext()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canManagePlugins = hasPermission(workspacePermissionKeys, 'plugin.manage')const isConfigurable = configurativeMethods.includes(ConfigurationMethodEnum.customizableModel)const setShowModelLoadBalancingModal = useModalContextSelector(state => state.setShowModelLoadBalancingModal)const onModifyLoadBalancing = useCallback((model: ModelItem, credential?: Credential) => {@@ -53,22 +52,22 @@ const ModelList: FC<ModelListProps> = ({return (<div className="rounded-b-xl px-2 pb-2"><div className="rounded-lg bg-components-panel-bg py-1">- <div className="flex items-center pr-[3px] pl-1">+ <div className="flex items-center pr-0.75 pl-1"><span className="group mr-2 flex shrink-0 items-center"><span className="inline-flex h-6 items-center pr-1.5 pl-1 system-xs-medium text-text-tertiary group-hover:hidden">{t('modelProvider.modelsNum', { ns: 'common', num: models.length })}- <RiArrowRightSLine className="mr-0.5 size-4 rotate-90" />+ <span className="mr-0.5 i-ri-arrow-right-s-line size-4 rotate-90" /></span><spanclassName="hidden h-6 cursor-pointer items-center rounded-lg bg-state-base-hover pr-1.5 pl-1 system-xs-medium text-text-tertiary group-hover:inline-flex"onClick={() => onCollapse()}>{t('modelProvider.modelsNum', { ns: 'common', num: models.length })}- <RiArrowRightSLine className="mr-0.5 size-4 rotate-90" />+ <span className="mr-0.5 i-ri-arrow-right-s-line size-4 rotate-90" /></span></span>{- isConfigurable && isCurrentWorkspaceManager && (+ isConfigurable && canManagePlugins && (<div className="flex grow justify-end"><ManageCustomModelCredentialsprovider={provider}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsxindex 94e290ea9c5..ae22c90588a 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx@@ -9,6 +9,7 @@ import Badge from '@/app/components/base/badge'import { HeaderModals } from '@/app/components/plugins/plugin-detail-panel/detail-header/components'import { useDetailHeaderState, usePluginOperations } from '@/app/components/plugins/plugin-detail-panel/detail-header/hooks'import OperationDropdown from '@/app/components/plugins/plugin-detail-panel/operation-dropdown'+import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import { PluginSource } from '@/app/components/plugins/types'import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'import { useLocale } from '@/context/i18n'@@ -24,6 +25,7 @@ const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {const { t } = useTranslation()const { theme } = useTheme()const locale = useLocale()+ const { canManagePlugin, canUpdatePlugin } = usePluginSettingsAccess()const { source, version, latest_version, latest_unique_identifier, meta } = detailconst author = detail.declaration?.author ?? ''@@ -47,6 +49,8 @@ const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {modalStates,versionPicker,isFromMarketplace,+ canManagePlugin,+ canUpdatePlugin,onUpdate,})@@ -77,7 +81,7 @@ const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {<>{!!version && (<PluginVersionPicker- disabled={!isFromMarketplace}+ disabled={!isFromMarketplace || !canUpdatePlugin}isShow={versionPicker.isShow}onShowChange={versionPicker.setIsShow}pluginID={detail.plugin_id}@@ -88,13 +92,13 @@ const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {trigger={(<BadgeclassName={cn(- isFromMarketplace && 'cursor-pointer hover:bg-state-base-hover',+ canUpdatePlugin && isFromMarketplace && 'cursor-pointer hover:bg-state-base-hover',)}uppercase={false}text={(<><span>{version}</span>- {isFromMarketplace && <span className="ml-1 i-ri-arrow-left-right-line size-3" />}+ {canUpdatePlugin && isFromMarketplace && <span className="ml-1 i-ri-arrow-left-right-line size-3" />}</>)}hasRedCornerMark={hasNewVersion}@@ -103,7 +107,7 @@ const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {/>)}- {(hasNewVersion || isFromGitHub) && (+ {canUpdatePlugin && (hasNewVersion || isFromGitHub) && (<Tooltip><TooltipTriggerdelay={300}@@ -132,6 +136,8 @@ const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {detailUrl={detailUrl}placement="bottom-start"destructiveRemove+ showCheckVersion={canUpdatePlugin}+ showRemove={canManagePlugin}/><HeaderModalsdiff --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 ecae5fc1818..6cf1b72113f 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@@ -11,6 +11,8 @@ import * as React from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'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 useTimestamp from '@/hooks/use-timestamp'@@ -85,11 +87,12 @@ const QuotaPanel: FC<QuotaPanelProps> = ({setTrue: showInstallFromMarketplace,setFalse: hideInstallFromMarketplace,}] = useBoolean(false)+ const { canInstallPlugin, canUpdatePlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()const selectedPluginIdRef = useRef<string | null>(null)const handleIconClick = useCallback((key: ModelProviderQuotaGetPaid) => {const isInstalled = providerMap.get(key)- if (!isInstalled && allPlugins) {+ if (!isInstalled && allPlugins && canInstallPlugin) {const pluginId = providerKeyToPluginId[key]const plugin = allPlugins.find(p => p.plugin_id === pluginId)if (plugin) {@@ -98,7 +101,7 @@ const QuotaPanel: FC<QuotaPanelProps> = ({showInstallFromMarketplace()}}- }, [allPlugins, providerMap, showInstallFromMarketplace])+ }, [allPlugins, canInstallPlugin, providerMap, showInstallFromMarketplace])useEffect(() => {if (isShowInstallModal && selectedPluginIdRef.current) {@@ -178,7 +181,7 @@ const QuotaPanel: FC<QuotaPanelProps> = ({aria-label={tooltipText}render={(<div- className={cn('relative size-6', !providerType && 'cursor-pointer hover:opacity-80')}+ className={cn('relative size-6', !providerType && canInstallPlugin && 'cursor-pointer hover:opacity-80')}onClick={() => handleIconClick(key)}><Icon className="size-6 rounded-lg" />@@ -197,13 +200,19 @@ const QuotaPanel: FC<QuotaPanelProps> = ({</div></div></div>- {isShowInstallModal && selectedPlugin && (- <InstallFromMarketplace- manifest={selectedPlugin}- uniqueIdentifier={selectedPlugin.latest_package_identifier}- onClose={hideInstallFromMarketplace}- onSuccess={hideInstallFromMarketplace}- />+ {isShowInstallModal && selectedPlugin && canInstallPlugin && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ canUpdatePlugin={canUpdatePlugin}+ currentDifyVersion={currentDifyVersion}+ >+ <InstallFromMarketplace+ manifest={selectedPlugin}+ uniqueIdentifier={selectedPlugin.latest_package_identifier}+ onClose={hideInstallFromMarketplace}+ onSuccess={hideInstallFromMarketplace}+ />+ </PluginInstallPermissionProvider>)}</div>)diff --git a/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsxindex 43d16754c4c..f7111646e76 100644--- a/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsx@@ -32,11 +32,11 @@ const mockInvalidateDefaultModel = vi.hoisted(() => vi.fn())const mockUpdateDefaultModel = vi.hoisted(() => vi.fn(() => Promise.resolve({ result: 'success' })))const mockModelSelectorProps = vi.hoisted(() => [] as Array<{ hideProviderSettingsFooter?: boolean, onConfigureEmptyState?: () => void, showModelMeta?: boolean }>)-let mockIsCurrentWorkspaceManager = true+let mockWorkspacePermissionKeys = ['plugin.manage']vi.mock('@/context/app-context', () => ({useAppContext: () => ({- isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager,+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -108,7 +108,7 @@ describe('SystemModel', () => {beforeEach(() => {vi.clearAllMocks()mockModelSelectorProps.length = 0- mockIsCurrentWorkspaceManager = true+ mockWorkspacePermissionKeys = ['plugin.manage']})it('should render settings button', () => {@@ -184,8 +184,8 @@ describe('SystemModel', () => {expect(mockUpdateModelList).not.toHaveBeenCalled()})- it('should disable save when user is not workspace manager', async () => {- mockIsCurrentWorkspaceManager = false+ it('should disable save without plugin manage permission', async () => {+ mockWorkspacePermissionKeys = []render(<SystemModel {...defaultProps} />)fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))diff --git a/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsx b/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsxindex 596c80b9d42..6ed2482b1fb 100644--- a/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsx@@ -18,6 +18,7 @@ import { Infotip } from '@/app/components/base/infotip'import { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import { updateDefaultModel } from '@/service/common'+import { hasPermission } from '@/utils/permission'import { ModelTypeEnum } from '../declarations'import {useInvalidateDefaultModel,@@ -65,8 +66,9 @@ const SystemModel: FC<SystemModelSelectorProps> = ({hideProviderSettingsFooter,}) => {const { t } = useTranslation()- const { isCurrentWorkspaceManager } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()const { textGenerationModelList } = useProviderContext()+ const canManageSystemDefaultModel = hasPermission(workspacePermissionKeys, 'plugin.manage')const updateModelList = useUpdateModelList()const invalidateDefaultModel = useInvalidateDefaultModel()const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)@@ -258,7 +260,7 @@ const SystemModel: FC<SystemModelSelectorProps> = ({className="min-w-[72px]"variant="primary"onClick={handleSave}- disabled={!isCurrentWorkspaceManager}+ disabled={!canManageSystemDefaultModel}>{t('operation.save', { ns: 'common' })}</Button>diff --git a/web/app/components/header/account-setting/permission-group-list.tsx b/web/app/components/header/account-setting/permission-group-list.tsxnew file mode 100644index 00000000000..462e0cd5223--- /dev/null+++ b/web/app/components/header/account-setting/permission-group-list.tsx@@ -0,0 +1,190 @@+'use client'++import type { PermissionGroup } from '@/models/access-control'+import { Checkbox } from '@langgenius/dify-ui/checkbox'+import { cn } from '@langgenius/dify-ui/cn'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'++type PermissionGroupListProps = {+ groups: PermissionGroup[]+ value: string[]+ onChange: (next: string[]) => void+ className?: string+ readonly?: boolean+}++const PermissionGroupList = ({+ groups,+ value,+ onChange,+ className,+ readonly = false,+}: PermissionGroupListProps) => {+ const { t } = useTranslation()+ const [expandedGroupKeys, setExpandedGroupKeys] = useState<Set<string> | null>(null)++ const selectedSet = useMemo(() => new Set(value), [value])++ const defaultExpandedGroupKeys = useMemo(() => {+ if (groups.length === 0)+ return new Set<string>()+ const firstSelectedGroup = groups.find(group =>+ group.permissions.some(permission => selectedSet.has(permission.key)),+ )+ return new Set([(firstSelectedGroup ?? groups[0]!).group_key])+ }, [groups, selectedSet])++ const expandedGroupKeysMerged = expandedGroupKeys ?? defaultExpandedGroupKeys++ const toggleGroupExpanded = (groupKey: string) => {+ setExpandedGroupKeys((prev) => {+ const next = new Set(prev ?? expandedGroupKeysMerged)+ if (next.has(groupKey))+ next.delete(groupKey)+ else+ next.add(groupKey)+ return next+ })+ }++ const togglePermission = (permissionKey: string) => {+ if (readonly)+ return++ if (selectedSet.has(permissionKey))+ onChange(value.filter(key => key !== permissionKey))+ else+ onChange([...value, permissionKey])+ }++ const toggleGroupSelection = (group: PermissionGroup, selectedCount: number) => {+ if (readonly)+ return++ const permissionKeys = group.permissions.map(permission => permission.key)+ if (selectedCount === permissionKeys.length) {+ const groupPermissionKeySet = new Set(permissionKeys)+ onChange(value.filter(key => !groupPermissionKeySet.has(key)))+ return+ }++ const next = new Set(value)+ permissionKeys.forEach(key => next.add(key))+ onChange(Array.from(next))+ }++ return (+ <div className={cn('min-h-0 flex-1 rounded-xl border border-components-panel-border bg-components-panel-bg shadow-xs', className)}>+ <ScrollArea+ className="h-full overflow-hidden rounded-xl"+ slotClassNames={{+ viewport: 'overscroll-contain',+ content: groups.length === 0 ? 'h-full' : undefined,+ }}+ >+ {groups.length === 0+ ? (+ <div className="flex h-full items-center justify-center px-3 py-6 text-center system-sm-regular text-text-tertiary">+ {t('permissionList.noPermissionsFound', { ns: 'permission' })}+ </div>+ )+ : (+ <div className="flex flex-col">+ {groups.map((group) => {+ const expanded = expandedGroupKeysMerged.has(group.group_key)+ const selectedCount = group.permissions.reduce(+ (count, permission) => count + (selectedSet.has(permission.key) ? 1 : 0),+ 0,+ )+ const totalCount = group.permissions.length+ const allSelected = totalCount > 0 && selectedCount === totalCount++ return (+ <div key={group.group_key} className="border-b border-b-divider-subtle">+ <div className="group/permission-category flex h-12 w-full items-center gap-3 px-3 hover:bg-state-base-hover">+ <button+ type="button"+ className="min-w-0 flex-1 truncate text-left system-md-medium text-text-secondary focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-components-input-border-active"+ aria-expanded={expanded}+ onClick={() => toggleGroupExpanded(group.group_key)}+ >+ {group.group_name}+ </button>+ {!readonly && totalCount > 0 && (+ <button+ type="button"+ className="shrink-0 rounded-md px-1.5 py-0.5 system-sm-medium text-text-accent opacity-0 group-hover/permission-category:opacity-100 hover:bg-state-accent-hover focus-visible:opacity-100 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-components-input-border-active"+ onClick={() => toggleGroupSelection(group, selectedCount)}+ >+ {allSelected+ ? t('permissionList.clearAll', { ns: 'permission' })+ : t('permissionList.selectAll', { ns: 'permission' })}+ </button>+ )}+ {selectedCount > 0 && (+ <span className="shrink-0 rounded-md bg-util-colors-blue-blue-100 px-2 py-0.5 system-sm-medium text-text-accent">+ {selectedCount}+ /+ {totalCount}+ </span>+ )}+ <button+ type="button"+ className="flex h-6 w-6 shrink-0 items-center justify-center focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-components-input-border-active"+ aria-label={expanded ? t('permissionList.collapseGroup', { ns: 'permission' }) : t('permissionList.expandGroup', { ns: 'permission' })}+ onClick={() => toggleGroupExpanded(group.group_key)}+ >+ <span+ aria-hidden+ className={cn(+ 'i-ri-arrow-right-s-fill h-4 w-4 text-text-tertiary transition-transform',+ expanded && 'rotate-90',+ )}+ />+ </button>+ </div>+ {expanded && (+ <div className="flex flex-col">+ {group.permissions.map((permission) => {+ const checked = selectedSet.has(permission.key)++ return (+ <div+ key={permission.key}+ className={cn(+ 'flex min-h-9 items-center gap-3 px-3 py-1.5',+ readonly ? 'cursor-default' : 'cursor-pointer hover:bg-state-base-hover',+ checked && 'bg-state-accent-hover',+ checked && !readonly && 'hover:bg-state-accent-hover',+ )}+ onClick={() => togglePermission(permission.key)}+ >+ <Checkbox+ checked={checked}+ disabled={readonly}+ className="shrink-0"+ onCheckedChange={() => {+ togglePermission(permission.key)+ }}+ />+ <span className="min-w-0 flex-1 truncate system-md-regular text-text-secondary">+ {permission.name}+ </span>+ </div>+ )+ })}+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}+ </ScrollArea>+ </div>+ )+}++export default PermissionGroupListdiff --git a/web/app/components/header/account-setting/permissions-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/permissions-page/__tests__/index.spec.tsxnew file mode 100644index 00000000000..b37c07d1054--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/__tests__/index.spec.tsx@@ -0,0 +1,230 @@+import type { AppContextValue } from '@/context/app-context'+import type { Role } from '@/models/access-control'+import { toast } from '@langgenius/dify-ui/toast'+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { useSelector as useAppContextSelector } from '@/context/app-context'+import { useCreateWorkspaceRole, useUpdateWorkspaceRole } from '@/service/access-control/use-workspace-roles'+import { useRoleGroups } from '../hooks'+import PermissionsPage from '../index'++const mocks = vi.hoisted(() => ({+ workspacePermissionKeys: [] as string[],+ createWorkspaceRole: vi.fn(),+ updateWorkspaceRole: vi.fn(),+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ success: vi.fn(),+ },+}))++vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn((selector: (state: AppContextValue) => unknown) => selector({+ workspacePermissionKeys: mocks.workspacePermissionKeys,+ } as AppContextValue)),+}))++vi.mock('@/service/access-control/use-workspace-roles', () => ({+ useCreateWorkspaceRole: vi.fn(),+ useUpdateWorkspaceRole: vi.fn(),+}))++vi.mock('../hooks', () => ({+ useRoleGroups: vi.fn(),+}))++vi.mock('../role-list', () => ({+ default: ({+ groups,+ isLoading,+ isFetchingNextPage,+ onView,+ onEdit,+ }: {+ groups: Array<{ items: Role[] }>+ isLoading?: boolean+ isFetchingNextPage?: boolean+ onView: (role: Role) => void+ onEdit: (role: Role) => void+ }) => {+ const role = groups[0]?.items[0]++ return (+ <div>+ {isLoading && <span>initial role loading</span>}+ {isFetchingNextPage && <span>next role page loading</span>}+ {role && (+ <>+ <span>{role.name}</span>+ <button type="button" onClick={() => onView(role)}>view role</button>+ <button type="button" onClick={() => onEdit(role)}>edit role</button>+ </>+ )}+ </div>+ )+ },+}))++vi.mock('../role-modal', () => ({+ default: ({+ mode,+ role,+ onSubmit,+ }: {+ mode: string+ role?: Role+ onSubmit: (data: { name: string, description: string, permissionKeys: string[] }) => void+ }) => (+ <div role="dialog" aria-label={`${mode} role`}>+ <span>{role?.name}</span>+ <button+ type="button"+ onClick={() => onSubmit({+ name: `${mode} name`,+ description: `${mode} description`,+ permissionKeys: ['workspace.member.manage'],+ })}+ >+ submit role+ </button>+ </div>+ ),+}))++const role: Role = {+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_custom',+ name: 'Custom manager',+ description: 'Can manage workspace members',+ is_builtin: false,+ permission_keys: ['workspace.member.manage'],+ role_tag: '',+}++const mockMutation = (mock: ReturnType<typeof vi.fn>) => {+ mock.mockImplementation((_payload, options) => {+ options?.onSuccess?.()+ return Promise.resolve()+ })++ return { mutateAsync: mock }+}++const renderPermissionsPage = () => {+ const containerRef = {+ current: document.createElement('div'),+ }++ Object.defineProperty(containerRef.current, 'clientHeight', {+ configurable: true,+ value: 800,+ })++ return render(<PermissionsPage containerRef={containerRef} />)+}++describe('PermissionsPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.workspacePermissionKeys = []+ vi.mocked(useAppContextSelector).mockImplementation((selector: (state: AppContextValue) => unknown) => selector({+ workspacePermissionKeys: mocks.workspacePermissionKeys,+ } as AppContextValue))+ vi.mocked(useRoleGroups).mockReturnValue({+ roleGroups: [{+ id: 'global_custom',+ category: 'global_custom',+ title: 'Custom roles',+ items: [role],+ }],+ isLoading: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ error: null,+ } as ReturnType<typeof useRoleGroups>)+ vi.mocked(useCreateWorkspaceRole).mockReturnValue(mockMutation(mocks.createWorkspaceRole) as unknown as ReturnType<typeof useCreateWorkspaceRole>)+ vi.mocked(useUpdateWorkspaceRole).mockReturnValue(mockMutation(mocks.updateWorkspaceRole) as unknown as ReturnType<typeof useUpdateWorkspaceRole>)+ })++ it('hides role creation without workspace role manage permission', () => {+ renderPermissionsPage()++ expect(screen.queryByRole('button', { name: 'permission.role.addRole' })).not.toBeInTheDocument()+ expect(screen.getByText('Custom manager')).toBeInTheDocument()+ })++ it('renders the workspace roles summary with the compact scheme bar style', () => {+ renderPermissionsPage()++ const title = screen.getByText('permission.role.workspaceRoles.title')+ const description = screen.getByText('permission.role.workspaceRoles.description')+ const schemeBar = title.parentElement?.parentElement as HTMLElement++ expect(schemeBar).toHaveClass(+ 'min-h-[67px]',+ 'overflow-hidden',+ 'rounded-xl',+ 'border-divider-regular',+ 'px-4',+ 'py-3',+ )+ expect(title).toHaveClass('truncate', 'system-md-semibold', 'text-text-secondary')+ expect(description).toHaveClass('truncate', 'system-xs-regular', 'text-text-tertiary')+ })++ it('passes role loading states to the role list', () => {+ vi.mocked(useRoleGroups).mockReturnValue({+ roleGroups: [],+ isLoading: true,+ isFetchingNextPage: true,+ fetchNextPage: vi.fn(),+ hasNextPage: true,+ error: null,+ } as ReturnType<typeof useRoleGroups>)++ renderPermissionsPage()++ expect(screen.getByText('initial role loading')).toBeInTheDocument()+ expect(screen.getByText('next role page loading')).toBeInTheDocument()+ })++ it('creates workspace roles when role management is allowed', async () => {+ mocks.workspacePermissionKeys = ['workspace.role.manage']++ renderPermissionsPage()++ await userEvent.click(screen.getByRole('button', { name: 'permission.role.addRole' }))+ expect(screen.getByRole('dialog', { name: 'create role' })).toBeInTheDocument()+ await userEvent.click(screen.getByRole('button', { name: 'submit role' }))++ expect(mocks.createWorkspaceRole).toHaveBeenCalledWith({+ name: 'create name',+ description: 'create description',+ permission_keys: ['workspace.member.manage'],+ }, expect.any(Object))+ expect(toast.success).toHaveBeenCalledWith('permission.role.created')+ })++ it('updates the selected workspace role from the edit modal', async () => {+ renderPermissionsPage()++ await userEvent.click(screen.getByRole('button', { name: 'edit role' }))+ const dialog = screen.getByRole('dialog', { name: 'edit role' })+ expect(dialog).toBeInTheDocument()+ expect(within(dialog).getByText('Custom manager')).toBeInTheDocument()+ await userEvent.click(screen.getByRole('button', { name: 'submit role' }))++ expect(mocks.updateWorkspaceRole).toHaveBeenCalledWith({+ id: 'role-1',+ name: 'edit name',+ description: 'edit description',+ permission_keys: ['workspace.member.manage'],+ }, expect.any(Object))+ expect(toast.success).toHaveBeenCalledWith('permission.role.updated')+ })+})diff --git a/web/app/components/header/account-setting/permissions-page/helpers.ts b/web/app/components/header/account-setting/permissions-page/helpers.tsnew file mode 100644index 00000000000..f302814fb63--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/helpers.ts@@ -0,0 +1,29 @@+import type { InfiniteData } from '@tanstack/react-query'+import type { RoleListGroup } from './role-list'+import type { RoleListResponse } from '@/models/access-control'++export const formatRoleGroups = (roleListResponse: InfiniteData<RoleListResponse> | undefined): RoleListGroup[] => {+ if (!roleListResponse)+ return []+ const roles = roleListResponse.pages.flatMap(page => page.data)+ const result: RoleListGroup[] = []+ const builtinRoles = roles.filter(role => role.is_builtin)+ const customRoles = roles.filter(role => !role.is_builtin)+ if (builtinRoles.length > 0) {+ result.push({+ id: 'builtin',+ category: 'global_system_default',+ title: 'System Roles',+ items: builtinRoles,+ })+ }+ if (customRoles.length > 0) {+ result.push({+ id: 'custom',+ category: 'global_custom',+ title: 'Custom Roles',+ items: customRoles,+ })+ }+ return result+}diff --git a/web/app/components/header/account-setting/permissions-page/hooks.ts b/web/app/components/header/account-setting/permissions-page/hooks.tsnew file mode 100644index 00000000000..19185eff73a--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/hooks.ts@@ -0,0 +1,26 @@+import type { RoleListRequest } from '@/models/access-control'+import { useMemo } from 'react'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'+import { formatRoleGroups } from './helpers'++export const useRoleGroups = (params: RoleListRequest) => {+ const {+ data: roleList,+ isFetchingNextPage,+ isLoading,+ fetchNextPage,+ hasNextPage,+ error,+ } = useWorkspaceRoleList(params)++ const roleGroups = useMemo(() => formatRoleGroups(roleList), [roleList])++ return {+ roleGroups,+ isFetchingNextPage,+ isLoading,+ fetchNextPage,+ hasNextPage,+ error,+ }+}diff --git a/web/app/components/header/account-setting/permissions-page/index.tsx b/web/app/components/header/account-setting/permissions-page/index.tsxnew file mode 100644index 00000000000..e5d3408106d--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/index.tsx@@ -0,0 +1,170 @@+'use client'++import type { RoleModalMode, submitRoleData } from './role-modal'+import type { Role } from '@/models/access-control'+import { Button } from '@langgenius/dify-ui/button'+import { toast } from '@langgenius/dify-ui/toast'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import { useCreateWorkspaceRole, useUpdateWorkspaceRole } from '@/service/access-control/use-workspace-roles'+import { hasPermission } from '@/utils/permission'+import { useRoleGroups } from './hooks'+import RoleList from './role-list'+import RoleModal from './role-modal'++type PermissionsPageProps = {+ containerRef: React.RefObject<HTMLDivElement | null>+}++type ModalState = {+ mode: RoleModalMode+ role?: Role+} | null++const PAGE_SIZE = 20++const PermissionsPage = ({ containerRef }: PermissionsPageProps) => {+ const { t } = useTranslation()+ const locale = useLocale()+ const [modalState, setModalState] = useState<ModalState>(null)+ const anchorRef = useRef<HTMLDivElement>(null)++ const workspacePermissionKeys = useAppContextWithSelector(s => s.workspacePermissionKeys)++ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])++ const {+ roleGroups,+ isLoading,+ isFetchingNextPage,+ fetchNextPage,+ hasNextPage,+ error,+ } = useRoleGroups({+ page: 1,+ limit: PAGE_SIZE,+ include_owner: 1,+ language,+ })++ const { mutateAsync: createWorkspaceRole } = useCreateWorkspaceRole()+ const { mutateAsync: updateWorkspaceRole } = useUpdateWorkspaceRole()++ const openCreate = useCallback(() => {+ setModalState({ mode: 'create' })+ }, [])++ const handleView = useCallback((role: Role) => {+ setModalState({ mode: 'view', role })+ }, [])++ const handleEdit = useCallback((role: Role) => {+ setModalState({ mode: 'edit', role })+ }, [])++ const closeModal = useCallback(() => setModalState(null), [])++ const handleSubmit = useCallback(+ (data: submitRoleData) => {+ const { name, description, permissionKeys } = data+ const mode = modalState?.mode ?? ''+ const roleId = modalState?.role?.id ?? ''+ if (mode === 'create') {+ createWorkspaceRole({ name, description, permission_keys: permissionKeys }, {+ onSuccess: () => {+ toast.success(t('role.created', { ns: 'permission' }))+ closeModal()+ },+ })+ }+ else if (mode === 'edit') {+ updateWorkspaceRole({ id: roleId, name, description, permission_keys: permissionKeys }, {+ onSuccess: () => {+ toast.success(t('role.updated', { ns: 'permission' }))+ closeModal()+ },+ })+ }+ },+ [createWorkspaceRole, updateWorkspaceRole, closeModal, modalState, t],+ )++ useEffect(() => {+ const hasMore = hasNextPage ?? true+ let observer: IntersectionObserver | undefined++ if (error) {+ if (observer)+ observer.disconnect()+ return+ }++ if (anchorRef.current && containerRef.current) {+ const containerHeight = containerRef.current.clientHeight+ const dynamicMargin = Math.max(100, Math.min(containerHeight * 0.2, 200))++ observer = new IntersectionObserver((entries) => {+ if (entries[0]!.isIntersecting && !isLoading && !isFetchingNextPage && !error && hasMore)+ fetchNextPage()+ }, {+ root: containerRef.current,+ rootMargin: `${dynamicMargin}px`,+ })+ observer.observe(anchorRef.current)+ }+ return () => observer?.disconnect()+ }, [isLoading, isFetchingNextPage, fetchNextPage, error, hasNextPage, containerRef])++ const canManageRoles = hasPermission(workspacePermissionKeys, 'workspace.role.manage')++ return (+ <>+ <div className="flex min-w-0 flex-col gap-y-6">+ <div className="flex min-h-[67px] min-w-0 items-center gap-3 overflow-hidden rounded-xl border-t-[0.5px] border-l-[0.5px] border-divider-regular bg-linear-to-b from-background-gradient-bg-fill-chat-bg-2 to-background-gradient-bg-fill-chat-bg-1 px-4 py-3">+ <div className="flex min-w-0 grow flex-col gap-y-1 overflow-hidden">+ <div className="truncate system-md-semibold text-text-secondary">+ {t('role.workspaceRoles.title', { ns: 'permission' })}+ </div>+ <div className="truncate system-xs-regular text-text-tertiary">+ {t('role.workspaceRoles.description', { ns: 'permission' })}+ </div>+ </div>+ {canManageRoles && (+ <div className="flex shrink-0 items-center">+ <Button+ variant="primary"+ size="small"+ onClick={openCreate}+ disabled={isLoading}+ >+ {t('role.addRole', { ns: 'permission' })}+ </Button>+ </div>+ )}+ </div>+ <RoleList+ groups={roleGroups}+ isLoading={isLoading}+ isFetchingNextPage={isFetchingNextPage}+ onView={handleView}+ onEdit={handleEdit}+ />+ <div ref={anchorRef} className="h-0" />+ </div>+ {modalState && (+ <RoleModal+ mode={modalState?.mode ?? 'create'}+ open+ role={modalState?.role}+ onClose={closeModal}+ onSubmit={handleSubmit}+ />+ )}+ </>+ )+}++export default PermissionsPagediff --git a/web/app/components/header/account-setting/permissions-page/role-list/__tests__/index.spec.tsx b/web/app/components/header/account-setting/permissions-page/role-list/__tests__/index.spec.tsxnew file mode 100644index 00000000000..c789b163b19--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-list/__tests__/index.spec.tsx@@ -0,0 +1,184 @@+import type { Role } from '@/models/access-control'+import { render, screen } from '@testing-library/react'+import RoleList from '../index'++const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['workspace.role.manage'] as string[],+}))++vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))++vi.mock('@/service/access-control/use-workspace-roles', () => ({+ useCopyWorkspaceRole: () => ({+ mutateAsync: vi.fn(),+ }),+ useDeleteWorkspaceRole: () => ({+ mutateAsync: vi.fn(),+ isPending: false,+ }),+ useGetMembersOfRole: () => ({+ data: {+ data: [],+ pagination: {+ total_count: 0,+ per_page: 1,+ current_page: 1,+ total_pages: 1,+ },+ },+ isPending: false,+ }),+}))++const createRole = (overrides: Partial<Role> = {}): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_system_default',+ name: 'Owner',+ description: 'Full access to all workspace features and settings',+ is_builtin: true,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})++describe('RoleList', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockWorkspacePermissionKeys.value = ['workspace.role.manage']+ })++ describe('Rendering', () => {+ it('shows a loading status while the first page is loading', () => {+ render(+ <RoleList+ groups={[]}+ isLoading+ />,+ )++ expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()+ expect(screen.queryByText(/permission\.role\.groups/)).not.toBeInTheDocument()+ })++ it('renders role groups with compact section labels', () => {+ render(+ <RoleList+ groups={[+ {+ id: 'builtin',+ category: 'global_system_default',+ title: 'System Roles',+ items: [createRole()],+ },+ {+ id: 'custom',+ category: 'global_custom',+ title: 'Custom Roles',+ items: [createRole({+ id: 'role-custom',+ category: 'global_custom',+ name: 'Executive',+ description: 'Unrestricted access to all workspace operations',+ is_builtin: false,+ })],+ },+ ]}+ />,+ )++ const systemLabel = screen.getByText(/permission\.role\.groups\.builtin/)+ const customLabel = screen.getByText(/permission\.role\.groups\.custom/)++ expect(systemLabel).toHaveClass('min-h-6', 'system-sm-medium', 'text-text-secondary')+ expect(customLabel).toHaveClass('min-h-6', 'system-sm-medium', 'text-text-secondary')+ expect(screen.getByText('Owner')).toBeInTheDocument()+ expect(screen.getByText('Executive')).toBeInTheDocument()+ })++ it('shows a bottom loading status while fetching the next page', () => {+ render(+ <RoleList+ groups={[+ {+ id: 'builtin',+ category: 'global_system_default',+ title: 'System Roles',+ items: [createRole()],+ },+ ]}+ isFetchingNextPage+ />,+ )++ expect(screen.getByText('Owner')).toBeInTheDocument()+ expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()+ })+ })++ describe('Row Styles', () => {+ it('renders rows as divided hoverable list items', () => {+ render(+ <RoleList+ groups={[+ {+ id: 'builtin',+ category: 'global_system_default',+ title: 'System Roles',+ items: [createRole()],+ },+ ]}+ />,+ )++ const name = screen.getByText('Owner')+ const row = name.closest('.border-b')++ expect(row).toHaveClass(+ 'border-b',+ 'border-divider-regular',+ 'px-3',+ 'py-3.5',+ 'hover:bg-background-default-hover',+ )+ expect(name).toHaveClass('truncate', 'system-sm-semibold', 'text-text-primary')+ expect(screen.getByText('Full access to all workspace features and settings')).toHaveClass(+ 'truncate',+ 'system-xs-regular',+ 'text-text-secondary',+ )+ })++ it('uses the no-description fallback with the row description style', () => {+ render(+ <RoleList+ groups={[+ {+ id: 'custom',+ category: 'global_custom',+ title: 'Custom Roles',+ items: [createRole({+ id: 'role-custom',+ category: 'global_custom',+ name: 'Partner',+ description: '',+ is_builtin: false,+ })],+ },+ ]}+ />,+ )++ expect(screen.getByText('permission.role.noDescription')).toHaveClass(+ 'truncate',+ 'system-xs-regular',+ 'text-text-secondary',+ )+ })+ })+})diff --git a/web/app/components/header/account-setting/permissions-page/role-list/__tests__/row-menu.spec.tsx b/web/app/components/header/account-setting/permissions-page/role-list/__tests__/row-menu.spec.tsxnew file mode 100644index 00000000000..90558b49896--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-list/__tests__/row-menu.spec.tsx@@ -0,0 +1,291 @@+import type { Role } from '@/models/access-control'+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import RowMenu from '../row-menu'++const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['workspace.role.manage'] as string[],+}))++const mockCopyRole = vi.hoisted(() => vi.fn((_variables, options?: { onSuccess?: () => void }) => {+ options?.onSuccess?.()+}))+const mockDeleteRole = vi.hoisted(() => vi.fn())+const membersOfRoleQueryMock = vi.hoisted(() => {+ const response = {+ data: [],+ pagination: {+ total_count: 3,+ per_page: 1,+ current_page: 1,+ total_pages: 3,+ },+ }++ return {+ useGetMembersOfRole: vi.fn(() => ({+ data: response,+ isPending: false,+ })),+ }+})++vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))++vi.mock('@/service/access-control/use-workspace-roles', () => ({+ useCopyWorkspaceRole: () => ({+ mutate: mockCopyRole,+ isPending: false,+ }),+ useDeleteWorkspaceRole: () => ({+ mutateAsync: mockDeleteRole,+ isPending: false,+ }),+ useGetMembersOfRole: membersOfRoleQueryMock.useGetMembersOfRole,+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ success: vi.fn(),+ },+}))++const createRole = (overrides: Partial<Role> = {}): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_system_default',+ name: 'Owner',+ description: 'Workspace owner',+ is_builtin: true,+ permission_keys: [],+ role_tag: '',+ ...overrides,+})++const openMenu = async () => {+ const user = userEvent.setup()+ await user.click(screen.getByRole('button', { name: 'common.operation.moreActions' }))+ const menus = screen.getAllByRole('menu')+ return {+ user,+ menu: menus[menus.length - 1]!,+ }+}++describe('RowMenu', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ document.body.querySelectorAll('[role="menu"], [role="menuitem"]').forEach(element => element.remove())+ mockWorkspacePermissionKeys.value = ['workspace.role.manage']+ })++ afterEach(() => {+ document.body.querySelectorAll('[role="menu"], [role="menuitem"]').forEach(element => element.remove())+ })++ describe('Rendering', () => {+ it('should render view action for the owner system role', async () => {+ render(+ <RowMenu+ roleCategory="global_system_default"+ role={createRole({ role_tag: 'owner' })}+ />,+ )++ const { menu } = await openMenu()++ expect(within(menu).getByRole('menuitem', { name: 'common.operation.view' })).toBeInTheDocument()+ expect(within(menu).getByRole('menuitem', { name: 'permission.common.duplicateAction' })).toBeInTheDocument()+ expect(within(menu).queryByRole('menuitem', { name: 'common.operation.edit' })).not.toBeInTheDocument()+ expect(within(menu).queryByRole('menuitem', { name: 'common.operation.delete' })).not.toBeInTheDocument()+ })++ it('should render view action for non-owner system roles', async () => {+ render(+ <RowMenu+ roleCategory="global_system_default"+ role={createRole({ id: 'role-editor', name: 'Editor' })}+ />,+ )++ const { menu } = await openMenu()++ expect(within(menu).getByRole('menuitem', { name: 'common.operation.view' })).toBeInTheDocument()+ expect(within(menu).queryByRole('menuitem', { name: 'common.operation.edit' })).not.toBeInTheDocument()+ })++ it('should hide view action for custom roles', async () => {+ render(+ <RowMenu+ roleCategory="global_custom"+ role={createRole({+ id: 'role-custom',+ category: 'global_custom',+ name: 'Custom role',+ is_builtin: false,+ })}+ />,+ )++ const { menu } = await openMenu()++ expect(within(menu).queryByRole('menuitem', { name: 'common.operation.view' })).not.toBeInTheDocument()+ expect(within(menu).getByRole('menuitem', { name: 'common.operation.edit' })).toBeInTheDocument()+ expect(within(menu).getByRole('menuitem', { name: 'permission.common.duplicateAction' })).toBeInTheDocument()+ expect(within(menu).getByRole('menuitem', { name: 'common.operation.delete' })).toBeInTheDocument()+ })++ it('should keep custom role management actions visible without manage permission', async () => {+ mockWorkspacePermissionKeys.value = []++ render(+ <RowMenu+ roleCategory="global_custom"+ role={createRole({+ id: 'role-custom',+ category: 'global_custom',+ name: 'Custom role',+ is_builtin: false,+ })}+ />,+ )++ const { menu } = await openMenu()++ expect(within(menu).getByRole('menuitem', { name: 'common.operation.edit' })).toHaveAttribute('aria-disabled', 'true')+ expect(within(menu).getByRole('menuitem', { name: 'permission.common.duplicateAction' })).toHaveAttribute('aria-disabled', 'true')+ expect(within(menu).getByRole('menuitem', { name: 'common.operation.delete' })).toHaveAttribute('aria-disabled', 'true')+ })+ })++ describe('User Interactions', () => {+ it('should call onView when clicking the owner view action', async () => {+ const onView = vi.fn()+ const role = createRole({ role_tag: 'owner' })+ render(+ <RowMenu+ roleCategory="global_system_default"+ role={role}+ onView={onView}+ />,+ )++ const { user, menu } = await openMenu()+ await user.click(within(menu).getByRole('menuitem', { name: 'common.operation.view' }))++ expect(onView).toHaveBeenCalledTimes(1)+ expect(onView).toHaveBeenCalledWith(role)+ })++ it('should ask before duplicating a system role and skipping member assignments', async () => {+ const role = createRole({ id: 'role-default-editor', name: 'Editor' })+ render(+ <RowMenu+ roleCategory="global_system_default"+ role={role}+ />,+ )++ const { user, menu } = await openMenu()+ await user.click(within(menu).getByRole('menuitem', { name: 'permission.common.duplicateAction' }))++ const dialog = screen.getByRole('alertdialog')+ expect(dialog).toHaveTextContent('permission.role.copyMembersTitle')+ expect(dialog).toHaveTextContent('permission.role.copyMembersDescription:{"name":"Editor","count":3}')+ expect(membersOfRoleQueryMock.useGetMembersOfRole).toHaveBeenCalledWith({+ roleId: role.id,+ page: 1,+ limit: 9999,+ })++ await user.click(within(dialog).getByRole('button', { name: 'common.operation.skip' }))++ expect(mockCopyRole).toHaveBeenCalledTimes(1)+ expect(mockCopyRole).toHaveBeenCalledWith({+ roleId: role.id,+ copy_member: false,+ }, expect.objectContaining({+ onSuccess: expect.any(Function),+ }))+ })++ it('should copy member assignments when confirming duplicate with copy', async () => {+ const role = createRole({ id: 'role-custom', category: 'global_custom', name: 'Support', is_builtin: false })+ render(+ <RowMenu+ roleCategory="global_custom"+ role={role}+ />,+ )++ const { user, menu } = await openMenu()+ await user.click(within(menu).getByRole('menuitem', { name: 'permission.common.duplicateAction' }))+ const dialog = screen.getByRole('alertdialog')++ await user.click(within(dialog).getByRole('button', { name: 'common.operation.copy' }))++ expect(mockCopyRole).toHaveBeenCalledTimes(1)+ expect(mockCopyRole).toHaveBeenCalledWith({+ roleId: role.id,+ copy_member: true,+ }, expect.objectContaining({+ onSuccess: expect.any(Function),+ }))+ })++ it('should close the copy member assignments dialog when clicking the backdrop', async () => {+ render(+ <RowMenu+ roleCategory="global_system_default"+ role={createRole({ id: 'role-default-editor', name: 'Editor' })}+ />,+ )++ const { user, menu } = await openMenu()+ await user.click(within(menu).getByRole('menuitem', { name: 'permission.common.duplicateAction' }))++ expect(screen.getByRole('alertdialog')).toBeInTheDocument()++ const backdrop = document.body.querySelector('.bg-background-overlay')+ expect(backdrop).toBeInTheDocument()+ fireEvent.click(backdrop!)++ await waitFor(() => {+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ })+ })++ it('should ignore role management actions without manage permission', async () => {+ mockWorkspacePermissionKeys.value = []+ const onEdit = vi.fn()+ const role = createRole({+ id: 'role-custom',+ category: 'global_custom',+ name: 'Custom role',+ is_builtin: false,+ })+ render(+ <RowMenu+ roleCategory="global_custom"+ role={role}+ onEdit={onEdit}+ />,+ )++ const { menu } = await openMenu()++ fireEvent.click(within(menu).getByRole('menuitem', { name: 'common.operation.edit' }))+ fireEvent.click(within(menu).getByRole('menuitem', { name: 'permission.common.duplicateAction' }))+ fireEvent.click(within(menu).getByRole('menuitem', { name: 'common.operation.delete' }))++ expect(onEdit).not.toHaveBeenCalled()+ expect(mockCopyRole).not.toHaveBeenCalled()+ expect(mockDeleteRole).not.toHaveBeenCalled()+ })+ })+})diff --git a/web/app/components/header/account-setting/permissions-page/role-list/copy-members-confirm-dialog.tsx b/web/app/components/header/account-setting/permissions-page/role-list/copy-members-confirm-dialog.tsxnew file mode 100644index 00000000000..59a347553a7--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-list/copy-members-confirm-dialog.tsx@@ -0,0 +1,82 @@+'use client'++import type { Role } from '@/models/access-control'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { Button } from '@langgenius/dify-ui/button'+import { useTranslation } from 'react-i18next'+import { useGetMembersOfRole } from '@/service/access-control/use-workspace-roles'++type CopyMembersConfirmDialogProps = {+ role: Role+ isCopyingRole: boolean+ onOpenChange: (open: boolean) => void+ onDuplicate: (copyMember: boolean) => void+}++export function CopyMembersConfirmDialog({+ role,+ isCopyingRole,+ onOpenChange,+ onDuplicate,+}: CopyMembersConfirmDialogProps) {+ const { t } = useTranslation()+ const { data: membersOfRole, isPending: isLoadingMembersOfRole } = useGetMembersOfRole({+ roleId: role.id,+ page: 1,+ limit: 9999,+ })+ const memberCount = membersOfRole?.pagination.total_count ?? 0+ const isLoadingMemberCount = isLoadingMembersOfRole && !membersOfRole+ const isActionDisabled = isCopyingRole || isLoadingMemberCount++ return (+ <AlertDialog open onOpenChange={onOpenChange}>+ <AlertDialogContent+ backdropProps={{+ forceRender: true,+ onClick: () => onOpenChange(false),+ }}+ >+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">+ <AlertDialogTitle className="w-full title-2xl-semi-bold text-text-primary">+ {t('role.copyMembersTitle', { ns: 'permission' })}+ </AlertDialogTitle>+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-secondary">+ {+ isLoadingMemberCount+ ? t('role.copyMembersLoading', { ns: 'permission' })+ : t('role.copyMembersDescription', {+ ns: 'permission',+ name: role.name,+ count: memberCount,+ })+ }+ </AlertDialogDescription>+ </div>+ <AlertDialogActions>+ <Button+ variant="secondary"+ disabled={isActionDisabled}+ onClick={() => onDuplicate(false)}+ >+ {t('operation.skip', { ns: 'common' })}+ </Button>+ <Button+ variant="primary"+ disabled={isActionDisabled}+ loading={isCopyingRole}+ onClick={() => onDuplicate(true)}+ >+ {t('operation.copy', { ns: 'common' })}+ </Button>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/web/app/components/header/account-setting/permissions-page/role-list/index.tsx b/web/app/components/header/account-setting/permissions-page/role-list/index.tsxnew file mode 100644index 00000000000..7afd0a3eb59--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-list/index.tsx@@ -0,0 +1,78 @@+'use client'++import type { Role, RoleCategory } from '@/models/access-control'+import { cn } from '@langgenius/dify-ui/cn'+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import Row from './row'++export type RoleListGroup = {+ id: string+ category: RoleCategory+ title: string+ items: Role[]+}++type RoleListProps = {+ groups: RoleListGroup[]+ className?: string+ isLoading?: boolean+ isFetchingNextPage?: boolean+ onView?: (role: Role) => void+ onEdit?: (role: Role) => void+}++const RoleList = ({+ groups,+ className,+ isLoading = false,+ isFetchingNextPage = false,+ onView,+ onEdit,+}: RoleListProps) => {+ const { t } = useTranslation()++ if (isLoading) {+ return (+ <div className={cn('px-1 py-8 text-center', className)}>+ <Loading type="app" />+ </div>+ )+ }++ return (+ <div className={cn('flex min-w-0 flex-col gap-y-6', className)}>+ {groups.map(group => (+ <section+ key={group.id}+ className="flex min-w-0 flex-col gap-y-1"+ >+ <div className="flex min-h-6 items-center system-sm-medium text-text-secondary">+ {t(`role.groups.${group.id}`, { ns: 'permission', defaultValue: group.title })}+ </div>+ <div className="flex flex-col">+ {group.items.map(row => (+ <Row+ key={row.id}+ name={row.name}+ description={row.description}+ roleCategory={group.category}+ role={row}+ onView={onView}+ onEdit={onEdit}+ />+ ))}+ </div>+ </section>+ ))}+ {isFetchingNextPage && (+ <div className="px-1 py-3 text-center">+ <Loading type="app" />+ </div>+ )}+ </div>+ )+}++export default memo(RoleList)diff --git a/web/app/components/header/account-setting/permissions-page/role-list/row-menu.tsx b/web/app/components/header/account-setting/permissions-page/role-list/row-menu.tsxnew file mode 100644index 00000000000..678357ea4bc--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-list/row-menu.tsx@@ -0,0 +1,192 @@+'use client'+import type { Role, RoleCategory } from '@/models/access-control'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { toast } from '@langgenius/dify-ui/toast'+import { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import ActionButton from '@/app/components/base/action-button'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { useCopyWorkspaceRole, useDeleteWorkspaceRole } from '@/service/access-control/use-workspace-roles'+import { hasPermission } from '@/utils/permission'+import { CopyMembersConfirmDialog } from './copy-members-confirm-dialog'++type RowMenuProps = {+ roleCategory: RoleCategory+ role: Role+ onView?: (role: Role) => void+ onEdit?: (role: Role) => void+}++const RowMenu = ({+ roleCategory,+ role,+ onView,+ onEdit,+}: RowMenuProps) => {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)+ const [showCopyMembersConfirm, setShowCopyMembersConfirm] = useState(false)++ const workspacePermissionKeys = useAppContextWithSelector(s => s.workspacePermissionKeys)+ const canManageRoles = hasPermission(workspacePermissionKeys, 'workspace.role.manage')++ const handleView = useCallback(() => onView?.(role), [onView, role])++ const handleEdit = useCallback(() => {+ if (!canManageRoles)+ return++ onEdit?.(role)+ }, [canManageRoles, onEdit, role])++ const { mutate: copyRole, isPending: isCopyingRole } = useCopyWorkspaceRole()++ const openCopyMembersConfirm = useCallback(() => {+ if (!canManageRoles)+ return++ setShowCopyMembersConfirm(true)+ setOpen(false)+ }, [canManageRoles])++ const handleDuplicate = useCallback((copyMember: boolean) => {+ if (!canManageRoles)+ return++ copyRole({+ roleId: role.id,+ copy_member: copyMember,+ }, {+ onSuccess: () => {+ toast.success(t('role.duplicated', { ns: 'permission' }))+ setShowCopyMembersConfirm(false)+ },+ })+ }, [canManageRoles, copyRole, role.id, t])++ const { mutateAsync: deleteRole, isPending: isDeletingRole } = useDeleteWorkspaceRole()++ const openDeleteConfirm = useCallback(() => {+ if (!canManageRoles)+ return++ setShowDeleteConfirm(true)+ setOpen(false)+ }, [canManageRoles])++ const handleDelete = useCallback(() => {+ if (!canManageRoles)+ return++ deleteRole(role.id, {+ onSuccess: () => {+ toast.success(t('role.deleted', { ns: 'permission' }))+ setShowDeleteConfirm(false)+ },+ })+ }, [canManageRoles, deleteRole, role.id, t])++ const hasViewAction = roleCategory === 'global_system_default'+ const hasEditAction = roleCategory === 'global_custom'+ const hasDeleteAction = roleCategory === 'global_custom'++ return (+ <>+ <DropdownMenu open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger render={<ActionButton size="m" className={cn('shrink-0', open && 'bg-state-base-hover')} aria-label={t('operation.moreActions', { ns: 'common' })} />}>+ <span aria-hidden className="i-ri-more-fill h-4 w-4 text-text-tertiary" />+ </DropdownMenuTrigger>+ <DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="min-w-[160px]">+ {+ hasViewAction && (+ <DropdownMenuItem className="system-sm-semibold text-text-secondary" onClick={handleView}>+ {t('operation.view', { ns: 'common' })}+ </DropdownMenuItem>+ )+ }+ {+ hasEditAction && (+ <DropdownMenuItem+ disabled={!canManageRoles}+ className="system-sm-semibold text-text-secondary"+ onClick={handleEdit}+ >+ {t('operation.edit', { ns: 'common' })}+ </DropdownMenuItem>+ )+ }+ <DropdownMenuItem+ disabled={!canManageRoles}+ className="system-sm-semibold text-text-secondary"+ onClick={openCopyMembersConfirm}+ >+ {t('common.duplicateAction', { ns: 'permission' })}+ </DropdownMenuItem>+ {+ hasDeleteAction && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={!canManageRoles}+ variant="destructive"+ className="system-sm-semibold"+ onClick={openDeleteConfirm}+ >+ {t('operation.delete', { ns: 'common' })}+ </DropdownMenuItem>+ </>+ )+ }+ </DropdownMenuContent>+ </DropdownMenu>+ <AlertDialog open={showDeleteConfirm} onOpenChange={open => !open && setShowDeleteConfirm(false)}>+ <AlertDialogContent backdropProps={{ forceRender: true }}>+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">+ {t('role.deleteTitle', { ns: 'permission', name: role.name })}+ </AlertDialogTitle>+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">+ {t('role.deleteDescription', { ns: 'permission' })}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions>+ <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>+ <AlertDialogConfirmButton+ disabled={isDeletingRole}+ onClick={handleDelete}+ >+ {t('operation.delete', { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ {showCopyMembersConfirm && (+ <CopyMembersConfirmDialog+ role={role}+ isCopyingRole={isCopyingRole}+ onOpenChange={setShowCopyMembersConfirm}+ onDuplicate={handleDuplicate}+ />+ )}+ </>+ )+}++export default RowMenudiff --git a/web/app/components/header/account-setting/permissions-page/role-list/row.tsx b/web/app/components/header/account-setting/permissions-page/role-list/row.tsxnew file mode 100644index 00000000000..b9a622da3d4--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-list/row.tsx@@ -0,0 +1,53 @@+import type { Role, RoleCategory } from '@/models/access-control'+import { cn } from '@langgenius/dify-ui/cn'+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import RowMenu from './row-menu'++type RowProps = {+ className?: string+ name: string+ description: string+ roleCategory: RoleCategory+ role: Role+ onView?: (role: Role) => void+ onEdit?: (role: Role) => void+}++const Row = ({+ className,+ name,+ description,+ roleCategory,+ role,+ onView,+ onEdit,+}: RowProps) => {+ const { t } = useTranslation()++ return (+ <div+ className={cn(+ 'flex min-w-0 items-center gap-3 border-b border-divider-regular px-3 py-3.5 hover:bg-background-default-hover',+ className,+ )}+ >+ <div className="min-w-0 flex-1 space-y-1">+ <div className="truncate system-sm-semibold text-text-primary">+ {name}+ </div>+ <p className="truncate system-xs-regular text-text-secondary">+ {description || t('role.noDescription', { ns: 'permission' })}+ </p>+ </div>+ <RowMenu+ roleCategory={roleCategory}+ role={role}+ onView={onView}+ onEdit={onEdit}+ />+ </div>+ )+}++export default memo(Row)diff --git a/web/app/components/header/account-setting/permissions-page/role-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/permissions-page/role-modal/__tests__/index.spec.tsxnew file mode 100644index 00000000000..15de6c99014--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-modal/__tests__/index.spec.tsx@@ -0,0 +1,164 @@+import type { PermissionGroup, Role } from '@/models/access-control'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import RoleModal from '../index'++const mockWorkspacePermissionCatalog = vi.hoisted(() => ({+ groups: [] as PermissionGroup[],+}))++vi.mock('@/service/access-control/use-permission-catalog', () => ({+ useWorkspacePermissionCatalog: () => ({+ data: { groups: mockWorkspacePermissionCatalog.groups },+ }),+}))++const createPermissionGroup = (overrides: Partial<PermissionGroup> = {}): PermissionGroup => ({+ group_key: 'workspace_management',+ group_name: 'Workspace management',+ description: '',+ permissions: [+ {+ key: 'workspace.member.manage',+ name: 'Manage members',+ description: '',+ },+ ],+ ...overrides,+})++const createRole = (overrides: Partial<Role> = {}): Role => ({+ id: 'role-1',+ tenant_id: 'tenant-1',+ type: 'workspace',+ category: 'global_custom',+ name: 'Operator',+ description: 'Can operate workspace',+ is_builtin: false,+ permission_keys: ['workspace.member.manage'],+ role_tag: '',+ ...overrides,+})++describe('RoleModal', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockWorkspacePermissionCatalog.groups = [createPermissionGroup()]+ })++ // Rendering keeps role fields and workspace permissions in one modal form.+ describe('Rendering', () => {+ it('should render edit mode with role values and selected permissions', () => {+ render(+ <RoleModal+ open+ mode="edit"+ role={createRole()}+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ expect(screen.getByText('permission.role.modal.edit.title')).toBeInTheDocument()+ expect(screen.getByLabelText('permission.role.modal.nameLabel')).toHaveValue('Operator')+ expect(screen.getByLabelText('permission.role.modal.descriptionLabel')).toHaveValue('Can operate workspace')+ expect(screen.getByRole('button', { name: /Workspace management/ })).toHaveAttribute('aria-expanded', 'true')+ expect(screen.getByText(/workspace\.member\.manage/)).toBeInTheDocument()+ })++ it('should disable confirm action when role name is empty', () => {+ render(+ <RoleModal+ open+ mode="create"+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ expect(screen.getByRole('button', { name: 'common.operation.confirm' })).toBeDisabled()+ })+ })++ // Submitting creates the payload expected by role create/update mutations.+ describe('User Interactions', () => {+ it('should submit trimmed role fields and selected permission keys', async () => {+ const user = userEvent.setup()+ const handleClose = vi.fn()+ const handleSubmit = vi.fn()++ render(+ <RoleModal+ open+ mode="create"+ onClose={handleClose}+ onSubmit={handleSubmit}+ />,+ )++ await user.type(screen.getByLabelText('permission.role.modal.nameLabel'), ' Support role ')+ await user.type(screen.getByLabelText('permission.role.modal.descriptionLabel'), ' Helps members ')+ await user.click(screen.getByText(/workspace\.member\.manage/))+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))++ expect(handleSubmit).toHaveBeenCalledTimes(1)+ expect(handleSubmit).toHaveBeenCalledWith({+ name: 'Support role',+ description: 'Helps members',+ permissionKeys: ['workspace.member.manage'],+ })+ expect(handleClose).toHaveBeenCalledTimes(1)+ })++ it('should submit an updated role description when editing an existing role', async () => {+ const user = userEvent.setup()+ const handleSubmit = vi.fn()++ render(+ <RoleModal+ open+ mode="edit"+ role={createRole({+ description: 'Original description',+ permission_keys: ['workspace.member.manage'],+ })}+ onClose={vi.fn()}+ onSubmit={handleSubmit}+ />,+ )++ const descriptionInput = screen.getByLabelText('permission.role.modal.descriptionLabel')+ await user.clear(descriptionInput)+ await user.type(descriptionInput, ' Updated role description ')+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))++ expect(handleSubmit).toHaveBeenCalledTimes(1)+ expect(handleSubmit).toHaveBeenCalledWith({+ name: 'Operator',+ description: 'Updated role description',+ permissionKeys: ['workspace.member.manage'],+ })+ })+ })++ // View mode preserves the permission display but blocks edits and confirmation.+ describe('Read-only Mode', () => {+ it('should render role details as read-only in view mode', () => {+ render(+ <RoleModal+ open+ mode="view"+ role={createRole()}+ onClose={vi.fn()}+ onSubmit={vi.fn()}+ />,+ )++ expect(screen.getByLabelText('permission.role.modal.nameLabel')).toBeDisabled()+ expect(screen.getByLabelText('permission.role.modal.descriptionLabel')).toBeDisabled()+ expect(screen.queryByRole('button', { name: 'common.operation.confirm' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'permission.permissionList.clearAll' })).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/header/account-setting/permissions-page/role-modal/hooks.ts b/web/app/components/header/account-setting/permissions-page/role-modal/hooks.tsnew file mode 100644index 00000000000..c3ea672a1ae--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-modal/hooks.ts@@ -0,0 +1,36 @@+import { useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { useWorkspacePermissionCatalog } from '@/service/access-control/use-permission-catalog'++export const useWorkspacePermissionGroups = () => {+ const { t } = useTranslation()+ const { data: workspacePermissionCatalog } = useWorkspacePermissionCatalog()++ const groups = useMemo(() => {+ return (workspacePermissionCatalog?.groups || []).map(group => ({+ ...group,+ group_name: t(`group.${group.group_key}`, {+ ns: 'permission',+ defaultValue: group.group_name,+ }),+ permissions: group.permissions.map(permission => ({+ ...permission,+ name: t(permission.key, {+ ns: 'permissionKeys',+ defaultValue: permission.name,+ }),+ })),+ }))+ }, [t, workspacePermissionCatalog?.groups])++ const allPermissions = groups.flatMap(g => g.permissions) || []++ const permissionMap = Object.fromEntries(+ allPermissions.map(p => [p.key, p]),+ )++ return {+ groups,+ permissionMap,+ }+}diff --git a/web/app/components/header/account-setting/permissions-page/role-modal/index.tsx b/web/app/components/header/account-setting/permissions-page/role-modal/index.tsxnew file mode 100644index 00000000000..fe7abf64672--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-modal/index.tsx@@ -0,0 +1,147 @@+'use client'++import type { Role } from '@/models/access-control'+import { Button } from '@langgenius/dify-ui/button'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { Input } from '@langgenius/dify-ui/input'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import PermissionField from './permission-field'++export type RoleModalMode = 'create' | 'view' | 'edit'++export type submitRoleData = {+ name: string+ description?: string+ permissionKeys?: string[]+}++type RoleModalProps = {+ mode: RoleModalMode+ open: boolean+ role?: Role+ onClose: () => void+ onSubmit?: (data: submitRoleData) => void+}++const RoleModal = ({+ mode,+ open,+ role,+ onClose,+ onSubmit,+}: RoleModalProps) => {+ const { t } = useTranslation()+ const [name, setName] = useState(role?.name ?? '')+ const [desc, setDesc] = useState(role?.description ?? '')+ const [permissionKeys, setPermissionKeys] = useState<string[]>(role?.permission_keys ?? [])++ const readonly = mode === 'view'++ const onRoleNameChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {+ setName(e.target.value)+ }, [])++ const onRoleDescChange = useCallback((value: string) => {+ setDesc(value)+ }, [])++ const handleSubmit = () => {+ onSubmit?.({ name: name.trim(), description: desc.trim(), permissionKeys })+ onClose()+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen)+ onClose()+ }}+ >+ <DialogContent+ className="flex h-[85vh] w-140 flex-col overflow-hidden p-0"+ backdropProps={{ forceRender: true }}+ >+ <div className="relative shrink-0 px-6 pt-6 pb-4">+ <DialogCloseButton />+ <div className="pr-8">+ <DialogTitle className="system-xl-semibold text-text-primary">+ {t(`role.modal.${mode}.title`, { ns: 'permission' })}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t(`role.modal.${mode}.description`, { ns: 'permission' })}+ </DialogDescription>+ </div>+ </div>+ <div className="border-t border-divider-subtle" />+ <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-hidden px-6 py-5">+ <div className="flex shrink-0 flex-col gap-1">+ <label htmlFor="role-name" className="system-sm-medium text-text-secondary">+ {t('role.modal.nameLabel', { ns: 'permission' })}+ </label>+ <Input+ id="role-name"+ value={name}+ onChange={onRoleNameChange}+ placeholder={t('role.modal.namePlaceholder', { ns: 'permission' })}+ disabled={readonly}+ />+ </div>+ <div className="flex shrink-0 flex-col gap-1">+ <label htmlFor="role-description" className="system-sm-medium text-text-secondary">+ {t('role.modal.descriptionLabel', { ns: 'permission' })}+ </label>+ <Textarea+ id="role-description"+ value={desc}+ onValueChange={onRoleDescChange}+ placeholder={t('role.modal.descriptionPlaceholder', { ns: 'permission' })}+ disabled={readonly}+ className="min-h-24 resize-none"+ />+ </div>+ <PermissionField+ value={permissionKeys}+ onChange={setPermissionKeys}+ readonly={readonly}+ />+ </div>+ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-divider-subtle px-6 py-4">+ <a+ href="https://docs.dify.ai/"+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 system-xs-medium text-text-accent hover:underline"+ >+ <span>{t('permissionSet.learnMore', { ns: 'permission' })}</span>+ <span aria-hidden className="i-ri-external-link-line h-3.5 w-3.5" />+ </a>+ <div className="flex items-center gap-2">+ <Button variant="secondary" onClick={onClose}>+ {readonly ? t('operation.close', { ns: 'common' }) : t('operation.cancel', { ns: 'common' })}+ </Button>+ {!readonly && (+ <Button+ variant="primary"+ disabled={!name.trim()}+ onClick={handleSubmit}+ >+ {t('operation.confirm', { ns: 'common' })}+ </Button>+ )}+ </div>+ </div>+ </DialogContent>+ </Dialog>+ )+}++export default RoleModaldiff --git a/web/app/components/header/account-setting/permissions-page/role-modal/permission-field.tsx b/web/app/components/header/account-setting/permissions-page/role-modal/permission-field.tsxnew file mode 100644index 00000000000..c0f4a6478dd--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-modal/permission-field.tsx@@ -0,0 +1,27 @@+'use client'++import { useTranslation } from 'react-i18next'+import PermissionPicker from './permission-picker'++type PermissionFieldProps = {+ value: string[]+ onChange: (next: string[]) => void+ readonly?: boolean+}++const PermissionField = ({+ value,+ onChange,+ readonly = false,+}: PermissionFieldProps) => {+ const { t } = useTranslation()++ return (+ <div className="flex min-h-0 flex-1 flex-col gap-2">+ <div className="system-sm-medium text-text-secondary">{t('permissionSet.permissions', { ns: 'permission' })}</div>+ <PermissionPicker value={value} onChange={onChange} readonly={readonly} />+ </div>+ )+}++export default PermissionFielddiff --git a/web/app/components/header/account-setting/permissions-page/role-modal/permission-picker.tsx b/web/app/components/header/account-setting/permissions-page/role-modal/permission-picker.tsxnew file mode 100644index 00000000000..c988a21c4c8--- /dev/null+++ b/web/app/components/header/account-setting/permissions-page/role-modal/permission-picker.tsx@@ -0,0 +1,32 @@+'use client'++import PermissionGroupList from '../../permission-group-list'+import { useWorkspacePermissionGroups } from './hooks'++type PermissionPickerProps = {+ value: string[]+ onChange: (next: string[]) => void+ className?: string+ readonly?: boolean+}++const PermissionPicker = ({+ value,+ onChange,+ className,+ readonly = false,+}: PermissionPickerProps) => {+ const { groups } = useWorkspacePermissionGroups()++ return (+ <PermissionGroupList+ groups={groups}+ value={value}+ onChange={onChange}+ className={className}+ readonly={readonly}+ />+ )+}++export default PermissionPickerdiff --git a/web/app/components/header/account-setting/plugin-page/SerpapiPlugin.tsx b/web/app/components/header/account-setting/plugin-page/SerpapiPlugin.tsxdeleted file mode 100644index 31c4ce2c3a0..00000000000--- a/web/app/components/header/account-setting/plugin-page/SerpapiPlugin.tsx+++ /dev/null@@ -1,69 +0,0 @@-import type { Form, ValidateValue } from '../key-validator/declarations'-import type { PluginProvider } from '@/models/common'-import { toast } from '@langgenius/dify-ui/toast'-import { useTranslation } from 'react-i18next'-import { useAppContext } from '@/context/app-context'-import SerpapiLogo from '../../assets/serpapi.png'-import KeyValidator from '../key-validator'-import { updatePluginKey, validatePluginKey } from './utils'--type SerpapiPluginProps = {- plugin: PluginProvider- onUpdate: () => void-}-const SerpapiPlugin = ({ plugin, onUpdate }: SerpapiPluginProps) => {- const { t } = useTranslation()- const { isCurrentWorkspaceManager } = useAppContext()- const forms: Form[] = [{- key: 'api_key',- title: t('plugin.serpapi.apiKey', { ns: 'common' }),- placeholder: t('plugin.serpapi.apiKeyPlaceholder', { ns: 'common' }),- value: plugin.credentials?.api_key,- validate: {- before: (v) => {- if (v?.api_key)- return true- },- run: async (v) => {- return validatePluginKey('serpapi', {- credentials: {- api_key: v?.api_key,- },- })- },- },- handleFocus: (v, dispatch) => {- if (v.api_key === plugin.credentials?.api_key)- dispatch({ ...v, api_key: '' })- },- }]- const handleSave = async (v: ValidateValue) => {- if (!v?.api_key || v?.api_key === plugin.credentials?.api_key)- return- const res = await updatePluginKey('serpapi', {- credentials: {- api_key: v?.api_key,- },- })- if (res.status === 'success') {- toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))- onUpdate()- return true- }- }- return (- <KeyValidator- type="serpapi"- title={<img alt="serpapi logo" src={SerpapiLogo.src} width={64} />}- status={plugin.credentials?.api_key ? 'success' : 'add'}- forms={forms}- keyFrom={{- text: t('plugin.serpapi.keyFrom', { ns: 'common' }),- link: 'https://serpapi.com/manage-api-key',- }}- onSave={handleSave}- disabled={!isCurrentWorkspaceManager}- />- )-}-export default SerpapiPlugindiff --git a/web/app/components/header/account-setting/plugin-page/__tests__/SerpapiPlugin.spec.tsx b/web/app/components/header/account-setting/plugin-page/__tests__/SerpapiPlugin.spec.tsxdeleted file mode 100644index 2055c0725de..00000000000--- a/web/app/components/header/account-setting/plugin-page/__tests__/SerpapiPlugin.spec.tsx+++ /dev/null@@ -1,213 +0,0 @@-import type { PluginProvider } from '@/models/common'-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { useAppContext } from '@/context/app-context'-import SerpapiPlugin from '../SerpapiPlugin'-import { updatePluginKey, validatePluginKey } from '../utils'--const mockEventEmitter = vi.hoisted(() => {- let subscriber: ((value: string) => void) | undefined- return {- useSubscription: vi.fn((callback: (value: string) => void) => {- subscriber = callback- }),- emit: vi.fn((value: string) => {- subscriber?.(value)- }),- reset: () => {- subscriber = undefined- },- }-})--const { mockToast } = vi.hoisted(() => {- const mockToast = Object.assign(vi.fn(), {- success: vi.fn(),- error: vi.fn(),- warning: vi.fn(),- info: vi.fn(),- dismiss: vi.fn(),- update: vi.fn(),- promise: vi.fn(),- })- return { mockToast }-})--vi.mock('@langgenius/dify-ui/toast', () => ({- toast: mockToast,-}))--vi.mock('@/context/app-context', () => ({- useAppContext: vi.fn(),-}))--vi.mock('../utils', () => ({- updatePluginKey: vi.fn(),- validatePluginKey: vi.fn(),-}))--vi.mock('@/context/event-emitter', () => ({- useEventEmitterContextContext: vi.fn(() => ({- eventEmitter: mockEventEmitter,- })),-}))--describe('SerpapiPlugin', () => {- const mockOnUpdate = vi.fn()- const mockUpdatePluginKey = updatePluginKey as ReturnType<typeof vi.fn>- const mockValidatePluginKey = validatePluginKey as ReturnType<typeof vi.fn>-- beforeEach(() => {- vi.clearAllMocks()- mockEventEmitter.reset()- const mockUseAppContext = useAppContext as ReturnType<typeof vi.fn>- mockUseAppContext.mockReturnValue({- isCurrentWorkspaceManager: true,- })- mockValidatePluginKey.mockResolvedValue({ status: 'success' })- mockUpdatePluginKey.mockResolvedValue({ status: 'success' })- })-- it('should show key input when manager clicks edit key', () => {- const mockPlugin: PluginProvider = {- tool_name: 'serpapi',- credentials: {- api_key: 'existing-key',- },- } as PluginProvider-- render(<SerpapiPlugin plugin={mockPlugin} onUpdate={mockOnUpdate} />)-- fireEvent.click(screen.getByText('common.provider.editKey'))- expect(screen.getByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder')).toBeInTheDocument()- })-- it('should clear existing key on focus and show validation error for invalid key', async () => {- vi.useFakeTimers()- try {- mockValidatePluginKey.mockResolvedValue({ status: 'error', message: 'Invalid API key' })-- const mockPlugin: PluginProvider = {- tool_name: 'serpapi',- credentials: {- api_key: 'existing-key',- },- } as PluginProvider-- render(<SerpapiPlugin plugin={mockPlugin} onUpdate={mockOnUpdate} />)-- fireEvent.click(screen.getByText('common.provider.editKey'))- const input = screen.getByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder')-- expect(input).toHaveValue('existing-key')- fireEvent.focus(input)- expect(input).toHaveValue('')-- fireEvent.change(input, {- target: { value: 'invalid-key' },- })-- await act(async () => {- await vi.advanceTimersByTimeAsync(1000)- })-- expect(screen.getByText(/Invalid API key/)).toBeInTheDocument()-- fireEvent.focus(input)- expect(input).toHaveValue('invalid-key')-- fireEvent.change(input, {- target: { value: '' },- })-- await act(async () => {- await vi.advanceTimersByTimeAsync(1000)- })-- expect(screen.queryByText(/Invalid API key/)).toBeNull()- }- finally {- vi.useRealTimers()- }- })-- it('should not open key input when user is not workspace manager', () => {- const mockUseAppContext = useAppContext as ReturnType<typeof vi.fn>- mockUseAppContext.mockReturnValue({- isCurrentWorkspaceManager: false,- })-- const mockPlugin = {- tool_name: 'serpapi',- is_enabled: true,- credentials: null,- } satisfies PluginProvider-- render(<SerpapiPlugin plugin={mockPlugin} onUpdate={mockOnUpdate} />)-- fireEvent.click(screen.getByText('common.provider.addKey'))-- expect(screen.queryByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder')).toBeNull()- })-- it('should save changed key and trigger success feedback', async () => {- const mockPlugin: PluginProvider = {- tool_name: 'serpapi',- credentials: {- api_key: 'existing-key',- },- } as PluginProvider-- render(<SerpapiPlugin plugin={mockPlugin} onUpdate={mockOnUpdate} />)-- fireEvent.click(screen.getByText('common.provider.editKey'))- fireEvent.change(screen.getByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder'), {- target: { value: 'new-key' },- })- fireEvent.click(screen.getByText('common.operation.save'))-- await waitFor(() => {- expect(screen.queryByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder')).toBeNull()- })- })-- it('should keep editor open when save request fails', async () => {- mockUpdatePluginKey.mockResolvedValue({ status: 'error', message: 'update failed' })-- const mockPlugin: PluginProvider = {- tool_name: 'serpapi',- credentials: {- api_key: 'existing-key',- },- } as PluginProvider-- render(<SerpapiPlugin plugin={mockPlugin} onUpdate={mockOnUpdate} />)-- fireEvent.click(screen.getByText('common.provider.editKey'))- fireEvent.change(screen.getByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder'), {- target: { value: 'new-key' },- })- fireEvent.click(screen.getByText('common.operation.save'))-- await waitFor(() => {- expect(screen.getByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder')).toBeInTheDocument()- })- })-- it('should keep editor open when key value is unchanged', async () => {- const mockPlugin: PluginProvider = {- tool_name: 'serpapi',- credentials: {- api_key: 'existing-key',- },- } as PluginProvider-- render(<SerpapiPlugin plugin={mockPlugin} onUpdate={mockOnUpdate} />)-- fireEvent.click(screen.getByText('common.provider.editKey'))- fireEvent.click(screen.getByText('common.operation.save'))-- await waitFor(() => {- expect(screen.getByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder')).toBeInTheDocument()- })- })-})diff --git a/web/app/components/header/account-setting/plugin-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/plugin-page/__tests__/index.spec.tsxdeleted file mode 100644index ca0c41a83bf..00000000000--- a/web/app/components/header/account-setting/plugin-page/__tests__/index.spec.tsx+++ /dev/null@@ -1,120 +0,0 @@-import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import { useState } from 'react'-import { useAppContext } from '@/context/app-context'-import PluginPage from '../index'-import { updatePluginKey, validatePluginKey } from '../utils'--const mockUsePluginProviders = vi.hoisted(() => vi.fn())--vi.mock('@/service/use-common', () => ({- usePluginProviders: mockUsePluginProviders,-}))--vi.mock('@/context/app-context', () => ({- useAppContext: vi.fn(),-}))--vi.mock('@langgenius/dify-ui/toast', async (importOriginal) => {- const actual = await importOriginal<typeof import('@langgenius/dify-ui/toast')>()- return {- ...actual,-- }-})--vi.mock('@/context/event-emitter', () => ({- useEventEmitterContextContext: () => ({- eventEmitter: {- emit: vi.fn(),- useSubscription: vi.fn(),- },- }),-}))--vi.mock('../utils', () => ({- updatePluginKey: vi.fn(),- validatePluginKey: vi.fn(),-}))--describe('PluginPage', () => {- const mockUpdatePluginKey = updatePluginKey as ReturnType<typeof vi.fn>- const mockValidatePluginKey = validatePluginKey as ReturnType<typeof vi.fn>-- beforeEach(() => {- vi.clearAllMocks()- const mockUseAppContext = useAppContext as ReturnType<typeof vi.fn>- mockUseAppContext.mockReturnValue({- isCurrentWorkspaceManager: true,- })- mockValidatePluginKey.mockResolvedValue({ status: 'success' })- mockUpdatePluginKey.mockResolvedValue({ status: 'success' })- })-- it('should render plugin settings with edit action when serpapi key exists', () => {- mockUsePluginProviders.mockReturnValue({- data: [- { tool_name: 'serpapi', credentials: { api_key: 'test-key' } },- ],- refetch: vi.fn(),- })-- render(<PluginPage />)- expect(screen.getByText('common.provider.editKey')).toBeInTheDocument()- })-- it('should render plugin settings with add action when serpapi key is missing', () => {- mockUsePluginProviders.mockReturnValue({- data: [- { tool_name: 'serpapi', credentials: null },- ],- refetch: vi.fn(),- })-- render(<PluginPage />)- expect(screen.getByText('common.provider.addKey')).toBeInTheDocument()- })-- it('should display encryption notice with PKCS1_OAEP link', () => {- mockUsePluginProviders.mockReturnValue({- data: [],- refetch: vi.fn(),- })-- render(<PluginPage />)- expect(screen.getByText(/common\.provider\.encrypted\.front/)).toBeInTheDocument()- expect(screen.getByText(/common\.provider\.encrypted\.back/)).toBeInTheDocument()- const link = screen.getByRole('link', { name: 'PKCS1_OAEP' })- expect(link).toHaveAttribute('target', '_blank')- expect(link).toHaveAttribute('href', 'https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html')- })-- it('should show reload state after saving key', async () => {- let showReloadedState = () => {}- const Wrapper = () => {- const [reloaded, setReloaded] = useState(false)- showReloadedState = () => setReloaded(true)- return (- <>- <PluginPage />- {reloaded && <div>providers-reloaded</div>}- </>- )- }- mockUsePluginProviders.mockImplementation(() => ({- data: [{ tool_name: 'serpapi', credentials: { api_key: 'existing-key' } }],- refetch: () => showReloadedState(),- }))-- render(<Wrapper />)-- fireEvent.click(screen.getByText('common.provider.editKey'))- fireEvent.change(screen.getByPlaceholderText('common.plugin.serpapi.apiKeyPlaceholder'), {- target: { value: 'new-key' },- })- fireEvent.click(screen.getByText('common.operation.save'))-- await waitFor(() => {- expect(screen.getByText('providers-reloaded')).toBeInTheDocument()- })- })-})diff --git a/web/app/components/header/account-setting/plugin-page/__tests__/utils.spec.ts b/web/app/components/header/account-setting/plugin-page/__tests__/utils.spec.tsdeleted file mode 100644index e49a9f41c9f..00000000000--- a/web/app/components/header/account-setting/plugin-page/__tests__/utils.spec.ts+++ /dev/null@@ -1,73 +0,0 @@-import { updatePluginProviderAIKey, validatePluginProviderKey } from '@/service/common'-import { ValidatedStatus } from '../../key-validator/declarations'-import { updatePluginKey, validatePluginKey } from '../utils'--vi.mock('@/service/common', () => ({- validatePluginProviderKey: vi.fn(),- updatePluginProviderAIKey: vi.fn(),-}))--const mockValidatePluginProviderKey = validatePluginProviderKey as ReturnType<typeof vi.fn>-const mockUpdatePluginProviderAIKey = updatePluginProviderAIKey as ReturnType<typeof vi.fn>--describe('Plugin Utils', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- describe.each([- {- name: 'validatePluginKey',- utilFn: validatePluginKey,- serviceMock: mockValidatePluginProviderKey,- successBody: { credentials: { api_key: 'test-key' } },- failureBody: { credentials: { api_key: 'invalid' } },- exceptionBody: { credentials: { api_key: 'test' } },- serviceErrorMessage: 'Invalid API key',- thrownErrorMessage: 'Network error',- },- {- name: 'updatePluginKey',- utilFn: updatePluginKey,- serviceMock: mockUpdatePluginProviderAIKey,- successBody: { credentials: { api_key: 'new-key' } },- failureBody: { credentials: { api_key: 'test' } },- exceptionBody: { credentials: { api_key: 'test' } },- serviceErrorMessage: 'Update failed',- thrownErrorMessage: 'Request failed',- },- ])('$name', ({ utilFn, serviceMock, successBody, failureBody, exceptionBody, serviceErrorMessage, thrownErrorMessage }) => {- it('should return success status when service succeeds', async () => {- serviceMock.mockResolvedValue({ result: 'success' })-- const result = await utilFn('serpapi', successBody)-- expect(result.status).toBe(ValidatedStatus.Success)- })-- it('should return error status with message when service returns an error', async () => {- serviceMock.mockResolvedValue({- result: 'error',- error: serviceErrorMessage,- })-- const result = await utilFn('serpapi', failureBody)-- expect(result).toMatchObject({- status: ValidatedStatus.Error,- message: serviceErrorMessage,- })- })-- it('should return error status when service throws exception', async () => {- serviceMock.mockRejectedValue(new Error(thrownErrorMessage))-- const result = await utilFn('serpapi', exceptionBody)-- expect(result).toMatchObject({- status: ValidatedStatus.Error,- message: thrownErrorMessage,- })- })- })-})diff --git a/web/app/components/header/account-setting/plugin-page/index.tsx b/web/app/components/header/account-setting/plugin-page/index.tsxdeleted file mode 100644index 15d83028746..00000000000--- a/web/app/components/header/account-setting/plugin-page/index.tsx+++ /dev/null@@ -1,38 +0,0 @@-import type { PluginProvider } from '@/models/common'-import { LockClosedIcon } from '@heroicons/react/24/solid'-import { useTranslation } from 'react-i18next'-import Link from '@/next/link'-import { usePluginProviders } from '@/service/use-common'-import SerpapiPlugin from './SerpapiPlugin'--const PluginPage = () => {- const { t } = useTranslation()- const { data: plugins, refetch: mutate } = usePluginProviders()-- const Plugin_MAP: Record<string, (plugin: PluginProvider) => React.JSX.Element> = {- serpapi: (plugin: PluginProvider) => <SerpapiPlugin key="serpapi" plugin={plugin} onUpdate={() => mutate()} />,- }-- return (- <div className="pb-7">- <div>- {plugins?.map(plugin => Plugin_MAP[plugin.tool_name]!(plugin))}- </div>- <div className="fixed bottom-0 flex h-[42px] w-[472px] items-center bg-white text-xs text-gray-500">- <LockClosedIcon className="mr-1 size-3" />- {t('provider.encrypted.front', { ns: 'common' })}- <Link- className="mx-1 text-primary-600"- target="_blank"- rel="noopener noreferrer"- href="https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html"- >- PKCS1_OAEP- </Link>- {t('provider.encrypted.back', { ns: 'common' })}- </div>- </div>- )-}--export default PluginPagediff --git a/web/app/components/header/account-setting/plugin-page/utils.ts b/web/app/components/header/account-setting/plugin-page/utils.tsdeleted file mode 100644index 385ef31cab2..00000000000--- a/web/app/components/header/account-setting/plugin-page/utils.ts+++ /dev/null@@ -1,34 +0,0 @@-import { updatePluginProviderAIKey, validatePluginProviderKey } from '@/service/common'-import { ValidatedStatus } from '../key-validator/declarations'--export const validatePluginKey = async (pluginType: string, body: any) => {- try {- const res = await validatePluginProviderKey({- url: `/workspaces/current/tool-providers/${pluginType}/credentials-validate`,- body,- })- if (res.result === 'success')- return Promise.resolve({ status: ValidatedStatus.Success })- else- return Promise.resolve({ status: ValidatedStatus.Error, message: res.error })- }- catch (e: any) {- return Promise.resolve({ status: ValidatedStatus.Error, message: e.message })- }-}--export const updatePluginKey = async (pluginType: string, body: any) => {- try {- const res = await updatePluginProviderAIKey({- url: `/workspaces/current/tool-providers/${pluginType}/credentials`,- body,- })- if (res.result === 'success')- return Promise.resolve({ status: ValidatedStatus.Success })- else- return Promise.resolve({ status: ValidatedStatus.Error, message: res.error })- }- catch (e: any) {- return Promise.resolve({ status: ValidatedStatus.Error, message: e.message })- }-}diff --git a/web/app/components/header/account-setting/workspace-role-checkbox-list.tsx b/web/app/components/header/account-setting/workspace-role-checkbox-list.tsxnew file mode 100644index 00000000000..f3afc856cba--- /dev/null+++ b/web/app/components/header/account-setting/workspace-role-checkbox-list.tsx@@ -0,0 +1,281 @@+'use client'++import type { Role } from '@/models/access-control'+import { Checkbox } from '@langgenius/dify-ui/checkbox'+import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'+import { RadioControl, RadioRoot } from '@langgenius/dify-ui/radio'+import { RadioGroup } from '@langgenius/dify-ui/radio-group'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useLocale } from '@/context/i18n'+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'+import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'++type WorkspaceRoleCheckboxListProps = {+ selectedRoleIds: string[]+ selectedRoles?: Role[]+ allowMultipleRoles?: boolean+ disabledRoleIds?: string[]+ onSelectedRolesChange: (selectedRoles: Role[]) => void+ includeOwner?: boolean+}++const PAGE_SIZE = 20+const EMPTY_DISABLED_ROLE_IDS: string[] = []++const createSelectedRolePlaceholder = (id: string): Role => ({+ id,+ tenant_id: '',+ type: 'workspace',+ category: 'global_custom',+ name: id,+ description: '',+ is_builtin: false,+ permission_keys: [],+ role_tag: '',+})++const WorkspaceRoleCheckboxList = ({+ selectedRoleIds,+ selectedRoles,+ allowMultipleRoles = true,+ disabledRoleIds = EMPTY_DISABLED_ROLE_IDS,+ onSelectedRolesChange,+ includeOwner = false,+}: WorkspaceRoleCheckboxListProps) => {+ const { t } = useTranslation()+ const locale = useLocale()+ const [keyword, setKeyword] = useState('')+ const containerRef = useRef<HTMLDivElement>(null)+ const anchorRef = useRef<HTMLDivElement>(null)+ const language = useMemo(() => getAccessControlTemplateLanguage(locale), [locale])++ const {+ data: rolesData,+ isLoading: rolesLoading,+ error,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ } = useWorkspaceRoleList({+ page: 1,+ limit: PAGE_SIZE,+ include_owner: includeOwner ? 1 : 0,+ language,+ })++ useEffect(() => {+ const hasMore = hasNextPage ?? true+ let observer: IntersectionObserver | undefined++ if (error)+ return++ if (anchorRef.current && containerRef.current) {+ const containerHeight = containerRef.current.clientHeight+ const dynamicMargin = Math.max(100, Math.min(containerHeight * 0.2, 200))++ observer = new IntersectionObserver((entries) => {+ if (entries[0]!.isIntersecting && !rolesLoading && !isFetchingNextPage && !error && hasMore)+ fetchNextPage()+ }, {+ root: containerRef.current,+ rootMargin: `${dynamicMargin}px`,+ })+ observer.observe(anchorRef.current)+ }+ return () => observer?.disconnect()+ }, [rolesLoading, isFetchingNextPage, fetchNextPage, error, hasNextPage])++ const roles = useMemo(() => rolesData?.pages.flatMap(page => page.data) ?? [], [rolesData])+ const roleById = useMemo(() => {+ return new Map(roles.map(role => [role.id, role]))+ }, [roles])+ const selectedRoleIdSet = useMemo(() => new Set(selectedRoleIds), [selectedRoleIds])+ const disabledRoleIdSet = useMemo(() => new Set(disabledRoleIds), [disabledRoleIds])+ const selectedRoleObjects = useMemo(() => {+ if (selectedRoles)+ return selectedRoles++ return selectedRoleIds.map(roleId => roleById.get(roleId) ?? createSelectedRolePlaceholder(roleId))+ }, [roleById, selectedRoleIds, selectedRoles])++ const filteredRoles = useMemo(() => {+ const trimmed = keyword.trim().toLowerCase()+ if (!trimmed)+ return roles++ return roles.filter(+ role =>+ role.name.toLowerCase().includes(trimmed)+ || role.description?.toLowerCase().includes(trimmed),+ )+ }, [roles, keyword])++ const toggleRole = useCallback((role: Role) => {+ if (disabledRoleIdSet.has(role.id))+ return++ if (!allowMultipleRoles) {+ onSelectedRolesChange(selectedRoleIdSet.has(role.id) ? selectedRoleObjects : [role])+ return+ }++ onSelectedRolesChange(+ selectedRoleIdSet.has(role.id)+ ? selectedRoleObjects.filter(selectedRole => selectedRole.id !== role.id)+ : [...selectedRoleObjects, role],+ )+ }, [allowMultipleRoles, disabledRoleIdSet, onSelectedRolesChange, selectedRoleIdSet, selectedRoleObjects])++ const handleRadioValueChange = useCallback((roleId: string) => {+ const role = roleById.get(roleId)+ if (!role || disabledRoleIdSet.has(role.id))+ return++ onSelectedRolesChange([role])+ }, [disabledRoleIdSet, onSelectedRolesChange, roleById])++ const renderRoleText = (role: Role) => (+ <div className="min-w-0 flex-1">+ <div className="system-sm-semibold text-text-secondary">+ {role.name}+ </div>+ <div className="mt-0.5 system-xs-regular text-text-tertiary">+ {role.description || t('role.noDescription', { ns: 'permission' })}+ </div>+ </div>+ )++ return (+ <>+ <div className="shrink-0 px-6 pt-3 pb-2">+ <div className="relative">+ <span+ aria-hidden+ className="pointer-events-none absolute top-1/2 left-3 i-ri-search-line size-4 -translate-y-1/2 text-text-tertiary"+ />+ <Input+ value={keyword}+ onChange={e => setKeyword(e.target.value)}+ placeholder={t('role.searchPlaceholder', { ns: 'permission' })}+ className="pr-8 pl-8"+ />+ {keyword && (+ <button+ type="button"+ className="absolute top-1/2 right-2 flex size-5 -translate-y-1/2 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-components-input-border-active"+ aria-label={t('operation.clear', { ns: 'common' })}+ onClick={() => setKeyword('')}+ >+ <span aria-hidden className="i-ri-close-line size-4" />+ </button>+ )}+ </div>+ </div>++ <ScrollArea+ ref={containerRef}+ className="min-h-0 flex-1"+ slotClassNames={{ viewport: 'px-3 overscroll-contain' }}+ >+ {rolesLoading+ ? (+ <div className="px-3 py-6 text-center system-sm-regular text-text-tertiary">+ {t('role.loading', { ns: 'permission' })}+ </div>+ )+ : filteredRoles.length === 0+ ? (+ <div className="px-3 py-6 text-center system-sm-regular text-text-tertiary">+ {t('role.noMatchingRoles', { ns: 'permission' })}+ </div>+ )+ : (+ <>+ {allowMultipleRoles+ ? (+ <ul className="flex flex-col gap-0.5 pb-2">+ {filteredRoles.map((role) => {+ const checked = selectedRoleIdSet.has(role.id)+ const disabled = disabledRoleIdSet.has(role.id)+ const handleToggle = () => toggleRole(role)++ return (+ <li key={role.id}>+ <div+ role="checkbox"+ aria-checked={checked}+ aria-disabled={disabled}+ tabIndex={disabled ? -1 : 0}+ className={cn(+ 'flex cursor-pointer items-start gap-3 rounded-lg px-3 py-2.5 hover:bg-state-base-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-components-input-border-active',+ checked && 'bg-state-accent-hover hover:bg-state-accent-hover',+ disabled && 'cursor-not-allowed opacity-50 hover:bg-transparent',+ )}+ onClick={handleToggle}+ onKeyDown={(e) => {+ if (e.key === ' ' || e.key === 'Enter') {+ e.preventDefault()+ handleToggle()+ }+ }}+ >+ <Checkbox+ checked={checked}+ disabled={disabled}+ className="pointer-events-none mt-0.5"+ />+ {renderRoleText(role)}+ </div>+ </li>+ )+ })}+ </ul>+ )+ : (+ <RadioGroup+ value={selectedRoleIds[0] ?? ''}+ onValueChange={handleRadioValueChange}+ className="flex-col items-stretch gap-0.5 pb-2"+ render={<ul />}+ >+ {filteredRoles.map((role) => {+ const checked = selectedRoleIdSet.has(role.id)+ const disabled = disabledRoleIdSet.has(role.id)++ return (+ <li key={role.id}>+ <RadioRoot+ value={role.id}+ disabled={disabled}+ variant="unstyled"+ render={(+ <div+ className={cn(+ 'flex cursor-pointer items-start gap-3 rounded-lg px-3 py-2.5 hover:bg-state-base-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-components-input-border-active',+ checked && 'bg-state-accent-hover hover:bg-state-accent-hover',+ disabled && 'cursor-not-allowed opacity-50 hover:bg-transparent',+ )}+ />+ )}+ >+ <RadioControl className="pointer-events-none mt-0.5" />+ {renderRoleText(role)}+ </RadioRoot>+ </li>+ )+ })}+ </RadioGroup>+ )}+ <div ref={anchorRef} className="h-0" />+ </>+ )}+ </ScrollArea>+ </>+ )+}++export default WorkspaceRoleCheckboxListdiff --git a/web/app/components/header/app-nav/__tests__/index.spec.tsx b/web/app/components/header/app-nav/__tests__/index.spec.tsxindex 1fd30271ac9..adcaf17d2da 100644--- a/web/app/components/header/app-nav/__tests__/index.spec.tsx+++ b/web/app/components/header/app-nav/__tests__/index.spec.tsx@@ -2,9 +2,9 @@ import { useInfiniteQuery } from '@tanstack/react-query'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useStore as useAppStore } from '@/app/components/app/store'-import { useAppContext } from '@/context/app-context'import { useParams } from '@/next/navigation'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import AppNav from '../index'const mockAppListInfiniteOptions = vi.hoisted(() => vi.fn((options: unknown) => options))@@ -19,14 +19,18 @@ vi.mock('react-i18next', () => ({}),}))-vi.mock('@/context/app-context', () => ({- useAppContext: vi.fn(),-}))-vi.mock('@/app/components/app/store', () => ({useStore: vi.fn(),}))+let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+vi.mock('@/service/client', () => ({consoleQuery: {apps: {@@ -151,11 +155,11 @@ const mockAppData = [icon: '🤖',icon_background: null,icon_url: null,+ permission_keys: [] as string[],},]const mockUseParams = vi.mocked(useParams)-const mockUseAppContext = vi.mocked(useAppContext)const mockUseAppStore = vi.mocked(useAppStore)const mockUseInfiniteQuery = vi.mocked(useInfiniteQuery)let mockAppDetail: { id: string, name: string } | null = null@@ -168,14 +172,12 @@ const setupDefaultMocks = (options?: {hasNextPage?: booleanrefetch?: () => voidfetchNextPage?: () => void- isEditor?: booleanappData?: typeof mockAppData}) => {const refetch = options?.refetch ?? vi.fn()const fetchNextPage = options?.fetchNextPage ?? vi.fn()mockUseParams.mockReturnValue({ appId: 'app-1' } as ReturnType<typeof useParams>)- mockUseAppContext.mockReturnValue({ isCurrentWorkspaceEditor: options?.isEditor ?? false } as ReturnType<typeof useAppContext>)mockUseAppStore.mockImplementation((selector: unknown) => (selector as (state: { appDetail: { id: string, name: string } | null }) => unknown)({ appDetail: mockAppDetail }))mockUseInfiniteQuery.mockReturnValue({data: { pages: [{ data: options?.appData ?? mockAppData }] },@@ -192,6 +194,7 @@ describe('AppNav', () => {beforeEach(() => {vi.clearAllMocks()mockAppDetail = null+ mockWorkspacePermissionKeys = ['app.create_and_management']setupDefaultMocks()})@@ -212,6 +215,15 @@ describe('AppNav', () => {expect(options.getNextPageParam({ has_more: false, page: 3 })).toBeUndefined()})+ it('should keep snippets configured as an active studio child link after rerender setup', () => {+ setupDefaultMocks()+ render(<AppNav />)++ expect(screen.getByTestId('nav-text')).toHaveTextContent('menus.apps')+ expect(screen.getByTestId('nav-active-segment')).toHaveTextContent(JSON.stringify(['apps', 'app', 'snippets']))+ expect(screen.getByTestId('nav-active-link')).toHaveTextContent('snippets:tabs.snippets->/snippets')+ })+it('should configure snippets as an active studio child link', () => {setupDefaultMocks()render(<AppNav />)@@ -221,9 +233,8 @@ describe('AppNav', () => {expect(screen.getByTestId('nav-active-link')).toHaveTextContent('snippets:tabs.snippets->/snippets')})- it('should build editor links and update app name when app detail changes', async () => {+ it('should build layout links from app ACL and update app name when app detail changes', async () => {setupDefaultMocks({- isEditor: true,appData: [{id: 'app-1',@@ -233,6 +244,7 @@ describe('AppNav', () => {icon: '🤖',icon_background: null,icon_url: null,+ permission_keys: [AppACLPermission.Edit],},{id: 'app-2',@@ -242,6 +254,7 @@ describe('AppNav', () => {icon: '⚙️',icon_background: null,icon_url: null,+ permission_keys: [AppACLPermission.TestAndRun],},],})@@ -304,6 +317,20 @@ describe('AppNav', () => {})})+ it('should not open create modals without app.create_and_management permission', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys = []+ render(<AppNav />)++ await user.click(screen.getByTestId('create-blank'))+ await user.click(screen.getByTestId('create-template'))+ await user.click(screen.getByTestId('create-dsl'))++ expect(screen.queryByTestId('create-app-modal')).not.toBeInTheDocument()+ expect(screen.queryByTestId('create-app-template-dialog')).not.toBeInTheDocument()+ expect(screen.queryByTestId('create-from-dsl-modal')).not.toBeInTheDocument()+ })+it('should load more when user clicks load more and more data is available', async () => {const user = userEvent.setup()const { fetchNextPage } = setupDefaultMocks({ hasNextPage: true })@@ -322,10 +349,9 @@ describe('AppNav', () => {expect(fetchNextPage).not.toHaveBeenCalled()})- // Non-editor link path: isCurrentWorkspaceEditor=false → link ends with /overview- it('should build overview links when user is not editor', () => {+ it('should build overview links when app layout ACL is missing', () => {// Arrange- setupDefaultMocks({ isEditor: false })+ setupDefaultMocks()// Actrender(<AppNav />)@@ -359,7 +385,6 @@ describe('AppNav', () => {it('should build workflow link for ADVANCED_CHAT mode when user is editor', () => {// ArrangesetupDefaultMocks({- isEditor: true,appData: [{id: 'app-3',@@ -369,6 +394,7 @@ describe('AppNav', () => {icon: '💬',icon_background: null,icon_url: null,+ permission_keys: [AppACLPermission.ViewLayout],},],})@@ -383,7 +409,20 @@ describe('AppNav', () => {// No-match update path: appDetail.id doesn't match any nav itemit('should not change nav item names when appDetail id does not match any item', async () => {// Arrange- setupDefaultMocks({ isEditor: true })+ setupDefaultMocks({+ appData: [+ {+ id: 'app-1',+ name: 'App 1',+ mode: AppModeEnum.AGENT_CHAT,+ icon_type: 'emoji',+ icon: '🤖',+ icon_background: null,+ icon_url: null,+ permission_keys: [AppACLPermission.Edit],+ },+ ],+ })const { rerender } = render(<AppNav />)// Act - set appDetail to a non-matching iddiff --git a/web/app/components/header/app-nav/index.tsx b/web/app/components/header/app-nav/index.tsxindex fffeb8055cd..47c3a56a9e3 100644--- a/web/app/components/header/app-nav/index.tsx+++ b/web/app/components/header/app-nav/index.tsx@@ -2,19 +2,16 @@import type { NavItem } from '../nav/nav-selector'import type { AppListQuery } from '@/contract/console/apps'-import {- RiRobot2Fill,- RiRobot2Line,-} from '@remixicon/react'import { keepPreviousData, useInfiniteQuery } from '@tanstack/react-query'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useStore as useAppStore } from '@/app/components/app/store'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import dynamic from '@/next/dynamic'import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/client'import { AppModeEnum } from '@/types/app'+import { getAppACLCapabilities, hasPermission } from '@/utils/permission'import Nav from '../nav'const CreateAppTemplateDialog = dynamic(() => import('@/app/components/app/create-app-dialog'), { ssr: false })@@ -27,8 +24,8 @@ const appNavListQuery = {name: '',} satisfies AppListQuery-const getAppLink = (isCurrentWorkspaceEditor: boolean, appId: string, appMode: AppModeEnum) => {- if (!isCurrentWorkspaceEditor)+const getAppLink = (canAccessLayout: boolean, appId: string, appMode: AppModeEnum) => {+ if (!canAccessLayout)return `/app/${appId}/overview`if (appMode === AppModeEnum.WORKFLOW || appMode === AppModeEnum.ADVANCED_CHAT)@@ -40,8 +37,10 @@ const getAppLink = (isCurrentWorkspaceEditor: boolean, appId: string, appMode: Aconst AppNav = () => {const { t } = useTranslation()const { appId } = useParams()- const { isCurrentWorkspaceEditor } = useAppContext()const appDetail = useAppStore(state => state.appDetail)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')const [showNewAppDialog, setShowNewAppDialog] = useState(false)const [showNewAppTemplateDialog, setShowNewAppTemplateDialog] = useState(false)const [showCreateFromDSLModal, setShowCreateFromDSLModal] = useState(false)@@ -72,14 +71,17 @@ const AppNav = () => {fetchNextPage()}, [fetchNextPage, hasNextPage])- const openModal = (state: string) => {+ const openModal = useCallback((state: string) => {+ if (!canCreateApp)+ return+if (state === 'blank')setShowNewAppDialog(true)if (state === 'template')setShowNewAppTemplateDialog(true)if (state === 'dsl')setShowCreateFromDSLModal(true)- }+ }, [canCreateApp])const navItems = useMemo<NavItem[]>(() => {const appItems = appsData?.pages.flatMap(appData => appData.data) ?? []@@ -92,16 +94,20 @@ const AppNav = () => {icon_url: app.icon_url,name: appDetail?.id === app.id ? appDetail.name : app.name,mode: app.mode,- link: getAppLink(isCurrentWorkspaceEditor, app.id, app.mode),+ link: getAppLink(getAppACLCapabilities(app.permission_keys, {+ currentUserId,+ resourceMaintainer: app.maintainer,+ workspacePermissionKeys,+ }).canAccessLayout, app.id, app.mode),}))- }, [appDetail?.id, appDetail?.name, appsData?.pages, isCurrentWorkspaceEditor])+ }, [appDetail?.id, appDetail?.name, appsData?.pages, currentUserId, workspacePermissionKeys])return (<><NavisApp- icon={<RiRobot2Line className="size-4" />}- activeIcon={<RiRobot2Fill className="size-4" />}+ icon={<span className="i-ri-robot-2-line size-4" />}+ activeIcon={<span className="i-ri-robot-2-fill size-4" />}text={t('menus.apps', { ns: 'common' })}activeSegment={['apps', 'app', 'snippets']}link="/apps"@@ -118,17 +124,17 @@ const AppNav = () => {isLoadingMore={isFetchingNextPage}/><CreateAppModal- show={showNewAppDialog}+ show={canCreateApp && showNewAppDialog}onClose={() => setShowNewAppDialog(false)}onSuccess={() => refetch()}/><CreateAppTemplateDialog- show={showNewAppTemplateDialog}+ show={canCreateApp && showNewAppTemplateDialog}onClose={() => setShowNewAppTemplateDialog(false)}onSuccess={() => refetch()}/><CreateFromDSLModal- show={showCreateFromDSLModal}+ show={canCreateApp && showCreateFromDSLModal}onClose={() => setShowCreateFromDSLModal(false)}onSuccess={() => refetch()}/>diff --git a/web/app/components/header/assets/serpapi.png b/web/app/components/header/assets/serpapi.pngdeleted file mode 100644index 9650453ed5f..00000000000Binary files a/web/app/components/header/assets/serpapi.png and /dev/null differdiff --git a/web/app/components/header/dataset-nav/__tests__/index.spec.tsx b/web/app/components/header/dataset-nav/__tests__/index.spec.tsxindex 7df00f5c8f0..38e4169eb24 100644--- a/web/app/components/header/dataset-nav/__tests__/index.spec.tsx+++ b/web/app/components/header/dataset-nav/__tests__/index.spec.tsx@@ -132,6 +132,7 @@ describe('DatasetNav', () => {} as unknown as ReturnType<typeof useDatasetList>)vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceEditor: true,+ workspacePermissionKeys: ['dataset.create_and_management'],} as unknown as ReturnType<typeof useAppContext>)})diff --git a/web/app/components/header/index.tsx b/web/app/components/header/index.tsxindex d604f96dbd5..d177152251c 100644--- a/web/app/components/header/index.tsx+++ b/web/app/components/header/index.tsx@@ -3,13 +3,14 @@ import { useSuspenseQuery } from '@tanstack/react-query'import DifyLogo from '@/app/components/base/logo/dify-logo'import WorkplaceSelector from '@/app/components/header/account-dropdown/workplace-selector'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'-import { useAppContext } from '@/context/app-context'+import { useAppContext, useSelector as useAppContextSelector } from '@/context/app-context'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { DeploymentsNav } from '@/features/deployments/nav'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import Link from '@/next/link'+import { hasPermission } from '@/utils/permission'import { Plan } from '../billing/type'import AccountDropdown from './account-dropdown'import AppNav from './app-nav'@@ -28,9 +29,10 @@ const navClassName = ``export function Header() {- const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator } = useAppContext()+ const workspacePermissionKeys = useAppContextSelector(s => s.workspacePermissionKeys)const media = useBreakpoints()const isMobile = media === MediaType.mobile+ const { isCurrentWorkspaceEditor } = useAppContext()const { enableBilling, plan } = useProviderContext()const { setShowPricingModal, setShowAccountSettingModal } = useModalContext()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())@@ -45,6 +47,9 @@ export function Header() {setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.BILLING })}+ const canAccessExplorePage = hasPermission(workspacePermissionKeys, 'app_library.access')+ const canAccessToolsPage = hasPermission(workspacePermissionKeys, ['tool.manage', 'mcp.manage'])+const logoLabel = isBrandingEnabled && systemFeatures.branding.application_title ? systemFeatures.branding.application_title : 'Dify'const renderLogo = () => (<Link@@ -80,10 +85,10 @@ export function Header() {</div></div><div className="my-1 flex items-center justify-center gap-1">- {!isCurrentWorkspaceDatasetOperator && <ExploreNav className={navClassName} />}- {!isCurrentWorkspaceDatasetOperator && <AppNav />}- {(isCurrentWorkspaceEditor || isCurrentWorkspaceDatasetOperator) && <DatasetNav />}- {!isCurrentWorkspaceDatasetOperator && <ToolsNav className={navClassName} />}+ {canAccessExplorePage && <ExploreNav className={navClassName} />}+ <AppNav />+ <DatasetNav />+ {canAccessToolsPage && <ToolsNav className={navClassName} />}{canUseAppDeploy && <DeploymentsNav />}</div></div>@@ -91,18 +96,18 @@ export function Header() {}return (- <div className="flex h-[56px] items-center">- <div className="flex min-w-0 flex-1 items-center overflow-hidden pr-2 pl-3 min-[1280px]:pr-3">+ <div className="flex h-14 items-center">+ <div className="flex min-w-0 flex-1 items-center overflow-hidden overflow-hidden pr-2 pl-3 min-[1280px]:pr-3">{renderLogo()}<div className="mx-1.5 shrink-0 font-light text-divider-deep">/</div><WorkplaceSelector />{enableBilling ? <PlanBadge allowHover sandboxAsUpgrade plan={plan.type} onClick={handlePlanClick} /> : <LicenseNav />}</div><div className="flex min-w-0 items-center justify-center gap-2 overflow-hidden py-3">- {!isCurrentWorkspaceDatasetOperator && <ExploreNav className={navClassName} />}- {!isCurrentWorkspaceDatasetOperator && <AppNav />}- {(isCurrentWorkspaceEditor || isCurrentWorkspaceDatasetOperator) && <DatasetNav />}- {!isCurrentWorkspaceDatasetOperator && <ToolsNav className={navClassName} />}+ {canAccessExplorePage && <ExploreNav className={navClassName} />}+ <AppNav />+ <DatasetNav />+ {canAccessToolsPage && <ToolsNav className={navClassName} />}{canUseAppDeploy && <DeploymentsNav />}</div><div className="flex min-w-0 flex-1 items-center justify-end gap-2 pr-3 pl-2 min-[1280px]:pl-3">diff --git a/web/app/components/header/nav/__tests__/index.spec.tsx b/web/app/components/header/nav/__tests__/index.spec.tsxindex c64eec87387..09c934f69e0 100644--- a/web/app/components/header/nav/__tests__/index.spec.tsx+++ b/web/app/components/header/nav/__tests__/index.spec.tsx@@ -102,6 +102,7 @@ describe('Nav Component', () => {vi.mocked(useAppStore).mockReturnValue(mockSetAppDetail)vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceEditor: true,+ workspacePermissionKeys: ['app.create_and_management', 'dataset.create_and_management'],} as unknown as AppContextValue)})@@ -292,6 +293,7 @@ describe('Nav Component', () => {it('should not show create button if NOT an editor', async () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceEditor: false,+ workspacePermissionKeys: [],} as unknown as AppContextValue)render(<Nav {...defaultProps} curNav={curNav} />)const selectorButton = screen.getByRole('button', { name: /Item 1/i })diff --git a/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx b/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsxindex 7f1a232f407..dc6886e7f4a 100644--- a/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx+++ b/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx@@ -70,6 +70,7 @@ describe('NavSelector Component', () => {vi.mocked(useAppStore).mockReturnValue(mockSetAppDetail)vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceEditor: true,+ workspacePermissionKeys: ['app.create_and_management', 'dataset.create_and_management'],} as unknown as AppContextValue)})@@ -195,17 +196,46 @@ describe('NavSelector Component', () => {expect(await screen.findByText(/app\.newApp\.startFromBlank/i))!.toBeInTheDocument()})- it('should not show create button for non-editors', async () => {+ it('should show create button when dataset.create_and_management permission is present', async () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceEditor: false,+ workspacePermissionKeys: ['dataset.create_and_management'],} as unknown as AppContextValue)render(<NavSelector {...defaultProps} />)const button = screen.getByRole('button')await act(async () => {fireEvent.click(button)})+ expect(screen.getByText('Create New')).toBeInTheDocument()+ })++ it('should hide dataset create button without dataset.create_and_management permission', async () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceEditor: true,+ workspacePermissionKeys: ['app.create_and_management'],+ } as unknown as AppContextValue)+ render(<NavSelector {...defaultProps} />)+ const button = screen.getByRole('button')+ await act(async () => {+ fireEvent.click(button)+ })+expect(screen.queryByText('Create New')).not.toBeInTheDocument()})++ it('should hide app create menu without app.create_and_management permission', async () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceEditor: true,+ workspacePermissionKeys: ['dataset.create_and_management'],+ } as unknown as AppContextValue)+ render(<NavSelector {...defaultProps} isApp />)+ const button = screen.getByRole('button')+ await act(async () => {+ fireEvent.click(button)+ })++ expect(screen.queryByRole('menuitem', { name: /Create New/i })).not.toBeInTheDocument()+ })})describe('Scroll behavior', () => {diff --git a/web/app/components/header/nav/nav-selector/index.tsx b/web/app/components/header/nav/nav-selector/index.tsxindex 853011cd289..03a4deb9ce9 100644--- a/web/app/components/header/nav/nav-selector/index.tsx+++ b/web/app/components/header/nav/nav-selector/index.tsx@@ -10,10 +10,6 @@ import {DropdownMenuSubTrigger,DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'-import {- RiAddLine,- RiArrowDownSLine,-} from '@remixicon/react'import { debounce } from 'es-toolkit/compat'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'@@ -24,6 +20,7 @@ import { FileArrow01, FilePlus01, FilePlus02 } from '@/app/components/base/iconsimport Loading from '@/app/components/base/loading'import { useAppContext } from '@/context/app-context'import { useRouter } from '@/next/navigation'+import { hasPermission } from '@/utils/permission'export type NavItem = {id: string@@ -170,8 +167,9 @@ function NavSelectorRouteItem({ nav, isCurrent, onBeforeNavigate }: {export function NavSelector({ curNav, navigationItems, createText, isApp, onCreate, onLoadMore, isLoadingMore }: INavSelectorProps) {const { t } = useTranslation()- const { isCurrentWorkspaceEditor } = useAppContext()+ const { workspacePermissionKeys } = useAppContext()const setAppDetail = useAppStore(state => state.setAppDetail)+ const canCreate = hasPermission(workspacePermissionKeys, isApp ? 'app.create_and_management' : 'dataset.create_and_management')const handleScroll = useCallback(debounce((e) => {if (typeof onLoadMore === 'function') {@@ -191,10 +189,7 @@ export function NavSelector({ curNav, navigationItems, createText, isApp, onCrea)}><div className="max-w-[157px] min-w-0 truncate">{curNav?.name}</div>- <RiArrowDownSLine- className="ml-1 size-3 shrink-0 opacity-50 group-hover:opacity-100 group-data-popup-open:opacity-100"- aria-hidden="true"- />+ <span className="ml-1 i-ri-arrow-down-s-line size-3 shrink-0 opacity-50 group-hover:opacity-100 group-data-popup-open:opacity-100" aria-hidden="true" /></DropdownMenuTrigger><DropdownMenuContentplacement="bottom-end"@@ -218,20 +213,20 @@ export function NavSelector({ curNav, navigationItems, createText, isApp, onCrea</div>)}</div>- {!isApp && isCurrentWorkspaceEditor && (+ {!isApp && canCreate && (<div className="p-1"><DropdownMenuItemclassName="h-9 gap-2 px-3 py-[6px]"onClick={() => onCreate('')}><div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-regular bg-background-default">- <RiAddLine className="size-4 text-text-primary" />+ <span className="i-ri-add-line size-4 text-text-primary" /></div><div className="grow text-left text-[14px] font-normal text-text-secondary">{createText}</div></DropdownMenuItem></div>)}- {isApp && isCurrentWorkspaceEditor && (+ {isApp && canCreate && (<AppCreateMenucreateText={createText}startFromBlankText={t('newApp.startFromBlank', { ns: 'app' })}diff --git a/web/app/components/integrations/__tests__/page.spec.tsx b/web/app/components/integrations/__tests__/page.spec.tsxindex 17c58cddc77..13c1f89bc16 100644--- a/web/app/components/integrations/__tests__/page.spec.tsx+++ b/web/app/components/integrations/__tests__/page.spec.tsx@@ -7,6 +7,10 @@ const { mockRouterPush, mockWindowOpen } = vi.hoisted(() => ({mockWindowOpen: vi.fn(),}))+const mockAppContextState = vi.hoisted(() => ({+ workspacePermissionKeys: ['tool.manage', 'mcp.manage'] as string[],+}))+const {mockCanManagement,mockCanDebugger,@@ -39,19 +43,35 @@ vi.mock('@/next/navigation', () => ({}),}))+vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockAppContextState.workspacePermissionKeys,+ }),+}))+vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({usePluginSettingsAccess: () => ({permission: mockReferenceSetting().permission,+ canInstallPlugin: mockCanManagement(),+ canManagePlugin: true,canManagement: mockCanManagement(),canDebugger: mockCanDebugger(),canSetPermissions: mockCanSetPermissions(),+ canSetPluginPreferences: mockCanSetPermissions(),+ canUpdatePlugin: true,+ canViewInstalledPlugins: true,setPluginPermissionSettings: mockSetReferenceSettings,}),default: () => ({referenceSetting: mockReferenceSetting(),+ canInstallPlugin: mockCanManagement(),+ canManagePlugin: true,canManagement: mockCanManagement(),canDebugger: mockCanDebugger(),canSetPermissions: mockCanSetPermissions(),+ canSetPluginPreferences: mockCanSetPermissions(),+ canUpdatePlugin: true,+ canViewInstalledPlugins: true,setReferenceSettings: mockSetReferenceSettings,}),}))@@ -245,6 +265,7 @@ describe('IntegrationsPage', () => {mockCanManagement.mockReturnValue(true)mockCanDebugger.mockReturnValue(true)mockCanSetPermissions.mockReturnValue(true)+ mockAppContextState.workspacePermissionKeys = ['tool.manage', 'mcp.manage']mockReferenceSetting.mockReturnValue({permission: {install_permission: 'everyone',@@ -396,6 +417,24 @@ describe('IntegrationsPage', () => {expect(screen.getByTestId('data-source-page')).toBeInTheDocument()})+ it('does not render the MCP management route without mcp.manage', () => {+ mockAppContextState.workspacePermissionKeys = ['tool.manage']++ const { container } = renderIntegrationsPage(undefined, 'mcp')++ expect(screen.queryByTestId('tool-provider-list')).not.toBeInTheDocument()+ expect(container.firstElementChild).toBeNull()+ })++ it.each(['custom-tool', 'workflow-tool'] as const)('does not render the %s management route without tool.manage', (section) => {+ mockAppContextState.workspacePermissionKeys = ['mcp.manage']++ const { container } = renderIntegrationsPage(undefined, section)++ expect(screen.queryByTestId('tool-provider-list')).not.toBeInTheDocument()+ expect(container.firstElementChild).toBeNull()+ })+it('remounts the tools section content when the route section changes', () => {const view = renderIntegrationsPage(undefined, 'builtin')@@ -490,6 +529,18 @@ describe('IntegrationsPage', () => {expect(onSectionChange).toHaveBeenCalledTimes(2)})+ it('hides custom and workflow tool entries without tool.manage while keeping MCP with mcp.manage', () => {+ mockAppContextState.workspacePermissionKeys = ['mcp.manage']+ renderIntegrationsPage(undefined, { section: 'provider', onSectionChange: vi.fn() })++ fireEvent.click(screen.getByRole('button', { name: 'common.menus.tools' }))++ expect(screen.getByRole('button', { name: 'common.toolsPage.toolPlugin' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'MCP' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'workflow.common.workflowAsTool' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'common.settings.swaggerAPIAsTool' })).not.toBeInTheDocument()+ })+it('opens tools to the tools plugin page when the parent tools nav is clicked', () => {renderIntegrationsPage(undefined, 'provider')diff --git a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsxindex 32121c9125d..57c78a8b36e 100644--- a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx+++ b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx@@ -89,11 +89,17 @@ const createDefaultCollections = () => [let mockCollectionData: ReturnType<typeof createDefaultCollections> = []let mockIsLoadingToolProviders = falseconst mockRefetch = vi.fn()+const mockUseAllToolProviders = vi.hoisted(() => vi.fn())vi.mock('@/service/use-tools', () => ({- useAllToolProviders: () => ({- data: mockCollectionData,- isLoading: mockIsLoadingToolProviders,- refetch: mockRefetch,+ useAllToolProviders: (enabled?: boolean) => mockUseAllToolProviders(enabled),+}))++const mockAppContextState = vi.hoisted(() => ({+ workspacePermissionKeys: ['tool.manage', 'mcp.manage'] as string[],+}))+vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockAppContextState.workspacePermissionKeys,}),}))@@ -131,13 +137,19 @@ const {vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({useCanSetPluginSettings: () => ({canSetPermissions: mockCanSetPermissions(),+ canSetPluginPreferences: mockCanSetPermissions(),}),usePluginSettingsAccess: () => ({canSetPermissions: mockCanSetPermissions(),+ canSetPluginPreferences: mockCanSetPermissions(),+ canManagePlugin: true,+ canUpdatePlugin: true,+ canViewInstalledPlugins: true,}),default: () => ({referenceSetting: mockReferenceSetting(),canSetPermissions: mockCanSetPermissions(),+ canSetPluginPreferences: mockCanSetPermissions(),setReferenceSettings: mockSetReferenceSettings,}),}))@@ -316,6 +328,12 @@ describe('ProviderList', () => {mockEnableMarketplace = falsemockCollectionData = createDefaultCollections()mockIsLoadingToolProviders = false+ mockAppContextState.workspacePermissionKeys = ['tool.manage', 'mcp.manage']+ mockUseAllToolProviders.mockImplementation((enabled = true) => ({+ data: enabled ? mockCollectionData : [],+ isLoading: enabled ? mockIsLoadingToolProviders : false,+ refetch: mockRefetch,+ }))mockCheckedInstalledData = nullmockCanSetPermissions.mockReturnValue(true)mockReferenceSetting.mockReturnValue({@@ -347,6 +365,43 @@ describe('ProviderList', () => {expect(screen.getByText('MCP')).toBeInTheDocument()})+ it('hides custom and workflow tabs without tool.manage while keeping MCP with mcp.manage', () => {+ mockAppContextState.workspacePermissionKeys = ['mcp.manage']++ renderProviderList()++ expect(screen.getByText('tools.type.builtIn')).toBeInTheDocument()+ expect(screen.queryByText('tools.type.custom')).not.toBeInTheDocument()+ expect(screen.queryByText('tools.type.workflow')).not.toBeInTheDocument()+ expect(screen.getByText('MCP')).toBeInTheDocument()+ })++ it('hides MCP tab without mcp.manage', () => {+ mockAppContextState.workspacePermissionKeys = ['tool.manage']++ renderProviderList()++ expect(screen.getByText('tools.type.builtIn')).toBeInTheDocument()+ expect(screen.getByText('tools.type.custom')).toBeInTheDocument()+ expect(screen.getByText('tools.type.workflow')).toBeInTheDocument()+ expect(screen.queryByText('MCP')).not.toBeInTheDocument()+ })++ it.each([+ ['api'],+ ['workflow'],+ ] as const)('does not query providers for %s category without tool.manage', (category) => {+ mockAppContextState.workspacePermissionKeys = []++ renderProviderList({ category })++ expect(mockUseAllToolProviders).toHaveBeenCalledWith(false)+ expect(screen.queryByTestId('card-my-api')).not.toBeInTheDocument()+ expect(screen.queryByTestId('card-wf-tool')).not.toBeInTheDocument()+ expect(screen.queryByTestId('custom-create-card')).not.toBeInTheDocument()+ expect(screen.queryByTestId('toolbar-add-custom-tool')).not.toBeInTheDocument()+ })+it('switches tab when clicked', () => {renderProviderList()fireEvent.click(screen.getByText('tools.type.custom'))@@ -745,6 +800,16 @@ describe('ProviderList', () => {expect(screen.getByTestId('mcp-list')).toBeInTheDocument()})+ it('does not render or query MCP management list without mcp.manage', () => {+ mockAppContextState.workspacePermissionKeys = ['tool.manage']++ renderProviderList({ category: 'mcp' })++ expect(mockUseAllToolProviders).toHaveBeenCalledWith(false)+ expect(screen.queryByTestId('mcp-list')).not.toBeInTheDocument()+ expect(screen.queryByTestId('toolbar-add-mcp')).not.toBeInTheDocument()+ })+it('keeps MCP creation in the empty card when there are no MCP servers', () => {renderProviderList({ category: 'mcp' })diff --git a/web/app/components/integrations/hooks/use-integration-nav.ts b/web/app/components/integrations/hooks/use-integration-nav.tsindex 5587f4b19f2..4640ca97306 100644--- a/web/app/components/integrations/hooks/use-integration-nav.ts+++ b/web/app/components/integrations/hooks/use-integration-nav.ts@@ -9,6 +9,11 @@ export type IntegrationHeader = {title: string}+type IntegrationNavOptions = {+ canManageTools?: boolean+ canManageMCP?: boolean+}+export const getPluginCategoryBySection = (section: IntegrationSection) => {if (section === 'builtin')return PluginCategoryEnum.tool@@ -20,8 +25,12 @@ export const getPluginCategoryBySection = (section: IntegrationSection) => {return PluginCategoryEnum.extension}-export function useIntegrationNav(section: IntegrationSection) {+export function useIntegrationNav(section: IntegrationSection, options: IntegrationNavOptions = {}) {const { t } = useTranslation()+ const {+ canManageMCP = true,+ canManageTools = true,+ } = optionsconst providerItem = useMemo<IntegrationSidebarNavItemData>(() => ({section: 'provider',label: t('settings.provider', { ns: 'common' }),@@ -39,36 +48,48 @@ export function useIntegrationNav(section: IntegrationSection) {icon: 'i-custom-vender-integrations-api-extension',iconClassName: 'h-[13px] w-3.5',}), [t])- const toolItems = useMemo<IntegrationSidebarNavItemData[]>(() => [- {- section: 'builtin',- label: t('toolsPage.toolPlugin', { ns: 'common' }),- icon: 'i-custom-vender-integrations-tools',- iconClassName: 'h-[14px] w-[12.5px]',- className: 'pl-8',- },- {- section: 'mcp',- label: 'MCP',- icon: 'i-custom-vender-integrations-mcp',- iconClassName: 'h-[14.5px] w-[13.5px]',- className: 'pl-8',- },- {- section: 'workflow-tool',- label: t('common.workflowAsTool', { ns: 'workflow' }),- icon: 'i-custom-vender-integrations-workflow-as-tool',- iconClassName: 'size-4',- className: 'pl-8',- },- {- section: 'custom-tool',- label: t('settings.swaggerAPIAsTool', { ns: 'common' }),- icon: 'i-custom-vender-integrations-custom-tool',- iconClassName: 'h-[14.5px] w-[12.5px]',- className: 'pl-8',- },- ], [t])+ const toolItems = useMemo<IntegrationSidebarNavItemData[]>(() => {+ const items: IntegrationSidebarNavItemData[] = [+ {+ section: 'builtin',+ label: t('toolsPage.toolPlugin', { ns: 'common' }),+ icon: 'i-custom-vender-integrations-tools',+ iconClassName: 'h-[14px] w-[12.5px]',+ className: 'pl-8',+ },+ ]++ if (canManageMCP) {+ items.push({+ section: 'mcp',+ label: 'MCP',+ icon: 'i-custom-vender-integrations-mcp',+ iconClassName: 'h-[14.5px] w-[13.5px]',+ className: 'pl-8',+ })+ }++ if (canManageTools) {+ items.push(+ {+ section: 'workflow-tool',+ label: t('common.workflowAsTool', { ns: 'workflow' }),+ icon: 'i-custom-vender-integrations-workflow-as-tool',+ iconClassName: 'size-4',+ className: 'pl-8',+ },+ {+ section: 'custom-tool',+ label: t('settings.swaggerAPIAsTool', { ns: 'common' }),+ icon: 'i-custom-vender-integrations-custom-tool',+ iconClassName: 'h-[14.5px] w-[12.5px]',+ className: 'pl-8',+ },+ )+ }++ return items+ }, [canManageMCP, canManageTools, t])const secondaryItems = useMemo<IntegrationSidebarNavItemData[]>(() => [{section: 'trigger',diff --git a/web/app/components/integrations/hooks/use-integration-permissions.ts b/web/app/components/integrations/hooks/use-integration-permissions.tsindex 9ecbd8f4c43..0b694b555e1 100644--- a/web/app/components/integrations/hooks/use-integration-permissions.ts+++ b/web/app/components/integrations/hooks/use-integration-permissions.ts@@ -10,15 +10,19 @@ const isPluginCategorySection = (section: IntegrationSection) => {export function useIntegrationPermissions(section: IntegrationSection) {const {permission,- canManagement,canDebugger,+ canInstallPlugin,+ canManagePlugin,+ canSetPluginPreferences,canSetPermissions,+ canUpdatePlugin,+ canViewInstalledPlugins,isPermissionLoading,permissionError,setPluginPermissionSettings,} = usePluginSettingsAccess()const isPluginCategory = isPluginCategorySection(section)- const showPluginCategorySetting = isPluginCategory && canSetPermissions+ const showPluginCategorySetting = isPluginCategory && canSetPluginPreferencesconst showPermissionQuickPanel = canSetPermissions && !!permissionconst handlePermissionChange = (key: PermissionSettingKey, value: PermissionType) => {@@ -33,7 +37,12 @@ export function useIntegrationPermissions(section: IntegrationSection) {return {canDebugger,- canManagement,+ canInstallPlugin,+ canManagePlugin,+ canSetPluginPreferences,+ canUpdatePlugin,+ canViewInstalledPlugins,+ canManagement: canInstallPlugin,handlePermissionChange,isPluginCategory,isReferenceSettingLoading: isPermissionLoading,diff --git a/web/app/components/integrations/page.tsx b/web/app/components/integrations/page.tsxindex 95ff41891ac..da7872df700 100644--- a/web/app/components/integrations/page.tsx+++ b/web/app/components/integrations/page.tsx@@ -13,6 +13,7 @@ import {buildMarketplaceUrlPathByIntegrationSection,toolCategoryBySection,} from '@/app/components/integrations/routes'+import { useCanManageMCP, useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import { useDocLink } from '@/context/i18n'import Link from '@/next/link'import { useRouter } from '@/next/navigation'@@ -104,9 +105,14 @@ export default function IntegrationsPage({const docLink = useDocLink()const router = useRouter()const section = useIntegrationSection(routeSection)+ const canManageMCP = useCanManageMCP()+ const canManageTools = useCanManageTools()const {- canManagement,canDebugger,+ canInstallPlugin,+ canManagePlugin,+ canUpdatePlugin,+ canViewInstalledPlugins,handlePermissionChange,isPluginCategory,permission,@@ -114,7 +120,7 @@ export default function IntegrationsPage({showPluginCategorySetting,} = useIntegrationPermissions(section)const [providerSearchText, setProviderSearchText] = useState('')- const showInstallAction = canManagement+ const showInstallAction = canInstallPluginconst showUtilityActions = canDebugger || showPermissionQuickPanelconst {activeItem,@@ -124,7 +130,7 @@ export default function IntegrationsPage({providerItem,secondaryItems,toolItems,- } = useIntegrationNav(section)+ } = useIntegrationNav(section, { canManageMCP, canManageTools })const isToolSection = Boolean(toolCategoryBySection[section])const [isToolsExpanded, setIsToolsExpanded] = useState(isToolSection)const useFillLayout = section === 'provider' || section === 'data-source' || section === 'custom-endpoint' || isToolSection || isPluginCategory@@ -193,6 +199,11 @@ export default function IntegrationsPage({</>)+ if (section === 'mcp' && !canManageMCP)+ return null+ if ((section === 'custom-tool' || section === 'workflow-tool') && !canManageTools)+ return null+return (<div className="flex h-full min-h-0 w-full flex-1 bg-components-panel-bg" style={sidebarWidthStyle}><aside className={cn(@@ -217,7 +228,7 @@ export default function IntegrationsPage({</div>{showInstallAction && (<IntegrationSidebarActions- canManagement={canManagement}+ canManagement={canInstallPlugin}installContextCategory={getPluginCategoryBySection(section)}onSwitchToMarketplace={handleSwitchToMarketplace}/>@@ -281,7 +292,10 @@ export default function IntegrationsPage({providerSearchText={providerSearchText}onProviderSearchTextChange={setProviderSearchText}onSwitchToMarketplace={handleSwitchToMarketplace}- canInstallPlugin={canManagement}+ canInstallPlugin={canInstallPlugin}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}+ canViewInstalledPlugins={canViewInstalledPlugins}pluginCategoryToolbarAction={pluginSettingAction}/></div>@@ -304,7 +318,10 @@ export default function IntegrationsPage({providerSearchText={providerSearchText}onProviderSearchTextChange={setProviderSearchText}onSwitchToMarketplace={handleSwitchToMarketplace}- canInstallPlugin={canManagement}+ canInstallPlugin={canInstallPlugin}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}+ canViewInstalledPlugins={canViewInstalledPlugins}pluginCategoryToolbarAction={pluginSettingAction}/></ScrollArea>diff --git a/web/app/components/integrations/plugin-category-page.tsx b/web/app/components/integrations/plugin-category-page.tsxindex 65d77fb1cbc..783266c8dd9 100644--- a/web/app/components/integrations/plugin-category-page.tsx+++ b/web/app/components/integrations/plugin-category-page.tsx@@ -15,6 +15,9 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'type PluginCategoryPageProps = {canInstall?: boolean+ canManagePlugin?: boolean+ canUpdatePlugin?: boolean+ canViewInstalledPlugins?: booleancategory: PluginCategoryEnumlayout?: (parts: { body: ReactNode, toolbar: ReactNode }) => ReactNodeonSwitchToMarketplace?: () => void@@ -25,6 +28,9 @@ const supportedLocalPackageExtensions = SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS.spconst PluginCategoryPageContent = ({canInstall = true,+ canManagePlugin = true,+ canUpdatePlugin = true,+ canViewInstalledPlugins = true,category,layout,onSwitchToMarketplace,@@ -65,7 +71,17 @@ const PluginCategoryPageContent = ({return (<div ref={containerRef} className="relative flex h-0 grow flex-col overflow-hidden bg-components-panel-bg">- <PluginsPanel canInstall={canInstall} contentInset="compact" fixedCategory={category} layout={layout} onSwitchToMarketplace={onSwitchToMarketplace} toolbarAction={toolbarAction} />+ <PluginsPanel+ canInstall={canInstall}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}+ canViewInstalledPlugins={canViewInstalledPlugins}+ contentInset="compact"+ fixedCategory={category}+ layout={layout}+ onSwitchToMarketplace={onSwitchToMarketplace}+ toolbarAction={toolbarAction}+ />{dragging && (<divclassName="absolute inset-0 m-0.5 rounded-2xl border-2 border-dashed border-components-dropzone-border-accent@@ -94,6 +110,9 @@ const PluginCategoryPageContent = ({const PluginCategoryPage = ({canInstall = true,+ canManagePlugin = true,+ canUpdatePlugin = true,+ canViewInstalledPlugins = true,category,layout,onSwitchToMarketplace,@@ -107,7 +126,16 @@ const PluginCategoryPage = ({return (<PluginPageContextProvider key={category} initialFilters={initialFilters}>- <PluginCategoryPageContent canInstall={canInstall} category={category} layout={layout} onSwitchToMarketplace={onSwitchToMarketplace} toolbarAction={toolbarAction} />+ <PluginCategoryPageContent+ canInstall={canInstall}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}+ canViewInstalledPlugins={canViewInstalledPlugins}+ category={category}+ layout={layout}+ onSwitchToMarketplace={onSwitchToMarketplace}+ toolbarAction={toolbarAction}+ /></PluginPageContextProvider>)}diff --git a/web/app/components/integrations/section-renderer.tsx b/web/app/components/integrations/section-renderer.tsxindex 051e4dd4c05..1250ba38d33 100644--- a/web/app/components/integrations/section-renderer.tsx+++ b/web/app/components/integrations/section-renderer.tsx@@ -14,6 +14,9 @@ import ToolProviderList from './tool-provider-list'type IntegrationSectionRendererProps = {canInstallPlugin?: boolean+ canManagePlugin?: boolean+ canUpdatePlugin?: boolean+ canViewInstalledPlugins?: booleandescription?: ReactNodeonProviderSearchTextChange: (value: string) => voidonSwitchToMarketplace?: () => void@@ -26,6 +29,9 @@ type IntegrationSectionRendererProps = {const IntegrationSectionRenderer = ({canInstallPlugin = true,+ canManagePlugin = true,+ canUpdatePlugin = true,+ canViewInstalledPlugins = true,description,onProviderSearchTextChange,onSwitchToMarketplace,@@ -66,6 +72,19 @@ const IntegrationSectionRenderer = ({{body}</>)+ const renderPluginCategoryPage = (category: PluginCategoryEnum) => (+ <PluginCategoryPage+ canInstall={canInstallPlugin}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}+ canViewInstalledPlugins={canViewInstalledPlugins}+ category={category}+ layout={renderDirectLayout}+ onSwitchToMarketplace={onSwitchToMarketplace}+ toolbarAction={pluginCategoryToolbarAction}+ />+ )+switch (section) {case 'provider':return (@@ -78,7 +97,7 @@ const IntegrationSectionRenderer = ({/>)case 'builtin':- return <PluginCategoryPage canInstall={canInstallPlugin} category={PluginCategoryEnum.tool} layout={renderDirectLayout} onSwitchToMarketplace={onSwitchToMarketplace} toolbarAction={pluginCategoryToolbarAction} />+ return renderPluginCategoryPage(PluginCategoryEnum.tool)case 'mcp':return <ToolProviderList category="mcp" contentInset="compact" layout={renderDirectLayout} />case 'custom-tool':@@ -92,11 +111,11 @@ const IntegrationSectionRenderer = ({case 'custom-endpoint':return <ApiBasedExtensionPage layout={renderScrollableLayout} />case 'trigger':- return <PluginCategoryPage canInstall={canInstallPlugin} category={PluginCategoryEnum.trigger} layout={renderDirectLayout} onSwitchToMarketplace={onSwitchToMarketplace} toolbarAction={pluginCategoryToolbarAction} />+ return renderPluginCategoryPage(PluginCategoryEnum.trigger)case 'agent-strategy':- return <PluginCategoryPage canInstall={canInstallPlugin} category={PluginCategoryEnum.agent} layout={renderDirectLayout} onSwitchToMarketplace={onSwitchToMarketplace} toolbarAction={pluginCategoryToolbarAction} />+ return renderPluginCategoryPage(PluginCategoryEnum.agent)case 'extension':- return <PluginCategoryPage canInstall={canInstallPlugin} category={PluginCategoryEnum.extension} layout={renderDirectLayout} onSwitchToMarketplace={onSwitchToMarketplace} toolbarAction={pluginCategoryToolbarAction} />+ return renderPluginCategoryPage(PluginCategoryEnum.extension)default:return null}diff --git a/web/app/components/integrations/tool-provider-list.tsx b/web/app/components/integrations/tool-provider-list.tsxindex 2a66a97b96c..0ebfd3e0ac4 100644--- a/web/app/components/integrations/tool-provider-list.tsx+++ b/web/app/components/integrations/tool-provider-list.tsx@@ -18,8 +18,9 @@ import { isSearchResultEmpty } from '@/app/components/base/search-input/search-simport { useTags } from '@/app/components/plugins/hooks'import Empty from '@/app/components/plugins/marketplace/empty'import PluginDetailPanel from '@/app/components/plugins/plugin-detail-panel'-import { useCanSetPluginSettings } from '@/app/components/plugins/plugin-page/use-reference-setting'+import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import { toolsContentInsetClassNames, toolsUnifiedContentFrameClassName } from '@/app/components/tools/content-inset'+import { useCanManageMCP, useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import Marketplace from '@/app/components/tools/marketplace'import MCPList from '@/app/components/tools/mcp'import ProviderDetail from '@/app/components/tools/provider/detail'@@ -87,8 +88,13 @@ const ProviderList = ({const { t } = useTranslation()const { getTagLabel } = useTags()const {- canSetPermissions,- } = useCanSetPluginSettings()+ canManagePlugin,+ canSetPluginPreferences,+ canUpdatePlugin,+ canViewInstalledPlugins,+ } = usePluginSettingsAccess()+ const canManageTools = useCanManageTools()+ const canManageMCP = useCanManageMCP()const { data: enable_marketplace } = useSuspenseQuery({...systemFeaturesQueryOptions(),select: s => s.enable_marketplace,@@ -96,13 +102,24 @@ const ProviderList = ({const { activeTab, handleCategoryChange, isRouteCategory } = useToolProviderCategory(category)const contentPaddingClassName = toolsContentInsetClassNames[contentInset]const toolListFrameClassName = cn(contentPaddingClassName, toolsUnifiedContentFrameClassName)- const showToolsUpdateSetting = activeTab === 'builtin' && canSetPermissions+ const showToolsUpdateSetting = activeTab === 'builtin' && canSetPluginPreferencesconst showLabelFilter = activeTab === 'builtin'+ const isToolManageTab = activeTab === 'api' || activeTab === 'workflow'+ const isMCPManageTab = activeTab === 'mcp'+ const canReadActiveTab = isMCPManageTab ? canManageMCP : !isToolManageTab || canManageToolsconst options = [{ value: 'builtin', text: t('type.builtIn', { ns: 'tools' }) },- { value: 'api', text: t('type.custom', { ns: 'tools' }) },- { value: 'workflow', text: t('type.workflow', { ns: 'tools' }) },- { value: 'mcp', text: 'MCP' },+ ...(canManageTools+ ? [+ { value: 'api', text: t('type.custom', { ns: 'tools' }) },+ { value: 'workflow', text: t('type.workflow', { ns: 'tools' }) },+ ]+ : []),+ ...(canManageMCP+ ? [+ { value: 'mcp', text: 'MCP' },+ ]+ : []),]const [tagFilterValue, setTagFilterValue] = useState<string[]>([])const handleTagsChange = (value: string[]) => {@@ -119,16 +136,19 @@ const ProviderList = ({const handleCreatedMCPProviderHandled = useCallback(() => {setCreatedMCPProviderId(undefined)}, [])- const { data: collectionList = [], isLoading: isCollectionListLoading, refetch } = useAllToolProviders()+ const { data: collectionList = [], isLoading: isCollectionListLoading, refetch } = useAllToolProviders(canReadActiveTab)const activeTabCollectionList = useMemo(() => {+ if (!canReadActiveTab)+ return []+return collectionList.filter(collection => collection.type === activeTab)- }, [activeTab, collectionList])+ }, [activeTab, canReadActiveTab, collectionList])const hasCategoryCollections = activeTabCollectionList.length > 0- const shouldShowCustomToolCreateCard = !(activeTab === 'api' && !isCollectionListLoading && hasCategoryCollections)- const shouldShowMCPCreateCard = !(activeTab === 'mcp' && hasCategoryCollections)+ const shouldShowCustomToolCreateCard = canManageTools && !(activeTab === 'api' && !isCollectionListLoading && hasCategoryCollections)+ const shouldShowMCPCreateCard = canManageMCP && !(activeTab === 'mcp' && hasCategoryCollections)const shouldShowToolbarCreateAction- = (activeTab === 'mcp' && hasCategoryCollections)- || (activeTab === 'api' && !isCollectionListLoading && hasCategoryCollections)+ = (activeTab === 'mcp' && canManageMCP && hasCategoryCollections)+ || (activeTab === 'api' && canManageTools && !isCollectionListLoading && hasCategoryCollections)const filteredCollectionList = useMemo(() => {return activeTabCollectionList.filter((collection) => {if (showLabelFilter && tagFilterValue.length > 0 && (!collection.labels || collection.labels.every(label => !tagFilterValue.includes(label))))@@ -152,7 +172,7 @@ const ProviderList = ({}, [currentProviderId, filteredCollectionList])const { data: checkedInstalledData } = useCheckInstalled({pluginIds: currentProvider?.plugin_id ? [currentProvider.plugin_id] : [],- enabled: !!currentProvider?.plugin_id,+ enabled: canViewInstalledPlugins && !!currentProvider?.plugin_id,})const invalidateInstalledPluginList = useInvalidateInstalledPluginList()const currentPluginDetail = useMemo(() => {@@ -229,7 +249,7 @@ const ProviderList = ({tagFilterValue={tagFilterValue}/>)}- {activeTab === 'mcp' && (+ {activeTab === 'mcp' && canManageMCP && (<MCPListsearchText={keywords}contentInset={contentInset}@@ -256,6 +276,8 @@ const ProviderList = ({detail={currentPluginDetail}onUpdate={() => invalidateInstalledPluginList()}onHide={() => setCurrentProviderId(undefined)}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}/></>)diff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsxindex d86576bcac6..42217d59431 100644--- a/web/app/components/main-nav/__tests__/index.spec.tsx+++ b/web/app/components/main-nav/__tests__/index.spec.tsx@@ -13,7 +13,7 @@ import { Plan } from '@/app/components/billing/type'import { LEARN_DIFY_HIDDEN_STORAGE_KEY } from '@/app/components/explore/learn-dify/atoms'import { useGotoAnythingOpen } from '@/app/components/goto-anything/atoms'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'-import { useAppContext } from '@/context/app-context'+import { useAppContext, useSelector as useAppContextSelector } from '@/context/app-context'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { usePathname, useRouter } from '@/next/navigation'@@ -40,6 +40,7 @@ vi.mock('@/features/agent-v2/feature-flag', () => ({vi.mock('@/context/app-context', () => ({useAppContext: vi.fn(),+ useSelector: vi.fn(),}))vi.mock('@/context/provider-context', () => ({@@ -205,6 +206,23 @@ let mockInstalledApps: InstalledApp[] = []let mockInstalledAppsPending = falselet mockWorkspaces: IWorkspace[] = []+const ownerWorkspacePermissionKeys = [+ 'workspace.member.manage',+ 'workspace.role.manage',+ 'app_library.access',+ 'app.create_and_management',+ 'dataset.create_and_management',+ 'dataset.external.connect',+ 'tool.manage',+ 'mcp.manage',+]++const datasetOperatorWorkspacePermissionKeys = [+ 'plugin.install',+ 'dataset.create_and_management',+ 'dataset.external.connect',+]+const createInstalledApp = (overrides: Partial<InstalledApp> = {}): InstalledApp => ({id: overrides.id ?? 'installed-1',uninstallable: overrides.uninstallable ?? false,@@ -260,7 +278,9 @@ const appContextValue: AppContextValue = {},useSelector: vi.fn(),isLoadingCurrentWorkspace: false,+ isLoadingWorkspacePermissionKeys: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: ownerWorkspacePermissionKeys,}type MainNavSystemFeatures = NonNullable<Parameters<typeof renderWithSystemFeatures>[1]>['systemFeatures']@@ -311,6 +331,7 @@ describe('MainNav', () => {refresh: vi.fn(),});(useAppContext as Mock).mockReturnValue(appContextValue)+ ;(useAppContextSelector as Mock).mockImplementation((selector: (state: AppContextValue) => unknown) => selector((useAppContext as Mock)() as AppContextValue));(useProviderContext as Mock).mockReturnValue({enableBilling: true,isEducationAccount: false,@@ -467,7 +488,7 @@ describe('MainNav', () => {expect(screen.getAllByText(Plan.team)).toHaveLength(1)})- it('hides app and tools entries for dataset operators', () => {+ it('keeps unrestricted main routes visible for dataset operators while hiding roster', () => {;(useAppContext as Mock).mockReturnValue({...appContextValue,currentWorkspace: {@@ -478,20 +499,22 @@ describe('MainNav', () => {isCurrentWorkspaceEditor: false,isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ workspacePermissionKeys: datasetOperatorWorkspacePermissionKeys,})renderMainNav()- expect(screen.queryByRole('link', { name: /common.mainNav.home/ })).not.toBeInTheDocument()- expect(screen.queryByRole('link', { name: /common.menus.apps/ })).not.toBeInTheDocument()+ expect(screen.getByRole('link', { name: /common.mainNav.home/ })).toHaveAttribute('href', '/')+ expect(screen.getByRole('link', { name: /common.menus.apps/ })).toHaveAttribute('href', '/apps')expect(screen.queryByRole('link', { name: /common.menus.roster/ })).not.toBeInTheDocument()expect(screen.getByRole('link', { name: /common.menus.datasets/ })).toHaveAttribute('href', '/datasets')- expect(screen.queryByRole('link', { name: /common.mainNav.integrations/ })).not.toBeInTheDocument()+ expect(screen.getByRole('link', { name: /common.mainNav.integrations/ })).toHaveAttribute('href', '/integrations/model-provider')expect(screen.getByRole('link', { name: /common.mainNav.marketplace/ })).toHaveAttribute('href', '/marketplace')+ expect(screen.queryByRole('link', { name: /common.menus.deployments/ })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: 'explore.sidebar.webApps' })).not.toBeInTheDocument()})- it('hides datasets for members without editor or dataset-operator access', () => {+ it('keeps unrestricted main routes visible without route permission keys', () => {;(useAppContext as Mock).mockReturnValue({...appContextValue,currentWorkspace: {@@ -502,6 +525,7 @@ describe('MainNav', () => {isCurrentWorkspaceEditor: false,isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ workspacePermissionKeys: ['app_library.access', 'tool.manage'],})renderMainNav({ branding: { enabled: false }, enable_app_deploy: true })@@ -509,7 +533,7 @@ describe('MainNav', () => {expect(screen.getByRole('link', { name: /common.mainNav.home/ })).toBeInTheDocument()expect(screen.getByRole('link', { name: /common.menus.apps/ })).toBeInTheDocument()expect(screen.getByRole('link', { name: /common.menus.roster/ })).toBeInTheDocument()- expect(screen.queryByRole('link', { name: /common.menus.datasets/ })).not.toBeInTheDocument()+ expect(screen.getByRole('link', { name: /common.menus.datasets/ })).toBeInTheDocument()expect(screen.getByRole('link', { name: /common.mainNav.integrations/ })).toBeInTheDocument()expect(screen.queryByRole('link', { name: /common.menus.deployments/ })).not.toBeInTheDocument()expect(screen.getByRole('link', { name: /common.mainNav.marketplace/ })).toBeInTheDocument()@@ -959,7 +983,7 @@ describe('MainNav', () => {expect(mockSetShowAccountSettingModal).not.toHaveBeenCalledWith({ payload: ACCOUNT_SETTING_TAB.BILLING })})- it('limits workspace settings and invite actions by role', async () => {+ it('limits invite members by member management permission', async () => {;(useAppContext as Mock).mockReturnValue({...appContextValue,currentWorkspace: {@@ -968,6 +992,7 @@ describe('MainNav', () => {},isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ workspacePermissionKeys: ownerWorkspacePermissionKeys.filter(key => key !== 'workspace.member.manage'),})renderMainNav()@@ -978,7 +1003,7 @@ describe('MainNav', () => {expect(screen.queryByText('common.mainNav.workspace.inviteMembers')).not.toBeInTheDocument()})- it('hides workspace settings actions for dataset operators', () => {+ it('keeps workspace settings visible and hides invite members without member management permission', () => {;(useAppContext as Mock).mockReturnValue({...appContextValue,currentWorkspace: {@@ -989,13 +1014,14 @@ describe('MainNav', () => {isCurrentWorkspaceEditor: false,isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ workspacePermissionKeys: datasetOperatorWorkspacePermissionKeys,})renderMainNav()fireEvent.click(screen.getByRole('button', { name: 'common.mainNav.workspace.openMenu' }))- expect(screen.queryByText('common.mainNav.workspace.settings')).not.toBeInTheDocument()+ expect(screen.getByText('common.mainNav.workspace.settings')).toBeInTheDocument()expect(screen.queryByText('common.mainNav.workspace.inviteMembers')).not.toBeInTheDocument()})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 2ae5061ce65..92683817aef 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@@ -1,3 +1,4 @@+import type { AppContextValue } from '@/context/app-context'import type { ModalContextState } from '@/context/modal-context'import type { ProviderContextState } from '@/context/provider-context'import type { ICurrentWorkspace, IWorkspace } from '@/models/common'@@ -5,6 +6,7 @@ import { fireEvent, screen, waitFor, within } from '@testing-library/react'import { createTestQueryClient, renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'import { Plan } from '@/app/components/billing/type'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'+import { useSelector as useAppContextSelector } from '@/context/app-context'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { LicenseStatus } from '@/features/system-features/constants'@@ -32,6 +34,10 @@ vi.mock('@/context/provider-context', () => ({useProviderContext: vi.fn(),}))+vi.mock('@/context/app-context', () => ({+ useSelector: vi.fn(),+}))+vi.mock('@/context/modal-context', () => ({useModalContext: vi.fn(),}))@@ -120,6 +126,12 @@ const renderWorkspaceCard = (options?: RenderWorkspaceCardOptions) => {})}+const mockWorkspacePermissionKeys = (workspacePermissionKeys: string[]) => {+ vi.mocked(useAppContextSelector).mockImplementation((selector: (state: AppContextValue) => unknown) => selector({+ workspacePermissionKeys,+ } as AppContextValue))+}+describe('WorkspaceCard', () => {beforeEach(() => {vi.clearAllMocks()@@ -137,6 +149,7 @@ describe('WorkspaceCard', () => {isFetchedPlan: true,plan: { type: Plan.sandbox },} as ProviderContextState)+ mockWorkspacePermissionKeys(['workspace.member.manage'])vi.mocked(useModalContext).mockReturnValue({setShowPricingModal: mockSetShowPricingModal,setShowAccountSettingModal: mockSetShowAccountSettingModal,@@ -308,6 +321,24 @@ describe('WorkspaceCard', () => {expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({ payload: ACCOUNT_SETTING_TAB.BILLING })})+ it('opens members settings from workspace menu when billing is disabled', async () => {+ vi.mocked(useProviderContext).mockReturnValue({+ enableBilling: false,+ isEducationAccount: false,+ isEducationWorkspace: false,+ isFetchedPlan: false,+ plan: { type: Plan.sandbox },+ } as ProviderContextState)++ renderWorkspaceCard()++ fireEvent.click(screen.getByRole('button', { name: 'common.mainNav.workspace.openMenu' }))+ fireEvent.click(await screen.findByRole('button', { name: 'common.mainNav.workspace.settings' }))++ expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({ payload: ACCOUNT_SETTING_TAB.MEMBERS })+ expect(mockSetShowAccountSettingModal).not.toHaveBeenCalledWith({ payload: ACCOUNT_SETTING_TAB.BILLING })+ })+it('switches workspace from the workspace switcher item', async () => {renderWorkspaceCard()@@ -317,11 +348,12 @@ describe('WorkspaceCard', () => {await waitFor(() => expect(mockSwitchWorkspace).toHaveBeenCalledWith({ body: { tenant_id: 'workspace-2' } }))})- it('hides workspace management actions for dataset operators', async () => {+ it('keeps workspace settings visible for dataset operators without member management permission', async () => {mockCurrentWorkspaceQuery({...currentWorkspaceValue,role: 'dataset_operator',})+ mockWorkspacePermissionKeys([])renderWorkspaceCard()@@ -329,7 +361,35 @@ describe('WorkspaceCard', () => {const panel = await screen.findByRole('dialog', { name: 'Solar Studio' })expect(panel).toBeInTheDocument()- expect(within(panel).queryByRole('button', { name: 'common.mainNav.workspace.settings' })).not.toBeInTheDocument()+ expect(within(panel).getByRole('button', { name: 'common.mainNav.workspace.settings' })).toBeInTheDocument()+ expect(within(panel).queryByRole('button', { name: 'common.mainNav.workspace.inviteMembers' })).not.toBeInTheDocument()+ })++ it('shows invite members when member management permission is available', async () => {+ mockCurrentWorkspaceQuery({+ ...currentWorkspaceValue,+ role: 'normal',+ })+ mockWorkspacePermissionKeys(['workspace.member.manage'])++ renderWorkspaceCard()++ fireEvent.click(screen.getByRole('button', { name: 'common.mainNav.workspace.openMenu' }))++ const panel = await screen.findByRole('dialog', { name: 'Solar Studio' })+ expect(within(panel).getByRole('button', { name: 'common.mainNav.workspace.settings' })).toBeInTheDocument()+ expect(within(panel).getByRole('button', { name: 'common.mainNav.workspace.inviteMembers' })).toBeInTheDocument()+ })++ it('hides invite members when member management permission is missing', async () => {+ mockWorkspacePermissionKeys([])++ renderWorkspaceCard()++ fireEvent.click(screen.getByRole('button', { name: 'common.mainNav.workspace.openMenu' }))++ const panel = await screen.findByRole('dialog', { name: 'Solar Studio' })+ expect(within(panel).getByRole('button', { name: 'common.mainNav.workspace.settings' })).toBeInTheDocument()expect(within(panel).queryByRole('button', { name: 'common.mainNav.workspace.inviteMembers' })).not.toBeInTheDocument()})})diff --git a/web/app/components/main-nav/components/web-apps-section.tsx b/web/app/components/main-nav/components/web-apps-section.tsxindex d31972d6796..65ea3a3564e 100644--- a/web/app/components/main-nav/components/web-apps-section.tsx+++ b/web/app/components/main-nav/components/web-apps-section.tsx@@ -26,8 +26,10 @@ import Divider from '@/app/components/base/divider'import { SearchInput } from '@/app/components/base/search-input'import { isInstalledAppPath } from '@/app/components/explore/installed-app/routes'import AppNavItem from '@/app/components/explore/sidebar/app-nav-item'+import { useAppContext } from '@/context/app-context'import { usePathname } from '@/next/navigation'import { useGetInstalledApps, useUninstallApp, useUpdateAppPinStatus } from '@/service/use-explore'+import { hasPermission } from '@/utils/permission'const appNavItemHeight = 32const appNavItemGap = 2@@ -72,7 +74,7 @@ type WebAppListRowkind: 'separator'}-const WebAppsSection = () => {+const WebAppsSectionContent = () => {const { t } = useTranslation()const pathname = usePathname()const scrollRef = useRef<HTMLDivElement>(null)@@ -210,6 +212,7 @@ const WebAppsSection = () => {value={searchText}onValueChange={setSearchText}placeholder={t('mainNav.webApps.searchPlaceholder', { ns: 'common' })}+ // eslint-disable-next-line jsx-a11y/no-autofocus -- The field is mounted after an explicit search action.autoFocus/></div>@@ -297,4 +300,14 @@ const WebAppsSection = () => {)}+const WebAppsSection = () => {+ const { workspacePermissionKeys } = useAppContext()+ const canAccessAppLibrary = hasPermission(workspacePermissionKeys, 'app_library.access')++ if (!canAccessAppLibrary)+ return null++ return <WebAppsSectionContent />+}+export default WebAppsSectiondiff --git a/web/app/components/main-nav/components/workspace-card.tsx b/web/app/components/main-nav/components/workspace-card.tsxindex 7bd78fb5a78..9a8dea0280c 100644--- a/web/app/components/main-nav/components/workspace-card.tsx+++ b/web/app/components/main-nav/components/workspace-card.tsx@@ -17,10 +17,12 @@ import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/conimport LicenseNav from '@/app/components/header/license-env'import { buildIntegrationPath } from '@/app/components/integrations/routes'import { IS_CLOUD_EDITION } from '@/config'+import { useSelector as useAppContextSelector } from '@/context/app-context'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import Link from '@/next/link'import { consoleQuery } from '@/service/client'+import { hasPermission } from '@/utils/permission'import { basePath } from '@/utils/var'import { formatCredits, getRemainingCredits } from '../utils'import { WorkspaceIcon, WorkspaceMenuItemContent } from './workspace-menu-content'@@ -160,7 +162,6 @@ function WorkspaceCardTrigger({function WorkspaceMenuHeader({name,status,- showWorkspaceSettings,showInviteMembers,settingsLabel,inviteMembersLabel,@@ -169,7 +170,6 @@ function WorkspaceMenuHeader({}: {name: stringstatus: ReactNode- showWorkspaceSettings: booleanshowInviteMembers: booleansettingsLabel: ReactNodeinviteMembersLabel: ReactNode@@ -186,15 +186,13 @@ function WorkspaceMenuHeader({</div><WorkspaceIcon name={name} className="h-9 w-9 shrink-0" /></div>- {showWorkspaceSettings && (- <button- type="button"- className="flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-1 text-left outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset"- onClick={onOpenSettings}- >- <WorkspaceMenuItemContent icon={<span aria-hidden className="i-custom-vender-main-nav-workspace-settings h-4 w-4" />} label={settingsLabel} />- </button>- )}+ <button+ type="button"+ className="flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-1 text-left outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset"+ onClick={onOpenSettings}+ >+ <WorkspaceMenuItemContent icon={<span aria-hidden className="i-custom-vender-main-nav-workspace-settings h-4 w-4" />} label={settingsLabel} />+ </button>{showInviteMembers && (<buttontype="button"@@ -234,6 +232,7 @@ export function WorkspaceCard() {const workspaces = workspacesData?.workspacesconst currentWorkspaceInList = workspaces?.find(workspace => workspace.current)const { enableBilling } = useProviderContext()+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)const { setShowPricingModal, setShowAccountSettingModal } = useModalContext()const showCloudBilling = IS_CLOUD_EDITION && enableBillingconst [open, setOpen] = useState(false)@@ -252,8 +251,7 @@ export function WorkspaceCard() {const isFreePlan = workspacePlan === Plan.sandboxconst showPlanAction = showCloudBillingconst planActionLabel = t(isFreePlan ? 'upgradeBtn.encourageShort' : 'upgradeBtn.plain', { ns: 'billing' })- const showWorkspaceSettings = currentWorkspace.role !== 'dataset_operator'- const showInviteMembers = showWorkspaceSettings && ['owner', 'admin'].includes(currentWorkspace.role)+ const showInviteMembers = hasPermission(workspacePermissionKeys, 'workspace.member.manage')const renderWorkspaceStatus = () => enableBilling ? <WorkspacePlanBadge plan={workspacePlan} /> : <LicenseNav />const handleSwitchWorkspace = async (tenant_id: string) => {@@ -293,13 +291,16 @@ export function WorkspaceCard() {<WorkspaceMenuHeadername={currentWorkspace.name}status={renderWorkspaceStatus()}- showWorkspaceSettings={showWorkspaceSettings}showInviteMembers={showInviteMembers}settingsLabel={t('mainNav.workspace.settings', { ns: 'common' })}inviteMembersLabel={t('mainNav.workspace.inviteMembers', { ns: 'common' })}onOpenSettings={() => {setOpen(false)- setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.BILLING })+ setShowAccountSettingModal({+ payload: enableBilling+ ? ACCOUNT_SETTING_TAB.BILLING+ : ACCOUNT_SETTING_TAB.MEMBERS,+ })}}onInviteMembers={() => {setOpen(false)diff --git a/web/app/components/main-nav/index.tsx b/web/app/components/main-nav/index.tsxindex aa1495b08cc..dbbf00f04ba 100644--- a/web/app/components/main-nav/index.tsx+++ b/web/app/components/main-nav/index.tsx@@ -190,7 +190,6 @@ const MainNav = ({agentV2Enabled,canUseAppDeploy,isCurrentWorkspaceDatasetOperator,- isCurrentWorkspaceEditor,})).map(route => ({href: route.href,@@ -198,7 +197,7 @@ const MainNav = ({active: route.active,icon: route.icon,activeIcon: route.activeIcon,- })), [agentV2Enabled, canUseAppDeploy, isCurrentWorkspaceDatasetOperator, isCurrentWorkspaceEditor, t])+ })), [agentV2Enabled, canUseAppDeploy, isCurrentWorkspaceDatasetOperator, t])const renderLogo = () => {const appTitle = systemFeatures.branding.enabled && systemFeatures.branding.application_title ? systemFeatures.branding.application_title : 'Dify'diff --git a/web/app/components/main-nav/routes.ts b/web/app/components/main-nav/routes.tsindex e63419cf226..438094a581e 100644--- a/web/app/components/main-nav/routes.ts+++ b/web/app/components/main-nav/routes.ts@@ -1,6 +1,6 @@import { buildIntegrationPath } from '@/app/components/integrations/routes'-type MainNavRouteVisibility = 'all' | 'notDatasetOperator' | 'editorOrDatasetOperator' | 'appDeployEditor'+type MainNavRouteVisibility = 'all' | 'notDatasetOperator' | 'appDeployEditor'export type MainNavRouteConfig = {key: string@@ -17,7 +17,6 @@ export type MainNavRouteVisibilityOptions = {agentV2Enabled: booleancanUseAppDeploy: booleanisCurrentWorkspaceDatasetOperator: boolean- isCurrentWorkspaceEditor: boolean}function isPathUnderRoute(pathname: string, route: string) {@@ -32,7 +31,7 @@ export const MAIN_NAV_ROUTES = [active: (path: string) => path === '/' || path === '/explore/apps',icon: 'i-custom-vender-main-nav-home',activeIcon: 'i-custom-vender-main-nav-home-active',- visibility: 'notDatasetOperator',+ visibility: 'all',},{key: 'apps',@@ -41,7 +40,7 @@ export const MAIN_NAV_ROUTES = [active: (path: string) => isPathUnderRoute(path, '/apps') || isPathUnderRoute(path, '/app') || isPathUnderRoute(path, '/snippets'),icon: 'i-custom-vender-main-nav-studio',activeIcon: 'i-custom-vender-main-nav-studio-active',- visibility: 'notDatasetOperator',+ visibility: 'all',},{key: 'roster',@@ -60,7 +59,7 @@ export const MAIN_NAV_ROUTES = [active: (path: string) => isPathUnderRoute(path, '/datasets'),icon: 'i-custom-vender-main-nav-knowledge',activeIcon: 'i-custom-vender-main-nav-knowledge-active',- visibility: 'editorOrDatasetOperator',+ visibility: 'all',},{key: 'integrations',@@ -69,7 +68,7 @@ export const MAIN_NAV_ROUTES = [active: (path: string) => isPathUnderRoute(path, '/integrations') || isPathUnderRoute(path, '/tools'),icon: 'i-custom-vender-main-nav-integrations',activeIcon: 'i-custom-vender-main-nav-integrations-active',- visibility: 'notDatasetOperator',+ visibility: 'all',},{key: 'marketplace',@@ -101,8 +100,5 @@ export function isMainNavRouteVisible(route: MainNavRouteConfig, options: MainNaif (route.visibility === 'notDatasetOperator')return !options.isCurrentWorkspaceDatasetOperator- if (route.visibility === 'editorOrDatasetOperator')- return options.isCurrentWorkspaceEditor || options.isCurrentWorkspaceDatasetOperator-return options.canUseAppDeploy}diff --git a/web/app/components/plugins/__tests__/provider-card.spec.tsx b/web/app/components/plugins/__tests__/provider-card.spec.tsxindex 71efd86bb07..7a4758c3147 100644--- a/web/app/components/plugins/__tests__/provider-card.spec.tsx+++ b/web/app/components/plugins/__tests__/provider-card.spec.tsx@@ -21,6 +21,10 @@ vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () =),}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission', () => ({+ default: () => ({ canInstallPlugin: true }),+}))+vi.mock('@/app/components/plugins/marketplace/utils', () => ({getPluginLinkInMarketplace: (plugin: Plugin, params: Record<string, string>) =>`/marketplace/${plugin.org}/${plugin.name}?language=${params.language}&theme=${params.theme}`,diff --git a/web/app/components/plugins/install-plugin/components/__tests__/plugin-install-permission-provider.spec.tsx b/web/app/components/plugins/install-plugin/components/__tests__/plugin-install-permission-provider.spec.tsxnew file mode 100644index 00000000000..453ef2c91b1--- /dev/null+++ b/web/app/components/plugins/install-plugin/components/__tests__/plugin-install-permission-provider.spec.tsx@@ -0,0 +1,88 @@+import { render, screen } from '@testing-library/react'+import usePluginInstallPermission from '../../hooks/use-plugin-install-permission'+import {+ PluginInstallPermissionProvider,+ PluginInstallPermissionProviderGuard,+} from '../plugin-install-permission-provider'++const PermissionProbe = () => {+ const {+ canInstallPlugin,+ canUpdatePlugin,+ currentDifyVersion,+ } = usePluginInstallPermission()++ return (+ <div>+ <span>+ install:+ {String(canInstallPlugin)}+ </span>+ <span>+ update:+ {String(canUpdatePlugin)}+ </span>+ <span>+ version:+ {currentDifyVersion}+ </span>+ </div>+ )+}++describe('PluginInstallPermissionProvider', () => {+ // Rendering provides plugin permission state to hook consumers.+ describe('Rendering', () => {+ it('should provide explicit install, update, and version values', () => {+ render(+ <PluginInstallPermissionProvider+ canInstallPlugin+ canUpdatePlugin={false}+ currentDifyVersion="1.2.3"+ >+ <PermissionProbe />+ </PluginInstallPermissionProvider>,+ )++ expect(screen.getByText('install:true')).toBeInTheDocument()+ expect(screen.getByText('update:false')).toBeInTheDocument()+ expect(screen.getByText('version:1.2.3')).toBeInTheDocument()+ })++ it('should update provided values after rerender', () => {+ const { rerender } = render(+ <PluginInstallPermissionProvider canInstallPlugin currentDifyVersion="1.0.0">+ <PermissionProbe />+ </PluginInstallPermissionProvider>,+ )++ rerender(+ <PluginInstallPermissionProvider canInstallPlugin={false} currentDifyVersion="2.0.0">+ <PermissionProbe />+ </PluginInstallPermissionProvider>,+ )++ expect(screen.getByText('install:false')).toBeInTheDocument()+ expect(screen.getByText('update:false')).toBeInTheDocument()+ expect(screen.getByText('version:2.0.0')).toBeInTheDocument()+ })+ })+})++describe('PluginInstallPermissionProviderGuard', () => {+ // Guard avoids replacing an existing provider higher in the tree.+ describe('Rendering', () => {+ it('should keep existing provider values when nested under a provider', () => {+ render(+ <PluginInstallPermissionProvider canInstallPlugin={false} currentDifyVersion="outer">+ <PluginInstallPermissionProviderGuard canInstallPlugin currentDifyVersion="inner">+ <PermissionProbe />+ </PluginInstallPermissionProviderGuard>+ </PluginInstallPermissionProvider>,+ )++ expect(screen.getByText('install:false')).toBeInTheDocument()+ expect(screen.getByText('version:outer')).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/plugins/install-plugin/components/plugin-install-permission-provider.tsx b/web/app/components/plugins/install-plugin/components/plugin-install-permission-provider.tsxnew file mode 100644index 00000000000..a9c980d67bc--- /dev/null+++ b/web/app/components/plugins/install-plugin/components/plugin-install-permission-provider.tsx@@ -0,0 +1,69 @@+'use client'++import type { ReactNode } from 'react'+import type { PluginInstallPermissionStore } from '../hooks/use-plugin-install-permission'+import { use, useEffect, useRef } from 'react'+import {+ createPluginInstallPermissionStore,+ PluginInstallPermissionContext,+} from '../hooks/use-plugin-install-permission'++type PluginInstallPermissionProviderProps = {+ canInstallPlugin: boolean+ canUpdatePlugin?: boolean+ currentDifyVersion?: string+ children: ReactNode+}++export const PluginInstallPermissionProvider = ({+ canInstallPlugin,+ canUpdatePlugin,+ currentDifyVersion,+ children,+}: PluginInstallPermissionProviderProps) => {+ const storeRef = useRef<PluginInstallPermissionStore | null>(null)++ if (!storeRef.current) {+ storeRef.current = createPluginInstallPermissionStore({+ canInstallPlugin,+ canUpdatePlugin,+ currentDifyVersion,+ })+ }++ useEffect(() => {+ storeRef.current?.getState().setPluginInstallPermission({+ canInstallPlugin,+ canUpdatePlugin: canUpdatePlugin ?? canInstallPlugin,+ currentDifyVersion,+ })+ }, [canInstallPlugin, canUpdatePlugin, currentDifyVersion])++ return (+ <PluginInstallPermissionContext value={storeRef.current}>+ {children}+ </PluginInstallPermissionContext>+ )+}++export const PluginInstallPermissionProviderGuard = ({+ canInstallPlugin,+ canUpdatePlugin,+ currentDifyVersion,+ children,+}: PluginInstallPermissionProviderProps) => {+ const store = use(PluginInstallPermissionContext)++ if (store)+ return children++ return (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ canUpdatePlugin={canUpdatePlugin}+ currentDifyVersion={currentDifyVersion}+ >+ {children}+ </PluginInstallPermissionProvider>+ )+}diff --git a/web/app/components/plugins/install-plugin/hooks/__tests__/use-plugin-install-permission.spec.tsx b/web/app/components/plugins/install-plugin/hooks/__tests__/use-plugin-install-permission.spec.tsxnew file mode 100644index 00000000000..bba2c65f9af--- /dev/null+++ b/web/app/components/plugins/install-plugin/hooks/__tests__/use-plugin-install-permission.spec.tsx@@ -0,0 +1,51 @@+import type { ReactNode } from 'react'+import { renderHook } from '@testing-library/react'+import usePluginInstallPermission, {+ createPluginInstallPermissionStore,+ PluginInstallPermissionContext,+ usePluginInstallPermissionStore,+} from '../use-plugin-install-permission'++describe('usePluginInstallPermission', () => {+ // Store creation defaults update permission to install permission when not provided.+ describe('Store Defaults', () => {+ it('should default update permission from install permission', () => {+ const store = createPluginInstallPermissionStore({+ canInstallPlugin: false,+ })++ expect(store.getState().canInstallPlugin).toBe(false)+ expect(store.getState().canUpdatePlugin).toBe(false)+ })+ })++ // Hook consumers read values from the plugin install permission context.+ describe('Context', () => {+ it('should expose plugin install permissions from context store', () => {+ const store = createPluginInstallPermissionStore({+ canInstallPlugin: true,+ canUpdatePlugin: false,+ currentDifyVersion: '1.2.3',+ })+ const wrapper = ({ children }: { children: ReactNode }) => (+ <PluginInstallPermissionContext value={store}>+ {children}+ </PluginInstallPermissionContext>+ )++ const { result } = renderHook(() => usePluginInstallPermission(), { wrapper })++ expect(result.current).toEqual({+ canInstallPlugin: true,+ canUpdatePlugin: false,+ currentDifyVersion: '1.2.3',+ })+ })++ it('should throw when provider is missing', () => {+ expect(() => {+ renderHook(() => usePluginInstallPermissionStore(state => state.canInstallPlugin))+ }).toThrow('Missing PluginInstallPermissionProvider in the tree')+ })+ })+})diff --git a/web/app/components/plugins/install-plugin/hooks/__tests__/use-workspace-plugin-install-permission.spec.ts b/web/app/components/plugins/install-plugin/hooks/__tests__/use-workspace-plugin-install-permission.spec.tsnew file mode 100644index 00000000000..8fdf23de333--- /dev/null+++ b/web/app/components/plugins/install-plugin/hooks/__tests__/use-workspace-plugin-install-permission.spec.ts@@ -0,0 +1,81 @@+import { renderHook } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import useWorkspacePluginInstallPermission from '../use-workspace-plugin-install-permission'++let mockWorkspacePermissionKeys: string[] = []++vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ langGeniusVersionInfo: { current_version: '1.0.0' },+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))++describe('useWorkspacePluginInstallPermission', () => {+ beforeEach(() => {+ mockWorkspacePermissionKeys = []+ })++ it('should grant install and update capabilities with plugin.install', () => {+ mockWorkspacePermissionKeys = ['plugin.install']++ const { result } = renderHook(() => useWorkspacePluginInstallPermission())++ expect(result.current.canInstallPlugin).toBe(true)+ expect(result.current.canUpdatePlugin).toBe(true)+ expect(result.current.canViewInstalledPlugins).toBe(true)+ expect(result.current.canManagePlugin).toBe(false)+ expect(result.current.canDebugPlugin).toBe(false)+ expect(result.current.canSetPluginPreferences).toBe(false)+ })++ it('should grant update, view, and manage capabilities but not install with plugin.manage', () => {+ mockWorkspacePermissionKeys = ['plugin.manage']++ const { result } = renderHook(() => useWorkspacePluginInstallPermission())++ expect(result.current.canInstallPlugin).toBe(false)+ expect(result.current.canUpdatePlugin).toBe(true)+ expect(result.current.canViewInstalledPlugins).toBe(true)+ expect(result.current.canManagePlugin).toBe(true)+ expect(result.current.canDebugPlugin).toBe(false)+ expect(result.current.canSetPluginPreferences).toBe(false)+ })++ it('should grant plugin debug capability with plugin.debug', () => {+ mockWorkspacePermissionKeys = ['plugin.debug']++ const { result } = renderHook(() => useWorkspacePluginInstallPermission())++ expect(result.current.canInstallPlugin).toBe(false)+ expect(result.current.canUpdatePlugin).toBe(false)+ expect(result.current.canViewInstalledPlugins).toBe(false)+ expect(result.current.canManagePlugin).toBe(false)+ expect(result.current.canDebugPlugin).toBe(true)+ expect(result.current.canSetPluginPreferences).toBe(false)+ })++ it('should grant plugin preference setting capability with plugin.plugin_preferences', () => {+ mockWorkspacePermissionKeys = ['plugin.plugin_preferences']++ const { result } = renderHook(() => useWorkspacePluginInstallPermission())++ expect(result.current.canInstallPlugin).toBe(false)+ expect(result.current.canUpdatePlugin).toBe(false)+ expect(result.current.canViewInstalledPlugins).toBe(false)+ expect(result.current.canManagePlugin).toBe(false)+ expect(result.current.canDebugPlugin).toBe(false)+ expect(result.current.canSetPluginPreferences).toBe(true)+ })++ it('should deny plugin capabilities without plugin install or manage permissions', () => {+ const { result } = renderHook(() => useWorkspacePluginInstallPermission())++ expect(result.current.canInstallPlugin).toBe(false)+ expect(result.current.canUpdatePlugin).toBe(false)+ expect(result.current.canViewInstalledPlugins).toBe(false)+ expect(result.current.canManagePlugin).toBe(false)+ expect(result.current.canDebugPlugin).toBe(false)+ expect(result.current.canSetPluginPreferences).toBe(false)+ })+})diff --git a/web/app/components/plugins/install-plugin/hooks/use-plugin-install-permission.ts b/web/app/components/plugins/install-plugin/hooks/use-plugin-install-permission.tsnew file mode 100644index 00000000000..2bb7f7f45ee--- /dev/null+++ b/web/app/components/plugins/install-plugin/hooks/use-plugin-install-permission.ts@@ -0,0 +1,73 @@+import type { StoreApi } from 'zustand'+import { createContext, use } from 'react'+import { useStore } from 'zustand'+import { createStore } from 'zustand/vanilla'++export type PluginInstallPermissionState = {+ canInstallPlugin: boolean+ canUpdatePlugin: boolean+ currentDifyVersion?: string+}++type PluginInstallPermissionAction = {+ setPluginInstallPermission: (state: PluginInstallPermissionState) => void+}++export type PluginInstallPermissionStoreState = PluginInstallPermissionState & PluginInstallPermissionAction++export type PluginInstallPermissionStore = StoreApi<PluginInstallPermissionStoreState>++const defaultPluginInstallPermissionState: PluginInstallPermissionState = {+ canInstallPlugin: true,+ canUpdatePlugin: true,+}++export const createPluginInstallPermissionStore = (initProps?: Partial<PluginInstallPermissionState>) => {+ const canInstallPlugin = initProps?.canInstallPlugin ?? defaultPluginInstallPermissionState.canInstallPlugin++ return createStore<PluginInstallPermissionStoreState>()(set => ({+ ...defaultPluginInstallPermissionState,+ ...initProps,+ canUpdatePlugin: initProps?.canUpdatePlugin ?? canInstallPlugin,+ setPluginInstallPermission: state => set(() => state),+ }))+}++const fallbackPluginInstallPermissionStore = createPluginInstallPermissionStore()++export const PluginInstallPermissionContext = createContext<PluginInstallPermissionStore | null>(null)++export const usePluginInstallPermissionStore = <T>(selector: (state: PluginInstallPermissionStoreState) => T): T => {+ const store = use(PluginInstallPermissionContext)+ if (!store)+ throw new Error('Missing PluginInstallPermissionProvider in the tree')++ return useStore(store, selector)+}++const usePluginInstallPermission = () => {+ const canInstallPlugin = usePluginInstallPermissionStore(state => state.canInstallPlugin)+ const canUpdatePlugin = usePluginInstallPermissionStore(state => state.canUpdatePlugin)+ const currentDifyVersion = usePluginInstallPermissionStore(state => state.currentDifyVersion)++ return {+ canInstallPlugin,+ canUpdatePlugin,+ currentDifyVersion,+ }+}++export const useOptionalPluginInstallPermission = () => {+ const store = use(PluginInstallPermissionContext) ?? fallbackPluginInstallPermissionStore+ const canInstallPlugin = useStore(store, state => state.canInstallPlugin)+ const canUpdatePlugin = useStore(store, state => state.canUpdatePlugin)+ const currentDifyVersion = useStore(store, state => state.currentDifyVersion)++ return {+ canInstallPlugin,+ canUpdatePlugin,+ currentDifyVersion,+ }+}++export default usePluginInstallPermissiondiff --git a/web/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission.ts b/web/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission.tsnew file mode 100644index 00000000000..59e7c1ad7f8--- /dev/null+++ b/web/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission.ts@@ -0,0 +1,45 @@+import { useMemo } from 'react'+import { useAppContext } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'++const pluginReadAndUpdatePermissionKeys = ['plugin.install', 'plugin.manage']++const useWorkspacePluginInstallPermission = () => {+ const { langGeniusVersionInfo, workspacePermissionKeys } = useAppContext()++ const canInstallPlugin = useMemo(() => {+ return hasPermission(workspacePermissionKeys, 'plugin.install')+ }, [workspacePermissionKeys])++ const canUpdatePlugin = useMemo(() => {+ return hasPermission(workspacePermissionKeys, pluginReadAndUpdatePermissionKeys)+ }, [workspacePermissionKeys])++ const canViewInstalledPlugins = useMemo(() => {+ return hasPermission(workspacePermissionKeys, pluginReadAndUpdatePermissionKeys)+ }, [workspacePermissionKeys])++ const canManagePlugin = useMemo(() => {+ return hasPermission(workspacePermissionKeys, 'plugin.manage')+ }, [workspacePermissionKeys])++ const canDebugPlugin = useMemo(() => {+ return hasPermission(workspacePermissionKeys, 'plugin.debug')+ }, [workspacePermissionKeys])++ const canSetPluginPreferences = useMemo(() => {+ return hasPermission(workspacePermissionKeys, 'plugin.plugin_preferences')+ }, [workspacePermissionKeys])++ return {+ canInstallPlugin,+ canUpdatePlugin,+ canViewInstalledPlugins,+ canManagePlugin,+ canDebugPlugin,+ canSetPluginPreferences,+ currentDifyVersion: langGeniusVersionInfo?.current_version,+ }+}++export default useWorkspacePluginInstallPermissiondiff --git a/web/app/components/plugins/install-plugin/install-from-marketplace/steps/__tests__/install.spec.tsx b/web/app/components/plugins/install-plugin/install-from-marketplace/steps/__tests__/install.spec.tsxindex b42b119bde6..222029ab013 100644--- a/web/app/components/plugins/install-plugin/install-from-marketplace/steps/__tests__/install.spec.tsx+++ b/web/app/components/plugins/install-plugin/install-from-marketplace/steps/__tests__/install.spec.tsx@@ -71,6 +71,12 @@ vi.mock('@/app/components/plugins/install-plugin/hooks/use-check-installed', ()}),}))+vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ langGeniusVersionInfo: mockLangGeniusVersionInfo,+ }),+}))+// Mock service hooksvi.mock('@/service/use-plugins', () => ({useInstallPackageFromMarketPlace: () => ({@@ -95,10 +101,10 @@ vi.mock('../../../base/check-task-status', () => ({}),}))-// Mock useAppContext-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- langGeniusVersionInfo: mockLangGeniusVersionInfo,+vi.mock('@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission', () => ({+ default: () => ({+ canInstallPlugin: true,+ currentDifyVersion: mockLangGeniusVersionInfo.current_version,}),}))diff --git a/web/app/components/plugins/marketplace/__tests__/index.spec.tsx b/web/app/components/plugins/marketplace/__tests__/index.spec.tsxindex cd9877467d4..5444d6ae6d7 100644--- a/web/app/components/plugins/marketplace/__tests__/index.spec.tsx+++ b/web/app/components/plugins/marketplace/__tests__/index.spec.tsx@@ -64,12 +64,22 @@ describe('Marketplace', () => {expect(getByTestId('list-wrapper')).toBeInTheDocument()})- it('should pass showInstallButton=true by default to ListWrapper', async () => {+ it('should pass showInstallButton=false by default to ListWrapper', async () => {const Marketplace = (await import('../index')).defaultconst element = await Marketplace({})const { getByTestId } = render(element as React.ReactElement)+ const listWrapper = getByTestId('list-wrapper')+ expect(listWrapper.getAttribute('data-show-install')).toBe('false')+ })++ it('should pass showInstallButton=true when specified', async () => {+ const Marketplace = (await import('../index')).default+ const element = await Marketplace({ showInstallButton: true })++ const { getByTestId } = render(element as React.ReactElement)+const listWrapper = getByTestId('list-wrapper')expect(listWrapper.getAttribute('data-show-install')).toBe('true')})diff --git a/web/app/components/plugins/marketplace/index.tsx b/web/app/components/plugins/marketplace/index.tsxindex c80aa1a2ba6..785669bd595 100644--- a/web/app/components/plugins/marketplace/index.tsx+++ b/web/app/components/plugins/marketplace/index.tsx@@ -1,4 +1,5 @@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 Description from './description'import { HydrateQueryClient } from './hydration-server'@@ -17,7 +18,7 @@ type MarketplaceProps = {}const Marketplace = async ({- showInstallButton = true,+ showInstallButton = false,pluginTypeSwitchClassName,isMarketplacePlatform = false,marketplaceNav,@@ -26,20 +27,22 @@ const Marketplace = async ({return (<TanstackQueryInitializer><HydrateQueryClient searchParams={searchParams}>- <Description- isMarketplacePlatform={isMarketplacePlatform}- marketplaceNav={marketplaceNav}- />- {- !isMarketplacePlatform && (- <StickySearchAndSwitchWrapper- pluginTypeSwitchClassName={pluginTypeSwitchClassName}- />- )- }- <ListWrapper- showInstallButton={showInstallButton}- />+ <PluginInstallPermissionProviderGuard canInstallPlugin={showInstallButton}>+ <Description+ isMarketplacePlatform={isMarketplacePlatform}+ marketplaceNav={marketplaceNav}+ />+ {+ !isMarketplacePlatform && (+ <StickySearchAndSwitchWrapper+ pluginTypeSwitchClassName={pluginTypeSwitchClassName}+ />+ )+ }+ <ListWrapper+ showInstallButton={showInstallButton}+ />+ </PluginInstallPermissionProviderGuard></HydrateQueryClient></TanstackQueryInitializer>)diff --git a/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx b/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsxindex 5d766548cc7..861bdbac345 100644--- a/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx+++ b/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx@@ -46,6 +46,11 @@ vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () =),}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission', () => ({+ default: () => ({ canInstallPlugin: true }),+ useOptionalPluginInstallPermission: () => ({ canInstallPlugin: true }),+}))+vi.mock('../../utils', () => ({getPluginDetailLinkInMarketplace: (plugin: Plugin) => `/detail/${plugin.org}/${plugin.name}`,getPluginLinkInMarketplace: (plugin: Plugin, params: Record<string, string>) => `/marketplace/${plugin.org}/${plugin.name}?language=${params.language}&theme=${params.theme}`,diff --git a/web/app/components/plugins/marketplace/list/card-wrapper.tsx b/web/app/components/plugins/marketplace/list/card-wrapper.tsxindex 0356b985199..7e38d660fde 100644--- a/web/app/components/plugins/marketplace/list/card-wrapper.tsx+++ b/web/app/components/plugins/marketplace/list/card-wrapper.tsx@@ -9,6 +9,7 @@ import { useLocale, useTranslation } from '#i18n'import Card from '@/app/components/plugins/card'import CardMoreInfo from '@/app/components/plugins/card/card-more-info'import { useTags } from '@/app/components/plugins/hooks'+import { useOptionalPluginInstallPermission } from '@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission'import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'import { getPluginLinkInMarketplace } from '../utils'@@ -26,6 +27,7 @@ const CardWrapperComponent = ({setTrue: showInstallFromMarketplace,setFalse: hideInstallFromMarketplace,}] = useBoolean(false)+ const { canInstallPlugin } = useOptionalPluginInstallPermission()const locale = useLocale()const { getTagLabel } = useTags()@@ -41,8 +43,9 @@ const CardWrapperComponent = ({const handleOpenMarketplaceDetail = () => {window.open(getPluginLinkInMarketplace(plugin, marketplaceLinkParams), '_blank', 'noopener,noreferrer')}+ const showInstallAction = !!showInstallButton && canInstallPlugin- if (showInstallButton) {+ if (showInstallAction) {return (<divclassName="group relative cursor-pointer rounded-xl"diff --git a/web/app/components/plugins/marketplace/list/index.tsx b/web/app/components/plugins/marketplace/list/index.tsxindex e1f4d71e5c6..3c02e708b32 100644--- a/web/app/components/plugins/marketplace/list/index.tsx+++ b/web/app/components/plugins/marketplace/list/index.tsx@@ -2,6 +2,7 @@import type { Plugin } from '../../types'import type { MarketplaceCollection, SearchParamsFromCollection } from '../types'import { cn } from '@langgenius/dify-ui/cn'+import { PluginInstallPermissionProviderGuard } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'import Empty from '../empty'import CardWrapper from './card-wrapper'import ListWithCollection from './list-with-collection'@@ -27,7 +28,7 @@ const List = ({onCollectionMoreClick,}: ListProps) => {return (- <>+ <PluginInstallPermissionProviderGuard canInstallPlugin={!!showInstallButton}>{!plugins && (<ListWithCollection@@ -69,7 +70,7 @@ const List = ({<Empty className={emptyClassName} />)}- </>+ </PluginInstallPermissionProviderGuard>)}diff --git a/web/app/components/plugins/marketplace/marketplace-install-permission-provider.tsx b/web/app/components/plugins/marketplace/marketplace-install-permission-provider.tsxnew file mode 100644index 00000000000..ffa83c2a0ef--- /dev/null+++ b/web/app/components/plugins/marketplace/marketplace-install-permission-provider.tsx@@ -0,0 +1,25 @@+'use client'++import type { ReactNode } from 'react'+import { PluginInstallPermissionProvider } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'+import { useAppContext } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'++type MarketplaceInstallPermissionProviderProps = {+ children: ReactNode+}++const MarketplaceInstallPermissionProvider = ({+ children,+}: MarketplaceInstallPermissionProviderProps) => {+ const { workspacePermissionKeys } = useAppContext()+ const canInstallPlugin = hasPermission(workspacePermissionKeys, 'plugin.install')++ return (+ <PluginInstallPermissionProvider canInstallPlugin={canInstallPlugin}>+ {children}+ </PluginInstallPermissionProvider>+ )+}++export default MarketplaceInstallPermissionProviderdiff --git a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsx b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsxindex d19c05efe12..6f8125ac132 100644--- a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsx+++ b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsx@@ -43,8 +43,11 @@ vi.mock('@/context/app-context', () => ({}),// Item renders useAppContextWithSelector(state => state.userProfile) for the// borrowed-row heuristic. Provide a minimal stub so the selector runs.- useSelector: (selector: (state: { userProfile: typeof mockUserProfile }) => unknown) =>- selector({ userProfile: mockUserProfile }),+ useSelector: (selector: (state: { userProfile: typeof mockUserProfile, workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ userProfile: mockUserProfile,+ workspacePermissionKeys: ['credential.manage', 'credential.use'],+ }),}))vi.mock('@/hooks/use-oauth', () => ({diff --git a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsx b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsxindex 5b07c571156..97d94cbd86d 100644--- a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsx+++ b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsx@@ -6,6 +6,9 @@ import { AuthCategory } from '../types'const mockUsePluginAuth = vi.fn()const mockSetShowAccountSettingModal = vi.fn()+const mockAppContext = vi.hoisted(() => ({+ workspacePermissionKeys: ['credential.manage', 'credential.use'] as string[],+}))vi.mock('../hooks/use-plugin-auth', () => ({usePluginAuth: (...args: unknown[]) => mockUsePluginAuth(...args),@@ -20,6 +23,13 @@ vi.mock('../authorized', () => ({),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ workspacePermissionKeys: mockAppContext.workspacePermissionKeys,+ }),+}))+vi.mock('@/context/modal-context', () => ({useModalContext: () => ({setShowAccountSettingModal: mockSetShowAccountSettingModal,@@ -34,6 +44,7 @@ const defaultPayload = {describe('PluginAuth', () => {beforeEach(() => {vi.clearAllMocks()+ mockAppContext.workspacePermissionKeys = ['credential.manage', 'credential.use']})afterEach(() => {@@ -46,7 +57,6 @@ describe('PluginAuth', () => {canOAuth: false,canApiKey: true,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -62,7 +72,6 @@ describe('PluginAuth', () => {canOAuth: true,canApiKey: true,credentials: [{ id: '1', name: 'key', is_default: true, provider: 'test' }],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -78,7 +87,6 @@ describe('PluginAuth', () => {canOAuth: false,canApiKey: true,credentials: [{ id: '1', name: 'key', is_default: true, provider: 'test' }],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -98,7 +106,6 @@ describe('PluginAuth', () => {canOAuth: false,canApiKey: true,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -113,7 +120,6 @@ describe('PluginAuth', () => {canOAuth: false,canApiKey: true,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -128,7 +134,6 @@ describe('PluginAuth', () => {canOAuth: false,canApiKey: false,credentials: [],- disabled: false,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -137,13 +142,13 @@ describe('PluginAuth', () => {expect(mockUsePluginAuth).toHaveBeenCalledWith(defaultPayload, true)})- it('renders permission hint when authorization configuration is disabled by workspace permissions', () => {+ it('renders permission hint and disables authorization configuration when credential.manage is missing', () => {+ mockAppContext.workspacePermissionKeys = ['credential.use']mockUsePluginAuth.mockReturnValue({isAuthorized: false,canOAuth: false,canApiKey: true,credentials: [],- disabled: true,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -157,12 +162,12 @@ describe('PluginAuth', () => {})it('opens members settings when permission hint action is clicked', () => {+ mockAppContext.workspacePermissionKeys = ['credential.use']mockUsePluginAuth.mockReturnValue({isAuthorized: false,canOAuth: false,canApiKey: true,credentials: [],- disabled: true,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -176,12 +181,12 @@ describe('PluginAuth', () => {})it('does not render permission hint for datasource authorization', () => {+ mockAppContext.workspacePermissionKeys = ['credential.use']mockUsePluginAuth.mockReturnValue({isAuthorized: false,canOAuth: false,canApiKey: true,credentials: [],- disabled: true,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: false,})@@ -192,12 +197,12 @@ describe('PluginAuth', () => {})it('does not render permission hint when custom credentials are unavailable', () => {+ mockAppContext.workspacePermissionKeys = ['credential.use']mockUsePluginAuth.mockReturnValue({isAuthorized: false,canOAuth: false,canApiKey: true,credentials: [],- disabled: true,invalidPluginCredentialInfo: vi.fn(),notAllowCustomCredential: true,})diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsxindex f9b382ef4fd..7b2df1f9918 100644--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx@@ -247,6 +247,18 @@ describe('ApiKeyModal', () => {expect(mockOnClose).toHaveBeenCalled()})+ it('should call onClose after controlled cancel closes the modal', async () => {+ const mockOnClose = vi.fn()+ render(<ControlledModalHarness ApiKeyModal={ApiKeyModal} onClose={mockOnClose} />)++ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))++ await waitFor(() => {+ expect(screen.getByTestId('modal-open-state')).toHaveTextContent('false')+ })+ expect(mockOnClose).toHaveBeenCalled()+ })+it('should close through controlled open state when cancel is clicked', async () => {const mockOnClose = vi.fn()render(<ControlledModalHarness ApiKeyModal={ApiKeyModal} onClose={mockOnClose} />)diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsxindex 5a705b14ebc..aad6a174730 100644--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsx@@ -28,6 +28,9 @@ const createWrapper = () => {// Mock API hooks - only mock network-related hooksconst mockGetPluginOAuthClientSchema = vi.fn()+const mockAppContext = vi.hoisted(() => ({+ workspacePermissionKeys: ['credential.manage', 'credential.use'] as string[],+}))vi.mock('../../hooks/use-credential', () => ({useGetPluginOAuthUrlHook: () => ({@@ -61,6 +64,13 @@ vi.mock('@/hooks/use-oauth', () => ({openOAuthPopup: vi.fn(),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ workspacePermissionKeys: mockAppContext.workspacePermissionKeys,+ }),+}))+// Mock service/use-triggers - API servicevi.mock('@/service/use-triggers', () => ({useTriggerPluginDynamicOptions: () => ({@@ -84,6 +94,7 @@ const createPluginPayload = (overrides: Partial<PluginPayload> = {}): PluginPayldescribe('Authorize', () => {beforeEach(() => {vi.clearAllMocks()+ mockAppContext.workspacePermissionKeys = ['credential.manage', 'credential.use']mockGetPluginOAuthClientSchema.mockReturnValue({schema: [],is_oauth_custom_client_enabled: false,@@ -240,15 +251,15 @@ describe('Authorize', () => {})})- describe('disabled prop', () => {- it('should disable OAuth button when disabled is true', () => {+ describe('credential.manage permission', () => {+ it('should disable OAuth button when credential.manage is missing', () => {const pluginPayload = createPluginPayload()+ mockAppContext.workspacePermissionKeys = ['credential.use']render(<AuthorizepluginPayload={pluginPayload}canOAuth={true}- disabled={true}/>,{ wrapper: createWrapper() },)@@ -256,14 +267,14 @@ describe('Authorize', () => {expect(screen.getByRole('button')).toBeDisabled()})- it('should disable API Key button when disabled is true', () => {+ it('should disable API Key button when credential.manage is missing', () => {const pluginPayload = createPluginPayload()+ mockAppContext.workspacePermissionKeys = ['credential.use']render(<AuthorizepluginPayload={pluginPayload}canApiKey={true}- disabled={true}/>,{ wrapper: createWrapper() },)@@ -271,7 +282,7 @@ describe('Authorize', () => {expect(screen.getByRole('button')).toBeDisabled()})- it('should not disable buttons when disabled is false', () => {+ it('should not disable buttons when credential.manage is present', () => {const pluginPayload = createPluginPayload()render(@@ -279,7 +290,6 @@ describe('Authorize', () => {pluginPayload={pluginPayload}canOAuth={true}canApiKey={true}- disabled={false}/>,{ wrapper: createWrapper() },)@@ -538,15 +548,15 @@ describe('Authorize', () => {}).not.toThrow()})- it('should handle both disabled and notAllowCustomCredential together', () => {+ it('should stay disabled when credential.manage is missing and custom credentials are unavailable', () => {const pluginPayload = createPluginPayload()+ mockAppContext.workspacePermissionKeys = ['credential.use']render(<AuthorizepluginPayload={pluginPayload}canOAuth={true}canApiKey={true}- disabled={true}notAllowCustomCredential={true}/>,{ wrapper: createWrapper() },@@ -730,15 +740,15 @@ describe('Authorize', () => {expect(buttons.length).toBe(2)})- it('should indicate disabled state for accessibility', () => {+ it('should indicate permission-disabled state for accessibility', () => {const pluginPayload = createPluginPayload()+ mockAppContext.workspacePermissionKeys = ['credential.use']render(<AuthorizepluginPayload={pluginPayload}canOAuth={true}canApiKey={true}- disabled={true}/>,{ wrapper: createWrapper() },)diff --git a/web/app/components/plugins/plugin-auth/authorize/index.tsx b/web/app/components/plugins/plugin-auth/authorize/index.tsxindex 925359e5190..e09afd2d860 100644--- a/web/app/components/plugins/plugin-auth/authorize/index.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/index.tsx@@ -8,6 +8,8 @@ import {useMemo,} from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'import AddApiKeyButton from './add-api-key-button'import AddOAuthButton from './add-oauth-button'@@ -17,7 +19,6 @@ type AuthorizeProps = {showDivider?: booleancanOAuth?: booleancanApiKey?: boolean- disabled?: booleanonUpdate?: () => voidnotAllowCustomCredential?: boolean/**@@ -34,12 +35,14 @@ const Authorize = ({showDivider = true,canOAuth,canApiKey,- disabled,onUpdate,notAllowCustomCredential,onApiKeyClick,}: AuthorizeProps) => {const { t } = useTranslation()+ const workspacePermissionKeys = useAppContextWithSelector(s => s.workspacePermissionKeys)+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')+const oAuthButtonProps: AddOAuthButtonProps = useMemo(() => {if (theme === 'secondary') {return {@@ -81,7 +84,7 @@ const Authorize = ({<div className={cn('min-w-0 flex-1', notAllowCustomCredential && 'opacity-50')}><AddOAuthButton{...oAuthButtonProps}- disabled={disabled || notAllowCustomCredential}+ disabled={!canManageCredential || notAllowCustomCredential}onUpdate={onUpdate}/></div>@@ -98,14 +101,14 @@ const Authorize = ({)}return Item- }, [notAllowCustomCredential, oAuthButtonProps, disabled, onUpdate, t])+ }, [notAllowCustomCredential, oAuthButtonProps, canManageCredential, onUpdate, t])const ApiKeyButton = useMemo(() => {const Item = (<div className={cn('min-w-0 flex-1', notAllowCustomCredential && 'opacity-50')}><AddApiKeyButton{...apiKeyButtonProps}- disabled={disabled || notAllowCustomCredential}+ disabled={!canManageCredential || notAllowCustomCredential}onUpdate={onUpdate}/></div>@@ -122,7 +125,7 @@ const Authorize = ({)}return Item- }, [notAllowCustomCredential, apiKeyButtonProps, disabled, onUpdate, t])+ }, [notAllowCustomCredential, apiKeyButtonProps, canManageCredential, onUpdate, t])return (<>diff --git a/web/app/components/plugins/plugin-auth/authorized-in-node.tsx b/web/app/components/plugins/plugin-auth/authorized-in-node.tsxindex de2bcab7c22..17f70f317dc 100644--- a/web/app/components/plugins/plugin-auth/authorized-in-node.tsx+++ b/web/app/components/plugins/plugin-auth/authorized-in-node.tsx@@ -37,7 +37,6 @@ const AuthorizedInNode = ({canApiKey,canOAuth,credentials,- disabled,invalidPluginCredentialInfo,notAllowCustomCredential,} = usePluginAuth(pluginPayload, true, credentialId ? [credentialId] : undefined)@@ -143,7 +142,6 @@ const AuthorizedInNode = ({placement="bottom-end"triggerPopupSameWidth={false}popupClassName="w-[360px]"- disabled={disabled}disableSetDefaultonItemClick={handleAuthorizationItemClick}extraAuthorizationItems={extraAuthorizationItems}diff --git a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsxindex 83c92eb4196..62e34ae2b6c 100644--- a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx@@ -75,6 +75,17 @@ vi.mock('@/hooks/use-oauth', () => ({vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))+const mockAppContext = vi.hoisted(() => ({+ userProfile: { id: 'test-user', name: 'Test User', email: '[email protected]', avatar_url: '' },+ workspacePermissionKeys: ['credential.manage', 'credential.use'] as string[],+}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: {+ userProfile: typeof mockAppContext.userProfile+ workspacePermissionKeys: string[]+ }) => unknown) => selector(mockAppContext),+}))+// Mock service/use-triggersvi.mock('@/service/use-triggers', () => ({useTriggerPluginDynamicOptions: () => ({@@ -130,6 +141,7 @@ const createCredential = (overrides: Partial<Credential> = {}): Credential => ({describe('Authorized Component', () => {beforeEach(() => {vi.clearAllMocks()+ mockAppContext.workspacePermissionKeys = ['credential.manage', 'credential.use']mockDeletePluginCredential.mockResolvedValue({})mockSetPluginDefaultCredential.mockResolvedValue({})mockUpdatePluginCredential.mockResolvedValue({})@@ -1445,32 +1457,42 @@ describe('Authorized Component', () => {expect(screen.getByText('API Keys'))!.toBeInTheDocument()})- it('should pass disabled to Item components', () => {+ it('should allow credential.use to set default when credential.manage is missing', () => {const pluginPayload = createPluginPayload()const credentials = [createCredential({ is_default: false })]+ mockAppContext.workspacePermissionKeys = ['credential.use']render(<AuthorizedpluginPayload={pluginPayload}credentials={credentials}isOpen={true}- disabled={true}/>,{ wrapper: createWrapper() },)- // When disabled is true, action buttons should be disabled- // Look for the set default button which should have disabled attributeconst setDefaultButton = screen.queryByText('plugin.auth.setDefault')- if (setDefaultButton) {- const button = setDefaultButton.closest('button')- expect(button)!.toBeDisabled()- }- else {- // If no set default button, verify the component rendered- // If no set default button, verify the component rendered- expect(screen.getByText('API Keys'))!.toBeInTheDocument()- }+ expect(setDefaultButton)!.toBeInTheDocument()+ expect(setDefaultButton!.closest('button'))!.toBeEnabled()+ })++ it('should disable set default when credential.use and credential.manage are missing', () => {+ const pluginPayload = createPluginPayload()+ const credentials = [createCredential({ is_default: false })]+ mockAppContext.workspacePermissionKeys = []++ render(+ <Authorized+ pluginPayload={pluginPayload}+ credentials={credentials}+ isOpen={true}+ />,+ { wrapper: createWrapper() },+ )++ const setDefaultButton = screen.queryByText('plugin.auth.setDefault')+ expect(setDefaultButton)!.toBeInTheDocument()+ expect(setDefaultButton!.closest('button'))!.toBeDisabled()})it('should pass disableSetDefault to Item components', () => {diff --git a/web/app/components/plugins/plugin-auth/authorized/__tests__/item.spec.tsx b/web/app/components/plugins/plugin-auth/authorized/__tests__/item.spec.tsxindex 22ea9d36bbd..e42b4317c44 100644--- a/web/app/components/plugins/plugin-auth/authorized/__tests__/item.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorized/__tests__/item.spec.tsx@@ -9,8 +9,11 @@ import Item from '../item'// borrowed-row heuristic; provide a minimal mock so the selector resolves.const mockUserProfile = { id: 'test-user', name: 'Test User', email: '[email protected]', avatar_url: '' }vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: { userProfile: typeof mockUserProfile }) => unknown) =>- selector({ userProfile: mockUserProfile }),+ useSelector: (selector: (state: { userProfile: typeof mockUserProfile, workspacePermissionKeys: string[] }) => unknown) =>+ selector({+ userProfile: mockUserProfile,+ workspacePermissionKeys: ['credential.manage', 'credential.use'],+ }),}))// ==================== Test Utilities ====================@@ -86,8 +89,7 @@ describe('Item Component', () => {/>,)- const svgs = container.querySelectorAll('svg')- expect(svgs.length).toBeGreaterThan(0)+ expect(container.querySelector('.i-ri-check-line')).toBeInTheDocument()})it('should not render selected icon when credential is not selected', () => {@@ -100,7 +102,8 @@ describe('Item Component', () => {selectedCredentialId="sel-id"/>,)- const selectedSvgCount = selectedContainer.querySelectorAll('svg').length+ const selectedIcon = selectedContainer.querySelector('.i-ri-check-line')+ expect(selectedIcon).not.toBeNull()cleanup()@@ -111,9 +114,9 @@ describe('Item Component', () => {selectedCredentialId="other-id"/>,)- const unselectedSvgCount = unselectedContainer.querySelectorAll('svg').length+ const unselectedIcon = unselectedContainer.querySelector('.i-ri-check-line')- expect(unselectedSvgCount).toBeLessThan(selectedSvgCount)+ expect(unselectedIcon).not.toBeInTheDocument()})it('should render with disabled appearance when not_allowed_to_use is true', () => {@@ -351,7 +354,7 @@ describe('Item Component', () => {/>,)- const editButton = container.querySelector('svg')?.closest('button') as HTMLElement+ const editButton = container.querySelector('.i-ri-equalizer-2-line')?.closest('button') as HTMLElementfireEvent.click(editButton)expect(onEdit).toHaveBeenCalledWith('edit-test-id', {api_key: 'secret',@@ -415,7 +418,7 @@ describe('Item Component', () => {/>,)- const deleteButton = container.querySelector('svg')?.closest('button') as HTMLElement+ const deleteButton = container.querySelector('.i-ri-delete-bin-line')?.closest('button') as HTMLElementfireEvent.click(deleteButton)expect(onDelete).toHaveBeenCalledWith('delete-test-id')})@@ -532,7 +535,7 @@ describe('Item Component', () => {/>,)- const deleteButton = container.querySelector('svg')?.closest('button') as HTMLElement+ const deleteButton = container.querySelector('.i-ri-delete-bin-line')?.closest('button') as HTMLElementfireEvent.click(deleteButton)expect(onDelete).toHaveBeenCalled()})diff --git a/web/app/components/plugins/plugin-auth/authorized/index.tsx b/web/app/components/plugins/plugin-auth/authorized/index.tsxindex be69685755f..7a72e36a4fa 100644--- a/web/app/components/plugins/plugin-auth/authorized/index.tsx+++ b/web/app/components/plugins/plugin-auth/authorized/index.tsx@@ -27,6 +27,7 @@ import {useState,} from 'react'import { useTranslation } from 'react-i18next'+import { useCredentialPermissions } from '@/hooks/use-credential-permissions'import Authorize from '../authorize'import ApiKeyModal from '../authorize/api-key-modal'import {@@ -42,7 +43,6 @@ type AuthorizedProps = {credentials: Credential[]canOAuth?: booleancanApiKey?: boolean- disabled?: booleanrenderTrigger?: (open?: boolean) => React.ReactNodeisOpen?: booleanonOpenChange?: (open: boolean) => void@@ -63,7 +63,6 @@ const Authorized = ({credentials,canOAuth,canApiKey,- disabled,renderTrigger,isOpen,onOpenChange,@@ -80,6 +79,7 @@ const Authorized = ({notAllowCustomCredential,}: AuthorizedProps) => {const { t } = useTranslation()+ const { canUseCredential, canManageCredential } = useCredentialPermissions()const [isLocalOpen, setIsLocalOpen] = useState(false)const mergedIsOpen = isOpen ?? isLocalOpenconst setMergedIsOpen = useCallback((open: boolean) => {@@ -94,12 +94,15 @@ const Authorized = ({const [deleteCredentialId, setDeleteCredentialId] = useState<string | null>(null)const { mutateAsync: deletePluginCredential } = useDeletePluginCredentialHook(pluginPayload)const openConfirm = useCallback((credentialId?: string) => {+ if (!canManageCredential)+ return+setMergedIsOpen(false)if (credentialId)pendingOperationCredentialIdRef.current = credentialIdsetDeleteCredentialId(pendingOperationCredentialIdRef.current)- }, [setMergedIsOpen])+ }, [canManageCredential, setMergedIsOpen])const closeConfirm = useCallback(() => {setDeleteCredentialId(null)pendingOperationCredentialIdRef.current = null@@ -111,7 +114,7 @@ const Authorized = ({setDoingAction(doing)}, [])const handleConfirm = useCallback(async () => {- if (doingActionRef.current)+ if (doingActionRef.current || !canManageCredential)returnif (!pendingOperationCredentialIdRef.current) {setDeleteCredentialId(null)@@ -128,15 +131,18 @@ const Authorized = ({finally {handleSetDoingAction(false)}- }, [deletePluginCredential, onUpdate, t, handleSetDoingAction])+ }, [canManageCredential, deletePluginCredential, onUpdate, t, handleSetDoingAction])const [editValues, setEditValues] = useState<Record<string, unknown> | null>(null)const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false)const handleEdit = useCallback((id: string, values: Record<string, unknown>) => {+ if (!canManageCredential)+ return+setMergedIsOpen(false)pendingOperationCredentialIdRef.current = idsetEditValues(values)setIsApiKeyModalOpen(true)- }, [setMergedIsOpen])+ }, [canManageCredential, setMergedIsOpen])const handleApiKeyModalOpenChange = useCallback((open: boolean) => {setIsApiKeyModalOpen(open)if (!open)@@ -146,15 +152,21 @@ const Authorized = ({// popover closes due to outside-click detection on the modal's portal.const [isAddApiKeyOpen, setIsAddApiKeyOpen] = useState(false)const handleAddApiKeyClick = useCallback(() => {+ if (!canManageCredential)+ return+setMergedIsOpen(false)setIsAddApiKeyOpen(true)- }, [setMergedIsOpen])+ }, [canManageCredential, setMergedIsOpen])const handleRemove = useCallback(() => {+ if (!canManageCredential)+ return+setDeleteCredentialId(pendingOperationCredentialIdRef.current)- }, [])+ }, [canManageCredential])const { mutateAsync: setPluginDefaultCredential } = useSetPluginDefaultCredentialHook(pluginPayload)const handleSetDefault = useCallback(async (id: string) => {- if (doingActionRef.current)+ if (doingActionRef.current || !canUseCredential)returntry {handleSetDoingAction(true)@@ -165,13 +177,13 @@ const Authorized = ({finally {handleSetDoingAction(false)}- }, [setPluginDefaultCredential, onUpdate, t, handleSetDoingAction])+ }, [canUseCredential, setPluginDefaultCredential, onUpdate, t, handleSetDoingAction])const { mutateAsync: updatePluginCredential } = useUpdatePluginCredentialHook(pluginPayload)const handleRename = useCallback(async (payload: {credential_id: stringname: string}) => {- if (doingActionRef.current)+ if (doingActionRef.current || !canManageCredential)returntry {handleSetDoingAction(true)@@ -182,7 +194,7 @@ const Authorized = ({finally {handleSetDoingAction(false)}- }, [updatePluginCredential, t, handleSetDoingAction, onUpdate])+ }, [canManageCredential, updatePluginCredential, t, handleSetDoingAction, onUpdate])const unavailableCredentials = credentials.filter(credential => credential.not_allowed_to_use)const unavailableCredential = credentials.find(credential => credential.not_allowed_to_use && credential.is_default)const resolvedOffset = typeof offset === 'number' || typeof offset === 'function' ? undefined : offset@@ -252,7 +264,6 @@ const Authorized = ({<Itemkey={credential.id}credential={credential}- disabled={disabled}onItemClick={onItemClick}disableRenamedisableEdit@@ -281,7 +292,6 @@ const Authorized = ({<Itemkey={credential.id}credential={credential}- disabled={disabled}disableEditonDelete={openConfirm}onSetDefault={handleSetDefault}@@ -311,7 +321,6 @@ const Authorized = ({<Itemkey={credential.id}credential={credential}- disabled={disabled}onDelete={openConfirm}onEdit={handleEdit}onSetDefault={handleSetDefault}@@ -339,7 +348,6 @@ const Authorized = ({showDivider={false}canOAuth={canOAuth}canApiKey={canApiKey}- disabled={disabled}onUpdate={onUpdate}onApiKeyClick={handleAddApiKeyClick}/>@@ -359,7 +367,7 @@ const Authorized = ({</div><AlertDialogActions><AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>- <AlertDialogConfirmButton disabled={doingAction} onClick={handleConfirm}>+ <AlertDialogConfirmButton disabled={!canManageCredential || doingAction} onClick={handleConfirm}>{t('operation.confirm', { ns: 'common' })}</AlertDialogConfirmButton></AlertDialogActions>@@ -374,7 +382,7 @@ const Authorized = ({editValues={editValues}onClose={() => handleApiKeyModalOpenChange(false)}onRemove={handleRemove}- disabled={disabled || doingAction}+ disabled={!canManageCredential || doingAction}onUpdate={onUpdate}/>)@@ -386,7 +394,7 @@ const Authorized = ({onOpenChange={setIsAddApiKeyOpen}pluginPayload={pluginPayload}onClose={() => setIsAddApiKeyOpen(false)}- disabled={disabled || doingAction}+ disabled={!canManageCredential || doingAction}onUpdate={onUpdate}/>)diff --git a/web/app/components/plugins/plugin-auth/authorized/item.tsx b/web/app/components/plugins/plugin-auth/authorized/item.tsxindex 5d91c34e8e1..88edd05b6b8 100644--- a/web/app/components/plugins/plugin-auth/authorized/item.tsx+++ b/web/app/components/plugins/plugin-auth/authorized/item.tsx@@ -4,10 +4,6 @@ import { cn } from '@langgenius/dify-ui/cn'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import {- RiCheckLine,- RiDeleteBinLine,- RiEditLine,- RiEqualizer2Line,RiInformationLine,} from '@remixicon/react'import {@@ -20,11 +16,11 @@ import ActionButton from '@/app/components/base/action-button'import Badge from '@/app/components/base/badge'import Input from '@/app/components/base/input'import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'import { CredentialTypeEnum } from '../types'type ItemProps = {credential: Credential- disabled?: booleanonDelete?: (id: string) => voidonEdit?: (id: string, values: Record<string, unknown>) => voidonSetDefault?: (id: string) => void@@ -39,10 +35,10 @@ type ItemProps = {onItemClick?: (id: string) => voidshowSelectedIcon?: booleanselectedCredentialId?: string+ disabled?: boolean}const Item = ({credential,- disabled,onDelete,onEdit,onSetDefault,@@ -54,10 +50,14 @@ const Item = ({onItemClick,showSelectedIcon,selectedCredentialId,+ disabled,}: ItemProps) => {const { t } = useTranslation()const [renaming, setRenaming] = useState(false)const [renameValue, setRenameValue] = useState(credential.name)+ const workspacePermissionKeys = useAppContextWithSelector(s => s.workspacePermissionKeys)+ const canManageCredential = hasPermission(workspacePermissionKeys, 'credential.manage')+ const canUseCredential = hasPermission(workspacePermissionKeys, ['credential.use', 'credential.manage'])const isOAuth = credential.credential_type === CredentialTypeEnum.OAUTH2const isPersonal = credential.visibility === 'only_me'const userProfile = useAppContextWithSelector(state => state.userProfile)@@ -81,10 +81,10 @@ const Item = ({className={cn('group flex h-8 items-center rounded-lg p-1 hover:bg-state-base-hover',renaming && 'bg-state-base-hover',- (disabled || credential.not_allowed_to_use) && 'cursor-not-allowed opacity-50',+ (disabled || !canUseCredential || credential.not_allowed_to_use) && 'cursor-not-allowed opacity-50',)}onClick={() => {- if (credential.not_allowed_to_use || disabled)+ if (disabled || credential.not_allowed_to_use || !canUseCredential)returnonItemClick?.(credential.id === '__workspace_default__' ? '' : credential.id)}}@@ -134,7 +134,7 @@ const Item = ({<div className="size-4">{selectedCredentialId === credential.id && (- <RiCheckLine className="size-4 text-text-accent" />+ <span className="i-ri-check-line size-4 text-text-accent" />)}</div>@@ -190,7 +190,7 @@ const Item = ({!credential.is_default && !disableSetDefault && !credential.not_allowed_to_use && !isBorrowed && (<Buttonsize="small"- disabled={disabled}+ disabled={disabled || !canUseCredential}onClick={(e) => {e.stopPropagation()onSetDefault?.(credential.id)@@ -206,14 +206,14 @@ const Item = ({<TooltipTriggerrender={(<ActionButton- disabled={disabled}+ disabled={disabled || !canManageCredential}onClick={(e) => {e.stopPropagation()setRenaming(true)setRenameValue(credential.name)}}>- <RiEditLine className="size-4 text-text-tertiary" />+ <span className="i-ri-edit-line size-4 text-text-tertiary" /></ActionButton>)}/>@@ -229,7 +229,7 @@ const Item = ({<TooltipTriggerrender={(<ActionButton- disabled={disabled}+ disabled={disabled || !canManageCredential}onClick={(e) => {e.stopPropagation()onEdit?.(@@ -242,7 +242,7 @@ const Item = ({)}}>- <RiEqualizer2Line className="size-4 text-text-tertiary" />+ <span className="i-ri-equalizer-2-line size-4 text-text-tertiary" /></ActionButton>)}/>@@ -259,13 +259,13 @@ const Item = ({render={(<ActionButtonclassName="hover:bg-transparent"- disabled={disabled}+ disabled={disabled || !canManageCredential}onClick={(e) => {e.stopPropagation()onDelete?.(credential.id)}}>- <RiDeleteBinLine className="size-4 text-text-tertiary hover:text-text-destructive" />+ <span className="i-ri-delete-bin-line size-4 text-text-tertiary hover:text-text-destructive" /></ActionButton>)}/>diff --git a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth.spec.ts b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth.spec.tsindex 2903eb8c341..11a7e602d38 100644--- a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth.spec.ts+++ b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth.spec.ts@@ -25,12 +25,6 @@ vi.mock('../use-credential', () => ({useInvalidPluginCredentialInfoHook: () => mockInvalidate,}))-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: true,- }),-}))-const basePayload = {category: AuthCategory.tool,provider: 'test-provider',@@ -55,12 +49,6 @@ describe('usePluginAuth', () => {expect(result.current.canApiKey).toBe(true)})- it('should return disabled=false for workspace managers', () => {- const { result } = renderHook(() => usePluginAuth(basePayload, true))-- expect(result.current.disabled).toBe(false)- })-it('should return notAllowCustomCredential=false when allowed', () => {const { result } = renderHook(() => usePluginAuth(basePayload, true))diff --git a/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth.ts b/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth.tsindex a06d3470828..e38fb021a3f 100644--- a/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth.ts+++ b/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth.ts@@ -1,5 +1,4 @@import type { PluginPayload } from '../types'-import { useAppContext } from '@/context/app-context'import { CredentialTypeEnum } from '../types'import {useGetPluginCredentialInfoHook,@@ -12,7 +11,6 @@ export const usePluginAuth = (includeCredentialIds?: string[],) => {const { data } = useGetPluginCredentialInfoHook(pluginPayload, enable, includeCredentialIds)- const { isCurrentWorkspaceManager } = useAppContext()const isAuthorized = !!data?.credentials.lengthconst canOAuth = data?.supported_credential_types.includes(CredentialTypeEnum.OAUTH2)const canApiKey = data?.supported_credential_types.includes(CredentialTypeEnum.API_KEY)@@ -23,7 +21,6 @@ export const usePluginAuth = (canOAuth,canApiKey,credentials: data?.credentials || [],- disabled: !isCurrentWorkspaceManager,notAllowCustomCredential: data?.allow_custom_token === false,invalidPluginCredentialInfo,}diff --git a/web/app/components/plugins/plugin-auth/plugin-auth-in-agent.tsx b/web/app/components/plugins/plugin-auth/plugin-auth-in-agent.tsxindex fea94915df1..efd2cf00905 100644--- a/web/app/components/plugins/plugin-auth/plugin-auth-in-agent.tsx+++ b/web/app/components/plugins/plugin-auth/plugin-auth-in-agent.tsx@@ -34,7 +34,6 @@ const PluginAuthInAgent = ({canOAuth,canApiKey,credentials,- disabled,invalidPluginCredentialInfo,notAllowCustomCredential,} = usePluginAuth(pluginPayload, true, credentialId ? [credentialId] : undefined)@@ -104,7 +103,6 @@ const PluginAuthInAgent = ({pluginPayload={pluginPayload}canOAuth={canOAuth}canApiKey={canApiKey}- disabled={disabled}onUpdate={invalidPluginCredentialInfo}notAllowCustomCredential={notAllowCustomCredential}/>@@ -117,7 +115,6 @@ const PluginAuthInAgent = ({credentials={credentials}canOAuth={canOAuth}canApiKey={canApiKey}- disabled={disabled}disableSetDefaultonItemClick={handleAuthorizationItemClick}extraAuthorizationItems={extraAuthorizationItems}diff --git a/web/app/components/plugins/plugin-auth/plugin-auth.tsx b/web/app/components/plugins/plugin-auth/plugin-auth.tsxindex c0d9fe54080..9017008fdae 100644--- a/web/app/components/plugins/plugin-auth/plugin-auth.tsx+++ b/web/app/components/plugins/plugin-auth/plugin-auth.tsx@@ -26,12 +26,10 @@ const PluginAuth = ({canOAuth,canApiKey,credentials,- disabled,invalidPluginCredentialInfo,notAllowCustomCredential,} = usePluginAuth(pluginPayload, !!pluginPayload.provider)const showPermissionHint = !isAuthorized- && disabled&& !notAllowCustomCredential&& pluginPayload.category === AuthCategory.tool&& (canOAuth || canApiKey)@@ -40,7 +38,6 @@ const PluginAuth = ({pluginPayload={pluginPayload}canOAuth={canOAuth}canApiKey={canApiKey}- disabled={disabled}onUpdate={invalidPluginCredentialInfo}notAllowCustomCredential={notAllowCustomCredential}/>@@ -88,7 +85,6 @@ const PluginAuth = ({credentials={credentials}canOAuth={canOAuth}canApiKey={canApiKey}- disabled={disabled}onUpdate={invalidPluginCredentialInfo}notAllowCustomCredential={notAllowCustomCredential}/>diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsxindex 1a74ca1ccc3..05c9d4bdc6f 100644--- a/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx@@ -158,6 +158,7 @@ let mockAutoUpgradeInfo: {vi.mock('../../plugin-page/use-reference-setting', () => ({default: () => ({referenceSetting: mockAutoUpgradeInfo ? { auto_upgrade: mockAutoUpgradeInfo } : null,+ canUpdate: true,}),}))diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsxindex 278555c0bf6..e809573a7ce 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx@@ -131,6 +131,7 @@ vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({upgrade_time_of_day: 0,},},+ canUpdate: true,}),}))diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.tsindex 2931c4e7051..57ed30fe15d 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.ts+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.ts@@ -14,6 +14,8 @@ import { checkForUpdates, fetchReleases } from '../../../install-plugin/hooks'import { PluginSource } from '../../../types'type UsePluginOperationsParams = {+ canManagePlugin?: boolean+ canUpdatePlugin?: booleandetail: PluginDetailmodalStates: ModalStatesversionPicker: {@@ -31,6 +33,8 @@ type UsePluginOperationsReturn = {}export const usePluginOperations = ({+ canManagePlugin = true,+ canUpdatePlugin = true,detail,modalStates,versionPicker,@@ -50,6 +54,9 @@ export const usePluginOperations = ({}, [invalidateCheckInstalled, onUpdate])const handleUpdate = useCallback(async (isDowngrade?: boolean) => {+ if (!canUpdatePlugin)+ return+if (isFromMarketplace) {versionPicker.setIsDowngrade(!!isDowngrade)modalStates.showUpdateModal()@@ -91,6 +98,7 @@ export const usePluginOperations = ({})}}, [+ canUpdatePlugin,isFromMarketplace,meta,author,@@ -110,6 +118,9 @@ export const usePluginOperations = ({}, [handlePluginUpdated, modalStates])const handleDelete = useCallback(async () => {+ if (!canManagePlugin)+ return+modalStates.showDeleting()const res = await uninstallPlugin(id)modalStates.hideDeleting()@@ -123,6 +134,7 @@ export const usePluginOperations = ({trackEvent('plugin_uninstalled', { plugin_id, plugin_name: name })}}, [+ canManagePlugin,id,category,plugin_id,diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsxindex d9e16052acd..64f8ee94038 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx@@ -34,6 +34,8 @@ import { HeaderModals, PluginSourceBadge } from './components'import { useDetailHeaderState, usePluginOperations } from './hooks'type Props = Readonly<{+ canManagePlugin?: boolean+ canUpdatePlugin?: booleandetail: PluginDetailisReadmeView?: booleanonHide?: () => void@@ -69,6 +71,8 @@ const getDetailUrl = (}const DetailHeader = ({+ canManagePlugin = true,+ canUpdatePlugin = true,detail,isReadmeView = false,onHide,@@ -119,6 +123,8 @@ const DetailHeader = ({modalStates,versionPicker,isFromMarketplace,+ canManagePlugin,+ canUpdatePlugin,onUpdate,})@@ -174,7 +180,7 @@ const DetailHeader = ({{/* Version Picker */}{!!version && (<PluginVersionPicker- disabled={!isFromMarketplace || isReadmeView}+ disabled={!canUpdatePlugin || !isFromMarketplace || isReadmeView}isShow={versionPicker.isShow}onShowChange={versionPicker.setIsShow}pluginID={plugin_id}@@ -185,13 +191,13 @@ const DetailHeader = ({className={cn('mx-1',versionPicker.isShow && 'bg-state-base-hover',- (versionPicker.isShow || isFromMarketplace) && 'hover:bg-state-base-hover',+ (versionPicker.isShow || (canUpdatePlugin && isFromMarketplace)) && 'hover:bg-state-base-hover',)}uppercase={false}text={(<><div>{isFromGitHub ? (meta?.version ?? version ?? '') : version}</div>- {isFromMarketplace && !isReadmeView && <span aria-hidden className="ml-1 i-ri-arrow-left-right-line size-3 text-text-tertiary" />}+ {canUpdatePlugin && isFromMarketplace && !isReadmeView && <span aria-hidden className="ml-1 i-ri-arrow-left-right-line size-3 text-text-tertiary" />}</>)}hasRedCornerMark={hasNewVersion}@@ -219,7 +225,7 @@ const DetailHeader = ({)}{/* Update Button */}- {(hasNewVersion || isFromGitHub) && (+ {canUpdatePlugin && (hasNewVersion || isFromGitHub) && (<Tooltip><TooltipTriggerdelay={300}@@ -264,6 +270,8 @@ const DetailHeader = ({onRemove={modalStates.showDeleteConfirm}onViewReadme={canViewReadme ? handleViewReadme : undefined}detailUrl={detailUrl}+ showCheckVersion={canUpdatePlugin}+ showRemove={canManagePlugin}/><ActionButton onClick={onHide}><span aria-hidden className="i-ri-close-line size-4" />diff --git a/web/app/components/plugins/plugin-detail-panel/index.tsx b/web/app/components/plugins/plugin-detail-panel/index.tsxindex b8571b11d73..f72e251a224 100644--- a/web/app/components/plugins/plugin-detail-panel/index.tsx+++ b/web/app/components/plugins/plugin-detail-panel/index.tsx@@ -24,12 +24,16 @@ import { SubscriptionList } from './subscription-list'import { TriggerEventsList } from './trigger/event-list'type Props = Readonly<{+ canManagePlugin?: boolean+ canUpdatePlugin?: booleandetail?: PluginDetailonUpdate: () => voidonHide: () => void}>const PluginDetailPanel: FC<Props> = ({+ canManagePlugin = true,+ canUpdatePlugin = true,detail,onUpdate,onHide,@@ -75,7 +79,13 @@ const PluginDetailPanel: FC<Props> = ({<DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">{detail && (<>- <DetailHeader detail={detail} onUpdate={handleUpdate} onHide={onHide} />+ <DetailHeader+ detail={detail}+ onUpdate={handleUpdate}+ onHide={onHide}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}+ /><div className="grow overflow-y-auto"><div className="flex min-h-full flex-col"><div className="flex-1">diff --git a/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx b/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsxindex b1b85155e58..a18807b0bb9 100644--- a/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx+++ b/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx@@ -28,6 +28,8 @@ type Props = Readonly<{popupClassName?: stringtriggerSize?: 'm' | 'xs'destructiveRemove?: boolean+ showCheckVersion?: boolean+ showRemove?: boolean}>const operationMenuPopupClassName = 'w-[192px] py-1'@@ -47,12 +49,22 @@ const OperationDropdown: FC<Props> = ({popupClassName,triggerSize = 'm',destructiveRemove = false,+ showCheckVersion = true,+ showRemove = true,}) => {const { t } = useTranslation()const { data: enable_marketplace } = useSuspenseQuery({...systemFeaturesQueryOptions(),select: s => s.enable_marketplace,})+ const showInfo = source === PluginSource.github+ const showCheckVersionAction = showCheckVersion && source === PluginSource.github+ const showMarketplaceDetail = (source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace+ const showRemoveAction = showRemove+ const showSeparator = showRemoveAction && (showMarketplaceDetail || !!onViewReadme)++ if (!showInfo && !showCheckVersionAction && !showMarketplaceDetail && !onViewReadme && !showRemoveAction)+ return nullreturn (<DropdownMenu>@@ -67,18 +79,28 @@ const OperationDropdown: FC<Props> = ({alignOffset={alignOffset}popupClassName={cn(operationMenuPopupClassName, popupClassName)}>- {source === PluginSource.github && (+ {showInfo && (<DropdownMenuItem className={operationMenuItemClassName} onClick={onInfo}><span className={operationMenuLabelClassName}>{t('detailPanel.operation.info', { ns: 'plugin' })}</span></DropdownMenuItem>)}- {source === PluginSource.github && (+ {showCheckVersionAction && (<DropdownMenuItem className={operationMenuItemClassName} onClick={onCheckVersion}><span className={operationMenuLabelClassName}>{t('detailPanel.operation.checkUpdate', { ns: 'plugin' })}</span></DropdownMenuItem>)}- {(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (- <DropdownMenuItem className={operationMenuItemClassName} render={<a href={detailUrl} target="_blank" rel="noopener noreferrer" />}>+ {showMarketplaceDetail && (+ <DropdownMenuItem+ className={operationMenuItemClassName}+ render={(+ <a+ href={detailUrl}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={t('detailPanel.operation.viewDetail', { ns: 'plugin' })}+ />+ )}+ ><span className={operationMenuLabelClassName}>{t('detailPanel.operation.viewDetail', { ns: 'plugin' })}</span><span className="i-ri-arrow-right-up-line size-3.5 shrink-0 text-text-tertiary" /></DropdownMenuItem>@@ -88,20 +110,22 @@ const OperationDropdown: FC<Props> = ({<span className={operationMenuLabelClassName}>{t('detailPanel.operation.viewReadme', { ns: 'plugin' })}</span></DropdownMenuItem>)}- {(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (+ {showSeparator && (<DropdownMenuSeparator className="my-0" />)}- <DropdownMenuItem- className={cn(- operationMenuItemClassName,- destructiveRemove && 'data-highlighted:bg-state-destructive-hover data-highlighted:text-text-destructive',- )}- onClick={onRemove}- >- <span className={cn(operationMenuLabelClassName, destructiveRemove && 'text-inherit')}>- {t('detailPanel.operation.remove', { ns: 'plugin' })}- </span>- </DropdownMenuItem>+ {showRemoveAction && (+ <DropdownMenuItem+ className={cn(+ operationMenuItemClassName,+ destructiveRemove && 'data-highlighted:bg-state-destructive-hover data-highlighted:text-text-destructive',+ )}+ onClick={onRemove}+ >+ <span className={cn(operationMenuLabelClassName, destructiveRemove && 'text-inherit')}>+ {t('detailPanel.operation.remove', { ns: 'plugin' })}+ </span>+ </DropdownMenuItem>+ )}</DropdownMenuContent></DropdownMenu>)diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/__tests__/index.spec.tsxindex f039ef11e75..4b1fee74415 100644--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/__tests__/index.spec.tsx@@ -192,6 +192,26 @@ vi.mock('@langgenius/dify-ui/popover', () => ({: children}</div>),+ PortalToFollowElemTrigger: ({+ children,+ render,+ onClick,+ }: {+ children: ReactNode+ render?: ReactNode+ onClick?: () => void+ }) => (+ <div data-testid="popover-trigger" onClick={onClick}>+ {render+ ? (+ <>+ {render}+ {children}+ </>+ )+ : children}+ </div>+ ),PopoverContent: ({ children }: { children: ReactNode }) => (<div data-testid="popover-content">{children}</div>),diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-item.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-item.tsxindex 5711326b104..cda69fe1824 100644--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-item.tsx+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-item.tsx@@ -4,17 +4,11 @@ import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'-import {- RiDeleteBinLine,- RiEqualizer2Line,- RiErrorWarningFill,-} from '@remixicon/react'import * as React from 'react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import ActionButton from '@/app/components/base/action-button'import AppIcon from '@/app/components/base/app-icon'-import { Group } from '@/app/components/base/icons/src/vender/other'import { InstallPluginButton } from '@/app/components/workflow/nodes/_base/components/install-plugin-button'import { useMCPToolAvailability } from '@/app/components/workflow/nodes/_base/components/mcp-tool-availability'import McpToolNotSupportTooltip from '@/app/components/workflow/nodes/_base/components/mcp-tool-not-support-tooltip'@@ -89,7 +83,7 @@ const ToolItem = ({)}><div className="flex size-5 items-center justify-center opacity-35">- <Group className="text-text-tertiary" />+ <span className="i-custom-vender-other-group text-text-tertiary" /></div></div>)}@@ -100,7 +94,7 @@ const ToolItem = ({<div className="hidden items-center gap-1 group-hover:flex">{!noAuth && !isError && !uninstalled && !versionMismatch && !isShowCanNotChooseMCPTip && (<ActionButton>- <RiEqualizer2Line className="size-4" />+ <span className="i-ri-equalizer-2-line size-4" /></ActionButton>)}<div@@ -112,7 +106,7 @@ const ToolItem = ({onMouseOver={() => setIsDeleting(true)}onMouseLeave={() => setIsDeleting(false)}>- <RiDeleteBinLine className="size-4" />+ <span className="i-ri-delete-bin-line size-4" /></div></div>{!isError && !uninstalled && !noAuth && !versionMismatch && !isShowCanNotChooseMCPTip && showSwitch && (@@ -143,7 +137,7 @@ const ToolItem = ({className="-mt-1"uniqueIdentifier={installInfo}tooltip={(- <div className="w-[180px]" data-testid="tooltip-content">+ <div className="w-45" data-testid="tooltip-content"><div className="mb-1.5 font-semibold text-text-secondary" data-testid="tooltip-content-title">{t('detailPanel.toolSelector.unsupportedTitle', { ns: 'plugin' })}</div>@@ -175,7 +169,7 @@ const ToolItem = ({aria-label={typeof errorTip === 'string' ? errorTip : t('detailPanel.toolSelector.unsupportedTitle', { ns: 'plugin' })}className="inline-flex border-0 bg-transparent p-0">- <RiErrorWarningFill className="size-4 text-text-destructive" />+ <span className="i-ri-error-warning-fill size-4 text-text-destructive" /></PopoverTrigger><PopoverContent popupClassName="px-3 py-2 system-xs-regular text-text-tertiary">{errorTip}diff --git a/web/app/components/plugins/plugin-item/index.tsx b/web/app/components/plugins/plugin-item/index.tsxindex c1748f77f97..8db022b5d30 100644--- a/web/app/components/plugins/plugin-item/index.tsx+++ b/web/app/components/plugins/plugin-item/index.tsx@@ -33,11 +33,15 @@ import { PluginSource } from '../types'import Action from './action'type Props = Readonly<{+ canManagePlugin?: boolean+ canUpdatePlugin?: booleanclassName?: stringplugin: PluginDetail}>const PluginItem: FC<Props> = ({+ canManagePlugin = true,+ canUpdatePlugin = true,className,plugin,}) => {@@ -152,9 +156,9 @@ const PluginItem: FC<Props> = ({author={author}pluginName={name}usedInApps={5}- isShowFetchNewVersion={source === PluginSource.github}+ isShowFetchNewVersion={canUpdatePlugin && source === PluginSource.github}isShowInfo={source === PluginSource.github}- isShowDelete+ isShowDelete={canManagePlugin}meta={meta}onDelete={handleDelete}category={category}diff --git a/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/index.spec.tsxindex a3b9c2266bf..3a74f455cb2 100644--- a/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx@@ -42,6 +42,8 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: true,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0' },+ workspacePermissionKeys: ['plugin.install', 'plugin.manage', 'plugin.debug', 'plugin.plugin_preferences'],}),}))diff --git a/web/app/components/plugins/plugin-page/__tests__/plugins-panel.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/plugins-panel.spec.tsxindex d30eab46e9e..f9bd4927969 100644--- a/web/app/components/plugins/plugin-page/__tests__/plugins-panel.spec.tsx+++ b/web/app/components/plugins/plugin-page/__tests__/plugins-panel.spec.tsx@@ -275,7 +275,7 @@ describe('PluginsPanel', () => {it('loads the scoped plugin category list whenever an integrations category panel mounts', () => {render(<PluginsPanel contentInset="compact" fixedCategory={PluginCategoryEnum.trigger} />)- expect(mockUseInstalledPluginList).toHaveBeenCalledWith(undefined, 100, {+ expect(mockUseInstalledPluginList).toHaveBeenCalledWith(false, 100, {category: PluginCategoryEnum.trigger,refetchOnMount: 'always',})@@ -285,7 +285,7 @@ describe('PluginsPanel', () => {render(<PluginsPanel contentInset="compact" fixedCategory={PluginCategoryEnum.tool} />)expect(screen.getByTestId('filter-management')).toHaveAttribute('data-hide-tag-filter', 'false')- expect(mockUseInstalledPluginList).toHaveBeenCalledWith(undefined, 100, {+ expect(mockUseInstalledPluginList).toHaveBeenCalledWith(false, 100, {category: PluginCategoryEnum.tool,refetchOnMount: 'always',})diff --git a/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts b/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.tsindex 639cf411791..aec8390ec15 100644--- a/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts+++ b/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts@@ -9,23 +9,15 @@ import { useInvalidateReferenceSettings, useMutationPluginPermissionSettings, usimport { PermissionType, PluginCategoryEnum } from '../../types'import useReferenceSetting, { useCanInstallPluginFromMarketplace } from '../use-reference-setting'-vi.mock('@/context/app-context', () => ({- useAppContext: vi.fn(),-}))+vi.mock('@/context/app-context', async () => {+ const actual = await vi.importActual('@/context/app-context')+ return {+ ...actual,+ useAppContext: vi.fn(),+ }+})vi.mock('@/service/use-plugins', () => ({- hasPluginPermission: vi.fn((permission: string | undefined, isAdmin: boolean) => {- if (!permission)- return false-- if (permission === 'noone')- return false-- if (permission === 'everyone')- return true-- return isAdmin- }),usePluginAutoUpgradeSettings: vi.fn(),usePluginPermissionSettings: vi.fn(),useMutationPluginPermissionSettings: vi.fn(),@@ -44,6 +36,8 @@ describe('useReferenceSetting Hook', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [] as string[],} as ReturnType<typeof useAppContext>)vi.mocked(usePluginAutoUpgradeSettings).mockReturnValue({@@ -79,8 +73,8 @@ describe('useReferenceSetting Hook', () => {vi.mocked(useInvalidateReferenceSettings).mockReturnValue(vi.fn())})- describe('hasPermission logic', () => {- it('should return false when permission is undefined', () => {+ describe('permission key access', () => {+ it('should return false without plugin permission keys', () => {vi.mocked(usePluginPermissionSettings).mockReturnValue({data: {install_permission: undefined,@@ -94,7 +88,7 @@ describe('useReferenceSetting Hook', () => {expect(result.current.canDebugger).toBe(false)})- it('should return false when permission is noOne', () => {+ it('should ignore legacy noOne permission when plugin keys are missing', () => {vi.mocked(usePluginPermissionSettings).mockReturnValue({data: {install_permission: PermissionType.noOne,@@ -108,7 +102,13 @@ describe('useReferenceSetting Hook', () => {expect(result.current.canDebugger).toBe(false)})- it('should return true when permission is everyone', () => {+ it('should allow install and debug when plugin permission keys are present', () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceManager: false,+ isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: ['plugin.install', 'plugin.debug'],+ } as ReturnType<typeof useAppContext>)vi.mocked(usePluginPermissionSettings).mockReturnValue({data: {install_permission: PermissionType.everyone,@@ -122,10 +122,12 @@ describe('useReferenceSetting Hook', () => {expect(result.current.canDebugger).toBe(true)})- it('should return isAdmin when permission is admin and user is manager', () => {+ it('should ignore legacy admin permission for managers without plugin keys', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceManager: true,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [] as string[],} as ReturnType<typeof useAppContext>)vi.mocked(usePluginPermissionSettings).mockReturnValue({@@ -137,14 +139,16 @@ describe('useReferenceSetting Hook', () => {const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool))- expect(result.current.canManagement).toBe(true)- expect(result.current.canDebugger).toBe(true)+ expect(result.current.canManagement).toBe(false)+ expect(result.current.canDebugger).toBe(false)})- it('should return isAdmin when permission is admin and user is owner', () => {+ it('should ignore legacy admin permission for owners without plugin keys', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: true,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [] as string[],} as ReturnType<typeof useAppContext>)vi.mocked(usePluginPermissionSettings).mockReturnValue({@@ -156,14 +160,16 @@ describe('useReferenceSetting Hook', () => {const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool))- expect(result.current.canManagement).toBe(true)- expect(result.current.canDebugger).toBe(true)+ expect(result.current.canManagement).toBe(false)+ expect(result.current.canDebugger).toBe(false)})- it('should return false when permission is admin and user is not admin', () => {+ it('should use plugin keys even when legacy admin permission is configured', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: ['plugin.install', 'plugin.debug'],} as ReturnType<typeof useAppContext>)vi.mocked(usePluginPermissionSettings).mockReturnValue({@@ -175,16 +181,18 @@ describe('useReferenceSetting Hook', () => {const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool))- expect(result.current.canManagement).toBe(false)- expect(result.current.canDebugger).toBe(false)+ expect(result.current.canManagement).toBe(true)+ expect(result.current.canDebugger).toBe(true)})})describe('canSetPermissions', () => {- it('should be true when user is workspace manager', () => {+ it('should be true with plugin preferences permission when RBAC is disabled', () => {vi.mocked(useAppContext).mockReturnValue({- isCurrentWorkspaceManager: true,+ isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: ['plugin.plugin_preferences'],} as ReturnType<typeof useAppContext>)const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool))@@ -192,21 +200,28 @@ describe('useReferenceSetting Hook', () => {expect(result.current.canSetPermissions).toBe(true)})- it('should be true when user is workspace owner', () => {+ it('should be false when RBAC is enabled even with plugin preferences permission', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceManager: false,isCurrentWorkspaceOwner: true,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: ['plugin.plugin_preferences'],} as ReturnType<typeof useAppContext>)- const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool))+ const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool), {+ systemFeatures: { rbac_enabled: true },+ })- expect(result.current.canSetPermissions).toBe(true)+ expect(result.current.canSetPermissions).toBe(false)+ expect(result.current.canSetPluginPreferences).toBe(true)})- it('should be false when user is neither manager nor owner', () => {+ it('should be false without plugin preferences permission', () => {vi.mocked(useAppContext).mockReturnValue({- isCurrentWorkspaceManager: false,+ isCurrentWorkspaceManager: true,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [] as string[],} as ReturnType<typeof useAppContext>)const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool))@@ -280,7 +295,13 @@ describe('useReferenceSetting Hook', () => {expect(result.current.isUpdatePending).toBe(true)})- it('should keep permissions available when reference setting data is still loading', () => {+ it('should keep permission key access available when reference setting data is still loading', () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceManager: false,+ isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: ['plugin.install', 'plugin.debug'],+ } as ReturnType<typeof useAppContext>)vi.mocked(usePluginAutoUpgradeSettings).mockReturnValue({data: undefined,} as unknown as ReturnType<typeof usePluginAutoUpgradeSettings>)@@ -292,6 +313,65 @@ describe('useReferenceSetting Hook', () => {expect(result.current.canDebugger).toBe(true)})})++ describe('RBAC permissions', () => {+ it('should use workspace permission keys when RBAC is enabled', () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceManager: false,+ isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [+ 'plugin.install',+ 'plugin.manage',+ 'plugin.debug',+ 'plugin.plugin_preferences',+ ],+ } as ReturnType<typeof useAppContext>)+ vi.mocked(usePluginPermissionSettings).mockReturnValue({+ data: {+ install_permission: PermissionType.noOne,+ debug_permission: PermissionType.noOne,+ },+ } as ReturnType<typeof usePluginPermissionSettings>)++ const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool), {+ systemFeatures: { rbac_enabled: true },+ })++ expect(result.current.canInstallPlugin).toBe(true)+ expect(result.current.canManagement).toBe(true)+ expect(result.current.canUpdatePlugin).toBe(true)+ expect(result.current.canViewInstalledPlugins).toBe(true)+ expect(result.current.canManagePlugin).toBe(true)+ expect(result.current.canDebugPlugin).toBe(true)+ expect(result.current.canDebugger).toBe(true)+ expect(result.current.canSetPermissions).toBe(false)+ expect(result.current.canSetPluginPreferences).toBe(true)+ })++ it('should ignore legacy plugin permission settings when RBAC is enabled', () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceManager: true,+ isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [] as string[],+ } as ReturnType<typeof useAppContext>)++ const { result } = renderHook(() => useReferenceSetting(PluginCategoryEnum.tool), {+ systemFeatures: { rbac_enabled: true },+ })++ expect(result.current.canInstallPlugin).toBe(false)+ expect(result.current.canManagement).toBe(false)+ expect(result.current.canUpdatePlugin).toBe(false)+ expect(result.current.canViewInstalledPlugins).toBe(false)+ expect(result.current.canManagePlugin).toBe(false)+ expect(result.current.canDebugPlugin).toBe(false)+ expect(result.current.canDebugger).toBe(false)+ expect(result.current.canSetPermissions).toBe(false)+ expect(result.current.canSetPluginPreferences).toBe(false)+ })+ })})describe('useCanInstallPluginFromMarketplace Hook', () => {@@ -301,6 +381,8 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {vi.mocked(useAppContext).mockReturnValue({isCurrentWorkspaceManager: true,isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: ['plugin.install'],} as ReturnType<typeof useAppContext>)vi.mocked(usePluginPermissionSettings).mockReturnValue({@@ -318,7 +400,7 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {vi.mocked(useInvalidateReferenceSettings).mockReturnValue(vi.fn())})- it('should return true when marketplace is enabled and canManagement is true', () => {+ it('should return true when marketplace is enabled and plugin.install is available', () => {const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {systemFeatures: { enable_marketplace: true },})@@ -334,13 +416,13 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {expect(result.current.canInstallPluginFromMarketplace).toBe(false)})- it('should return false when canManagement is false', () => {- vi.mocked(usePluginPermissionSettings).mockReturnValue({- data: {- install_permission: PermissionType.noOne,- debug_permission: PermissionType.noOne,- },- } as ReturnType<typeof usePluginPermissionSettings>)+ it('should return false without plugin.install', () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceManager: true,+ isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [] as string[],+ } as ReturnType<typeof useAppContext>)const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {systemFeatures: { enable_marketplace: true },@@ -349,13 +431,13 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {expect(result.current.canInstallPluginFromMarketplace).toBe(false)})- it('should return false when both marketplace is disabled and canManagement is false', () => {- vi.mocked(usePluginPermissionSettings).mockReturnValue({- data: {- install_permission: PermissionType.noOne,- debug_permission: PermissionType.noOne,- },- } as ReturnType<typeof usePluginPermissionSettings>)+ it('should return false when both marketplace is disabled and plugin.install is missing', () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceManager: true,+ isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: [] as string[],+ } as ReturnType<typeof useAppContext>)const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {systemFeatures: { enable_marketplace: false },@@ -364,12 +446,36 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {expect(result.current.canInstallPluginFromMarketplace).toBe(false)})- it('should only read plugin permissions and not fetch category auto-upgrade settings', () => {+ it('should not fetch legacy plugin permissions or category auto-upgrade settings', () => {renderHook(() => useCanInstallPluginFromMarketplace(), {systemFeatures: { enable_marketplace: true },})- expect(usePluginPermissionSettings).toHaveBeenCalled()+ expect(usePluginPermissionSettings).not.toHaveBeenCalled()expect(usePluginAutoUpgradeSettings).not.toHaveBeenCalled()})++ it('should use plugin.install when marketplace and RBAC are enabled', () => {+ vi.mocked(useAppContext).mockReturnValue({+ isCurrentWorkspaceManager: false,+ isCurrentWorkspaceOwner: false,+ langGeniusVersionInfo: { current_version: '1.0.0', latest_version: '', version: '' },+ workspacePermissionKeys: ['plugin.install'],+ } as ReturnType<typeof useAppContext>)+ vi.mocked(usePluginPermissionSettings).mockReturnValue({+ data: {+ install_permission: PermissionType.noOne,+ debug_permission: PermissionType.noOne,+ },+ } as ReturnType<typeof usePluginPermissionSettings>)++ const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {+ systemFeatures: {+ enable_marketplace: true,+ rbac_enabled: true,+ },+ })++ expect(result.current.canInstallPluginFromMarketplace).toBe(true)+ })})diff --git a/web/app/components/plugins/plugin-page/index.tsx b/web/app/components/plugins/plugin-page/index.tsxindex e6348fbd1fb..914ed72efb0 100644--- a/web/app/components/plugins/plugin-page/index.tsx+++ b/web/app/components/plugins/plugin-page/index.tsx@@ -14,7 +14,7 @@ import {import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import { noop } from 'es-toolkit/function'-import { useEffect, useMemo, useState } from 'react'+import { cloneElement, isValidElement, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import TabSlider from '@/app/components/base/tab-slider'import ReferenceSettingModal from '@/app/components/plugins/reference-setting-modal'@@ -27,6 +27,7 @@ import Link from '@/next/link'import { fetchBundleInfoFromMarketPlace, fetchManifestFromMarketPlace } from '@/service/plugins'import { sleep } from '@/utils'import { PLUGIN_PAGE_TABS_MAP } from '../hooks'+import { PluginInstallPermissionProvider } from '../install-plugin/components/plugin-install-permission-provider'import InstallFromLocalPackage from '../install-plugin/install-from-local-package'import InstallFromMarketplace from '../install-plugin/install-from-marketplace'import { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/constants'@@ -53,6 +54,12 @@ export type PluginPageProps = {plugins: React.ReactNodemarketplace: React.ReactNode}+type PluginPanelPermissionProps = {+ canInstall?: boolean+ canManagePlugin?: boolean+ canUpdatePlugin?: boolean+ canViewInstalledPlugins?: boolean+}const PluginPage = ({plugins,marketplace,@@ -78,10 +85,32 @@ const PluginPage = ({const [manifest, setManifest] = useState<PluginDeclaration | PluginManifestInMarket | null>(null)+ const {+ referenceSetting,+ canInstallPlugin,+ canUpdatePlugin,+ canViewInstalledPlugins,+ canManagePlugin,+ canDebugger,+ canSetPermissions,+ canSetPluginPreferences,+ currentDifyVersion,+ isPermissionLoading,+ isReferenceSettingLoading,+ setReferenceSettings,+ } = useReferenceSetting(PluginCategoryEnum.tool)+useEffect(() => {(async () => {setUniqueIdentifier(null)await sleep(100)+ if (isPermissionLoading)+ return++ if (!canInstallPlugin) {+ setInstallState(null)+ return+ }if (packageId) {const { data } = await fetchManifestFromMarketPlace(encodeURIComponent(packageId))const { plugin, version } = data@@ -105,17 +134,7 @@ const PluginPage = ({}}})()- }, [packageId, bundleInfo, showInstallFromMarketplace])-- const {- referenceSetting,- canManagement,- canDebugger,- canSetPermissions,- isPermissionLoading,- isReferenceSettingLoading,- setReferenceSettings,- } = useReferenceSetting(PluginCategoryEnum.tool)+ }, [packageId, bundleInfo, canInstallPlugin, isPermissionLoading, setInstallState, showInstallFromMarketplace])const [showPluginSettingModal, {setTrue: setShowPluginSettingModal,setFalse: setHidePluginSettingModal,@@ -140,6 +159,11 @@ const PluginPage = ({: t('metadata.title', { ns: 'plugin' }))const handleFileChange = (file: File | null) => {+ if (!canInstallPlugin) {+ setCurrentFile(null)+ return+ }+if (!file || !file.name.endsWith('.difypkg')) {setCurrentFile(null)return@@ -150,10 +174,22 @@ const PluginPage = ({const uploaderProps = useUploader({onFileChange: handleFileChange,containerRef,- enabled: isPluginsTab && canManagement,+ enabled: isPluginsTab && canInstallPlugin,})const { dragging, fileUploader, fileChangeHandle, removeFile } = uploaderProps+ const pluginsWithPermission = useMemo(() => {+ if (!isValidElement(plugins) || typeof plugins.type === 'string')+ return plugins++ return cloneElement(plugins as React.ReactElement<PluginPanelPermissionProps>, {+ canInstall: canInstallPlugin,+ canManagePlugin,+ canUpdatePlugin,+ canViewInstalledPlugins,+ })+ }, [canInstallPlugin, canManagePlugin, canUpdatePlugin, canViewInstalledPlugins, plugins])+return (<divid="marketplace-container"@@ -212,9 +248,9 @@ const PluginPage = ({)}<PluginTasks />- {(canManagement || isPermissionLoading) && (+ {(canInstallPlugin || isPermissionLoading) && (<InstallPluginDropdown- disabled={isPermissionLoading || !canManagement}+ disabled={isPermissionLoading || !canInstallPlugin}onSwitchToMarketplaceTab={() => setActiveTab('discover')}/>)}@@ -233,7 +269,7 @@ const PluginPage = ({</Button>)}{- canSetPermissions && (+ (canSetPermissions || canSetPluginPreferences) && (<Tooltip><TooltipTriggerrender={(@@ -259,7 +295,13 @@ const PluginPage = ({</div>{isPluginsTab && (<>- {plugins}+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ canUpdatePlugin={canUpdatePlugin}+ currentDifyVersion={currentDifyVersion}+ >+ {pluginsWithPermission}+ </PluginInstallPermissionProvider>{dragging && (<divclassName="absolute inset-0 m-0.5 rounded-2xl border-2 border-dashed border-components-dropzone-border-accent@@ -267,10 +309,12 @@ const PluginPage = ({></div>)}- <div className={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}>- <RiDragDropLine className="size-4" />- <span className="system-xs-regular">{t('installModal.dropPluginToInstall', { ns: 'plugin' })}</span>- </div>+ {canInstallPlugin && (+ <div className={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}>+ <RiDragDropLine className="size-4" />+ <span className="system-xs-regular">{t('installModal.dropPluginToInstall', { ns: 'plugin' })}</span>+ </div>+ )}{currentFile && (<InstallFromLocalPackagefile={currentFile}@@ -289,12 +333,22 @@ const PluginPage = ({</>)}{- isExploringMarketplace && enable_marketplace && marketplace+ isExploringMarketplace && enable_marketplace && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ canUpdatePlugin={canUpdatePlugin}+ currentDifyVersion={currentDifyVersion}+ >+ {marketplace}+ </PluginInstallPermissionProvider>+ )}{showPluginSettingModal && referenceSetting && (<ReferenceSettingModalpayload={referenceSetting}+ canSetPermissions={canSetPermissions}+ canSetAutoUpdate={canSetPluginPreferences}onHide={setHidePluginSettingModal}onSave={setReferenceSettings}/>diff --git a/web/app/components/plugins/plugin-page/list/index.tsx b/web/app/components/plugins/plugin-page/list/index.tsxindex b4cf4db76cf..2d7595f29b3 100644--- a/web/app/components/plugins/plugin-page/list/index.tsx+++ b/web/app/components/plugins/plugin-page/list/index.tsx@@ -3,11 +3,18 @@ import type { PluginDetail } from '../../types'import PluginItem from '../../plugin-item'type IPluginListProps = {+ canManagePlugin?: boolean+ canUpdatePlugin?: booleanchildren?: ReactNodepluginList: PluginDetail[]}-const PluginList: FC<IPluginListProps> = ({ children, pluginList }) => {+const PluginList: FC<IPluginListProps> = ({+ canManagePlugin = true,+ canUpdatePlugin = true,+ children,+ pluginList,+}) => {return (<div className="pb-3"><div className="grid grid-cols-1 gap-3 lg:grid-cols-2">@@ -15,6 +22,8 @@ const PluginList: FC<IPluginListProps> = ({ children, pluginList }) => {<PluginItemkey={plugin.plugin_id}plugin={plugin}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}/>))}{children}diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/error-plugin-item.spec.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/error-plugin-item.spec.tsxindex fcae8d67169..9d705185535 100644--- a/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/error-plugin-item.spec.tsx+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/error-plugin-item.spec.tsx@@ -24,6 +24,13 @@ vi.mock('@/service/plugins', () => ({fetchPluginInfoFromMarketPlace: vi.fn(),}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission', () => ({+ default: () => ({+ canInstallPlugin: true,+ currentDifyVersion: '1.0.0',+ }),+}))+const mockFetch = vi.mocked(fetchPluginInfoFromMarketPlace)const mockGetIconUrl = vi.fn((icon: string) => `https://icons/${icon}`)diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/error-plugin-item.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/error-plugin-item.tsxindex 5489db495a0..83fc9995dce 100644--- a/web/app/components/plugins/plugin-page/plugin-tasks/components/error-plugin-item.tsx+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/error-plugin-item.tsx@@ -4,6 +4,8 @@ import type { Locale } from '@/i18n-config'import { Button } from '@langgenius/dify-ui/button'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'+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 { PluginSource } from '@/app/components/plugins/types'import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'@@ -22,6 +24,7 @@ const ErrorPluginItem: FC<ErrorPluginItemProps> = ({ plugin, getIconUrl, languagconst [showInstallModal, setShowInstallModal] = useState(false)const [installPayload, setInstallPayload] = useState<{ uniqueIdentifier: string, manifest: Plugin } | null>(null)const [isFetching, setIsFetching] = useState(false)+ const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()const handleInstallFromMarketplace = useCallback(async () => {const parts = plugin.plugin_id.split('/')@@ -75,7 +78,7 @@ const ErrorPluginItem: FC<ErrorPluginItemProps> = ({ plugin, getIconUrl, languagconst errorMsg = t(errorMsgKey, { ns: 'plugin' })const renderAction = () => {- if (source === PluginSource.marketplace) {+ if (source === PluginSource.marketplace && canInstallPlugin) {return (<div className="pt-1"><Button variant="secondary" size="small" loading={isFetching} onClick={handleInstallFromMarketplace}>@@ -84,7 +87,7 @@ const ErrorPluginItem: FC<ErrorPluginItemProps> = ({ plugin, getIconUrl, languag</div>)}- if (source === PluginSource.github) {+ if (source === PluginSource.github && canInstallPlugin) {return (<div className="pt-1"><Button variant="secondary" size="small">@@ -116,16 +119,21 @@ const ErrorPluginItem: FC<ErrorPluginItemProps> = ({ plugin, getIconUrl, languagaction={renderAction()}onClear={onClear}/>- {showInstallModal && installPayload && (- <InstallFromMarketplace- uniqueIdentifier={installPayload.uniqueIdentifier}- manifest={installPayload.manifest}- onClose={() => setShowInstallModal(false)}- onSuccess={() => {- setShowInstallModal(false)- onClear()- }}- />+ {showInstallModal && installPayload && canInstallPlugin && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ currentDifyVersion={currentDifyVersion}+ >+ <InstallFromMarketplace+ uniqueIdentifier={installPayload.uniqueIdentifier}+ manifest={installPayload.manifest}+ onClose={() => setShowInstallModal(false)}+ onSuccess={() => {+ setShowInstallModal(false)+ onClear()+ }}+ />+ </PluginInstallPermissionProvider>)}</>)diff --git a/web/app/components/plugins/plugin-page/plugins-panel-results.tsx b/web/app/components/plugins/plugin-page/plugins-panel-results.tsxindex cd81024fd4c..ce84b37f933 100644--- a/web/app/components/plugins/plugin-page/plugins-panel-results.tsx+++ b/web/app/components/plugins/plugin-page/plugins-panel-results.tsx@@ -58,6 +58,8 @@ const BuiltinMarketplacePanel = ({}type PluginsPanelResultsProps = {+ canManagePlugin: boolean+ canUpdatePlugin: booleancontainerRef: RefObject<HTMLDivElement | null>contentFrameClassName: stringcontentInset: PluginPageContentInset@@ -78,6 +80,8 @@ type PluginsPanelResultsProps = {}const PluginsPanelResults = ({+ canManagePlugin,+ canUpdatePlugin,containerRef,contentFrameClassName,contentInset,@@ -117,7 +121,11 @@ const PluginsPanelResults = ({)}>{(hasVisiblePlugins || hasVisibleBuiltinTools) && (- <List pluginList={filteredList}>+ <List+ pluginList={filteredList}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}+ >{filteredBuiltinTools.map(collection => (<buttonkey={collection.id}diff --git a/web/app/components/plugins/plugin-page/plugins-panel.tsx b/web/app/components/plugins/plugin-page/plugins-panel.tsxindex 20ace911115..d1ccc4e36f0 100644--- a/web/app/components/plugins/plugin-page/plugins-panel.tsx+++ b/web/app/components/plugins/plugin-page/plugins-panel.tsx@@ -52,6 +52,9 @@ const matchesSearchQuery = (plugin: PluginDetail & { latest_version: string }, qtype PluginsPanelProps = {canInstall?: boolean+ canManagePlugin?: boolean+ canUpdatePlugin?: boolean+ canViewInstalledPlugins?: booleancontentInset?: PluginPageContentInsetfixedCategory?: PluginCategoryEnumlayout?: (parts: { body: ReactNode, toolbar: ReactNode }) => ReactNode@@ -61,6 +64,9 @@ type PluginsPanelProps = {const PluginsPanel = ({canInstall = true,+ canManagePlugin = true,+ canUpdatePlugin = true,+ canViewInstalledPlugins = true,contentInset = 'default',fixedCategory,layout,@@ -82,7 +88,7 @@ const PluginsPanel = ({select: s => s.enable_marketplace,})const { data: pluginList, isLoading: isPluginListLoading, isFetching, isLastPage, loadNextPage } = useInstalledPluginList(- undefined,+ !canViewInstalledPlugins,100,fixedCategory? {@@ -217,6 +223,8 @@ const PluginsPanel = ({scrollAreaLabel={scrollAreaLabel}setCurrentBuiltinToolID={setCurrentBuiltinToolID}tagFilterValue={filters.tags}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}/>): isIntegrationCategorySearchEmpty@@ -251,6 +259,8 @@ const PluginsPanel = ({detail={currentPluginDetail}onUpdate={() => invalidateInstalledPluginList()}onHide={handleHide}+ canManagePlugin={canManagePlugin}+ canUpdatePlugin={canUpdatePlugin}/>{currentBuiltinTool && !currentBuiltinTool.plugin_id && (<ProviderDetaildiff --git a/web/app/components/plugins/plugin-page/use-reference-setting.ts b/web/app/components/plugins/plugin-page/use-reference-setting.tsindex 1c6258b29f8..0b779ccdd96 100644--- a/web/app/components/plugins/plugin-page/use-reference-setting.ts+++ b/web/app/components/plugins/plugin-page/use-reference-setting.ts@@ -5,19 +5,29 @@ import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useAppContext } from '@/context/app-context'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { hasPluginPermission, useInvalidateReferenceSettings, useMutationPluginPermissionSettings, useMutationReferenceSettings, usePluginAutoUpgradeSettings, usePluginPermissionSettings } from '@/service/use-plugins'+import { useInvalidateReferenceSettings, useMutationPluginPermissionSettings, useMutationReferenceSettings, usePluginAutoUpgradeSettings, usePluginPermissionSettings } from '@/service/use-plugins'+import { hasPermission } from '@/utils/permission'-export const useCanSetPluginSettings = () => {- const { isCurrentWorkspaceManager, isCurrentWorkspaceOwner } = useAppContext()+const pluginReadAndUpdatePermissionKeys = ['plugin.install', 'plugin.manage']++const useCanSetPluginSettings = () => {+ const { workspacePermissionKeys } = useAppContext()+ const { data: rbacEnabled } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: s => s.rbac_enabled,+ })+ const canSetPluginPreferences = hasPermission(workspacePermissionKeys, 'plugin.plugin_preferences')return {- canSetPermissions: isCurrentWorkspaceManager || isCurrentWorkspaceOwner,+ canSetPermissions: !rbacEnabled && canSetPluginPreferences,+ canSetPluginPreferences,}}export const usePluginSettingsAccess = () => {const { t } = useTranslation()- const { canSetPermissions } = useCanSetPluginSettings()+ const { workspacePermissionKeys, langGeniusVersionInfo } = useAppContext()+ const { canSetPermissions, canSetPluginPreferences } = useCanSetPluginSettings()const permissionQuery = usePluginPermissionSettings()const { data: permissions } = permissionQueryconst { mutate: setPluginPermissionSettings, isPending: isPermissionUpdatePending } = useMutationPluginPermissionSettings({@@ -25,13 +35,25 @@ export const usePluginSettingsAccess = () => {toast.success(t('api.actionSuccess', { ns: 'common' }))},})+ const canInstallPlugin = hasPermission(workspacePermissionKeys, 'plugin.install')+ const canUpdatePlugin = hasPermission(workspacePermissionKeys, pluginReadAndUpdatePermissionKeys)+ const canViewInstalledPlugins = hasPermission(workspacePermissionKeys, pluginReadAndUpdatePermissionKeys)+ const canManagePlugin = hasPermission(workspacePermissionKeys, 'plugin.manage')+ const canDebugPlugin = hasPermission(workspacePermissionKeys, 'plugin.debug')return {permission: permissions,setPluginPermissionSettings,- canManagement: hasPluginPermission(permissions?.install_permission, canSetPermissions),- canDebugger: hasPluginPermission(permissions?.debug_permission, canSetPermissions),+ canInstallPlugin,+ canUpdatePlugin,+ canViewInstalledPlugins,+ canManagePlugin,+ canDebugPlugin,+ canSetPluginPreferences,+ canManagement: canInstallPlugin,+ canDebugger: canDebugPlugin,canSetPermissions,+ currentDifyVersion: langGeniusVersionInfo?.current_version,isPermissionLoading: permissionQuery.isLoading || permissionQuery.isFetching,permissionError: permissionQuery.error,isPermissionUpdatePending,@@ -63,7 +85,14 @@ const useReferenceSetting = (category: PluginCategoryEnum) => {setReferenceSettings: updateReferenceSetting,canManagement: permissionAccess.canManagement,canDebugger: permissionAccess.canDebugger,+ canInstallPlugin: permissionAccess.canInstallPlugin,+ canUpdatePlugin: permissionAccess.canUpdatePlugin,+ canViewInstalledPlugins: permissionAccess.canViewInstalledPlugins,+ canManagePlugin: permissionAccess.canManagePlugin,+ canDebugPlugin: permissionAccess.canDebugPlugin,canSetPermissions: permissionAccess.canSetPermissions,+ canSetPluginPreferences: permissionAccess.canSetPluginPreferences,+ currentDifyVersion: permissionAccess.currentDifyVersion,isPermissionLoading: permissionAccess.isPermissionLoading,permissionError: permissionAccess.permissionError,isReferenceSettingLoading: autoUpgradeQuery.isLoading || autoUpgradeQuery.isFetching,@@ -73,20 +102,16 @@ const useReferenceSetting = (category: PluginCategoryEnum) => {}export const useCanInstallPluginFromMarketplace = () => {- const { data: enable_marketplace } = useSuspenseQuery({+ const { data: marketplaceAccess } = useSuspenseQuery({...systemFeaturesQueryOptions(),select: s => s.enable_marketplace,})- const { isCurrentWorkspaceManager, isCurrentWorkspaceOwner } = useAppContext()- const { data: permissions } = usePluginPermissionSettings()- const canManagement = hasPluginPermission(- permissions?.install_permission,- isCurrentWorkspaceManager || isCurrentWorkspaceOwner,- )+ const { workspacePermissionKeys } = useAppContext()+ const canInstallPlugin = hasPermission(workspacePermissionKeys, 'plugin.install')const canInstallPluginFromMarketplace = useMemo(() => {- return enable_marketplace && canManagement- }, [enable_marketplace, canManagement])+ return Boolean(marketplaceAccess && canInstallPlugin)+ }, [marketplaceAccess, canInstallPlugin])return {canInstallPluginFromMarketplace,diff --git a/web/app/components/plugins/provider-card.tsx b/web/app/components/plugins/provider-card.tsxindex 710a748a853..86e18f126ac 100644--- a/web/app/components/plugins/provider-card.tsx+++ b/web/app/components/plugins/provider-card.tsx@@ -3,12 +3,12 @@ import type { FC } from 'react'import type { Plugin } from './types'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'-import { RiArrowRightUpLine } from '@remixicon/react'import { useBoolean } from 'ahooks'import { useTheme } from 'next-themes'import * as React from 'react'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'+import usePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission'import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'import { getPluginLinkInMarketplace } from '@/app/components/plugins/marketplace/utils'import { useLocale } from '@/context/i18n'@@ -35,6 +35,7 @@ const ProviderCardComponent: FC<Props> = ({setTrue: showInstallFromMarketplace,setFalse: hideInstallFromMarketplace,}] = useBoolean(false)+ const { canInstallPlugin } = usePluginInstallPermission()const { org, label } = payloadconst locale = useLocale()@@ -69,20 +70,22 @@ const ProviderCardComponent: FC<Props> = ({<divclassName="absolute inset-x-0 bottom-0 hidden items-center gap-2 rounded-xl bg-linear-to-tr from-components-panel-on-panel-item-bg to-background-gradient-mask-transparent p-4 pt-4 group-hover:flex">- <Button- className="grow"- variant="primary"- onClick={showInstallFromMarketplace}- >- {t('detailPanel.operation.install', { ns: 'plugin' })}- </Button>+ {canInstallPlugin && (+ <Button+ className="grow"+ variant="primary"+ onClick={showInstallFromMarketplace}+ >+ {t('detailPanel.operation.install', { ns: 'plugin' })}+ </Button>+ )}<ButtonclassName="grow"variant="secondary"><a href={getPluginLinkInMarketplace(payload, marketplaceLinkParams)} target="_blank" className="flex items-center gap-0.5">{t('detailPanel.operation.detail', { ns: 'plugin' })}- <RiArrowRightUpLine className="size-4" />+ <span className="i-ri-arrow-right-up-line size-4" /></a></Button></div>diff --git a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsxindex 22060d4431c..74ff07e9102 100644--- a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx+++ b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx@@ -9,7 +9,10 @@ import { PermissionType } from '@/app/components/plugins/types'import { AUTO_UPDATE_MODE, AUTO_UPDATE_STRATEGY } from '../auto-update-setting/types'import ReferenceSettingModal from '../index'-const mockSystemFeatures = { enable_marketplace: true }+const mockSystemFeatures = {+ enable_marketplace: true,+ rbac_enabled: false,+}const render = (ui: ReactElement) =>renderWithSystemFeatures(ui, { systemFeatures: mockSystemFeatures })@@ -37,19 +40,26 @@ vi.mock('@langgenius/dify-ui/dialog', () => ({// Mock OptionCard componentvi.mock('@/app/components/workflow/nodes/_base/components/option-card', () => ({- default: ({ title, onSelect, selected, className }: {+ default: ({ title, onSelect, selected, className, disabled, tooltip }: {title: stringonSelect: () => voidselected: booleanclassName?: string+ disabled?: boolean+ tooltip?: string}) => (<buttondata-testid={`option-card-${title.toLowerCase().replace(/\s+/g, '-')}`}- onClick={onSelect}+ onClick={() => {+ if (!disabled)+ onSelect()+ }}aria-pressed={selected}+ disabled={disabled}className={className}>{title}+ {tooltip && <span>{tooltip}</span>}</button>),}))@@ -113,6 +123,7 @@ describe('reference-setting-modal', () => {beforeEach(() => {vi.clearAllMocks()mockSystemFeatures.enable_marketplace = true+ mockSystemFeatures.rbac_enabled = false})// Label component tests moved to label.spec.tsx@@ -123,6 +134,8 @@ describe('reference-setting-modal', () => {describe('ReferenceSettingModal (index.tsx)', () => {const defaultProps = {payload: createMockReferenceSetting(),+ canSetPermissions: true,+ canSetAutoUpdate: true,onHide: vi.fn(),onSave: vi.fn(),}@@ -227,6 +240,19 @@ describe('reference-setting-modal', () => {expect(screen.queryByTestId('auto-update-setting')).not.toBeInTheDocument()})+ it('should hide permission controls when permission editing is disabled', () => {+ render(<ReferenceSettingModal {...defaultProps} canSetPermissions={false} />)++ expect(screen.queryByText('plugin.privilege.whoCanInstall')).not.toBeInTheDocument()+ expect(screen.queryByText('plugin.privilege.whoCanDebug')).not.toBeInTheDocument()+ })++ it('should hide AutoUpdateSetting when auto update editing is disabled', () => {+ render(<ReferenceSettingModal {...defaultProps} canSetAutoUpdate={false} />)++ expect(screen.queryByTestId('auto-update-setting')).not.toBeInTheDocument()+ })+it('should render modal with closable attribute', () => {// Arrange & Actrender(<ReferenceSettingModal {...defaultProps} />)@@ -235,6 +261,16 @@ describe('reference-setting-modal', () => {// Assertexpect(screen.getByTestId('modal-close'))!.toBeInTheDocument()})++ it('should disable permission controls with settings permissions tooltip beside titles when RBAC is enabled', () => {+ mockSystemFeatures.rbac_enabled = true++ render(<ReferenceSettingModal {...defaultProps} />)++ expect(screen.getAllByLabelText('plugin.privilege.configurePermissionsInSettings')).toHaveLength(2)+ expect(screen.queryByText('plugin.privilege.configurePermissionsInSettings')).not.toBeInTheDocument()+ expect(screen.getAllByTestId(/option-card/).every(option => option.hasAttribute('disabled'))).toBe(true)+ })})describe('State Management', () => {@@ -272,6 +308,16 @@ describe('reference-setting-modal', () => {expect(noOneOptions[0])!.toHaveAttribute('aria-pressed', 'true')})+ it('should not update permission when RBAC disables permission controls', () => {+ mockSystemFeatures.rbac_enabled = true+ render(<ReferenceSettingModal {...defaultProps} />)++ const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')+ fireEvent.click(noOneOptions[0]!)++ expect(noOneOptions[0])!.toHaveAttribute('aria-pressed', 'false')+ })+it('should initialize with payload auto_upgrade values', () => {// Arrangeconst payload = createMockReferenceSetting({@@ -411,6 +457,66 @@ describe('reference-setting-modal', () => {}))})})++ it('should preserve permission values when permission editing is disabled', async () => {+ const onSave = vi.fn().mockResolvedValue(undefined)+ const payload = createMockReferenceSetting({+ permission: {+ install_permission: PermissionType.admin,+ debug_permission: PermissionType.noOne,+ },+ })++ render(+ <ReferenceSettingModal+ {...defaultProps}+ payload={payload}+ canSetPermissions={false}+ onSave={onSave}+ />,+ )+ fireEvent.click(screen.getByTestId('auto-update-change'))+ fireEvent.click(screen.getByText('common.operation.save'))++ await waitFor(() => {+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({+ permission: payload.permission,+ auto_upgrade: expect.objectContaining({+ strategy_setting: AUTO_UPDATE_STRATEGY.latest,+ }),+ }))+ })+ })++ it('should preserve auto update values when auto update editing is disabled', async () => {+ const onSave = vi.fn().mockResolvedValue(undefined)+ const payload = createMockReferenceSetting({+ auto_upgrade: createMockAutoUpdateConfig({+ strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,+ }),+ })++ render(+ <ReferenceSettingModal+ {...defaultProps}+ payload={payload}+ canSetAutoUpdate={false}+ onSave={onSave}+ />,+ )+ const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')+ fireEvent.click(noOneOptions[0]!)+ fireEvent.click(screen.getByText('common.operation.save'))++ await waitFor(() => {+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({+ permission: expect.objectContaining({+ install_permission: PermissionType.noOne,+ }),+ auto_upgrade: payload.auto_upgrade,+ }))+ })+ })})describe('Callback Stability and Memoization', () => {@@ -727,7 +833,7 @@ describe('reference-setting-modal', () => {// Assertconst modal = screen.getByTestId('modal')- expect(modal)!.toHaveClass('w-[620px]', 'max-w-[620px]', 'p-0!')+ expect(modal)!.toHaveClass('w-155', 'max-w-155', 'p-0!')})it('should pass isShow=true to Modal', () => {@@ -801,6 +907,8 @@ describe('reference-setting-modal', () => {render(<ReferenceSettingModalpayload={initialPayload}+ canSetPermissions+ canSetAutoUpdateonHide={onHide}onSave={onSave}/>,@@ -845,6 +953,8 @@ describe('reference-setting-modal', () => {render(<ReferenceSettingModalpayload={initialPayload}+ canSetPermissions+ canSetAutoUpdateonHide={onHide}onSave={onSave}/>,@@ -866,6 +976,8 @@ describe('reference-setting-modal', () => {// Arrangeconst props = {payload: createMockReferenceSetting(),+ canSetPermissions: true,+ canSetAutoUpdate: true,onHide: vi.fn(),onSave: vi.fn(),}diff --git a/web/app/components/plugins/reference-setting-modal/index.tsx b/web/app/components/plugins/reference-setting-modal/index.tsxindex eaa97f7043e..451f0e45e3e 100644--- a/web/app/components/plugins/reference-setting-modal/index.tsx+++ b/web/app/components/plugins/reference-setting-modal/index.tsx@@ -26,12 +26,16 @@ const autoUpdateDefaultValue: AutoUpdateConfig = {type Props = Readonly<{payload: ReferenceSetting+ canSetPermissions?: boolean+ canSetAutoUpdate?: booleanonHide: () => voidonSave: (payload: ReferenceSetting) => void}>const PluginSettingModal: FC<Props> = ({payload,+ canSetPermissions = false,+ canSetAutoUpdate = false,onHide,onSave,}) => {@@ -39,26 +43,27 @@ const PluginSettingModal: FC<Props> = ({const { auto_upgrade: autoUpdateConfig, permission: privilege } = payload || {}const [tempPrivilege, setTempPrivilege] = useState<Permissions>(privilege)const [tempAutoUpdateConfig, setTempAutoUpdateConfig] = useState<AutoUpdateConfig>(autoUpdateConfig || autoUpdateDefaultValue)- const { data: enable_marketplace } = useSuspenseQuery({- ...systemFeaturesQueryOptions(),- select: s => s.enable_marketplace,- })+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const isPermissionDisabledByRBAC = systemFeatures.rbac_enabled+ const permissionDisabledTip = t(`${i18nPrefix}.configurePermissionsInSettings`, { ns: 'plugin' })const handlePrivilegeChange = useCallback((key: string) => {return (value: PermissionType) => {+ if (isPermissionDisabledByRBAC)+ returnsetTempPrivilege({...tempPrivilege,[key]: value,})}- }, [tempPrivilege])+ }, [isPermissionDisabledByRBAC, tempPrivilege])const handleSave = useCallback(async () => {await onSave({- permission: tempPrivilege,- auto_upgrade: tempAutoUpdateConfig,+ permission: canSetPermissions ? tempPrivilege : (privilege || tempPrivilege),+ auto_upgrade: canSetAutoUpdate ? tempAutoUpdateConfig : (autoUpdateConfig || tempAutoUpdateConfig),})onHide()- }, [onHide, onSave, tempAutoUpdateConfig, tempPrivilege])+ }, [autoUpdateConfig, canSetAutoUpdate, canSetPermissions, onHide, onSave, privilege, tempAutoUpdateConfig, tempPrivilege])return (<Dialog@@ -68,48 +73,54 @@ const PluginSettingModal: FC<Props> = ({onHide()}}>- <DialogContent className="w-[620px] max-w-[620px] overflow-hidden! border-none p-0! text-left align-middle">+ <DialogContent className="w-155 max-w-155 overflow-hidden! border-none p-0! text-left align-middle"><DialogCloseButton /><div className="shadows-shadow-xl flex w-full flex-col items-start rounded-2xl border border-components-panel-border bg-components-panel-bg"><div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6"><span className="self-stretch title-2xl-semi-bold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'plugin' })}</span></div>- <div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">- {[- { title: t(`${i18nPrefix}.whoCanInstall`, { ns: 'plugin' }), key: 'install_permission', value: tempPrivilege?.install_permission || PermissionType.noOne },- { title: t(`${i18nPrefix}.whoCanDebug`, { ns: 'plugin' }), key: 'debug_permission', value: tempPrivilege?.debug_permission || PermissionType.noOne },- ].map(({ title, key, value }) => (- <div key={key} className="flex flex-col items-start gap-1 self-stretch">- <Label label={title} />- <div className="flex w-full items-start justify-between gap-2">- {[PermissionType.everyone, PermissionType.admin, PermissionType.noOne].map(option => (- <OptionCard- key={option}- title={t(`${i18nPrefix}.${option}`, { ns: 'plugin' })}- onSelect={() => handlePrivilegeChange(key)(option)}- selected={value === option}- className="flex-1"- />- ))}+ {canSetPermissions && (+ <div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">+ {[+ { title: t(`${i18nPrefix}.whoCanInstall`, { ns: 'plugin' }), key: 'install_permission', value: tempPrivilege?.install_permission || PermissionType.noOne },+ { title: t(`${i18nPrefix}.whoCanDebug`, { ns: 'plugin' }), key: 'debug_permission', value: tempPrivilege?.debug_permission || PermissionType.noOne },+ ].map(({ title, key, value }) => (+ <div key={key} className="flex flex-col items-start gap-1 self-stretch">+ <Label+ label={title}+ tooltip={isPermissionDisabledByRBAC ? permissionDisabledTip : undefined}+ />+ <div className="flex w-full items-start justify-between gap-2">+ {[PermissionType.everyone, PermissionType.admin, PermissionType.noOne].map(option => (+ <OptionCard+ key={option}+ title={t(`${i18nPrefix}.${option}`, { ns: 'plugin' })}+ onSelect={() => handlePrivilegeChange(key)(option)}+ selected={value === option}+ disabled={isPermissionDisabledByRBAC}+ className="flex-1"+ />+ ))}+ </div></div>- </div>- ))}- </div>+ ))}+ </div>+ )}{- enable_marketplace && (+ systemFeatures.enable_marketplace && canSetAutoUpdate && (<AutoUpdateSetting payload={tempAutoUpdateConfig} onChange={setTempAutoUpdateConfig} />)}- <div className="flex h-[76px] items-center justify-end gap-2 self-stretch p-6 pt-5">+ <div className="flex h-19 items-center justify-end gap-2 self-stretch p-6 pt-5"><Button- className="min-w-[72px]"+ className="min-w-18"onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button><Button- className="min-w-[72px]"+ className="min-w-18"variant="primary"onClick={handleSave}>diff --git a/web/app/components/plugins/reference-setting-modal/label.tsx b/web/app/components/plugins/reference-setting-modal/label.tsxindex fdc8965e2ec..4fc2415c346 100644--- a/web/app/components/plugins/reference-setting-modal/label.tsx+++ b/web/app/components/plugins/reference-setting-modal/label.tsx@@ -1,21 +1,41 @@'use client'import type { FC } from 'react'import { cn } from '@langgenius/dify-ui/cn'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import * as React from 'react'type Props = Readonly<{label: stringdescription?: string+ tooltip?: string}>const Label: FC<Props> = ({label,description,+ tooltip,}) => {+ const tooltipIcon = (+ <span+ aria-label={tooltip}+ className="ml-1 flex size-4 shrink-0 cursor-pointer items-center justify-center"+ >+ <span aria-hidden className="i-ri-question-line size-3.5 text-text-quaternary" />+ </span>+ )+return (<div><div className={cn('flex h-6 items-center', description && 'h-4')}><span className="system-sm-semibold text-text-secondary">{label}</span>+ {tooltip && (+ <Tooltip>+ <TooltipTrigger render={tooltipIcon} />+ <TooltipContent>+ {tooltip}+ </TooltipContent>+ </Tooltip>+ )}</div>{description && (<div className="mt-1 body-xs-regular text-text-tertiary">diff --git a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsxindex cb11e5baf44..489fe005380 100644--- a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx@@ -9,6 +9,24 @@ vi.mock('@/next/navigation', () => ({useParams: () => ({ datasetId: 'ds-123' }),}))+let mockDatasetDetailState = {+ dataset: {+ permission_keys: ['dataset.acl.edit'],+ maintainer: 'maintainer-id',+ },+}+vi.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContextWithSelector: (selector: (state: typeof mockDatasetDetailState) => unknown) => selector(mockDatasetDetailState),+}))++let mockAppContextState = {+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [] as string[],+}+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector(mockAppContextState),+}))+vi.mock('@/service/use-pipeline', () => ({useConvertDatasetToPipeline: () => ({mutateAsync: mockConvert,@@ -54,6 +72,16 @@ vi.mock('../screenshot', () => ({describe('Conversion', () => {beforeEach(() => {vi.clearAllMocks()+ mockDatasetDetailState = {+ dataset: {+ permission_keys: ['dataset.acl.edit'],+ maintainer: 'maintainer-id',+ },+ }+ mockAppContextState = {+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],+ }})afterEach(() => {@@ -74,6 +102,25 @@ describe('Conversion', () => {expect(screen.getByText('datasetPipeline.operations.convert')).toBeInTheDocument()})+ it('should disable convert button when dataset lacks edit ACL', () => {+ mockDatasetDetailState = {+ dataset: {+ permission_keys: ['dataset.acl.readonly'],+ maintainer: 'maintainer-id',+ },+ }++ render(<Conversion />)++ const convertButton = screen.getByRole('button', { name: 'datasetPipeline.operations.convert' })+ expect(convertButton).toBeDisabled()++ fireEvent.click(convertButton)++ expect(screen.queryByText('datasetPipeline.conversion.confirm.title')).not.toBeInTheDocument()+ expect(mockConvert).not.toHaveBeenCalled()+ })+it('should render warning text', () => {render(<Conversion />)diff --git a/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/index.spec.tsxindex 3b171c2494e..dc3df5a7a4e 100644--- a/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx@@ -82,6 +82,17 @@ vi.mock('@/app/components/workflow/store', () => {}})+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canImportExportDSL: boolean, canRun: boolean, canReleaseAndVersion: boolean } }) => T): T =>+ selector({+ accessControl: {+ canImportExportDSL: true,+ canRun: true,+ canReleaseAndVersion: true,+ },+ }),+}))+const {mockHandlePaneContextmenuCancel,mockExportCheck,@@ -208,6 +219,24 @@ vi.mock('@/service/knowledge/use-dataset', () => ({useInvalidDatasetList: () => vi.fn(),}))+let mockDatasetDetailState = {+ dataset: {+ permission_keys: ['dataset.acl.edit'],+ maintainer: 'maintainer-id',+ },+}+vi.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContextWithSelector: (selector: (state: typeof mockDatasetDetailState) => unknown) => selector(mockDatasetDetailState),+}))++let mockAppContextState = {+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [] as string[],+}+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: typeof mockAppContextState) => unknown) => selector(mockAppContextState),+}))+vi.mock('@/service/workflow', () => ({fetchWorkflowDraft: vi.fn().mockResolvedValue({graph: { nodes: [], edges: [], viewport: {} },@@ -374,6 +403,16 @@ function getAppIcon() {describe('Conversion', () => {beforeEach(() => {vi.clearAllMocks()+ mockDatasetDetailState = {+ dataset: {+ permission_keys: ['dataset.acl.edit'],+ maintainer: 'maintainer-id',+ },+ }+ mockAppContextState = {+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],+ }})describe('Rendering', () => {diff --git a/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-children.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-children.spec.tsxindex fcb208fc674..56baf482d77 100644--- a/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-children.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-children.spec.tsx@@ -42,6 +42,15 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canImportExportDSL: boolean } }) => T): T =>+ selector({+ accessControl: {+ canImportExportDSL: true,+ },+ }),+}))+vi.mock('@/app/components/workflow/hooks', () => ({useDSL: () => ({exportCheck: mockExportCheck,diff --git a/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsxindex 22d38861dad..d175780a029 100644--- a/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx@@ -2,14 +2,23 @@ import type { PropsWithChildren } from 'react'import type { Edge, Node, Viewport } from 'reactflow'import { cleanup, render, screen } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { DatasetACLPermission } from '@/utils/permission'import RagPipelineMain from '../rag-pipeline-main'+const mockPermissionState = vi.hoisted(() => ({+ permissionKeys: ['dataset.acl.edit'] as string[],+}))+vi.mock('../../hooks', () => ({useAvailableNodesMetaData: () => ({ nodes: [], nodesMap: {} }),useDSL: () => ({exportCheck: vi.fn(),handleExportDSL: vi.fn(),}),+ useDSLByCanEdit: () => ({+ exportCheck: vi.fn(),+ handleExportDSL: vi.fn(),+ }),useGetRunAndTraceUrl: () => ({getWorkflowRunAndTraceUrl: vi.fn(),}),@@ -17,6 +26,10 @@ vi.mock('../../hooks', () => ({doSyncWorkflowDraft: vi.fn(),syncWorkflowDraftWhenPageClose: vi.fn(),}),+ useNodesSyncDraftByCanEdit: () => ({+ doSyncWorkflowDraft: vi.fn(),+ syncWorkflowDraftWhenPageClose: vi.fn(),+ }),usePipelineRefreshDraft: () => ({handleRefreshWorkflowDraft: vi.fn(),}),@@ -27,10 +40,21 @@ vi.mock('../../hooks', () => ({handleRun: vi.fn(),handleStopRun: vi.fn(),}),+ usePipelineRunByCanEdit: () => ({+ handleBackupDraft: vi.fn(),+ handleLoadBackupDraft: vi.fn(),+ handleRestoreFromPublishedWorkflow: vi.fn(),+ handleRun: vi.fn(),+ handleStopRun: vi.fn(),+ }),usePipelineStartRun: () => ({handleStartWorkflowRun: vi.fn(),handleWorkflowStartRunInWorkflow: vi.fn(),}),+ usePipelineStartRunByCanEdit: () => ({+ handleStartWorkflowRun: vi.fn(),+ handleWorkflowStartRunInWorkflow: vi.fn(),+ }),}))vi.mock('../../hooks/use-configs-map', () => ({@@ -77,9 +101,16 @@ vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () =>}),}))+vi.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContextWithSelector: (selector: (state: { dataset: { permission_keys: string[] } }) => unknown) =>+ selector({ dataset: { permission_keys: mockPermissionState.permissionKeys } }),+}))+vi.mock('@/app/components/workflow', () => ({- WorkflowWithInnerContext: ({ children, onWorkflowDataUpdate }: PropsWithChildren<{ onWorkflowDataUpdate?: (payload: unknown) => void }>) => (+ WorkflowWithInnerContext: ({ children, onWorkflowDataUpdate, hooksStore }: PropsWithChildren<{ onWorkflowDataUpdate?: (payload: unknown) => void, hooksStore?: { accessControl?: { canComment?: boolean, canEdit?: boolean } } }>) => (<div data-testid="workflow-inner-context">+ <div data-testid="can-comment">{String(hooksStore?.accessControl?.canComment)}</div>+ <div data-testid="can-edit">{String(hooksStore?.accessControl?.canEdit)}</div>{children}<buttondata-testid="trigger-update"@@ -120,6 +151,7 @@ describe('RagPipelineMain', () => {beforeEach(() => {vi.clearAllMocks()+ mockPermissionState.permissionKeys = [DatasetACLPermission.Edit]})describe('rendering', () => {@@ -191,6 +223,15 @@ describe('RagPipelineMain', () => {})describe('hooks integration', () => {+ it('should pass readonly ACL permission as comment-only workflow access', () => {+ mockPermissionState.permissionKeys = [DatasetACLPermission.Readonly]++ render(<RagPipelineMain {...defaultProps} />)++ expect(screen.getByTestId('can-comment')).toHaveTextContent('true')+ expect(screen.getByTestId('can-edit')).toHaveTextContent('false')+ })+it('should use useNodesSyncDraft hook', () => {render(<RagPipelineMain {...defaultProps} />)diff --git a/web/app/components/rag-pipeline/components/conversion.tsx b/web/app/components/rag-pipeline/components/conversion.tsxindex 5e500a88a69..48f8fec4c1e 100644--- a/web/app/components/rag-pipeline/components/conversion.tsx+++ b/web/app/components/rag-pipeline/components/conversion.tsx@@ -12,19 +12,34 @@ import { toast } from '@langgenius/dify-ui/toast'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useParams } from '@/next/navigation'import { datasetDetailQueryKeyPrefix } from '@/service/knowledge/use-dataset'import { useInvalid } from '@/service/use-base'import { useConvertDatasetToPipeline } from '@/service/use-pipeline'+import { getDatasetACLCapabilities } from '@/utils/permission'import PipelineScreenShot from './screenshot'const Conversion = () => {const { t } = useTranslation()const { datasetId } = useParams()+ const dataset = useDatasetDetailContextWithSelector(state => state.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const [showConfirmModal, setShowConfirmModal] = useState(false)const { mutateAsync: convert, isPending } = useConvertDatasetToPipeline()const invalidDatasetDetail = useInvalid([...datasetDetailQueryKeyPrefix, datasetId])+ const datasetACLCapabilities = React.useMemo(() => getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }), [currentUserId, dataset?.maintainer, dataset?.permission_keys, workspacePermissionKeys])+ const canConvertDataset = datasetACLCapabilities.canEditconst handleConvert = useCallback(() => {+ if (!canConvertDataset || !datasetId)+ return+convert(datasetId as string, {onSuccess: (res) => {if (res.status === 'success') {@@ -40,10 +55,13 @@ const Conversion = () => {toast.error(t('conversion.errorMessage', { ns: 'datasetPipeline' }))},})- }, [convert, datasetId, invalidDatasetDetail, t])+ }, [canConvertDataset, convert, datasetId, invalidDatasetDetail, t])const handleShowConfirmModal = useCallback(() => {+ if (!canConvertDataset)+ return+setShowConfirmModal(true)- }, [])+ }, [canConvertDataset])const handleCancelConversion = useCallback(() => {setShowConfirmModal(false)}, [])@@ -63,7 +81,7 @@ const Conversion = () => {</div></div><div className="flex items-center gap-x-4">- <Button variant="primary" className="w-32" onClick={handleShowConfirmModal}>+ <Button variant="primary" className="w-32" disabled={!canConvertDataset} onClick={handleShowConfirmModal}>{t('operations.convert', { ns: 'datasetPipeline' })}</Button><span className="system-xs-regular text-text-warning">@@ -93,7 +111,7 @@ const Conversion = () => {<AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>- <AlertDialogConfirmButton loading={isPending} disabled={isPending} onClick={handleConvert}>+ <AlertDialogConfirmButton loading={isPending} disabled={isPending || !canConvertDataset} onClick={handleConvert}>{t('operation.confirm', { ns: 'common' })}</AlertDialogConfirmButton></AlertDialogActions>diff --git a/web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsxindex d362b31057f..8b9b93480c5 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsx@@ -16,6 +16,7 @@ const mockCloseAllInputFieldPanels = vi.fn()const mockToggleInputFieldPreviewPanel = vi.fn()let mockIsPreviewing = falselet mockIsEditing = false+let mockCanEdit = truevi.mock('@/app/components/rag-pipeline/hooks', () => ({useInputFieldPanel: () => ({@@ -26,6 +27,15 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({}),}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canEdit: boolean } }) => T): T =>+ selector({+ accessControl: {+ canEdit: mockCanEdit,+ },+ }),+}))+let mockRagPipelineVariables: RAGPipelineVariables = []const mockSetRagPipelineVariables = vi.fn()@@ -178,11 +188,13 @@ const setupMocks = (options?: {ragPipelineVariables?: RAGPipelineVariablesisPreviewing?: booleanisEditing?: boolean+ canEdit?: boolean}) => {mockNodesData = options?.nodes || []mockRagPipelineVariables = options?.ragPipelineVariables || []mockIsPreviewing = options?.isPreviewing || falsemockIsEditing = options?.isEditing || false+ mockCanEdit = options?.canEdit ?? true}describe('InputFieldPanel', () => {@@ -429,6 +441,16 @@ describe('InputFieldPanel', () => {'false',)})++ it('should set readonly to true when access control cannot edit', () => {+ setupMocks({ canEdit: false })++ render(<InputFieldPanel />)++ expect(screen.getByTestId('field-list-readonly-shared'))!.toHaveTextContent(+ 'true',+ )+ })})describe('Input Fields Change Handler', () => {@@ -514,6 +536,41 @@ describe('InputFieldPanel', () => {const hasSharedField = setVarsCall.some(isSharedField)expect(hasSharedField).toBe(true)})++ it('should ignore input field changes when access control cannot edit', () => {+ const nodes = [createDataSourceNode('node-1', 'DataSource 1')]+ setupMocks({ nodes, canEdit: false })+ render(<InputFieldPanel />)++ fireEvent.click(screen.getByTestId('trigger-change-node-1'))++ expect(mockSetRagPipelineVariables).not.toHaveBeenCalled()+ expect(mockHandleSyncWorkflowDraft).not.toHaveBeenCalled()+ })++ it('should ignore input field changes while previewing', () => {+ const nodes = [createDataSourceNode('node-1', 'DataSource 1')]+ setupMocks({ nodes, isPreviewing: true })+ render(<InputFieldPanel />)++ fireEvent.click(screen.getByTestId('trigger-change-node-1'))++ expect(mockSetRagPipelineVariables).not.toHaveBeenCalled()+ expect(mockHandleSyncWorkflowDraft).not.toHaveBeenCalled()+ })++ it('should still persist input field changes while edit panel is open if access control can edit', async () => {+ const nodes = [createDataSourceNode('node-1', 'DataSource 1')]+ setupMocks({ nodes, isEditing: true, canEdit: true })+ render(<InputFieldPanel />)++ fireEvent.click(screen.getByTestId('trigger-change-node-1'))++ await waitFor(() => {+ expect(mockSetRagPipelineVariables).toHaveBeenCalled()+ })+ expect(mockHandleSyncWorkflowDraft).toHaveBeenCalled()+ })})describe('Label Class Names', () => {diff --git a/web/app/components/rag-pipeline/components/panel/input-field/index.tsx b/web/app/components/rag-pipeline/components/panel/input-field/index.tsxindex 3572d6012fc..410cbb3f75f 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/index.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/index.tsx@@ -16,6 +16,7 @@ import Divider from '@/app/components/base/divider'import { Infotip } from '@/app/components/base/infotip'import { useInputFieldPanel } from '@/app/components/rag-pipeline/hooks'import { useNodesSyncDraft } from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import FieldList from './field-list'@@ -32,6 +33,9 @@ const InputFieldPanel = () => {isPreviewing,isEditing,} = useInputFieldPanel()+ const canEdit = useHooksStore(s => s.accessControl.canEdit)+ const shouldIgnoreInputFieldChange = !canEdit || isPreviewing+ const isReadonly = shouldIgnoreInputFieldChange || isEditingconst ragPipelineVariables = useStore(state => state.ragPipelineVariables)const setRagPipelineVariables = useStore(state => state.setRagPipelineVariables)@@ -61,6 +65,9 @@ const InputFieldPanel = () => {}, [nodes])const updateInputFields = useCallback(async (key: string, value: InputVar[]) => {+ if (shouldIgnoreInputFieldChange)+ return+inputFieldsMap.current[key] = valueconst datasourceNodeInputFields: RAGPipelineVariables = []const globalInputFields: RAGPipelineVariables = []@@ -85,7 +92,7 @@ const InputFieldPanel = () => {const newRagPipelineVariables = [...datasourceNodeInputFields, ...globalInputFields]setRagPipelineVariables?.(newRagPipelineVariables)handleSyncWorkflowDraft()- }, [setRagPipelineVariables, handleSyncWorkflowDraft])+ }, [shouldIgnoreInputFieldChange, setRagPipelineVariables, handleSyncWorkflowDraft])const closePanel = useCallback(() => {closeAllInputFieldPanels()@@ -154,7 +161,7 @@ const InputFieldPanel = () => {nodeId={key}LabelRightContent={<Datasource nodeData={datasourceNodeDataMap[key]!} />}inputFields={inputFields}- readonly={isPreviewing || isEditing}+ readonly={isReadonly}labelClassName="pt-1 pb-1"handleInputFieldsChange={updateInputFields}allVariableNames={allVariableNames}@@ -168,7 +175,7 @@ const InputFieldPanel = () => {nodeId="shared"LabelRightContent={<GlobalInputs />}inputFields={inputFieldsMap.current.shared || []}- readonly={isPreviewing || isEditing}+ readonly={isReadonly}labelClassName="pt-2 pb-1"handleInputFieldsChange={updateInputFields}allVariableNames={allVariableNames}diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-children.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-children.tsxindex 3ce17737aaf..c5539114bed 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-children.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-children.tsx@@ -9,6 +9,7 @@ import {useDSL,usePanelInteractions,} from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useEventEmitterContextContext } from '@/context/event-emitter'import PluginDependency from '../../workflow/plugin-dependency'import { useStore } from '../../workflow/store'@@ -23,6 +24,7 @@ const RagPipelineChildren = () => {const [secretEnvList, setSecretEnvList] = useState<EnvironmentVariable[]>([])const showImportDSLModal = useStore(s => s.showImportDSLModal)const setShowImportDSLModal = useStore(s => s.setShowImportDSLModal)+ const canImportExportDSL = useHooksStore(s => s.accessControl.canImportExportDSL)const {handlePaneContextmenuCancel,} = usePanelInteractions()@@ -43,7 +45,7 @@ const RagPipelineChildren = () => {<><PluginDependency />{- showImportDSLModal && (+ canImportExportDSL && showImportDSLModal && (<UpdateDSLModalonCancel={() => setShowImportDSLModal(false)}onBackup={exportCheck!}@@ -52,7 +54,7 @@ const RagPipelineChildren = () => {)}{- secretEnvList.length > 0 && (+ canImportExportDSL && secretEnvList.length > 0 && (<DSLExportConfirmModalenvList={secretEnvList}onConfirm={handleExportDSL!}diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsxindex 69f93d12051..72ea0e06f4a 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx@@ -50,6 +50,16 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canRun: boolean, canReleaseAndVersion: boolean } }) => T): T =>+ selector({+ accessControl: {+ canRun: true,+ canReleaseAndVersion: true,+ },+ }),+}))+const mockHandleSyncWorkflowDraft = vi.fn()const mockHandleCheckBeforePublish = vi.fn().mockResolvedValue(true)const mockHandleStopRun = vi.fn()@@ -122,8 +132,29 @@ vi.mock('@/service/knowledge/use-dataset', () => ({}))const mockMutateDatasetRes = vi.fn()+let mockDatasetPermissionKeys = ['dataset.acl.use']+let mockDatasetMaintainer: string | undefined+let mockCurrentUserId = 'user-1'+let mockIsLoadingWorkspacePermissionKeys = false+let mockWorkspacePermissionKeys: string[] = []vi.mock('@/context/dataset-detail', () => ({- useDatasetDetailContextWithSelector: () => mockMutateDatasetRes,+ useDatasetDetailContextWithSelector: (selector: (state: Record<string, unknown>) => unknown) => selector({+ dataset: {+ permission_keys: mockDatasetPermissionKeys,+ maintainer: mockDatasetMaintainer,+ },+ mutateDatasetRes: mockMutateDatasetRes,+ }),+}))++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: Record<string, unknown>) => unknown) => selector({+ userProfile: {+ id: mockCurrentUserId,+ },+ isLoadingWorkspacePermissionKeys: mockIsLoadingWorkspacePermissionKeys,+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),}))const mockSetShowPricingModal = vi.fn()@@ -221,6 +252,11 @@ describe('RagPipelineHeader', () => {setShowEnvPanel: mockSetShowEnvPanel,}mockProviderContextValue = createMockProviderContextValue()+ mockDatasetPermissionKeys = ['dataset.acl.use']+ mockDatasetMaintainer = undefined+ mockCurrentUserId = 'user-1'+ mockIsLoadingWorkspacePermissionKeys = false+ mockWorkspacePermissionKeys = []})describe('Rendering', () => {diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsxindex 7655952aede..7c02bd65b23 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx@@ -35,6 +35,12 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: (selector: (state: { accessControl: { canRun: boolean } }) => unknown) => selector({+ accessControl: { canRun: true },+ }),+}))+vi.mock('@/app/components/workflow/types', () => ({WorkflowRunningStatus: { Running: 'running' },}))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 bb50bf2f689..9625edc7e57 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@@ -93,10 +93,21 @@ vi.mock('@/app/components/workflow/hooks', () => ({}),}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: (selector: (state: { accessControl: { canReleaseAndVersion: boolean } }) => unknown) => selector({+ accessControl: { canReleaseAndVersion: true },+ }),+}))+const mockPublishedAt = vi.fn(() => null as number | null)const mockDraftUpdatedAt = vi.fn(() => 1700000000)const mockPipelineId = vi.fn(() => 'test-pipeline-id')const mockSetPublishedAt = vi.fn()+let mockDatasetPermissionKeys = ['dataset.acl.use']+let mockDatasetMaintainer: string | undefined+let mockCurrentUserId = 'user-1'+let mockIsLoadingWorkspacePermissionKeys = false+let mockWorkspacePermissionKeys: string[] = []vi.mock('@/app/components/workflow/store', () => ({useStore: (selector: (s: Record<string, unknown>) => unknown) => {@@ -117,11 +128,27 @@ vi.mock('@/app/components/workflow/store', () => ({const mockMutateDatasetRes = vi.fn()vi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: (selector: (s: Record<string, unknown>) => unknown) => {- const state = { mutateDatasetRes: mockMutateDatasetRes }+ const state = {+ dataset: {+ permission_keys: mockDatasetPermissionKeys,+ maintainer: mockDatasetMaintainer,+ },+ mutateDatasetRes: mockMutateDatasetRes,+ }return selector(state)},}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: Record<string, unknown>) => unknown) => selector({+ userProfile: {+ id: mockCurrentUserId,+ },+ isLoadingWorkspacePermissionKeys: mockIsLoadingWorkspacePermissionKeys,+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+const mockSetShowPricingModal = vi.fn()vi.mock('@/context/modal-context', () => ({useModalContextSelector: <T,>(selector: (state: { setShowPricingModal: typeof mockSetShowPricingModal }) => T): T =>@@ -247,6 +274,11 @@ describe('publisher', () => {mockPipelineId.mockReturnValue('test-pipeline-id')mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)mockHandleCheckBeforePublish.mockResolvedValue(true)+ mockDatasetPermissionKeys = ['dataset.acl.use']+ mockDatasetMaintainer = undefined+ mockCurrentUserId = 'user-1'+ mockIsLoadingWorkspacePermissionKeys = false+ mockWorkspacePermissionKeys = []})describe('Publisher (index.tsx)', () => {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 e6f39fc91ea..8ba56ad0af0 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@@ -61,6 +61,11 @@ let mockPublishedAt: string | undefined = '2024-01-01T00:00:00Z'let mockDraftUpdatedAt: string | undefined = '2024-06-01T00:00:00Z'let mockPipelineId: string | undefined = 'pipeline-123'let mockIsAllowPublishAsCustom = true+let mockDatasetPermissionKeys = ['dataset.acl.use']+let mockDatasetMaintainer: string | undefined+let mockCurrentUserId = 'user-1'+let mockIsLoadingWorkspacePermissionKeys = false+let mockWorkspacePermissionKeys: string[] = []const mockUseBoolean = vi.hoisted(() => vi.fn())vi.mock('@/next/navigation', () => ({useParams: () => ({ datasetId: 'ds-123' }),@@ -141,7 +146,23 @@ vi.mock('@/app/components/workflow/hooks', () => ({}))vi.mock('@/context/dataset-detail', () => ({- useDatasetDetailContextWithSelector: () => mockMutateDatasetRes,+ useDatasetDetailContextWithSelector: (selector: (state: Record<string, unknown>) => unknown) => selector({+ dataset: {+ permission_keys: mockDatasetPermissionKeys,+ maintainer: mockDatasetMaintainer,+ },+ mutateDatasetRes: mockMutateDatasetRes,+ }),+}))++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: Record<string, unknown>) => unknown) => selector({+ userProfile: {+ id: mockCurrentUserId,+ },+ isLoadingWorkspacePermissionKeys: mockIsLoadingWorkspacePermissionKeys,+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),}))vi.mock('@/context/i18n', () => ({@@ -218,6 +239,11 @@ describe('Popup', () => {mockDraftUpdatedAt = '2024-06-01T00:00:00Z'mockPipelineId = 'pipeline-123'mockIsAllowPublishAsCustom = true+ mockDatasetPermissionKeys = ['dataset.acl.use']+ mockDatasetMaintainer = undefined+ mockCurrentUserId = 'user-1'+ mockIsLoadingWorkspacePermissionKeys = false+ mockWorkspacePermissionKeys = []mockUseBoolean.mockImplementation((initial: boolean) => [initial, {setFalse: vi.fn(),setTrue: vi.fn(),@@ -306,6 +332,14 @@ describe('Popup', () => {expect(btn).toBeDisabled()})+ it('should disable add documents button when dataset cannot add documents', () => {+ mockDatasetPermissionKeys = ['dataset.acl.edit']+ render(<Popup />)++ const btn = screen.getByText('pipeline.common.goToAddDocuments').closest('button')+ expect(btn).toBeDisabled()+ })+it('should disable publish-as button when not published', () => {mockPublishedAt = undefinedrender(<Popup />)diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsxindex c452c3b9c00..b07d21f6a42 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx@@ -12,6 +12,7 @@ import {} from 'react'import { useTranslation } from 'react-i18next'import { useNodesSyncDraft } from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useStore } from '@/app/components/workflow/store'import { useDocLink } from '@/context/i18n'import Link from '@/next/link'@@ -24,6 +25,7 @@ const Publisher = () => {const [open, setOpen] = useState(false)const [confirmVisible, { setFalse: hideConfirm, setTrue: showConfirm }] = useBoolean(false)const { handleSyncWorkflowDraft } = useNodesSyncDraft()+ const canPipelineRelease = useHooksStore(s => s.accessControl.canReleaseAndVersion)const docLink = useDocLink()const pipelineId = useStore(s => s.pipelineId)const { mutateAsync: publishAsCustomizedPipeline } = usePublishAsCustomizedPipeline()@@ -34,10 +36,10 @@ const Publisher = () => {const handleOpenChange = useCallback((newOpen: boolean) => {if (!newOpen && confirmVisible)return- if (newOpen)+ if (newOpen && canPipelineRelease)handleSyncWorkflowDraft(true)- setOpen(newOpen)- }, [confirmVisible, handleSyncWorkflowDraft])+ setOpen(canPipelineRelease && newOpen)+ }, [confirmVisible, handleSyncWorkflowDraft, canPipelineRelease])const closePopover = useCallback(() => {setOpen(false)}, [])@@ -91,6 +93,7 @@ const Publisher = () => {<ButtonclassName="px-2"variant="primary"+ disabled={!canPipelineRelease}><span className="pl-1">{t('common.publish', { ns: 'workflow' })}</span><RiArrowDownSLine className="size-4" />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 6d12adf42e3..1baad279036 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@@ -24,6 +24,7 @@ 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 { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useModalContextSelector } from '@/context/modal-context'import { useProviderContextSelector } from '@/context/provider-context'@@ -35,6 +36,7 @@ import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'import { useInvalid } from '@/service/use-base'import { publishedPipelineInfoQueryKeyPrefix } from '@/service/use-pipeline'import { usePublishWorkflow } from '@/service/use-workflow'+import { getDatasetACLCapabilities } from '@/utils/permission'const PUBLISH_SHORTCUT = ['Mod', 'Shift', 'P']type PopupProps = {@@ -60,7 +62,11 @@ const Popup = ({const publishedAt = useStore(s => s.publishedAt)const draftUpdatedAt = useStore(s => s.draftUpdatedAt)const pipelineId = useStore(s => s.pipelineId)+ const dataset = useDatasetDetailContextWithSelector(s => s.dataset)const mutateDatasetRes = useDatasetDetailContextWithSelector(s => s.mutateDatasetRes)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const isLoadingWorkspacePermissionKeys = useAppContextWithSelector(state => state.isLoadingWorkspacePermissionKeys)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const [published, setPublished] = useState(false)const { formatTimeFromNow } = useFormatTimeFromNow()const { handleCheckBeforePublish } = useChecklistBeforePublish()@@ -69,6 +75,12 @@ const Popup = ({const isAllowPublishAsCustomKnowledgePipelineTemplate = useProviderContextSelector(s => s.isAllowPublishAsCustomKnowledgePipelineTemplate)const setShowPricingModal = useModalContextSelector(s => s.setShowPricingModal)const apiReferenceUrl = useDatasetApiAccessUrl()+ const canAddDocumentsToDataset = getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }).canUse+ const isAddDocumentsDisabled = !publishedAt || isLoadingWorkspacePermissionKeys || !canAddDocumentsToDatasetconst [localConfirmVisible, { setFalse: hideLocalConfirm, setTrue: showLocalConfirm }] = useBoolean(false)const confirmVisible = controlledConfirmVisible ?? localConfirmVisibleconst showConfirm = onShowConfirm ?? showLocalConfirm@@ -141,8 +153,11 @@ const Popup = ({handlePublish()})const goToAddDocuments = useCallback(() => {+ if (isAddDocumentsDisabled)+ return+push(`/datasets/${datasetId}/documents/create-from-pipeline`)- }, [datasetId, push])+ }, [datasetId, isAddDocumentsDisabled, push])const handleClickPublishAsKnowledgePipeline = useCallback(() => {onRequestClose?.()if (!isAllowPublishAsCustomKnowledgePipelineTemplate) {@@ -193,7 +208,7 @@ const Popup = ({</Button></div><div className="border-t-[0.5px] border-t-divider-regular p-4 pt-3">- <Button className="mb-1 w-full hover:bg-state-accent-hover hover:text-text-accent" variant="tertiary" onClick={goToAddDocuments} disabled={!publishedAt}>+ <Button className="mb-1 w-full hover:bg-state-accent-hover hover:text-text-accent" variant="tertiary" onClick={goToAddDocuments} disabled={isAddDocumentsDisabled}><div className="flex grow items-center"><RiPlayCircleLine className="mr-2 size-4" />{t('common.goToAddDocuments', { ns: 'pipeline' })}diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsxindex 2002141265b..71c44c5b6f4 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx@@ -7,6 +7,7 @@ import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { StopCircle } from '@/app/components/base/icons/src/vender/line/mediaAndDevices'import { useWorkflowRun, useWorkflowStartRun } from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'@@ -25,9 +26,10 @@ const RunMode = ({const workflowStore = useWorkflowStore()const workflowRunningData = useStore(s => s.workflowRunningData)const isPreparingDataSource = useStore(s => s.isPreparingDataSource)+ const canRun = useHooksStore(s => s.accessControl.canRun)const isRunning = workflowRunningData?.result.status === WorkflowRunningStatus.Running- const isDisabled = isPreparingDataSource || isRunning+ const isDisabled = isPreparingDataSource || isRunning || !canRunconst handleStop = useCallback(() => {handleStopRun(workflowRunningData?.task_id || '')@@ -45,6 +47,9 @@ const RunMode = ({handleStop()})+ if (!canRun)+ return null+return (<div className="flex items-center gap-x-px"><button@@ -55,7 +60,8 @@ const RunMode = ({isDisabled ? 'rounded-l-md' : 'rounded-md',)}onClick={() => {- handleWorkflowStartRunInWorkflow()+ if (canRun)+ handleWorkflowStartRunInWorkflow()}}disabled={isDisabled}>diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-main.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-main.tsxindex 7175b0675ee..e8b05c576e9 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-main.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-main.tsx@@ -6,14 +6,17 @@ import {import { WorkflowWithInnerContext } from '@/app/components/workflow'import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'import { useWorkflowStore } from '@/app/components/workflow/store'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'+import { getDatasetACLCapabilities } from '@/utils/permission'import {useAvailableNodesMetaData,- useDSL,+ useDSLByCanEdit,useGetRunAndTraceUrl,- useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,usePipelineRefreshDraft,- usePipelineRun,- usePipelineStartRun,+ usePipelineRunByCanEdit,+ usePipelineStartRunByCanEdit,} from '../hooks'import { useConfigsMap } from '../hooks/use-configs-map'import { useInspectVarsCrud } from '../hooks/use-inspect-vars-crud'@@ -26,6 +29,17 @@ const RagPipelineMain = ({viewport,}: RagPipelineMainProps) => {const workflowStore = useWorkflowStore()+ const dataset = useDatasetDetailContextWithSelector(s => s.dataset)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const datasetACLCapabilities = useMemo(+ () => getDatasetACLCapabilities(dataset?.permission_keys, {+ currentUserId,+ resourceMaintainer: dataset?.maintainer,+ workspacePermissionKeys,+ }),+ [dataset?.maintainer, dataset?.permission_keys, currentUserId, workspacePermissionKeys],+ )const handleWorkflowDataUpdate = useCallback((payload: any) => {const {@@ -45,7 +59,7 @@ const RagPipelineMain = ({const {doSyncWorkflowDraft,syncWorkflowDraftWhenPageClose,- } = useNodesSyncDraft()+ } = useNodesSyncDraftByCanEdit(datasetACLCapabilities.canEdit)const { handleRefreshWorkflowDraft } = usePipelineRefreshDraft()const {handleBackupDraft,@@ -53,17 +67,17 @@ const RagPipelineMain = ({handleRestoreFromPublishedWorkflow,handleRun,handleStopRun,- } = usePipelineRun()+ } = usePipelineRunByCanEdit(datasetACLCapabilities.canEdit)const {handleStartWorkflowRun,handleWorkflowStartRunInWorkflow,- } = usePipelineStartRun()+ } = usePipelineStartRunByCanEdit(datasetACLCapabilities.canEdit)const availableNodesMetaData = useAvailableNodesMetaData()const { getWorkflowRunAndTraceUrl } = useGetRunAndTraceUrl()const {exportCheck,handleExportDSL,- } = useDSL()+ } = useDSLByCanEdit(datasetACLCapabilities.canEdit)const configsMap = useConfigsMap()const { fetchInspectVars } = useSetWorkflowVarsWithValue({@@ -117,6 +131,13 @@ const RagPipelineMain = ({invalidateSysVarValues,resetConversationVar,invalidateConversationVarValues,+ accessControl: {+ canEdit: datasetACLCapabilities.canEdit,+ canComment: datasetACLCapabilities.canReadonly || datasetACLCapabilities.canEdit,+ canRun: datasetACLCapabilities.canPipelineTest,+ canImportExportDSL: datasetACLCapabilities.canImportExportDSL,+ canReleaseAndVersion: datasetACLCapabilities.canPipelineRelease,+ },configsMap,}}, [@@ -149,6 +170,7 @@ const RagPipelineMain = ({invalidateSysVarValues,resetConversationVar,invalidateConversationVarValues,+ datasetACLCapabilities,configsMap,])diff --git a/web/app/components/rag-pipeline/hooks/use-DSL.ts b/web/app/components/rag-pipeline/hooks/use-DSL.tsindex 12bcbe041b0..249862450ef 100644--- a/web/app/components/rag-pipeline/hooks/use-DSL.ts+++ b/web/app/components/rag-pipeline/hooks/use-DSL.ts@@ -7,13 +7,17 @@ import { useEventEmitterContextContext } from '@/context/event-emitter'import { useExportPipelineDSL } from '@/service/use-pipeline'import { fetchWorkflowDraft } from '@/service/workflow'import { downloadBlob } from '@/utils/download'-import { useNodesSyncDraft } from './use-nodes-sync-draft'+import {+ useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,+} from './use-nodes-sync-draft'-export const useDSL = () => {+type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']++const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const { t } = useTranslation()const { eventEmitter } = useEventEmitterContextContext()const [exporting, setExporting] = useState(false)- const { doSyncWorkflowDraft } = useNodesSyncDraft()const workflowStore = useWorkflowStore()const { mutateAsync: exportPipelineConfig } = useExportPipelineDSL()const handleExportDSL = useCallback(async (include = false) => {@@ -66,3 +70,15 @@ export const useDSL = () => {handleExportDSL,}}++export const useDSLByCanEdit = (canEdit: boolean) => {+ const { doSyncWorkflowDraft } = useNodesSyncDraftByCanEdit(canEdit)++ return useDSLBase(doSyncWorkflowDraft)+}++export const useDSL = () => {+ const { doSyncWorkflowDraft } = useNodesSyncDraft()++ return useDSLBase(doSyncWorkflowDraft)+}diff --git a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.tsindex 184adb582ff..fe5d8df971c 100644--- a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts+++ b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts@@ -5,6 +5,7 @@ import { useStoreApi } from 'reactflow'import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'import {useNodesReadOnly,+ useNodesReadOnlyByCanEdit,} from '@/app/components/workflow/hooks/use-workflow'import {useWorkflowStore,@@ -14,10 +15,9 @@ import { postWithKeepalive } from '@/service/fetch'import { syncWorkflowDraft } from '@/service/workflow'import { usePipelineRefreshDraft } from '.'-export const useNodesSyncDraft = () => {+const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {const store = useStoreApi()const workflowStore = useWorkflowStore()- const { getNodesReadOnly } = useNodesReadOnly()const { handleRefreshWorkflowDraft } = usePipelineRefreshDraft()const getPostParams = useCallback(() => {@@ -123,3 +123,15 @@ export const useNodesSyncDraft = () => {syncWorkflowDraftWhenPageClose,}}++export const useNodesSyncDraftByCanEdit = (canEdit: boolean) => {+ const { getNodesReadOnly } = useNodesReadOnlyByCanEdit(canEdit)++ return useNodesSyncDraftBase(getNodesReadOnly)+}++export const useNodesSyncDraft = () => {+ const { getNodesReadOnly } = useNodesReadOnly()++ return useNodesSyncDraftBase(getNodesReadOnly)+}diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-run.tsindex b35441365b3..33387184596 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts@@ -15,13 +15,17 @@ import { ssePost } from '@/service/base'import { useInvalidAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'import { stopWorkflowRun } from '@/service/workflow'import { FlowType } from '@/types/common'-import { useNodesSyncDraft } from './use-nodes-sync-draft'+import {+ useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,+} from './use-nodes-sync-draft'-export const usePipelineRun = () => {+type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']++const usePipelineRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const store = useStoreApi()const workflowStore = useWorkflowStore()const reactflow = useReactFlow()- const { doSyncWorkflowDraft } = useNodesSyncDraft()const { handleUpdateWorkflowCanvas } = useWorkflowUpdate()const {@@ -315,3 +319,15 @@ export const usePipelineRun = () => {handleRestoreFromPublishedWorkflow,}}++export const usePipelineRunByCanEdit = (canEdit: boolean) => {+ const { doSyncWorkflowDraft } = useNodesSyncDraftByCanEdit(canEdit)++ return usePipelineRunBase(doSyncWorkflowDraft)+}++export const usePipelineRun = () => {+ const { doSyncWorkflowDraft } = useNodesSyncDraft()++ return usePipelineRunBase(doSyncWorkflowDraft)+}diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsx b/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsxindex ca57aefeb06..9434e6d71f5 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsx+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsx@@ -7,12 +7,14 @@ import {import {useInputFieldPanel,useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,} from '.'-export const usePipelineStartRun = () => {+type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']++const usePipelineStartRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const workflowStore = useWorkflowStore()const { handleCancelDebugAndPreviewPanel } = useWorkflowInteractions()- const { doSyncWorkflowDraft } = useNodesSyncDraft()const { closeAllInputFieldPanels } = useInputFieldPanel()const handleWorkflowStartRunInWorkflow = useCallback(async () => {@@ -62,3 +64,15 @@ export const usePipelineStartRun = () => {handleWorkflowStartRunInWorkflow,}}++export const usePipelineStartRunByCanEdit = (canEdit: boolean) => {+ const { doSyncWorkflowDraft } = useNodesSyncDraftByCanEdit(canEdit)++ return usePipelineStartRunBase(doSyncWorkflowDraft)+}++export const usePipelineStartRun = () => {+ const { doSyncWorkflowDraft } = useNodesSyncDraft()++ return usePipelineStartRunBase(doSyncWorkflowDraft)+}diff --git a/web/app/components/snippet-list/__tests__/index.spec.tsx b/web/app/components/snippet-list/__tests__/index.spec.tsxindex d87db18579a..dca361764eb 100644--- a/web/app/components/snippet-list/__tests__/index.spec.tsx+++ b/web/app/components/snippet-list/__tests__/index.spec.tsx@@ -70,12 +70,31 @@ vi.mock('@/service/client', () => ({const mockIsCurrentWorkspaceEditor = vi.fn(() => true)const mockIsCurrentWorkspaceDatasetOperator = vi.fn(() => false)+const mockWorkspacePermissionKeys = vi.fn(() => ['snippets.create_and_modify'])vi.mock('@/context/app-context', () => ({- useAppContext: () => ({+ useAppContext: () => {+ const state = {+ isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor(),+ isCurrentWorkspaceDatasetOperator: mockIsCurrentWorkspaceDatasetOperator(),+ isLoadingCurrentWorkspace: false,+ userProfile: { id: 'creator-1' },+ workspacePermissionKeys: mockWorkspacePermissionKeys(),+ }++ return state+ },+ useSelector: <T,>(selector: (state: {+ isCurrentWorkspaceEditor: boolean+ isCurrentWorkspaceDatasetOperator: boolean+ isLoadingCurrentWorkspace: boolean+ userProfile: { id: string }+ workspacePermissionKeys: string[]+ }) => T): T => selector({isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor(),isCurrentWorkspaceDatasetOperator: mockIsCurrentWorkspaceDatasetOperator(),isLoadingCurrentWorkspace: false,userProfile: { id: 'creator-1' },+ workspacePermissionKeys: mockWorkspacePermissionKeys(),}),}))@@ -228,6 +247,7 @@ describe('SnippetList', () => {mockQueryState.creatorIDs = []mockIsCurrentWorkspaceEditor.mockReturnValue(true)mockIsCurrentWorkspaceDatasetOperator.mockReturnValue(false)+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify'])mockUseInfiniteSnippetList.mockReturnValue({...mockSnippetListState,refetch: mockRefetch,@@ -294,14 +314,35 @@ describe('SnippetList', () => {expect(mockSetCreatorIDs).toHaveBeenCalledWith(['creator-2'])})- it('hides the create button for non-editors', () => {- mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ it('hides the create button without snippet create permission', () => {+ mockWorkspacePermissionKeys.mockReturnValue([])renderList()expect(screen.queryByRole('button', { name: 'snippet.create' })).not.toBeInTheDocument()})+ it('does not fetch or render snippets without snippet list permissions', () => {+ mockWorkspacePermissionKeys.mockReturnValue([])++ renderList()++ expect(mockUseInfiniteSnippetList).toHaveBeenCalledWith(expect.any(Object), {+ enabled: false,+ })+ expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()+ expect(screen.getByText('workflow.tabs.noSnippetsFound')).toBeInTheDocument()+ })++ it('shows the create button for users with snippet create permission even when they are not workspace editors', () => {+ mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify'])++ renderList()++ expect(screen.getByRole('button', { name: 'snippet.create' })).toBeInTheDocument()+ })+it('shows an empty state when no snippets are returned', () => {mockUseInfiniteSnippetList.mockReturnValue({...mockSnippetListState,@@ -355,14 +396,21 @@ describe('SnippetList', () => {expect(mockFetchNextPage).toHaveBeenCalledTimes(1)})- it('does not fetch snippets or register infinite scroll for dataset operators', () => {+ it('fetches snippets for dataset operators when they have snippet list permissions', () => {mockIsCurrentWorkspaceDatasetOperator.mockReturnValue(true)renderList()expect(mockUseInfiniteSnippetList).toHaveBeenCalledWith(expect.any(Object), {- enabled: false,+ enabled: true,})+ })++ it('does not register infinite scroll without snippet list permissions', () => {+ mockWorkspacePermissionKeys.mockReturnValue([])++ renderList()+intersectionCallback?.([{ isIntersecting: true } as IntersectionObserverEntry,], {} as IntersectionObserver)diff --git a/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx b/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsxindex 8166c2850fd..30b063c47a6 100644--- a/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx+++ b/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx@@ -8,6 +8,7 @@ const {mockExportMutateAsync,mockOnRefresh,mockIsCurrentWorkspaceEditor,+ mockWorkspacePermissionKeys,mockToastError,mockToastSuccess,mockUpdateMutate,@@ -16,6 +17,7 @@ const {mockDownloadBlob: vi.fn(),mockExportMutateAsync: vi.fn(),mockIsCurrentWorkspaceEditor: vi.fn(() => true),+ mockWorkspacePermissionKeys: vi.fn(() => ['snippets.create_and_modify', 'snippets.management']),mockOnRefresh: vi.fn(),mockToastError: vi.fn(),mockToastSuccess: vi.fn(),@@ -25,6 +27,14 @@ const {vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor(),+ workspacePermissionKeys: mockWorkspacePermissionKeys(),+ }),+ useSelector: <T,>(selector: (state: {+ isCurrentWorkspaceEditor: boolean+ workspacePermissionKeys: string[]+ }) => T): T => selector({+ isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor(),+ workspacePermissionKeys: mockWorkspacePermissionKeys(),}),}))@@ -105,6 +115,7 @@ describe('SnippetCard', () => {beforeEach(() => {vi.clearAllMocks()mockIsCurrentWorkspaceEditor.mockReturnValue(true)+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify', 'snippets.management'])})describe('Rendering', () => {@@ -149,14 +160,40 @@ describe('SnippetCard', () => {expect(screen.queryByRole('menuitem', { name: /duplicate/i })).not.toBeInTheDocument()})- it('should hide operations for users without editor permission', () => {- mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ it('should hide operations for users without snippet permissions', () => {+ mockWorkspacePermissionKeys.mockReturnValue([])render(<SnippetCard snippet={createSnippet()} />)expect(screen.queryByRole('button', { name: 'common.operation.more' })).not.toBeInTheDocument()})+ it('should show edit info with create-and-modify permission without management actions', async () => {+ mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify'])++ render(<SnippetCard snippet={createSnippet()} />)++ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))++ expect(await screen.findByRole('menuitem', { name: 'snippet.menu.editInfo' })).toBeInTheDocument()+ expect(screen.queryByRole('menuitem', { name: 'snippet.menu.exportSnippet' })).not.toBeInTheDocument()+ expect(screen.queryByRole('menuitem', { name: 'snippet.menu.deleteSnippet' })).not.toBeInTheDocument()+ })++ it('should show export and delete with snippet management permission without edit info', async () => {+ mockIsCurrentWorkspaceEditor.mockReturnValue(false)+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.management'])++ render(<SnippetCard snippet={createSnippet()} />)++ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))++ expect(screen.queryByRole('menuitem', { name: 'snippet.menu.editInfo' })).not.toBeInTheDocument()+ expect(await screen.findByRole('menuitem', { name: 'snippet.menu.exportSnippet' })).toBeInTheDocument()+ expect(await screen.findByRole('menuitem', { name: 'snippet.menu.deleteSnippet' })).toBeInTheDocument()+ })+it('should forward tag selector actions without navigating the card link', () => {const onOpenTagManagement = vi.fn()const onTagsChange = vi.fn()@@ -178,6 +215,7 @@ describe('SnippetCard', () => {})it('should export a snippet from the operations menu', async () => {+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.management'])mockExportMutateAsync.mockResolvedValue('snippet-yaml')render(<SnippetCard snippet={createSnippet()} />)@@ -194,6 +232,7 @@ describe('SnippetCard', () => {})it('should show an error toast when snippet export fails', async () => {+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.management'])mockExportMutateAsync.mockRejectedValue(new Error('export failed'))render(<SnippetCard snippet={createSnippet()} />)diff --git a/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx b/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsxindex ec62cf8941a..025654bcfb5 100644--- a/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx+++ b/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx@@ -1,7 +1,7 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react'import SnippetCreateButton from '../snippet-create-button'-const { mockPush, mockCreateMutateAsync, mockSyncDraftWorkflow, mockImportMutateAsync, mockConfirmImportMutateAsync, mockToastSuccess, mockToastError } = vi.hoisted(() => ({+const { mockPush, mockCreateMutateAsync, mockSyncDraftWorkflow, mockImportMutateAsync, mockConfirmImportMutateAsync, mockToastSuccess, mockToastError, mockWorkspacePermissionKeys } = vi.hoisted(() => ({mockPush: vi.fn(),mockCreateMutateAsync: vi.fn(),mockSyncDraftWorkflow: vi.fn(),@@ -9,6 +9,7 @@ const { mockPush, mockCreateMutateAsync, mockSyncDraftWorkflow, mockImportMutatemockConfirmImportMutateAsync: vi.fn(),mockToastSuccess: vi.fn(),mockToastError: vi.fn(),+ mockWorkspacePermissionKeys: vi.fn(() => ['snippets.create_and_modify']),}))vi.mock('@/next/navigation', () => ({@@ -24,6 +25,15 @@ vi.mock('@langgenius/dify-ui/toast', () => ({},}))+vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ workspacePermissionKeys: mockWorkspacePermissionKeys(),+ }),+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys(),+ }),+}))+vi.mock('@/service/use-snippets', () => ({useCreateSnippetMutation: () => ({mutateAsync: mockCreateMutateAsync,@@ -50,6 +60,15 @@ vi.mock('@/service/client', () => ({describe('SnippetCreateButton', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify'])+ })++ it('should not render without snippet create permission', () => {+ mockWorkspacePermissionKeys.mockReturnValue([])++ render(<SnippetCreateButton />)++ expect(screen.queryByRole('button', { name: 'snippet.create' })).not.toBeInTheDocument()})it('should open the create dialog and create a snippet from the modal', async () => {diff --git a/web/app/components/snippet-list/components/snippet-card.tsx b/web/app/components/snippet-list/components/snippet-card.tsxindex 55d73719ac7..96a42ffc13b 100644--- a/web/app/components/snippet-list/components/snippet-card.tsx+++ b/web/app/components/snippet-list/components/snippet-card.tsx@@ -22,7 +22,8 @@ import { toast } from '@langgenius/dify-ui/toast'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import CreateSnippetDialog from '@/app/components/snippets/create-snippet-dialog'-import { useAppContext } from '@/context/app-context'+import { canCreateAndModifySnippets, canManageSnippets } from '@/app/components/snippets/utils/permission'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { TagSelector } from '@/features/tag-management/components/tag-selector'import Link from '@/next/link'import { useMembers } from '@/service/use-common'@@ -45,7 +46,7 @@ const SnippetCard = ({}: Props) => {const { t } = useTranslation('snippet')const { t: tCommon } = useTranslation()- const { isCurrentWorkspaceEditor } = useAppContext()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const { data: membersData } = useMembers()const [isOperationsMenuOpen, setIsOperationsMenuOpen] = useState(false)const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)@@ -53,6 +54,9 @@ const SnippetCard = ({const updateSnippetMutation = useUpdateSnippetMutation()const exportSnippetMutation = useExportSnippetMutation()const deleteSnippetMutation = useDeleteSnippetMutation()+ const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)+ const canManageSnippet = canManageSnippets(workspacePermissionKeys)+ const canShowOperations = canCreateAndModifySnippet || canManageSnippetconst memberNameById = useMemo(() => {return new Map((membersData?.accounts ?? []).map(member => [member.id, member.name]))@@ -78,6 +82,9 @@ const SnippetCard = ({}const handleExportSnippet = async () => {+ if (!canManageSnippet)+ return+setIsOperationsMenuOpen(false)try {const data = await exportSnippetMutation.mutateAsync({ snippetId: snippet.id })@@ -166,7 +173,7 @@ const SnippetCard = ({/></div></div>- {isCurrentWorkspaceEditor && (+ {canShowOperations && (<divclassName={cn('absolute top-1/2 right-1.5 flex -translate-y-1/2 items-center transition-opacity',@@ -195,23 +202,29 @@ const SnippetCard = ({sideOffset={4}popupClassName="w-[216px]">- <DropdownMenuItem className="gap-2 px-3" onClick={handleOpenEditDialog}>- <span className="system-sm-regular text-text-secondary">{t('menu.editInfo')}</span>- </DropdownMenuItem>- <DropdownMenuItem className="gap-2 px-3" onClick={handleExportSnippet}>- <span className="system-sm-regular text-text-secondary">{t('menu.exportSnippet')}</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- className="gap-2 px-3"- onClick={() => {- setIsOperationsMenuOpen(false)- setIsDeleteDialogOpen(true)- }}- >- <span className="system-sm-regular">{t('menu.deleteSnippet')}</span>- </DropdownMenuItem>+ {canCreateAndModifySnippet && (+ <DropdownMenuItem className="gap-2 px-3" onClick={handleOpenEditDialog}>+ <span className="system-sm-regular text-text-secondary">{t('menu.editInfo')}</span>+ </DropdownMenuItem>+ )}+ {canManageSnippet && (+ <>+ <DropdownMenuItem className="gap-2 px-3" onClick={handleExportSnippet}>+ <span className="system-sm-regular text-text-secondary">{t('menu.exportSnippet')}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ className="gap-2 px-3"+ onClick={() => {+ setIsOperationsMenuOpen(false)+ setIsDeleteDialogOpen(true)+ }}+ >+ <span className="system-sm-regular">{t('menu.deleteSnippet')}</span>+ </DropdownMenuItem>+ </>+ )}</DropdownMenuContent></DropdownMenu></div>diff --git a/web/app/components/snippet-list/components/snippet-create-button.tsx b/web/app/components/snippet-list/components/snippet-create-button.tsxindex 59397121152..1d117e4dad5 100644--- a/web/app/components/snippet-list/components/snippet-create-button.tsx+++ b/web/app/components/snippet-list/components/snippet-create-button.tsx@@ -15,6 +15,7 @@ import ImportSnippetDSLDialog from '@/app/components/snippets/import-snippet-dslconst SnippetCreateButton = () => {const { t } = useTranslation('snippet')const {+ canCreateAndModifySnippet,createSnippetMutation,handleCreateSnippet,isCreatingSnippet,@@ -24,6 +25,9 @@ const SnippetCreateButton = () => {const [isMenuOpen, setIsMenuOpen] = useState(false)const isSubmitting = isCreatingSnippet || createSnippetMutation.isPending+ if (!canCreateAndModifySnippet)+ return null+return (<><Popover open={isMenuOpen} onOpenChange={setIsMenuOpen}>diff --git a/web/app/components/snippet-list/index.tsx b/web/app/components/snippet-list/index.tsxindex b317c08ee09..e62216a7c4a 100644--- a/web/app/components/snippet-list/index.tsx+++ b/web/app/components/snippet-list/index.tsx@@ -6,7 +6,7 @@ import { Input } from '@langgenius/dify-ui/input'import { useDebounce } from 'ahooks'import { useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { TagFilter } from '@/features/tag-management/components/tag-filter'import useDocumentTitle from '@/hooks/use-document-title'import dynamic from '@/next/dynamic'@@ -15,6 +15,7 @@ import { useInfiniteSnippetList } from '@/service/use-snippets'import CreatorsFilter from '../apps/creators-filter'import Empty from '../apps/empty'import { StudioListHeader } from '../apps/studio-list-header'+import { canAccessSnippets } from '../snippets/utils/permission'import SnippetCard from './components/snippet-card'import SnippetCreateButton from './components/snippet-create-button'import { SNIPPET_LIST_SEARCH_DEBOUNCE_MS } from './constants'@@ -45,7 +46,8 @@ const SnippetCardSkeleton = ({ count }: SnippetCardSkeletonProps) => {const SnippetList = () => {const { t } = useTranslation()- const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator, isLoadingCurrentWorkspace } = useAppContext()+ const isLoadingCurrentWorkspace = useAppContextWithSelector(state => state.isLoadingCurrentWorkspace)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)// eslint-disable-next-line react/use-state -- custom URL query hook, not React.useStateconst {query: { tagIDs, keywords, creatorIDs },@@ -67,6 +69,7 @@ const SnippetList = () => {...(tagIDs.length ? { tag_ids: tagIDs } : {}),...(creatorIDs.length ? { creator_ids: creatorIDs } : {}),}), [creatorIDs, debouncedKeywords, tagIDs])+ const canQuerySnippetList = canAccessSnippets(workspacePermissionKeys)const {data,@@ -78,11 +81,11 @@ const SnippetList = () => {error,refetch,} = useInfiniteSnippetList(snippetListQuery, {- enabled: !isCurrentWorkspaceDatasetOperator,+ enabled: canQuerySnippetList,})useEffect(() => {- if (isCurrentWorkspaceDatasetOperator)+ if (!canQuerySnippetList)returnconst hasMore = hasNextPage ?? true@@ -110,12 +113,12 @@ const SnippetList = () => {}return () => observer?.disconnect()- }, [error, fetchNextPage, hasNextPage, isCurrentWorkspaceDatasetOperator, isFetchingNextPage, isLoading])+ }, [canQuerySnippetList, error, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading])- const pages = useMemo(() => data?.pages ?? [], [data?.pages])+ const pages = useMemo(() => canQuerySnippetList ? data?.pages ?? [] : [], [canQuerySnippetList, data?.pages])const snippets = useMemo<SnippetListItem[]>(() => pages.flatMap(({ data: pageSnippets }) => pageSnippets), [pages])const hasAnySnippet = (pages[0]?.total ?? 0) > 0- const showSkeleton = isLoading || (isFetching && pages.length === 0)+ const showSkeleton = isLoadingCurrentWorkspace || (canQuerySnippetList && (isLoading || (isFetching && pages.length === 0)))return (<div ref={containerRef} className="relative flex h-0 shrink-0 grow flex-col overflow-y-auto bg-background-body">@@ -162,9 +165,7 @@ const SnippetList = () => {)}</div></div>- {(isCurrentWorkspaceEditor || isLoadingCurrentWorkspace) && (- <SnippetCreateButton />- )}+ <SnippetCreateButton /></div></StudioListHeader><div className={cn(diff --git a/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx b/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsxindex c1295ddb585..90517f9d419 100644--- a/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx+++ b/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx@@ -16,10 +16,23 @@ const toastMocks = vi.hoisted(() => ({error: vi.fn(),}))+const contextMocks = vi.hoisted(() => ({+ workspacePermissionKeys: ['snippets.create_and_modify'] as string[],+}))+vi.mock('@/next/navigation', () => ({useRouter: () => routerMocks,}))+vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ workspacePermissionKeys: contextMocks.workspacePermissionKeys,+ }),+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: contextMocks.workspacePermissionKeys,+ }),+}))+vi.mock('@langgenius/dify-ui/toast', () => ({toast: toastMocks,}))@@ -52,6 +65,7 @@ vi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({describe('ImportSnippetDSLDialog', () => {beforeEach(() => {vi.clearAllMocks()+ contextMocks.workspacePermissionKeys = ['snippets.create_and_modify']})it('should import a snippet DSL from URL and navigate to the imported snippet', async () => {@@ -130,4 +144,18 @@ describe('ImportSnippetDSLDialog', () => {expect(onClose).not.toHaveBeenCalled()})})++ it('should disable import without snippet create permission', async () => {+ const user = userEvent.setup()+ contextMocks.workspacePermissionKeys = []++ render(<ImportSnippetDSLDialog isOpen onClose={vi.fn()} />)++ await user.click(screen.getByRole('button', { name: 'snippet.importFromDSLUrl' }))+ await user.type(screen.getByPlaceholderText('snippet.importFromDSLUrlPlaceholder'), 'https://example.com/snippet.yml')+ await user.click(screen.getByRole('button', { name: 'common.operation.create' }))++ expect(screen.getByRole('button', { name: 'common.operation.create' })).toBeDisabled()+ expect(serviceMocks.importMutateAsync).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx b/web/app/components/snippets/components/__tests__/snippet-main.spec.tsxindex 1cabdc903f2..5be724ce257 100644--- a/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx+++ b/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx@@ -26,6 +26,9 @@ const mockHandleWorkflowStartRunInWorkflow = vi.fn()const mockHandleCheckBeforePublish = vi.fn()const mockPush = vi.hoisted(() => vi.fn())const mockUseAvailableNodesMetaData = vi.hoisted(() => vi.fn())+const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['snippets.create_and_modify'],+}))const mockInspectVarsCrud = {hasNodeInspectVars: vi.fn(),hasSetInspectVar: vi.fn(),@@ -49,6 +52,12 @@ vi.mock('@langgenius/dify-ui/toast', () => ({success: vi.fn(),},}))++vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))let capturedHooksStore: Record<string, unknown> | undefinedlet capturedWorkflowNodes: WorkflowProps['nodes'] | undefinedlet snippetDetailStoreState: {@@ -160,9 +169,11 @@ vi.mock('@/app/components/snippets/components/snippet-children', () => ({onExitEditingWithoutSave,onPublish,canSave,+ canEdit,isEditing,}: {canSave: boolean+ canEdit: booleanisEditing: booleanonCancel: () => voidonEdit: () => void@@ -170,7 +181,7 @@ vi.mock('@/app/components/snippets/components/snippet-children', () => ({onPublish: () => void}) => (<div>- {!isEditing && <button type="button" onClick={onEdit}>edit</button>}+ {!isEditing && canEdit && <button type="button" onClick={onEdit}>edit</button>}<a href="/snippets">snippets list</a><button type="button" onClick={onExitEditingWithoutSave}>exit without save</button><button type="button" disabled={!canSave} onClick={onPublish}>publish</button>@@ -324,6 +335,7 @@ describe('SnippetMain', () => {reset: mockReset,setFields: mockSetFields,}+ mockWorkspacePermissionKeys.value = ['snippets.create_and_modify']})describe('Initial Mode', () => {@@ -339,6 +351,23 @@ describe('SnippetMain', () => {expect(capturedWorkflowNodes?.map(node => node.id)).toEqual(['draft-node'])})+ it('should stay readonly without snippet create-and-modify permission', async () => {+ mockWorkspacePermissionKeys.value = []+ const draftNode = createDraftNode('draft-node')++ renderSnippetMain({+ hasPublishedWorkflow: false,+ workflowDraftNodes: [draftNode],+ })++ expect(screen.queryByRole('button', { name: 'edit' })).not.toBeInTheDocument()++ const doSyncWorkflowDraft = capturedHooksStore?.doSyncWorkflowDraft as (() => Promise<void>)+ await doSyncWorkflowDraft()++ expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()+ })+it('should enter readonly mode with published graph by default when published workflow exists', async () => {const publishedNode = createDraftNode('published-node')const draftNode = createDraftNode('draft-node')diff --git a/web/app/components/snippets/components/hooks/use-snippet-input-field-actions.ts b/web/app/components/snippets/components/hooks/use-snippet-input-field-actions.tsindex d8142232cfb..862cb3cfc29 100644--- a/web/app/components/snippets/components/hooks/use-snippet-input-field-actions.ts+++ b/web/app/components/snippets/components/hooks/use-snippet-input-field-actions.ts@@ -5,10 +5,12 @@ import { useNodesSyncDraft } from '../../hooks/use-nodes-sync-draft'import { useSnippetDetailStore } from '../../store'type UseSnippetInputFieldActionsOptions = {+ canEdit?: booleansnippetId: string}export const useSnippetInputFieldActions = ({+ canEdit = true,snippetId,}: UseSnippetInputFieldActionsOptions) => {const { syncInputFieldsDraft } = useNodesSyncDraft(snippetId)@@ -21,11 +23,14 @@ export const useSnippetInputFieldActions = ({})))const handleFieldsChange = useCallback((newFields: SnippetInputField[]) => {+ if (!canEdit)+ return+setFields(newFields)void syncInputFieldsDraft(newFields, {onRefresh: setFields,})- }, [setFields, syncInputFieldsDraft])+ }, [canEdit, setFields, syncInputFieldsDraft])return {fields,diff --git a/web/app/components/snippets/components/snippet-children.tsx b/web/app/components/snippets/components/snippet-children.tsxindex 4675ad8fa1f..8ce66be3053 100644--- a/web/app/components/snippets/components/snippet-children.tsx+++ b/web/app/components/snippets/components/snippet-children.tsx@@ -8,6 +8,7 @@ type SnippetChildrenProps = {snippetId: stringfields: SnippetInputField[]canDiscardChanges: boolean+ canEdit?: booleancanSave: booleanhasDraftChanges: booleanisEditing: boolean@@ -24,6 +25,7 @@ const SnippetChildren = ({snippetId,fields,canDiscardChanges,+ canEdit = true,canSave,hasDraftChanges,isEditing,@@ -42,6 +44,7 @@ const SnippetChildren = ({<SnippetHeadersnippetId={snippetId}canDiscardChanges={canDiscardChanges}+ canEdit={canEdit}canSave={canSave}hasDraftChanges={hasDraftChanges}isEditing={isEditing}diff --git a/web/app/components/snippets/components/snippet-header/index.tsx b/web/app/components/snippets/components/snippet-header/index.tsxindex 63d904c78e7..b2d433d7197 100644--- a/web/app/components/snippets/components/snippet-header/index.tsx+++ b/web/app/components/snippets/components/snippet-header/index.tsx@@ -16,6 +16,7 @@ import RunMode from './run-mode'type SnippetHeaderProps = {snippetId: stringcanDiscardChanges: boolean+ canEdit?: booleancanSave: booleanhasDraftChanges: booleanisEditing: boolean@@ -39,6 +40,7 @@ const ViewOnlyBadge = () => {}const EditActions = ({+ canEdit = true,canSave,hasDraftChanges,isEditing,@@ -48,11 +50,14 @@ const EditActions = ({onExitEditingWithoutSave,onPublish,onSaveAndExitEditing,-}: Pick<SnippetHeaderProps, 'canSave' | 'hasDraftChanges' | 'isEditing' | 'isPublishing' | 'onEdit' | 'onExitEditing' | 'onExitEditingWithoutSave' | 'onPublish' | 'onSaveAndExitEditing'>) => {+}: Pick<SnippetHeaderProps, 'canEdit' | 'canSave' | 'hasDraftChanges' | 'isEditing' | 'isPublishing' | 'onEdit' | 'onExitEditing' | 'onExitEditingWithoutSave' | 'onPublish' | 'onSaveAndExitEditing'>) => {const { t } = useTranslation('snippet')const [exitConfirmOpen, setExitConfirmOpen] = useState(false)if (!isEditing) {+ if (!canEdit)+ return null+return (<Button variant="primary" onClick={onEdit}>{t('edit')}@@ -67,8 +72,11 @@ const EditActions = ({onOpenChange={setExitConfirmOpen}trigger={(<Button- disabled={isPublishing}+ disabled={isPublishing || !canEdit}onClick={(event) => {+ if (!canEdit)+ return+if (!hasDraftChanges) {event.preventDefault()void onExitEditing()@@ -81,8 +89,8 @@ const EditActions = ({{t('exitEditing')}</Button>)}- disabled={isPublishing}- saveDisabled={!canSave}+ disabled={isPublishing || !canEdit}+ saveDisabled={!canEdit || !canSave}loading={isPublishing}onDiscard={async () => {await onExitEditingWithoutSave()@@ -96,7 +104,7 @@ const EditActions = ({<Buttonvariant="primary"loading={isPublishing}- disabled={isPublishing || !canSave}+ disabled={isPublishing || !canEdit || !canSave}onClick={onPublish}>{t('save')}@@ -108,6 +116,7 @@ const EditActions = ({const SnippetHeader = ({snippetId,canDiscardChanges,+ canEdit = true,canSave,hasDraftChanges,isEditing,@@ -135,6 +144,7 @@ const SnippetHeader = ({: <ViewOnlyBadge />,left: (<EditActions+ canEdit={canEdit}canSave={canSave}hasDraftChanges={hasDraftChanges}isEditing={isEditing}@@ -164,7 +174,7 @@ const SnippetHeader = ({viewHistoryProps,},}- }, [canDiscardChanges, canSave, hasDraftChanges, isEditing, isPublishing, onCancel, onEdit, onExitEditing, onExitEditingWithoutSave, onPublish, onSaveAndExitEditing, t, viewHistoryProps])+ }, [canDiscardChanges, canEdit, canSave, hasDraftChanges, isEditing, isPublishing, onCancel, onEdit, onExitEditing, onExitEditingWithoutSave, onPublish, onSaveAndExitEditing, t, viewHistoryProps])return <Header {...headerProps} />}diff --git a/web/app/components/snippets/components/snippet-main.tsx b/web/app/components/snippets/components/snippet-main.tsxindex 1126e271f27..9f9ecab698a 100644--- a/web/app/components/snippets/components/snippet-main.tsx+++ b/web/app/components/snippets/components/snippet-main.tsx@@ -23,6 +23,7 @@ import {initialEdges,initialNodes,} from '@/app/components/workflow/utils'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useRouter } from '@/next/navigation'import { useSnippetPublishedWorkflow } from '@/service/use-snippet-workflows'import { useConfigsMap } from '../hooks/use-configs-map'@@ -33,6 +34,7 @@ import { useSnippetRefreshDraft } from '../hooks/use-snippet-refresh-draft'import { useSnippetRun } from '../hooks/use-snippet-run'import { useSnippetStartRun } from '../hooks/use-snippet-start-run'import { useSnippetDetailStore } from '../store'+import { canCreateAndModifySnippets } from '../utils/permission'import { useSnippetInputFieldActions } from './hooks/use-snippet-input-field-actions'import { useSnippetPublish } from './hooks/use-snippet-publish'import SaveBeforeLeavingDialog from './save-before-leaving-dialog'@@ -54,6 +56,7 @@ type SnippetMainContentProps = {snippetId: stringfields: SnippetInputField[]canDiscardChanges: boolean+ canEdit: booleancanSave: booleanhasDraftChanges: booleanisEditing: boolean@@ -92,6 +95,7 @@ const SnippetMainContent = ({snippetId,fields,canDiscardChanges,+ canEdit,canSave,hasDraftChanges,isEditing,@@ -224,6 +228,7 @@ const SnippetMainContent = ({snippetId={snippetId}fields={fields}canDiscardChanges={canDiscardChanges}+ canEdit={canEdit}canSave={canSave}hasDraftChanges={hasDraftChanges}isEditing={isEditing}@@ -261,7 +266,10 @@ const SnippetMain = ({draftEdges,draftViewport,}: SnippetMainProps) => {- const [isEditing, setIsEditing] = useState(!hasPublishedWorkflow)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)+ const [isEditingState, setIsEditingState] = useState(!hasPublishedWorkflow)+ const isEditing = canCreateAndModifySnippet && isEditingStateconst [localDraftState, setLocalDraftState] = useState<LocalDraftState>()const [draftChangeState, setDraftChangeState] = useState({initial: hasInitialDraftChanges,@@ -365,6 +373,7 @@ const SnippetMain = ({fields,handleFieldsChange,} = useSnippetInputFieldActions({+ canEdit: canCreateAndModifySnippet,snippetId,})const {@@ -405,7 +414,7 @@ const SnippetMain = ({const doSyncWorkflowDraft = useCallback((...args: Parameters<typeof syncWorkflowDraft>) => {- if (!isEditing)+ if (!canCreateAndModifySnippet || !isEditing)return Promise.resolve()const [@@ -421,19 +430,22 @@ const SnippetMain = ({setHasDraftChanges(true)return syncWorkflowDraft(...args)- }, [isEditing, setHasDraftChanges, syncWorkflowDraft])+ }, [canCreateAndModifySnippet, isEditing, setHasDraftChanges, syncWorkflowDraft])const syncWorkflowDraftWhenPageCloseInEditing = useCallback(() => {- if (!isEditing)+ if (!canCreateAndModifySnippet || !isEditing)returnsyncWorkflowDraftWhenPageClose()- }, [isEditing, syncWorkflowDraftWhenPageClose])+ }, [canCreateAndModifySnippet, isEditing, syncWorkflowDraftWhenPageClose])const handleFieldsChangeInEditing = useCallback((nextFields: SnippetInputField[]) => {+ if (!canCreateAndModifySnippet || !isEditing)+ return+handleFieldsChange(nextFields)setHasDraftChanges(true)- }, [handleFieldsChange, setHasDraftChanges])+ }, [canCreateAndModifySnippet, handleFieldsChange, isEditing, setHasDraftChanges])const updateLocalDraftFromSyncPayload = useCallback((syncedDraftPayload?: Omit<SnippetDraftSyncPayload, 'hash'> | void,@@ -468,6 +480,9 @@ const SnippetMain = ({}, [draftPayload, fields, setFields])const handleCancelChanges = useCallback(async () => {+ if (!canCreateAndModifySnippet)+ return+const workflow = publishedWorkflow ?? (await refetchPublishedWorkflow()).dataif (!workflow)return@@ -485,32 +500,41 @@ const SnippetMain = ({onRefresh: setFields,})setHasDraftChanges(false)- }, [handleRestoreFromPublishedWorkflow, publishedWorkflow, refetchPublishedWorkflow, setFields, setHasDraftChanges, syncInputFieldsDraft, updateLocalDraftFromSyncPayload])+ }, [canCreateAndModifySnippet, handleRestoreFromPublishedWorkflow, publishedWorkflow, refetchPublishedWorkflow, setFields, setHasDraftChanges, syncInputFieldsDraft, updateLocalDraftFromSyncPayload])const handleExitEditing = useCallback(async () => {- if (hasDraftChanges)+ if (!canCreateAndModifySnippet || hasDraftChanges)return- setIsEditing(false)- }, [hasDraftChanges])+ setIsEditingState(false)+ }, [canCreateAndModifySnippet, hasDraftChanges])const handleExitEditingWithoutSave = useCallback(async () => {+ if (!canCreateAndModifySnippet)+ return+const syncedDraftPayload = await syncWorkflowDraft(true)updateLocalDraftFromSyncPayload(syncedDraftPayload)skipNextForcedDraftSyncRef.current = true- setIsEditing(false)- }, [syncWorkflowDraft, updateLocalDraftFromSyncPayload])+ setIsEditingState(false)+ }, [canCreateAndModifySnippet, syncWorkflowDraft, updateLocalDraftFromSyncPayload])const handleDiscardAndRoute = useCallback(async () => {+ if (!canCreateAndModifySnippet)+ return+const syncedDraftPayload = await syncWorkflowDraft(true)updateLocalDraftFromSyncPayload(syncedDraftPayload)skipNextForcedDraftSyncRef.current = true- }, [syncWorkflowDraft, updateLocalDraftFromSyncPayload])+ }, [canCreateAndModifySnippet, syncWorkflowDraft, updateLocalDraftFromSyncPayload])const handleEdit = useCallback(() => {+ if (!canCreateAndModifySnippet)+ return+skipNextForcedDraftSyncRef.current = true- setIsEditing(true)- }, [])+ setIsEditingState(true)+ }, [canCreateAndModifySnippet])const hooksStore = useMemo(() => {return {@@ -594,6 +618,7 @@ const SnippetMain = ({snippetId={snippetId}fields={fields}canDiscardChanges={hasPublishedWorkflow}+ canEdit={canCreateAndModifySnippet}canSave={canSave}hasDraftChanges={hasDraftChanges}isEditing={isEditing}@@ -609,7 +634,7 @@ const SnippetMain = ({}}onSavedAndExitEditing={() => {setHasDraftChanges(false)- setIsEditing(false)+ setIsEditingState(false)}}/></WorkflowWithInnerContext>diff --git a/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsx b/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsxindex d4b7de7cc0a..73b0f81ab35 100644--- a/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsx+++ b/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsx@@ -8,12 +8,14 @@ const {mockSyncDraftWorkflow,mockToastError,mockToastSuccess,+ mockWorkspacePermissionKeys,} = vi.hoisted(() => ({mockMutateAsync: vi.fn(),mockPush: vi.fn(),mockSyncDraftWorkflow: vi.fn(),mockToastError: vi.fn(),mockToastSuccess: vi.fn(),+ mockWorkspacePermissionKeys: vi.fn(() => ['snippets.create_and_modify']),}))vi.mock('@/next/navigation', () => ({@@ -35,6 +37,15 @@ vi.mock('@/service/client', () => ({},}))+vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ workspacePermissionKeys: mockWorkspacePermissionKeys(),+ }),+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys(),+ }),+}))+vi.mock('@langgenius/dify-ui/toast', () => ({toast: {success: (...args: unknown[]) => mockToastSuccess(...args),@@ -45,6 +56,7 @@ vi.mock('@langgenius/dify-ui/toast', () => ({describe('useCreateSnippet', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify'])})describe('State', () => {diff --git a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.tsindex e9ac6848425..ee5a2663134 100644--- a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts+++ b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts@@ -6,6 +6,7 @@ import { useNodesSyncDraft } from '../use-nodes-sync-draft'const mockGetNodes = vi.fn()const mockGetNodesReadOnly = vi.fn()+const mockUseNodesReadOnlyByCanEdit = vi.fn()const mockPostWithKeepalive = vi.fn()const mockSyncDraftWorkflow = vi.fn()const mockSetDraftUpdatedAt = vi.fn()@@ -30,7 +31,10 @@ vi.mock('reactflow', () => ({}))vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({- useNodesReadOnly: () => ({ getNodesReadOnly: mockGetNodesReadOnly }),+ useNodesReadOnly: () => {+ throw new Error('Missing HooksStoreContext.Provider in the tree')+ },+ useNodesReadOnlyByCanEdit: (canEdit: boolean) => mockUseNodesReadOnlyByCanEdit(canEdit),}))vi.mock('@/app/components/workflow/hooks/use-serial-async-callback', () => ({@@ -96,6 +100,7 @@ describe('snippet/use-nodes-sync-draft', () => {setDraftUpdatedAt: mockSetDraftUpdatedAt,setSyncWorkflowDraftHash: mockSetSyncWorkflowDraftHash,}+ mockUseNodesReadOnlyByCanEdit.mockReturnValue({ getNodesReadOnly: mockGetNodesReadOnly })mockGetNodesReadOnly.mockReturnValue(false)mockGetNodes.mockReturnValue([{ id: 'node-1', position: { x: 0, y: 0 }, data: { title: 'Start', _temp: 'drop' } },@@ -131,6 +136,7 @@ describe('snippet/use-nodes-sync-draft', () => {hash: 'draft-hash',},})+ expect(mockUseNodesReadOnlyByCanEdit).toHaveBeenCalledWith(true)})it('should snapshot graph before queued draft sync executes', async () => {diff --git a/web/app/components/snippets/hooks/use-create-snippet.ts b/web/app/components/snippets/hooks/use-create-snippet.tsindex 90a5b20d4dd..7ace87cbafd 100644--- a/web/app/components/snippets/hooks/use-create-snippet.ts+++ b/web/app/components/snippets/hooks/use-create-snippet.ts@@ -2,18 +2,25 @@ import type { CreateSnippetDialogPayload } from '@/app/components/snippets/creatimport { toast } from '@langgenius/dify-ui/toast'import { useState } from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useRouter } from '@/next/navigation'import { consoleClient } from '@/service/client'import { useCreateSnippetMutation } from '@/service/use-snippets'+import { canCreateAndModifySnippets } from '../utils/permission'export const useCreateSnippet = () => {const { t } = useTranslation()const { push } = useRouter()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const createSnippetMutation = useCreateSnippetMutation()const [isCreateSnippetDialogOpen, setIsCreateSnippetDialogOpen] = useState(false)const [isCreatingSnippet, setIsCreatingSnippet] = useState(false)+ const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)const handleOpenCreateSnippetDialog = () => {+ if (!canCreateAndModifySnippet)+ return+setIsCreateSnippetDialogOpen(true)}@@ -27,6 +34,9 @@ export const useCreateSnippet = () => {graph,input_fields,}: CreateSnippetDialogPayload) => {+ if (!canCreateAndModifySnippet)+ return+setIsCreatingSnippet(true)try {@@ -60,6 +70,7 @@ export const useCreateSnippet = () => {}return {+ canCreateAndModifySnippet,createSnippetMutation,handleCloseCreateSnippetDialog,handleCreateSnippet,diff --git a/web/app/components/snippets/hooks/use-nodes-sync-draft.ts b/web/app/components/snippets/hooks/use-nodes-sync-draft.tsindex 9dd5515ea0e..e38a0539aa6 100644--- a/web/app/components/snippets/hooks/use-nodes-sync-draft.ts+++ b/web/app/components/snippets/hooks/use-nodes-sync-draft.ts@@ -4,7 +4,7 @@ import type { SnippetDraftSyncPayload, SnippetDraftSyncResponse, SnippetWorkflowimport { produce } from 'immer'import { useCallback } from 'react'import { useStoreApi } from 'reactflow'-import { useNodesReadOnly } from '@/app/components/workflow/hooks/use-workflow'+import { useNodesReadOnlyByCanEdit } from '@/app/components/workflow/hooks/use-workflow'import { useWorkflowStore } from '@/app/components/workflow/store'import { API_PREFIX } from '@/config'import { consoleClient } from '@/service/client'@@ -46,7 +46,7 @@ const enqueueSnippetDraftSync = <Result>(export const useNodesSyncDraft = (snippetId: string) => {const store = useStoreApi()const workflowStore = useWorkflowStore()- const { getNodesReadOnly } = useNodesReadOnly()+ const { getNodesReadOnly } = useNodesReadOnlyByCanEdit(true)const { handleRefreshWorkflowDraft } = useSnippetRefreshDraft(snippetId)const getInputFieldsSyncPayload = useCallback((inputFields?: SnippetInputField[]) => {diff --git a/web/app/components/snippets/import-snippet-dsl-dialog.tsx b/web/app/components/snippets/import-snippet-dsl-dialog.tsxindex 9933db7418d..7e99726102f 100644--- a/web/app/components/snippets/import-snippet-dsl-dialog.tsx+++ b/web/app/components/snippets/import-snippet-dsl-dialog.tsx@@ -19,11 +19,13 @@ import { toast } from '@langgenius/dify-ui/toast'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import Uploader from '@/app/components/app/create-from-dsl-modal/uploader'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useRouter } from '@/next/navigation'import {useConfirmSnippetImportMutation,useImportSnippetDSLMutation,} from '@/service/use-snippets'+import { canCreateAndModifySnippets } from './utils/permission'type ImportSnippetDSLDialogProps = {isOpen: boolean@@ -105,6 +107,8 @@ function ImportSnippetDSLDialog({}: ImportSnippetDSLDialogProps) {const { t } = useTranslation()const { push } = useRouter()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)const importSnippetMutation = useImportSnippetDSLMutation()const confirmSnippetImportMutation = useConfirmSnippetImportMutation()const [currentTab, setCurrentTab] = useState<ImportSnippetDSLDialogTab>(ImportSnippetDSLDialogTab.FromFile)@@ -162,6 +166,9 @@ function ImportSnippetDSLDialog({}, [handleImportSuccess])const handleImport = useCallback(async () => {+ if (!canCreateAndModifySnippet)+ return+try {const response = await importSnippetMutation.mutateAsync({mode: currentTab === ImportSnippetDSLDialogTab.FromFile ? 'yaml-content' : 'yaml-url',@@ -175,10 +182,10 @@ function ImportSnippetDSLDialog({if (error instanceof Error && error.message)toast.error(error.message)}- }, [currentTab, dslUrl, fileContent, handleImportResponse, importSnippetMutation])+ }, [canCreateAndModifySnippet, currentTab, dslUrl, fileContent, handleImportResponse, importSnippetMutation])const handleConfirmImport: MouseEventHandler = useCallback(async () => {- if (!importId)+ if (!canCreateAndModifySnippet || !importId)returntry {@@ -189,7 +196,7 @@ function ImportSnippetDSLDialog({if (error instanceof Error && error.message)toast.error(error.message)}- }, [confirmSnippetImportMutation, handleImportResponse, importId])+ }, [canCreateAndModifySnippet, confirmSnippetImportMutation, handleImportResponse, importId])const tabs = useMemo(() => [{@@ -204,6 +211,7 @@ function ImportSnippetDSLDialog({const isSubmitting = importSnippetMutation.isPending || confirmSnippetImportMutation.isPendingconst importDisabled = isSubmitting+ || !canCreateAndModifySnippet|| (currentTab === ImportSnippetDSLDialogTab.FromFile && !currentFile)|| (currentTab === ImportSnippetDSLDialogTab.FromUrl && !dslUrl.trim())@@ -277,7 +285,7 @@ function ImportSnippetDSLDialog({{showConfirmModal && (<SnippetDSLConfirmDialogversions={versions}- confirmDisabled={confirmSnippetImportMutation.isPending}+ confirmDisabled={confirmSnippetImportMutation.isPending || !canCreateAndModifySnippet}onCancel={() => setShowConfirmModal(false)}onConfirm={handleConfirmImport}/>diff --git a/web/app/components/snippets/utils/permission.ts b/web/app/components/snippets/utils/permission.tsnew file mode 100644index 00000000000..0eb2018ea76--- /dev/null+++ b/web/app/components/snippets/utils/permission.ts@@ -0,0 +1,22 @@+import type { PermissionKey } from '@/models/access-control'+import { hasPermission } from '@/utils/permission'++export const SnippetPermission = {+ CreateAndModify: 'snippets.create_and_modify',+ Management: 'snippets.management',+} as const satisfies Record<string, PermissionKey>++export const canCreateAndModifySnippets = (workspacePermissionKeys: readonly PermissionKey[] | null | undefined) => {+ return hasPermission(workspacePermissionKeys, SnippetPermission.CreateAndModify)+}++export const canManageSnippets = (workspacePermissionKeys: readonly PermissionKey[] | null | undefined) => {+ return hasPermission(workspacePermissionKeys, SnippetPermission.Management)+}++export const canAccessSnippets = (workspacePermissionKeys: readonly PermissionKey[] | null | undefined) => {+ return hasPermission(workspacePermissionKeys, [+ SnippetPermission.CreateAndModify,+ SnippetPermission.Management,+ ])+}diff --git a/web/app/components/tools/edit-custom-collection-modal/index.tsx b/web/app/components/tools/edit-custom-collection-modal/index.tsxindex ef3218bb570..4c745256b83 100644--- a/web/app/components/tools/edit-custom-collection-modal/index.tsx+++ b/web/app/components/tools/edit-custom-collection-modal/index.tsx@@ -14,7 +14,6 @@ import {DrawerViewport,} from '@langgenius/dify-ui/drawer'import { Input } from '@langgenius/dify-ui/input'-import { ScrollArea } from '@langgenius/dify-ui/scroll-area'import { Textarea } from '@langgenius/dify-ui/textarea'import { toast } from '@langgenius/dify-ui/toast'import { RiSettings2Line } from '@remixicon/react'@@ -221,7 +220,7 @@ const EditCustomCollectionModal: FC<Props> = ({: 'data-[swipe-direction=right]:right-2',)}>- <DrawerContent className="flex min-h-0 flex-1 flex-col overflow-hidden p-0 pb-0">+ <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0"><div className="shrink-0 border-b border-divider-regular py-4"><div className="flex h-6 items-center justify-between pr-5 pl-6"><DrawerTitle className="min-w-0 truncate system-xl-semibold text-text-primary">@@ -234,14 +233,8 @@ const EditCustomCollectionModal: FC<Props> = ({</div></div><div className="min-h-0 flex-1">- <div className="flex h-full min-h-0 flex-col">- <ScrollArea- className="min-h-0 flex-1 overflow-hidden"- slotClassNames={{- viewport: 'overscroll-contain',- content: 'space-y-4 py-3 pr-8 pl-6',- }}- >+ <div className="flex h-full flex-col">+ <div className="h-0 grow space-y-4 overflow-y-auto px-6 py-3"><div><div className="py-2 system-sm-medium text-text-primary">{t('createTool.name', { ns: 'tools' })}@@ -380,7 +373,7 @@ const EditCustomCollectionModal: FC<Props> = ({/></div>- </ScrollArea>+ </div><div className={cn(isEdit ? 'justify-between' : 'justify-end', 'mt-2 flex shrink-0 rounded-b-[10px] border-t border-divider-regular bg-background-section-burn px-6 py-4')}>{isEdit && (diff --git a/web/app/components/tools/hooks/use-tool-permissions.ts b/web/app/components/tools/hooks/use-tool-permissions.tsnew file mode 100644index 00000000000..2d393007a29--- /dev/null+++ b/web/app/components/tools/hooks/use-tool-permissions.ts@@ -0,0 +1,16 @@+'use client'++import { useSelector as useAppContextSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'++export const useCanManageTools = () => {+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)++ return hasPermission(workspacePermissionKeys, 'tool.manage')+}++export const useCanManageMCP = () => {+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)++ return hasPermission(workspacePermissionKeys, 'mcp.manage')+}diff --git a/web/app/components/tools/mcp/__tests__/create-card.spec.tsx b/web/app/components/tools/mcp/__tests__/create-card.spec.tsxindex 335eee0bf65..0d8c0b9bc2f 100644--- a/web/app/components/tools/mcp/__tests__/create-card.spec.tsx+++ b/web/app/components/tools/mcp/__tests__/create-card.spec.tsx@@ -40,14 +40,11 @@ vi.mock('../modal', () => ({},}))-// Mutable workspace manager state-let mockIsCurrentWorkspaceManager = true+let mockWorkspacePermissionKeys: string[] = ['mcp.manage']-// Mock the app contextvi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager,- isCurrentWorkspaceEditor: true,+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -87,7 +84,7 @@ describe('NewMCPCard', () => {beforeEach(() => {mockCreateMCP.mockClear()- mockIsCurrentWorkspaceManager = true+ mockWorkspacePermissionKeys = ['mcp.manage']})describe('Rendering', () => {@@ -108,8 +105,7 @@ describe('NewMCPCard', () => {it('should render add icon', () => {render(<NewMCPCard {...defaultProps} />, { wrapper: createWrapper() })- const svgElements = document.querySelectorAll('svg')- expect(svgElements.length).toBeGreaterThan(0)+ expect(document.querySelector('.border-dashed')).toBeInTheDocument()})it('should render toolbar button', () => {@@ -154,17 +150,17 @@ describe('NewMCPCard', () => {})})- describe('Non-Manager User', () => {- it('should not render card when user is not workspace manager', () => {- mockIsCurrentWorkspaceManager = false+ describe('mcp.manage Permission', () => {+ it('should not render card when user lacks mcp.manage', () => {+ mockWorkspacePermissionKeys = []render(<NewMCPCard {...defaultProps} />, { wrapper: createWrapper() })expect(screen.queryByText('tools.mcp.create.cardTitle')).not.toBeInTheDocument()})- it('should not render toolbar button when user is not workspace manager', () => {- mockIsCurrentWorkspaceManager = false+ it('should not render toolbar button when user lacks mcp.manage', () => {+ mockWorkspacePermissionKeys = []render(<NewMCPButton {...defaultProps} />, { wrapper: createWrapper() })diff --git a/web/app/components/tools/mcp/__tests__/index.spec.tsx b/web/app/components/tools/mcp/__tests__/index.spec.tsxindex 4f12310ea1a..264d71db190 100644--- a/web/app/components/tools/mcp/__tests__/index.spec.tsx+++ b/web/app/components/tools/mcp/__tests__/index.spec.tsx@@ -12,14 +12,25 @@ type MockDetail = MockProvider | undefined// Mock dependenciesconst mockRefetch = vi.fn()+const mockUseAllToolProviders = vi.fn()let mockProviders: MockProvider[] = []let mockIsLoadingToolProviders = false+let mockWorkspacePermissionKeys = ['mcp.manage']vi.mock('@/service/use-tools', () => ({- useAllToolProviders: () => ({- data: mockProviders,- isLoading: mockIsLoadingToolProviders,- refetch: mockRefetch,+ useAllToolProviders: (enabled?: boolean) => {+ mockUseAllToolProviders(enabled)+ return {+ data: mockProviders,+ isLoading: mockIsLoadingToolProviders,+ refetch: mockRefetch,+ }+ },+}))++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -36,9 +47,9 @@ vi.mock('@/app/components/tools/provider/tool-card-skeleton', () => ({// Mock child componentsvi.mock('../create-card', () => ({default: ({ handleCreate }: { handleCreate: (provider: { id: string, name: string }) => void }) => (- <div data-testid="create-card" onClick={() => handleCreate({ id: 'new-id', name: 'New Provider' })}>+ <button data-testid="create-card" type="button" onClick={() => handleCreate({ id: 'new-id', name: 'New Provider' })}>Create Card- </div>+ </button>),}))@@ -47,7 +58,7 @@ vi.mock('../provider-card', () => ({const displayName = typeof data.name === 'string' ? data.name : Object.values(data.name)[0]return (<div data-testid={`provider-card-${data.id}`}>- <span onClick={() => handleSelect(data.id)}>{displayName}</span>+ <button type="button" onClick={() => handleSelect(data.id)}>{displayName}</button><button data-testid={`update-btn-${data.id}`} onClick={() => onUpdate(data.id)}>Update</button><button data-testid={`delete-btn-${data.id}`} onClick={onDeleted}>Delete</button></div>@@ -78,6 +89,7 @@ describe('MCPList', () => {vi.useFakeTimers()mockProviders = []mockIsLoadingToolProviders = false+ mockWorkspacePermissionKeys = ['mcp.manage']mockRefetch.mockResolvedValue(undefined)})@@ -98,6 +110,16 @@ describe('MCPList', () => {expect(screen.getByTestId('create-card')).toBeInTheDocument()})+ it('should not render or query providers when user lacks mcp.manage', () => {+ mockWorkspacePermissionKeys = []++ const { container } = render(<MCPList searchText="" />)++ expect(container.firstElementChild).toBeNull()+ expect(mockUseAllToolProviders).toHaveBeenCalledWith(false)+ expect(screen.queryByTestId('create-card')).not.toBeInTheDocument()+ })+it('should hide create card when parent moves creation into the toolbar', () => {mockProviders = [{ id: '1', name: 'Provider 1', type: 'mcp' },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 62c6d5f3f61..c9814e8c8d6 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@@ -57,7 +57,7 @@ type MockHookState = {description: stringparameters: Record<string, unknown>} | undefined- isCurrentWorkspaceManager: boolean+ canManageMCP: booleantoggleDisabled: booleanisMinimalState: booleanappUnpublished: boolean@@ -80,7 +80,7 @@ const createDefaultHookState = (overrides: Partial<MockHookState> = {}): MockHoodescription: 'Test server',parameters: {},},- isCurrentWorkspaceManager: true,+ canManageMCP: true,toggleDisabled: false,isMinimalState: false,appUnpublished: false,@@ -143,6 +143,28 @@ describe('MCPServiceCard', () => {expect(screen.getByRole('switch')).toBeInTheDocument()})+ it('should keep status visible and disable management controls without mcp.manage', () => {+ mockHookState = createDefaultHookState({+ canManageMCP: false,+ toggleDisabled: true,+ })++ render(<MCPServiceCard appInfo={createMockAppInfo()} />, { wrapper: createWrapper() })++ expect(screen.getByText('tools.mcp.server.title')).toBeInTheDocument()+ expect(screen.getByText(/appOverview.overview.status/)).toBeInTheDocument()+ expect(screen.getByText('https://api.example.com/mcp/server/abc123/mcp')).toBeInTheDocument()++ const switchElement = screen.getByRole('switch')+ expect(switchElement.className).toContain('cursor-not-allowed')++ const editButton = screen.getByRole('button', { name: /tools\.mcp\.server\.edit/i })+ expect(editButton).toBeDisabled()++ const regenerateButton = screen.getByRole('button', { name: /appOverview\.overview\.appInfo\.regenerate/i })+ expect(regenerateButton).toBeDisabled()+ })+it('should render edit button in full state', () => {render(<MCPServiceCard appInfo={createMockAppInfo()} />, { wrapper: createWrapper() })diff --git a/web/app/components/tools/mcp/__tests__/provider-card.spec.tsx b/web/app/components/tools/mcp/__tests__/provider-card.spec.tsxindex 4ac9e354637..6ff54b6ec1c 100644--- a/web/app/components/tools/mcp/__tests__/provider-card.spec.tsx+++ b/web/app/components/tools/mcp/__tests__/provider-card.spec.tsx@@ -81,11 +81,11 @@ vi.mock('../detail/operation-dropdown', () => ({),}))-// Mock the app context+let mockWorkspacePermissionKeys: string[] = ['mcp.manage']+vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: true,- isCurrentWorkspaceEditor: true,+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -155,6 +155,7 @@ describe('MCPCard', () => {mockDeleteMCP.mockClear()mockUpdateMCP.mockResolvedValue({ result: 'success' })mockDeleteMCP.mockResolvedValue({ result: 'success' })+ mockWorkspacePermissionKeys = ['mcp.manage']})describe('Rendering', () => {@@ -335,12 +336,20 @@ describe('MCPCard', () => {})describe('Operation Dropdown', () => {- it('should render operation dropdown for workspace managers', () => {+ it('should render operation dropdown when user has mcp.manage', () => {render(<MCPCard {...defaultProps} />, { wrapper: createWrapper() })expect(screen.getByTestId('operation-dropdown')).toBeInTheDocument()})+ it('should not render operation dropdown when user lacks mcp.manage', () => {+ mockWorkspacePermissionKeys = []++ render(<MCPCard {...defaultProps} />, { wrapper: createWrapper() })++ expect(screen.queryByTestId('operation-dropdown')).not.toBeInTheDocument()+ })+it('should stop propagation when clicking on dropdown container', () => {const handleSelect = vi.fn()render(<MCPCard {...defaultProps} handleSelect={handleSelect} />, { wrapper: createWrapper() })diff --git a/web/app/components/tools/mcp/create-card.tsx b/web/app/components/tools/mcp/create-card.tsxindex 1ec9e99f3ad..58faa5368f5 100644--- a/web/app/components/tools/mcp/create-card.tsx+++ b/web/app/components/tools/mcp/create-card.tsx@@ -3,7 +3,7 @@ import type { ToolWithProvider } from '@/app/components/workflow/types'import { Button } from '@langgenius/dify-ui/button'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useAppContext } from '@/context/app-context'+import { useCanManageMCP } from '@/app/components/tools/hooks/use-tool-permissions'import { useDocLink } from '@/context/i18n'import { useCreateMCP } from '@/service/use-tools'import CreateEntryCard from '../provider/create-entry-card'@@ -14,18 +14,21 @@ type Props = Readonly<{}>function useMCPCreateAction({ handleCreate }: Props) {- const { isCurrentWorkspaceManager } = useAppContext()+ const canManageMCP = useCanManageMCP()const { mutateAsync: createMCP } = useCreateMCP()const [showModal, setShowModal] = useState(false)const create = async (info: Parameters<typeof createMCP>[0]) => {+ if (!canManageMCP)+ return+const provider = await createMCP(info)await handleCreate(provider)}return {+ canManageMCP,create,- isCurrentWorkspaceManager,setShowModal,showModal,}@@ -35,13 +38,13 @@ export function NewMCPButton({ handleCreate }: Props) {const { t } = useTranslation()const addMCPServerLabel = t('mcp.create.cardTitle', { ns: 'tools' })const {+ canManageMCP,create,- isCurrentWorkspaceManager,setShowModal,showModal,} = useMCPCreateAction({ handleCreate })- if (!isCurrentWorkspaceManager)+ if (!canManageMCP)return nullreturn (@@ -56,7 +59,7 @@ export function NewMCPButton({ handleCreate }: Props) {<span aria-hidden className="i-ri-add-line size-4 shrink-0" />{addMCPServerLabel}</Button>- {showModal && (+ {canManageMCP && showModal && (<MCPModalshow={showModal}onConfirm={create}@@ -71,8 +74,8 @@ const NewMCPCard = ({ handleCreate }: Props) => {const { t } = useTranslation()const docLink = useDocLink()const {+ canManageMCP,create,- isCurrentWorkspaceManager,setShowModal,showModal,} = useMCPCreateAction({ handleCreate })@@ -81,7 +84,7 @@ const NewMCPCard = ({ handleCreate }: Props) => {return (<>- {isCurrentWorkspaceManager && (+ {canManageMCP && (<CreateEntryCardtitle={t('mcp.create.cardTitle', { ns: 'tools' })}linkText={t('mcp.create.cardLink', { ns: 'tools' })}@@ -89,7 +92,7 @@ const NewMCPCard = ({ handleCreate }: Props) => {onCreate={() => setShowModal(true)}/>)}- {showModal && (+ {canManageMCP && showModal && (<MCPModalshow={showModal}onConfirm={create}diff --git a/web/app/components/tools/mcp/detail/__tests__/content.spec.tsx b/web/app/components/tools/mcp/detail/__tests__/content.spec.tsxindex 8f01d3f8d90..584b84f3ee3 100644--- a/web/app/components/tools/mcp/detail/__tests__/content.spec.tsx+++ b/web/app/components/tools/mcp/detail/__tests__/content.spec.tsx@@ -107,14 +107,13 @@ vi.mock('../tool-item', () => ({),}))-// Mutable workspace manager state-let mockIsCurrentWorkspaceManager = true+// Mutable workspace permission state+let mockWorkspacePermissionKeys: string[] = ['mcp.manage']// Mock the app contextvi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager,- isCurrentWorkspaceEditor: true,+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -196,7 +195,7 @@ describe('MCPDetailContent', () => {mockIsFetching = falsemockIsUpdating = falsemockIsAuthorizing = false- mockIsCurrentWorkspaceManager = true+ mockWorkspacePermissionKeys = ['mcp.manage']})describe('Rendering', () => {@@ -232,13 +231,13 @@ describe('MCPDetailContent', () => {expect(screen.getByTestId('operation-dropdown')).toBeInTheDocument()})- it('should not render operation dropdown for non-workspace managers', () => {- mockIsCurrentWorkspaceManager = false+ it('should not render detail when user lacks mcp.manage', () => {+ mockWorkspacePermissionKeys = []render(<MCPDetailContent {...defaultProps} />, { wrapper: createWrapper() })expect(screen.queryByTestId('operation-dropdown')).not.toBeInTheDocument()- expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeInTheDocument()+ expect(screen.queryByText('Test MCP Server')).not.toBeInTheDocument()})})@@ -466,16 +465,15 @@ describe('MCPDetailContent', () => {})})- it('should disable authorize button when not workspace manager', () => {- mockIsCurrentWorkspaceManager = false+ it('should not render authorize action when user lacks mcp.manage', () => {+ mockWorkspacePermissionKeys = []const detail = createMockDetail({ is_team_authorization: false })render(<MCPDetailContent {...defaultProps} detail={detail} />,{ wrapper: createWrapper() },)- const authorizeBtn = screen.getByText('tools.mcp.authorize')- expect(authorizeBtn.closest('button'))!.toBeDisabled()+ expect(screen.queryByText('tools.mcp.authorize')).not.toBeInTheDocument()})})@@ -757,21 +755,18 @@ describe('MCPDetailContent', () => {})})- it('should not call handleUpdateTools if not workspace manager', async () => {- mockIsCurrentWorkspaceManager = false+ it('should not render OAuth authorization action when user lacks mcp.manage', async () => {+ mockWorkspacePermissionKeys = []mockAuthorizeMcp.mockResolvedValue({ authorization_url: 'https://oauth.example.com' })const detail = createMockDetail({ is_team_authorization: false })- // OAuth callback should not trigger update for non-manager- // The button is disabled, so we simulate a scenario where OAuth was already startedrender(<MCPDetailContent {...defaultProps} detail={detail} />,{ wrapper: createWrapper() },)- // Button should be disabled- const authorizeBtn = screen.getByText('tools.mcp.authorize')- expect(authorizeBtn.closest('button'))!.toBeDisabled()+ expect(screen.queryByText('tools.mcp.authorize')).not.toBeInTheDocument()+ expect(mockAuthorizeMcp).not.toHaveBeenCalled()})})@@ -802,16 +797,15 @@ describe('MCPDetailContent', () => {})})- it('should disable authorized button when not workspace manager', () => {- mockIsCurrentWorkspaceManager = false+ it('should not render authorized button when user lacks mcp.manage', () => {+ mockWorkspacePermissionKeys = []const detail = createMockDetail({ is_team_authorization: true })render(<MCPDetailContent {...defaultProps} detail={detail} />,{ wrapper: createWrapper() },)- const authorizedBtn = screen.getByText('tools.auth.authorized')- expect(authorizedBtn.closest('button'))!.toBeDisabled()+ expect(screen.queryByText('tools.auth.authorized')).not.toBeInTheDocument()})})diff --git a/web/app/components/tools/mcp/detail/content.tsx b/web/app/components/tools/mcp/detail/content.tsxindex f3bb250acd7..97c85e33f64 100644--- a/web/app/components/tools/mcp/detail/content.tsx+++ b/web/app/components/tools/mcp/detail/content.tsx@@ -21,7 +21,7 @@ import { useCallback, useEffect } from 'react'import { useTranslation } from 'react-i18next'import ActionButton from '@/app/components/base/action-button'import Icon from '@/app/components/plugins/card/base/card-icon'-import { useAppContext } from '@/context/app-context'+import { useCanManageMCP } from '@/app/components/tools/hooks/use-tool-permissions'import { openOAuthPopup } from '@/hooks/use-oauth'import {useAuthorizeMCP,@@ -58,9 +58,9 @@ const MCPDetailContent: FC<Props> = ({onFirstCreate,}) => {const { t } = useTranslation()- const { isCurrentWorkspaceManager } = useAppContext()+ const canManageMCP = useCanManageMCP()- const { data, isFetching: isGettingTools } = useMCPTools(detail.is_team_authorization ? detail.id : '')+ const { data, isFetching: isGettingTools } = useMCPTools(canManageMCP && detail.is_team_authorization ? detail.id : '')const invalidateMCPTools = useInvalidateMCPTools()const invalidateAllMCPTools = useInvalidateAllMCPTools()const { mutateAsync: updateTools, isPending: isUpdating } = useUpdateMCPTools()@@ -74,13 +74,13 @@ const MCPDetailContent: FC<Props> = ({const handleUpdateTools = useCallback(async () => {hideUpdateConfirm()- if (!detail)+ if (!canManageMCP || !detail)returnawait updateTools(detail.id)invalidateMCPTools(detail.id)invalidateAllMCPTools()onUpdate()- }, [detail, hideUpdateConfirm, invalidateAllMCPTools, invalidateMCPTools, onUpdate, updateTools])+ }, [canManageMCP, detail, hideUpdateConfirm, invalidateAllMCPTools, invalidateMCPTools, onUpdate, updateTools])const { mutateAsync: updateMCP } = useUpdateMCP({})const { mutateAsync: deleteMCP } = useDeleteMCP({})@@ -101,17 +101,17 @@ const MCPDetailContent: FC<Props> = ({}] = useBoolean(false)const handleOAuthCallback = useCallback(() => {- if (!isCurrentWorkspaceManager)+ if (!canManageMCP)returnif (!detail.id)returnhandleUpdateTools()- }, [detail.id, handleUpdateTools, isCurrentWorkspaceManager])+ }, [canManageMCP, detail.id, handleUpdateTools])const handleAuthorize = useCallback(async () => {- onFirstCreate()- if (!isCurrentWorkspaceManager)+ if (!canManageMCP)return+ onFirstCreate()if (!detail)returntry {@@ -129,10 +129,10 @@ const MCPDetailContent: FC<Props> = ({// to update the connection status indicatoronUpdate()}- }, [onFirstCreate, isCurrentWorkspaceManager, detail, authorizeMcp, handleUpdateTools, handleOAuthCallback, onUpdate])+ }, [canManageMCP, onFirstCreate, detail, authorizeMcp, handleUpdateTools, handleOAuthCallback, onUpdate])const handleUpdate = useCallback(async (data: MCPModalConfirmPayload) => {- if (!detail)+ if (!canManageMCP || !detail)returnconst res = await updateMCP({...data,@@ -143,10 +143,10 @@ const MCPDetailContent: FC<Props> = ({onUpdate()handleAuthorize()}- }, [detail, updateMCP, hideUpdateModal, onUpdate, handleAuthorize])+ }, [canManageMCP, detail, updateMCP, hideUpdateModal, onUpdate, handleAuthorize])const handleDelete = useCallback(async () => {- if (!detail)+ if (!canManageMCP || !detail)returnshowDeleting()const res = await deleteMCP(detail.id) as MutationResult@@ -155,14 +155,14 @@ const MCPDetailContent: FC<Props> = ({hideDeleteConfirm()onUpdate(true)}- }, [detail, showDeleting, deleteMCP, hideDeleting, hideDeleteConfirm, onUpdate])+ }, [canManageMCP, detail, showDeleting, deleteMCP, hideDeleting, hideDeleteConfirm, onUpdate])useEffect(() => {if (isTriggerAuthorize)handleAuthorize()}, [])- if (!detail)+ if (!detail || !canManageMCP)return nullconst identifierLabel = t('mcp.identifier', { ns: 'tools' })const serverUrlLabel = t('mcp.modal.serverUrl', { ns: 'tools' })@@ -214,7 +214,7 @@ const MCPDetailContent: FC<Props> = ({</div></div><div className="flex gap-1">- {isCurrentWorkspaceManager && (+ {canManageMCP && (<OperationDropdownonEdit={showUpdateModal}onRemove={showDeleteConfirm}@@ -231,7 +231,7 @@ const MCPDetailContent: FC<Props> = ({variant="secondary"className="w-full"onClick={handleAuthorize}- disabled={!isCurrentWorkspaceManager}+ disabled={!canManageMCP}><StatusDot className="mr-2" status="success" />{t('auth.authorized', { ns: 'tools' })}@@ -242,7 +242,7 @@ const MCPDetailContent: FC<Props> = ({variant="primary"className="w-full"onClick={handleAuthorize}- disabled={!isCurrentWorkspaceManager}+ disabled={!canManageMCP}>{t('mcp.authorize', { ns: 'tools' })}</Button>@@ -318,7 +318,7 @@ const MCPDetailContent: FC<Props> = ({</div>)}</div>- {isShowUpdateModal && (+ {canManageMCP && isShowUpdateModal && (<MCPModaldata={detail}show={isShowUpdateModal}@@ -326,7 +326,7 @@ const MCPDetailContent: FC<Props> = ({onHide={hideUpdateModal}/>)}- <AlertDialog open={isShowDeleteConfirm} onOpenChange={open => !open && hideDeleteConfirm()}>+ <AlertDialog open={canManageMCP && isShowDeleteConfirm} onOpenChange={open => !open && hideDeleteConfirm()}><AlertDialogContent><div className="flex flex-col gap-2 px-6 pt-6 pb-4"><AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">diff --git a/web/app/components/tools/mcp/hooks/__tests__/use-mcp-service-card.spec.ts b/web/app/components/tools/mcp/hooks/__tests__/use-mcp-service-card.spec.tsindex a11365e4456..30c34f5b300 100644--- a/web/app/components/tools/mcp/hooks/__tests__/use-mcp-service-card.spec.ts+++ b/web/app/components/tools/mcp/hooks/__tests__/use-mcp-service-card.spec.ts@@ -6,6 +6,7 @@ import { act, renderHook } from '@testing-library/react'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import { useMCPServiceCardState } from '../use-mcp-service-card'// Mutable mock data for MCP server detail@@ -22,20 +23,29 @@ let mockMCPServerDetailData: {description: 'Test server',parameters: {},}+const mockUpdateMCPServer = vi.fn().mockResolvedValue({})+const mockRefreshMCPServerCode = vi.fn().mockResolvedValue({})+const mockInvalidateMCPServerDetail = vi.fn()+let mockUseMCPServerDetailAppID = ''+let mockUseMCPServerDetailEnabled: boolean | undefined// Mock service hooksvi.mock('@/service/use-tools', () => ({useUpdateMCPServer: () => ({- mutateAsync: vi.fn().mockResolvedValue({}),+ mutateAsync: mockUpdateMCPServer,}),useRefreshMCPServerCode: () => ({- mutateAsync: vi.fn().mockResolvedValue({}),+ mutateAsync: mockRefreshMCPServerCode,isPending: false,}),- useMCPServerDetail: () => ({- data: mockMCPServerDetailData,- }),- useInvalidateMCPServerDetail: () => vi.fn(),+ useMCPServerDetail: (appID: string, enabled?: boolean) => {+ mockUseMCPServerDetailAppID = appID+ mockUseMCPServerDetailEnabled = enabled+ return {+ data: mockMCPServerDetailData,+ }+ },+ useInvalidateMCPServerDetail: () => mockInvalidateMCPServerDetail,}))// Mock workflow hook@@ -53,14 +63,6 @@ vi.mock('@/service/use-workflow', () => ({}),}))-// Mock app context-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: true,- isCurrentWorkspaceEditor: true,- }),-}))-// Mock apps servicevi.mock('@/service/apps', () => ({fetchAppDetail: vi.fn().mockResolvedValue({@@ -84,14 +86,19 @@ describe('useMCPServiceCardState', () => {React.createElement(QueryClientProvider, { client: queryClient }, children)}- const createMockAppInfo = (mode: AppModeEnum = AppModeEnum.CHAT): AppDetailResponse & Partial<AppSSO> => ({+ const createMockAppInfo = (+ mode: AppModeEnum = AppModeEnum.CHAT,+ permissionKeys: string[] = [AppACLPermission.Edit],+ ): AppDetailResponse & Partial<AppSSO> => ({id: 'app-123',name: 'Test App',mode,api_base_url: 'https://api.example.com/v1',+ permission_keys: permissionKeys,} as AppDetailResponse & Partial<AppSSO>)beforeEach(() => {+ vi.clearAllMocks()// Reset mock data to default (published server)mockMCPServerDetailData = {id: 'server-123',@@ -100,6 +107,8 @@ describe('useMCPServiceCardState', () => {description: 'Test server',parameters: {},}+ mockUseMCPServerDetailAppID = ''+ mockUseMCPServerDetailEnabled = undefined})describe('Initialization', () => {@@ -150,14 +159,58 @@ describe('useMCPServiceCardState', () => {})describe('Permission Flags', () => {- it('should have isCurrentWorkspaceManager as true', () => {+ it('should expose MCP manage capability from app edit ACL', () => {const appInfo = createMockAppInfo()const { result } = renderHook(() => useMCPServiceCardState(appInfo, false),{ wrapper: createWrapper() },)- expect(result.current.isCurrentWorkspaceManager).toBe(true)+ expect(result.current.canManageMCP).toBe(true)+ })++ it('should keep MCP server status readable and disable mutations without app edit ACL', async () => {+ const appInfo = createMockAppInfo(AppModeEnum.CHAT, [])+ const { result } = renderHook(+ () => useMCPServiceCardState(appInfo, false),+ { wrapper: createWrapper() },+ )++ expect(result.current.canManageMCP).toBe(false)+ expect(result.current.toggleDisabled).toBe(true)+ expect(result.current.serverPublished).toBe(true)+ expect(result.current.serverActivated).toBe(true)+ expect(result.current.serverURL).toBe('https://api.example.com/mcp/server/abc123/mcp')+ expect(mockUseMCPServerDetailAppID).toBe('app-123')+ expect(mockUseMCPServerDetailEnabled).toBe(true)++ act(() => {+ result.current.openServerModal()+ result.current.openConfirmDelete()+ })+ expect(result.current.showMCPServerModal).toBe(false)+ expect(result.current.showConfirmDelete).toBe(false)++ await act(async () => {+ await result.current.handleGenCode()+ await result.current.handleStatusChange(true)+ })+ expect(mockRefreshMCPServerCode).not.toHaveBeenCalled()+ expect(mockUpdateMCPServer).not.toHaveBeenCalled()+ })++ it('should read workflow state without app edit ACL for workflow apps', () => {+ const appInfo = createMockAppInfo(AppModeEnum.WORKFLOW, [])+ const { result } = renderHook(+ () => useMCPServiceCardState(appInfo, false),+ { wrapper: createWrapper() },+ )++ expect(result.current.canManageMCP).toBe(false)+ expect(result.current.isLoading).toBe(false)+ expect(result.current.appUnpublished).toBe(false)+ expect(result.current.missingStartNode).toBe(false)+ expect(result.current.toggleDisabled).toBe(true)})it('should have toggleDisabled false when editor has permissions', () => {diff --git a/web/app/components/tools/mcp/hooks/use-mcp-service-card.ts b/web/app/components/tools/mcp/hooks/use-mcp-service-card.tsindex 5ea6a237fcf..81d3b84302a 100644--- a/web/app/components/tools/mcp/hooks/use-mcp-service-card.ts+++ b/web/app/components/tools/mcp/hooks/use-mcp-service-card.ts@@ -4,7 +4,7 @@ import type { AppSSO } from '@/types/app'import { useQuery, useQueryClient } from '@tanstack/react-query'import { useCallback, useMemo, useState } from 'react'import { BlockEnum } from '@/app/components/workflow/types'-import { useAppContext } from '@/context/app-context'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { fetchAppDetail } from '@/service/apps'import {useInvalidateMCPServerDetail,@@ -14,6 +14,7 @@ import {} from '@/service/use-tools'import { useAppWorkflow } from '@/service/use-workflow'import { AppModeEnum } from '@/types/app'+import { getAppACLCapabilities } from '@/utils/permission'const BASIC_APP_CONFIG_KEY = 'basicAppConfig'@@ -35,9 +36,17 @@ export const useMCPServiceCardState = (const { mutateAsync: updateMCPServer } = useUpdateMCPServer()const { mutateAsync: refreshMCPServerCode, isPending: genLoading } = useRefreshMCPServerCode()const invalidateMCPServerDetail = useInvalidateMCPServerDetail()-- // Context- const { isCurrentWorkspaceManager, isCurrentWorkspaceEditor } = useAppContext()+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)++ const canManageMCP = useMemo(+ () => getAppACLCapabilities(appInfo.permission_keys, {+ currentUserId,+ resourceMaintainer: appInfo.maintainer,+ workspacePermissionKeys,+ }).canEdit,+ [appInfo.maintainer, appInfo.permission_keys, currentUserId, workspacePermissionKeys],+ )// UI stateconst [showConfirmDelete, setShowConfirmDelete] = useState(false)@@ -62,7 +71,7 @@ export const useMCPServiceCardState = (})// MCP server detail- const { data: detail } = useMCPServerDetail(appId)+ const { data: detail } = useMCPServerDetail(appId, !!appId)const { id, status, server_code } = detail ?? {}// Server state@@ -76,7 +85,7 @@ export const useMCPServiceCardState = (const appUnpublished = isAdvancedApp ? !currentWorkflow?.graph : !basicAppConfig.updated_atconst hasStartNode = currentWorkflow?.graph?.nodes?.some(node => node.data.type === BlockEnum.Start)const missingStartNode = isWorkflowApp && !hasStartNode- const hasInsufficientPermissions = !isCurrentWorkspaceEditor+ const hasInsufficientPermissions = !canManageMCPconst toggleDisabled = hasInsufficientPermissions || appUnpublished || missingStartNode || triggerModeDisabledconst isMinimalState = appUnpublished || missingStartNode@@ -107,11 +116,17 @@ export const useMCPServiceCardState = (// Handlersconst handleGenCode = useCallback(async () => {+ if (!canManageMCP)+ return+await refreshMCPServerCode(detail?.id || '')invalidateMCPServerDetail(appId)- }, [refreshMCPServerCode, detail?.id, invalidateMCPServerDetail, appId])+ }, [canManageMCP, refreshMCPServerCode, detail?.id, invalidateMCPServerDetail, appId])const handleStatusChange = useCallback(async (state: boolean) => {+ if (!canManageMCP)+ return { activated: false }+if (state && !serverPublished) {setShowMCPServerModal(true)return { activated: false }@@ -126,7 +141,7 @@ export const useMCPServiceCardState = (})invalidateMCPServerDetail(appId)return { activated: state }- }, [serverPublished, updateMCPServer, appId, id, detail, invalidateMCPServerDetail])+ }, [canManageMCP, serverPublished, updateMCPServer, appId, id, detail, invalidateMCPServerDetail])const handleServerModalHide = useCallback((wasActivated: boolean) => {setShowMCPServerModal(false)@@ -134,9 +149,19 @@ export const useMCPServiceCardState = (return { shouldDeactivate: !wasActivated }}, [])- const openConfirmDelete = useCallback(() => setShowConfirmDelete(true), [])+ const openConfirmDelete = useCallback(() => {+ if (!canManageMCP)+ return++ setShowConfirmDelete(true)+ }, [canManageMCP])const closeConfirmDelete = useCallback(() => setShowConfirmDelete(false), [])- const openServerModal = useCallback(() => setShowMCPServerModal(true), [])+ const openServerModal = useCallback(() => {+ if (!canManageMCP)+ return++ setShowMCPServerModal(true)+ }, [canManageMCP])const invalidateBasicAppConfig = useCallback(() => {queryClient.invalidateQueries({ queryKey: [BASIC_APP_CONFIG_KEY, appId] })@@ -154,7 +179,7 @@ export const useMCPServiceCardState = (detail,// Permission & validation flags- isCurrentWorkspaceManager,+ canManageMCP,toggleDisabled,isMinimalState,appUnpublished,diff --git a/web/app/components/tools/mcp/index.tsx b/web/app/components/tools/mcp/index.tsxindex 77b6fae7064..57e10003c5d 100644--- a/web/app/components/tools/mcp/index.tsx+++ b/web/app/components/tools/mcp/index.tsx@@ -3,6 +3,7 @@ import type { ToolsContentInset } from '../content-inset'import type { ToolWithProvider } from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'import { useEffect, useMemo, useState } from 'react'+import { useCanManageMCP } from '@/app/components/tools/hooks/use-tool-permissions'import ToolCardSkeletonGrid from '@/app/components/tools/provider/tool-card-skeleton'import {useAllToolProviders,@@ -27,7 +28,8 @@ const MCPList = ({onCreatedProviderHandled,showCreateCard = true,}: Props) => {- const { data: list = [] as ToolWithProvider[], isLoading, refetch } = useAllToolProviders()+ const canManageMCP = useCanManageMCP()+ const { data: list = [] as ToolWithProvider[], isLoading, refetch } = useAllToolProviders(canManageMCP)const [isTriggerAuthorize, setIsTriggerAuthorize] = useState<boolean>(false)const filteredList = useMemo(() => {@@ -47,13 +49,16 @@ const MCPList = ({}, [list, currentProviderID])const handleCreate = async (provider: ToolWithProvider) => {+ if (!canManageMCP)+ return+await refetch() // update listsetCurrentProviderID(provider.id)setIsTriggerAuthorize(true)}useEffect(() => {- if (!createdProviderId)+ if (!canManageMCP || !createdProviderId)returnlet isActive = true@@ -78,15 +83,21 @@ const MCPList = ({return () => {isActive = false}- }, [createdProviderId, onCreatedProviderHandled, refetch])+ }, [canManageMCP, createdProviderId, onCreatedProviderHandled, refetch])const handleUpdate = async (providerID: string) => {+ if (!canManageMCP)+ return+await refetch() // update listsetCurrentProviderID(providerID)setIsTriggerAuthorize(true)}const contentPaddingClassName = toolsContentInsetClassNames[contentInset]const contentFrameClassName = cn(contentPaddingClassName, toolsUnifiedContentFrameClassName)+ if (!canManageMCP)+ return null+return (<><divdiff --git a/web/app/components/tools/mcp/mcp-service-card.tsx b/web/app/components/tools/mcp/mcp-service-card.tsxindex a897d39dbdd..fd0a1a6f79b 100644--- a/web/app/components/tools/mcp/mcp-service-card.tsx+++ b/web/app/components/tools/mcp/mcp-service-card.tsx@@ -19,7 +19,6 @@ import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popimport { StatusDot } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { RiEditLine, RiLoopLeftLine } from '@remixicon/react'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import CopyFeedback from '@/app/components/base/copy-feedback'@@ -53,7 +52,7 @@ const StatusIndicator: FC<StatusIndicatorProps> = ({ serverActivated }) => {type ServerURLSectionProps = {serverURL: stringserverPublished: boolean- isCurrentWorkspaceManager: boolean+ canManageMCP: booleangenLoading: booleanonRegenerate: () => void}@@ -61,7 +60,7 @@ type ServerURLSectionProps = {const ServerURLSection: FC<ServerURLSectionProps> = ({serverURL,serverPublished,- isCurrentWorkspaceManager,+ canManageMCP,genLoading,onRegenerate,}) => {@@ -81,25 +80,29 @@ const ServerURLSection: FC<ServerURLSectionProps> = ({<><CopyFeedback content={serverURL} className="size-6!" /><Divider type="vertical" className="mx-0.5! h-3.5! shrink-0" />- {isCurrentWorkspaceManager && (- <Tooltip>- <TooltipTrigger- render={(- <button- type="button"- className="cursor-pointer rounded-md p-1 outline-hidden hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-components-input-border-hover"- aria-label={t('overview.appInfo.regenerate', { ns: 'appOverview' }) || ''}- onClick={onRegenerate}- >- <RiLoopLeftLine className={cn('size-4 text-text-tertiary hover:text-text-secondary', genLoading && 'animate-spin')} />- </button>- )}- />- <TooltipContent>- {t('overview.appInfo.regenerate', { ns: 'appOverview' })}- </TooltipContent>- </Tooltip>- )}+ <Tooltip>+ <TooltipTrigger+ render={(+ <button+ type="button"+ className={cn(+ 'rounded-md p-1 outline-hidden focus-visible:ring-1 focus-visible:ring-components-input-border-hover',+ canManageMCP+ ? 'cursor-pointer hover:bg-state-base-hover'+ : 'cursor-not-allowed',+ )}+ aria-label={t('overview.appInfo.regenerate', { ns: 'appOverview' }) || ''}+ disabled={!canManageMCP}+ onClick={onRegenerate}+ >+ <span className={cn('i-ri-loop-left-line', 'size-4 text-text-tertiary hover:text-text-secondary', genLoading && 'animate-spin')} />+ </button>+ )}+ />+ <TooltipContent>+ {t('overview.appInfo.regenerate', { ns: 'appOverview' })}+ </TooltipContent>+ </Tooltip></>)}</div>@@ -205,7 +208,7 @@ const MCPServiceCard: FC<IAppCardProps> = ({serverActivated,serverURL,detail,- isCurrentWorkspaceManager,+ canManageMCP,toggleDisabled,isMinimalState,appUnpublished,@@ -363,7 +366,7 @@ const MCPServiceCard: FC<IAppCardProps> = ({<ServerURLSectionserverURL={serverURL}serverPublished={serverPublished}- isCurrentWorkspaceManager={isCurrentWorkspaceManager}+ canManageMCP={canManageMCP}genLoading={genLoading}onRegenerate={openConfirmDelete}/>@@ -378,7 +381,7 @@ const MCPServiceCard: FC<IAppCardProps> = ({onClick={openServerModal}><div className="flex items-center justify-center gap-px">- <RiEditLine className="size-3.5" />+ <span className="i-ri-edit-line size-3.5" /><div className="px-[3px] system-xs-medium text-text-tertiary">{serverPublished ? t('mcp.server.edit', { ns: 'tools' }) : t('mcp.server.addDescription', { ns: 'tools' })}</div>diff --git a/web/app/components/tools/mcp/provider-card.tsx b/web/app/components/tools/mcp/provider-card.tsxindex 7e2be5efab0..0142b812351 100644--- a/web/app/components/tools/mcp/provider-card.tsx+++ b/web/app/components/tools/mcp/provider-card.tsx@@ -1,4 +1,5 @@'use client'+import type { ComponentProps, KeyboardEvent, MouseEvent } from 'react'import type { ToolWithProvider } from '../../workflow/types'import {AlertDialog,@@ -14,7 +15,7 @@ import { useBoolean } from 'ahooks'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import Icon from '@/app/components/plugins/card/base/card-icon'-import { useAppContext } from '@/context/app-context'+import { useCanManageMCP } from '@/app/components/tools/hooks/use-tool-permissions'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'import { useDeleteMCP, useUpdateMCP } from '@/service/use-tools'import OperationDropdown from './detail/operation-dropdown'@@ -28,6 +29,15 @@ type Props = Readonly<{onDeleted: () => void}>+type MCPModalConfirmPayload = Parameters<ComponentProps<typeof MCPModal>['onConfirm']>[0]+type MutationResult = {+ result?: string+}++const isMCPCardActionTarget = (target: EventTarget | null) => {+ return target instanceof HTMLElement && Boolean(target.closest('[data-mcp-card-action]'))+}+const MCPCard = ({currentProvider,data,@@ -37,7 +47,7 @@ const MCPCard = ({}: Props) => {const { t } = useTranslation()const { formatTimeFromNow } = useFormatTimeFromNow()- const { isCurrentWorkspaceManager } = useAppContext()+ const canManageMCP = useCanManageMCP()const isConfigured = data.is_team_authorization && data.tools.length > 0const updatedAtText = data.updated_at? `${t('mcp.updateTime', { ns: 'tools' })} ${formatTimeFromNow(data.updated_at * 1000)}`@@ -63,30 +73,60 @@ const MCPCard = ({setFalse: hideDeleting,}] = useBoolean(false)- const handleUpdate = useCallback(async (form: any) => {+ const handleUpdate = useCallback(async (form: MCPModalConfirmPayload) => {+ if (!canManageMCP)+ return+const res = await updateMCP({...form,provider_id: data.id,- })- if ((res as any)?.result === 'success') {+ }) as MutationResult+ if (res.result === 'success') {hideUpdateModal()onUpdate(data.id)}- }, [data, updateMCP, hideUpdateModal, onUpdate])+ }, [canManageMCP, data, updateMCP, hideUpdateModal, onUpdate])const handleDelete = useCallback(async () => {+ if (!canManageMCP)+ return+showDeleting()- const res = await deleteMCP(data.id)+ const res = await deleteMCP(data.id) as MutationResulthideDeleting()- if ((res as any)?.result === 'success') {+ if (res.result === 'success') {hideDeleteConfirm()onDeleted()}- }, [showDeleting, deleteMCP, data.id, hideDeleting, hideDeleteConfirm, onDeleted])+ }, [canManageMCP, showDeleting, deleteMCP, data.id, hideDeleting, hideDeleteConfirm, onDeleted])++ const handleSelectProvider = useCallback(() => {+ handleSelect(data.id)+ }, [data.id, handleSelect])++ const handleCardClick = useCallback((event: MouseEvent<HTMLDivElement>) => {+ if (isMCPCardActionTarget(event.target))+ return++ handleSelectProvider()+ }, [handleSelectProvider])++ const handleCardKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {+ if (isMCPCardActionTarget(event.target))+ return+ if (event.key !== 'Enter' && event.key !== ' ')+ return++ event.preventDefault()+ handleSelectProvider()+ }, [handleSelectProvider])return (<div- onClick={() => handleSelect(data.id)}+ role="button"+ tabIndex={0}+ onClick={handleCardClick}+ onKeyDown={handleCardKeyDown}className={cn('group relative flex cursor-pointer flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs hover:bg-components-panel-on-panel-item-bg-hover',currentProvider?.id === data.id && 'border-components-option-card-option-selected-border bg-components-panel-on-panel-item-bg-hover',@@ -124,8 +164,8 @@ const MCPCard = ({</div>)}</div>- {isCurrentWorkspaceManager && (- <div className={cn('absolute top-2.5 right-2.5 hidden group-hover:block', isOperationShow && 'block')} onClick={e => e.stopPropagation()}>+ {canManageMCP && (+ <div data-mcp-card-action className={cn('absolute top-2.5 right-2.5 hidden group-hover:block', isOperationShow && 'block')}><OperationDropdowninCardonOpenChange={setIsOperationShow}@@ -134,7 +174,7 @@ const MCPCard = ({/></div>)}- {isShowUpdateModal && (+ {canManageMCP && isShowUpdateModal && (<MCPModaldata={data}show={isShowUpdateModal}@@ -142,7 +182,7 @@ const MCPCard = ({onHide={hideUpdateModal}/>)}- <AlertDialog open={isShowDeleteConfirm} onOpenChange={open => !open && hideDeleteConfirm()}>+ <AlertDialog open={canManageMCP && isShowDeleteConfirm} onOpenChange={open => !open && hideDeleteConfirm()}><AlertDialogContent><div className="flex flex-col gap-2 px-6 pt-6 pb-4"><AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">diff --git a/web/app/components/tools/provider/__tests__/custom-create-card.spec.tsx b/web/app/components/tools/provider/__tests__/custom-create-card.spec.tsxindex 28003bc919c..c15ddb95550 100644--- a/web/app/components/tools/provider/__tests__/custom-create-card.spec.tsx+++ b/web/app/components/tools/provider/__tests__/custom-create-card.spec.tsx@@ -4,13 +4,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { AuthType } from '../../types'import CustomCreateCard, { NewCustomToolButton } from '../custom-create-card'-// Mock workspace manager state-let mockIsWorkspaceManager = true+let mockWorkspacePermissionKeys: string[] = ['tool.manage']-// Mock useAppContextvi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: mockIsWorkspaceManager,+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,}),}))@@ -83,28 +81,23 @@ describe('CustomCreateCard', () => {beforeEach(() => {vi.clearAllMocks()- mockIsWorkspaceManager = true+ mockWorkspacePermissionKeys = ['tool.manage']mockModalVisible = falsemockCreateCustomCollection.mockResolvedValue({})})- // Tests for conditional rendering based on workspace manager status- describe('Workspace Manager Conditional Rendering', () => {- it('should render card when user is workspace manager', () => {- mockIsWorkspaceManager = true-+ describe('tool.manage conditional rendering', () => {+ it('should render card when user has tool.manage', () => {render(<CustomCreateCard onRefreshData={mockOnRefreshData} />)- // Card should be visible with create textexpect(screen.getByText(/createSwaggerAPIAsTool/i)).toBeInTheDocument()})- it('should not render anything when user is not workspace manager', () => {- mockIsWorkspaceManager = false+ it('should not render anything when user does not have tool.manage', () => {+ mockWorkspacePermissionKeys = []const { container } = render(<CustomCreateCard onRefreshData={mockOnRefreshData} />)- // Container should be empty (firstChild is null when nothing renders)expect(container.firstChild).toBeNull()})})@@ -146,12 +139,20 @@ describe('CustomCreateCard', () => {})describe('Toolbar Button Rendering', () => {- it('should render toolbar add button for workspace managers', () => {+ it('should render toolbar add button when user has tool.manage', () => {render(<NewCustomToolButton onRefreshData={mockOnRefreshData} />)expect(screen.getByRole('button', { name: /tools\.addSwaggerAPIAsTool/i })).toBeInTheDocument()})+ it('should not render toolbar add button when user does not have tool.manage', () => {+ mockWorkspacePermissionKeys = []++ const { container } = render(<NewCustomToolButton onRefreshData={mockOnRefreshData} />)++ expect(container.firstChild).toBeNull()+ })+it('should open modal when toolbar add button is clicked', () => {render(<NewCustomToolButton onRefreshData={mockOnRefreshData} />)diff --git a/web/app/components/tools/provider/__tests__/detail.spec.tsx b/web/app/components/tools/provider/__tests__/detail.spec.tsxindex af17cc27e1e..9aca087cf7d 100644--- a/web/app/components/tools/provider/__tests__/detail.spec.tsx+++ b/web/app/components/tools/provider/__tests__/detail.spec.tsx@@ -13,10 +13,16 @@ vi.mock('@/i18n-config/language', () => ({}))const mockIsCurrentWorkspaceManager = vi.fn(() => true)+const mockAppContextState = vi.hoisted(() => ({+ workspacePermissionKeys: ['tool.manage', 'credential.manage', 'credential.use'] as string[],+}))vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager(),}),+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockAppContextState.workspacePermissionKeys,+ }),}))const mockSetShowModelModal = vi.fn()@@ -118,10 +124,10 @@ vi.mock('@/app/components/tools/edit-custom-collection-modal', () => ({}))vi.mock('@/app/components/tools/setting/build-in/config-credentials', () => ({- default: ({ onCancel, onSaved, onRemove }: { onCancel: () => void, onSaved: (val: Record<string, string>) => Promise<void>, onRemove: () => Promise<void> }) => (- <div data-testid="config-credential">- <button data-testid="credential-save" onClick={() => onSaved({ key: 'val' })}>Save</button>- <button data-testid="credential-remove" onClick={onRemove}>Remove</button>+ default: ({ onCancel, onSaved, onRemove, readonly }: { onCancel: () => void, onSaved: (val: Record<string, string>) => Promise<void>, onRemove: () => Promise<void>, readonly?: boolean }) => (+ <div data-testid="config-credential" data-readonly={readonly ? 'true' : 'false'}>+ <button data-testid="credential-save" disabled={readonly} onClick={() => onSaved({ key: 'val' })}>Save</button>+ <button data-testid="credential-remove" disabled={readonly} onClick={onRemove}>Remove</button><button data-testid="credential-cancel" onClick={onCancel}>Cancel</button></div>),@@ -167,6 +173,7 @@ describe('ProviderDetail', () => {])mockFetchCustomToolList.mockResolvedValue([])mockFetchModelToolList.mockResolvedValue([])+ mockAppContextState.workspacePermissionKeys = ['tool.manage', 'credential.manage', 'credential.use']})afterEach(() => {@@ -330,6 +337,24 @@ describe('ProviderDetail', () => {expect(configureButton.querySelector('.i-ri-equalizer-2-line')).toBeInTheDocument()})++ it('does not fetch or enable custom tool management without tool.manage', async () => {+ mockAppContextState.workspacePermissionKeys = []++ render(+ <ProviderDetail+ collection={createMockCollection({ type: CollectionType.custom })}+ onHide={mockOnHide}+ onRefreshData={mockOnRefreshData}+ />,+ )++ const configureButton = (await screen.findByText('tools.createTool.editAction')).closest('button')!++ expect(mockFetchCustomCollection).not.toHaveBeenCalled()+ expect(mockFetchCustomToolList).not.toHaveBeenCalled()+ expect(configureButton).toBeDisabled()+ })})describe('Workflow Collection', () => {@@ -395,6 +420,22 @@ describe('ProviderDetail', () => {expect(actions).toHaveClass('-mx-4', 'px-4', 'border-b-[0.5px]', 'border-divider-subtle')})++ it('does not fetch or show workflow tool edit actions without tool.manage', () => {+ mockAppContextState.workspacePermissionKeys = []++ render(+ <ProviderDetail+ collection={createMockCollection({ type: CollectionType.workflow })}+ onHide={mockOnHide}+ onRefreshData={mockOnRefreshData}+ />,+ )++ expect(mockFetchWorkflowToolDetail).not.toHaveBeenCalled()+ expect(screen.queryByText('tools.openInStudio')).not.toBeInTheDocument()+ expect(screen.queryByText('tools.createTool.editAction')).not.toBeInTheDocument()+ })})describe('Model Collection', () => {@@ -494,6 +535,46 @@ describe('ProviderDetail', () => {expect(screen.getByTestId('config-credential'))!.toBeInTheDocument()})+ it('does not open setup credential drawer without credential.manage', async () => {+ mockAppContextState.workspacePermissionKeys = ['tool.manage', 'credential.use']++ render(+ <ProviderDetail+ collection={createMockCollection({ allow_delete: true, is_team_authorization: false })}+ onHide={mockOnHide}+ onRefreshData={mockOnRefreshData}+ />,+ )+ await waitFor(() => {+ expect(screen.getByText('tools.auth.unauthorized'))!.toBeInTheDocument()+ })++ const setupButton = screen.getByText('tools.auth.unauthorized').closest('button')!+ expect(setupButton).toBeDisabled()+ fireEvent.click(setupButton)+ expect(screen.queryByTestId('config-credential')).not.toBeInTheDocument()+ })++ it('opens authorized credential drawer as readonly with credential.use only', async () => {+ mockAppContextState.workspacePermissionKeys = ['tool.manage', 'credential.use']++ render(+ <ProviderDetail+ collection={createMockCollection({ allow_delete: true, is_team_authorization: true })}+ onHide={mockOnHide}+ onRefreshData={mockOnRefreshData}+ />,+ )+ await waitFor(() => {+ expect(screen.getByText('tools.auth.authorized'))!.toBeInTheDocument()+ })++ fireEvent.click(screen.getByText('tools.auth.authorized'))+ expect(screen.getByTestId('config-credential'))!.toHaveAttribute('data-readonly', 'true')+ expect(screen.getByTestId('credential-save'))!.toBeDisabled()+ expect(screen.getByTestId('credential-remove'))!.toBeDisabled()+ })+it('saves credentials and refreshes data', async () => {render(<ProviderDetaildiff --git a/web/app/components/tools/provider/custom-create-card.tsx b/web/app/components/tools/provider/custom-create-card.tsxindex 0eb159478c3..b4ce4968492 100644--- a/web/app/components/tools/provider/custom-create-card.tsx+++ b/web/app/components/tools/provider/custom-create-card.tsx@@ -6,7 +6,7 @@ import { toast } from '@langgenius/dify-ui/toast'import { useState } from 'react'import { useTranslation } from 'react-i18next'import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'-import { useAppContext } from '@/context/app-context'+import { useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import { useDocLink } from '@/context/i18n'import { createCustomCollection } from '@/service/tools'import CreateEntryCard from './create-entry-card'@@ -17,10 +17,13 @@ type Props = Readonly<{function useCustomToolCreateAction({ onRefreshData }: Props) {const { t } = useTranslation()- const { isCurrentWorkspaceManager } = useAppContext()+ const canManageTools = useCanManageTools()const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {+ if (!canManageTools)+ return+await createCustomCollection(data)toast.success(t('api.actionSuccess', { ns: 'common' }))setIsShowEditCustomCollectionModal(false)@@ -28,8 +31,8 @@ function useCustomToolCreateAction({ onRefreshData }: Props) {}return {+ canManageTools,doCreateCustomToolCollection,- isCurrentWorkspaceManager,isShowEditCollectionToolModal,setIsShowEditCustomCollectionModal,}@@ -39,13 +42,13 @@ export const NewCustomToolButton = ({ onRefreshData }: Props) => {const { t } = useTranslation()const addSwaggerAPIAsToolLabel = t('addSwaggerAPIAsTool', { ns: 'tools' })const {+ canManageTools,doCreateCustomToolCollection,- isCurrentWorkspaceManager,isShowEditCollectionToolModal,setIsShowEditCustomCollectionModal,} = useCustomToolCreateAction({ onRefreshData })- if (!isCurrentWorkspaceManager)+ if (!canManageTools)return nullreturn (@@ -75,15 +78,15 @@ const Contribute = ({ onRefreshData }: Props) => {const { t } = useTranslation()const docLink = useDocLink()const {+ canManageTools,doCreateCustomToolCollection,- isCurrentWorkspaceManager,isShowEditCollectionToolModal,setIsShowEditCustomCollectionModal,} = useCustomToolCreateAction({ onRefreshData })return (<>- {isCurrentWorkspaceManager && (+ {canManageTools && (<CreateEntryCardclassName="min-w-0"title={t('createSwaggerAPIAsTool', { ns: 'tools' })}diff --git a/web/app/components/tools/provider/detail.tsx b/web/app/components/tools/provider/detail.tsxindex d53bf1d1526..adf993c44d8 100644--- a/web/app/components/tools/provider/detail.tsx+++ b/web/app/components/tools/provider/detail.tsx@@ -36,13 +36,14 @@ import Description from '@/app/components/plugins/card/base/description'import OrgInfo from '@/app/components/plugins/card/base/org-info'import Title from '@/app/components/plugins/card/base/title'import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'+import { useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'import { WorkflowToolDrawer } from '@/app/components/tools/workflow-tool'-import { useAppContext } from '@/context/app-context'import { useLocale } from '@/context/i18n'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { useCredentialPermissions } from '@/hooks/use-credential-permissions'import { getLanguage } from '@/i18n-config/language'import {deleteWorkflowTool,@@ -81,7 +82,9 @@ const ProviderDetail = ({const isAuthed = collection.is_team_authorizationconst isBuiltIn = collection.type === CollectionType.builtInconst isModel = collection.type === CollectionType.model- const { isCurrentWorkspaceManager } = useAppContext()+ const { canUseCredential, canManageCredential } = useCredentialPermissions()+ const canOpenCredentialSettings = isAuthed ? canUseCredential : canManageCredential+ const canManageTools = useCanManageTools()const invalidateAllWorkflowTools = useInvalidateAllWorkflowTools()const [isDetailLoading, setIsDetailLoading] = useState(false)@@ -90,6 +93,9 @@ const ProviderDetail = ({const { setShowModelModal } = useModalContext()const { modelProviders: providers } = useProviderContext()const showSettingAuthModal = () => {+ if (!canOpenCredentialSettings)+ return+if (isModel) {const provider = providers.find(item => item.provider === collection?.id)if (provider) {@@ -116,6 +122,9 @@ const ProviderDetail = ({const [deleteAction, setDeleteAction] = useState('')const getCustomProvider = useCallback(async () => {+ if (!canManageTools)+ return+setIsDetailLoading(true)const res = await fetchCustomCollection(collection.name)if (res.credentials.auth_type === AuthType.apiKey && !res.credentials.api_key_header_prefix) {@@ -128,9 +137,12 @@ const ProviderDetail = ({provider: collection.name,})setIsDetailLoading(false)- }, [collection.labels, collection.name])+ }, [canManageTools, collection.labels, collection.name])const doUpdateCustomToolCollection = async (data: CustomCollectionBackend) => {+ if (!canManageTools)+ return+await updateCustomCollection(data)onRefreshData()await getCustomProvider()@@ -140,6 +152,9 @@ const ProviderDetail = ({setIsShowEditCustomCollectionModal(false)}const doRemoveCustomToolCollection = async () => {+ if (!canManageTools)+ return+await removeCustomCollection(collection?.name as string)onRefreshData()toast.success(t('api.actionSuccess', { ns: 'common' }))@@ -148,6 +163,9 @@ const ProviderDetail = ({// workflow providerconst [workflowToolDrawerOpen, setWorkflowToolDrawerOpen] = useState(false)const getWorkflowToolProvider = useCallback(async () => {+ if (!canManageTools)+ return+setIsDetailLoading(true)const res = await fetchWorkflowToolDetail(collection.id)const payload = {@@ -165,8 +183,11 @@ const ProviderDetail = ({}setCustomCollection(payload)setIsDetailLoading(false)- }, [collection.id])+ }, [canManageTools, collection.id])const removeWorkflowToolProvider = async () => {+ if (!canManageTools)+ return+await deleteWorkflowTool(collection.id)onRefreshData()toast.success(t('api.actionSuccess', { ns: 'common' }))@@ -176,6 +197,9 @@ const ProviderDetail = ({workflow_app_id: stringworkflow_tool_id: string}>) => {+ if (!canManageTools)+ return+await saveWorkflowToolProvider(data)invalidateAllWorkflowTools()onRefreshData()@@ -218,21 +242,27 @@ const ProviderDetail = ({setToolList([])}else {+ if (!canManageTools) {+ setToolList([])+ setIsDetailLoading(false)+ return+ }+const list = await fetchCustomToolList(collection.name)setToolList(list)}}catch { }setIsDetailLoading(false)- }, [collection.name, collection.type])+ }, [canManageTools, collection.name, collection.type])useEffect(() => {- if (collection.type === CollectionType.custom)+ if (collection.type === CollectionType.custom && canManageTools)getCustomProvider()- if (collection.type === CollectionType.workflow)+ if (collection.type === CollectionType.workflow && canManageTools)getWorkflowToolProvider()getProviderToolList()- }, [collection.name, collection.type, getCustomProvider, getProviderToolList, getWorkflowToolProvider])+ }, [canManageTools, collection.name, collection.type, getCustomProvider, getProviderToolList, getWorkflowToolProvider])return (<Drawer@@ -288,6 +318,7 @@ const ProviderDetail = ({<ButtonclassName={cn('my-3 w-full shrink-0')}onClick={() => setIsShowEditCustomCollectionModal(true)}+ disabled={!canManageTools}><span aria-hidden className="mr-1 i-ri-equalizer-2-line size-4 text-components-button-secondary-text" /><div className="system-sm-medium text-text-secondary">{t('createTool.editAction', { ns: 'tools' })}</div>@@ -308,7 +339,7 @@ const ProviderDetail = ({variant="secondary"className={cn('my-3 h-8 min-w-0 flex-1 rounded-lg px-3 py-2')}onClick={() => setWorkflowToolDrawerOpen(true)}- disabled={!isCurrentWorkspaceManager}+ disabled={!canManageTools}><span aria-hidden className="i-ri-equalizer-2-line size-4 shrink-0 text-components-button-secondary-text" /><span className="min-w-0 truncate px-0.5 system-sm-medium text-components-button-secondary-text">{t('createTool.editAction', { ns: 'tools' })}</span>@@ -332,7 +363,7 @@ const ProviderDetail = ({if (collection.type === CollectionType.builtIn || collection.type === CollectionType.model)showSettingAuthModal()}}- disabled={!isCurrentWorkspaceManager}+ disabled={!canOpenCredentialSettings}><StatusDot className="mr-2" status="success" />{t('auth.authorized', { ns: 'tools' })}@@ -354,7 +385,7 @@ const ProviderDetail = ({if (collection.type === CollectionType.builtIn || collection.type === CollectionType.model)showSettingAuthModal()}}- disabled={!isCurrentWorkspaceManager}+ disabled={!canOpenCredentialSettings}>{t('auth.unauthorized', { ns: 'tools' })}</Button>@@ -401,20 +432,27 @@ const ProviderDetail = ({collection={collection}onCancel={() => setShowSettingAuth(false)}onSaved={async (value) => {+ if (!canManageCredential)+ return+await updateBuiltInToolCredential(collection.name, value)toast.success(t('api.actionSuccess', { ns: 'common' }))await onRefreshData()setShowSettingAuth(false)}}onRemove={async () => {+ if (!canManageCredential)+ return+await removeBuiltInToolCredential(collection.name)toast.success(t('api.actionSuccess', { ns: 'common' }))await onRefreshData()setShowSettingAuth(false)}}+ readonly={!canManageCredential}/>)}- {isShowEditCollectionToolModal && (+ {isShowEditCollectionToolModal && canManageTools && (<EditCustomToolModalpayload={customCollection}onHide={() => setIsShowEditCustomCollectionModal(false)}@@ -422,7 +460,7 @@ const ProviderDetail = ({onRemove={onClickCustomToolDelete}/>)}- {workflowToolDrawerOpen && (+ {workflowToolDrawerOpen && canManageTools && (<WorkflowToolDrawerpayload={customCollection as unknown as WorkflowToolDrawerPayload}onHide={() => setWorkflowToolDrawerOpen(false)}diff --git a/web/app/components/tools/setting/build-in/config-credentials.tsx b/web/app/components/tools/setting/build-in/config-credentials.tsxindex a7ef23657d9..0b5e61444bf 100644--- a/web/app/components/tools/setting/build-in/config-credentials.tsx+++ b/web/app/components/tools/setting/build-in/config-credentials.tsx@@ -33,6 +33,7 @@ type Props = Readonly<{isHideRemoveBtn?: booleanonRemove?: () => voidisSaving?: boolean+ readonly?: boolean}>const ConfigCredential: FC<Props> = ({@@ -42,6 +43,7 @@ const ConfigCredential: FC<Props> = ({isHideRemoveBtn,onRemove = noop,isSaving,+ readonly,}) => {const { t } = useTranslation()const language = useLanguage()@@ -118,6 +120,7 @@ const ConfigCredential: FC<Props> = ({}}formSchemas={credentialSchema}isEditMode={true}+ readonly={readonly}showOnVariableMap={{}}validating={false}inputClassName="bg-components-input-bg-normal!"@@ -137,13 +140,15 @@ const ConfigCredential: FC<Props> = ({/><div className={cn((collection.is_team_authorization && !isHideRemoveBtn) ? 'justify-between' : 'justify-end', 'mt-2 flex')}>{- (collection.is_team_authorization && !isHideRemoveBtn) && (+ (collection.is_team_authorization && !isHideRemoveBtn && !readonly) && (<Button onClick={onRemove}>{t('operation.remove', { ns: 'common' })}</Button>)}<div className="flex space-x-2"><Button onClick={onCancel}>{t('operation.cancel', { ns: 'common' })}</Button>- <Button loading={isLoading || isSaving} disabled={isLoading || isSaving} variant="primary" onClick={handleSave}>{t('operation.save', { ns: 'common' })}</Button>+ {!readonly && (+ <Button loading={isLoading || isSaving} disabled={isLoading || isSaving} variant="primary" onClick={handleSave}>{t('operation.save', { ns: 'common' })}</Button>+ )}</div></div></>diff --git a/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsx b/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsxindex 06b9a77b5c5..079c838cc84 100644--- a/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsx+++ b/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsx@@ -22,14 +22,6 @@ vi.mock('@/next/navigation', () => ({useParams: () => ({}),}))-// Mock app context-const mockIsCurrentWorkspaceManager = vi.fn(() => true)-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager(),- }),-}))-// Mock API services - only mock external servicesconst mockCreateWorkflowToolProvider = vi.fn()const mockSaveWorkflowToolProvider = vi.fn()@@ -140,7 +132,6 @@ const createDefaultConfigureButtonProps = (overrides = {}) => ({published: false,isLoading: false,outdated: false,- isCurrentWorkspaceManager: true,onConfigure: vi.fn(),...overrides,})@@ -177,7 +168,6 @@ const createDefaultDrawerPayload = (overrides: Partial<WorkflowToolDrawerPayloaddescribe('WorkflowToolConfigureButton', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCurrentWorkspaceManager.mockReturnValue(true)mockUseWorkflowToolDetailByAppID.mockImplementation((_appId: string, enabled: boolean) => ({data: enabled ? createMockWorkflowToolDetail() : undefined,isLoading: false,@@ -274,18 +264,6 @@ describe('WorkflowToolConfigureButton', () => {expect(screen.getByText('workflow.common.manageInTools'))!.toBeInTheDocument()})})-- it('should render different UI for non-workspace manager', () => {- // Arrange- const props = createDefaultConfigureButtonProps({ isCurrentWorkspaceManager: false })-- // Act- render(<WorkflowToolConfigureButton {...props} />)-- // Assert- const textElement = screen.getByText('workflow.common.workflowAsTool')- expect(textElement)!.toHaveClass('text-text-tertiary')- })})// Props Testing (REQUIRED)@@ -452,9 +430,9 @@ describe('WorkflowToolConfigureButton', () => {})})- it('should disable configure button when not workspace manager', async () => {+ it('should disable configure button when workflow tool is disabled', async () => {// Arrange- const props = createDefaultConfigureButtonProps({ published: true, isCurrentWorkspaceManager: false })+ const props = createDefaultConfigureButtonProps({ published: true, disabled: true })// Actrender(<WorkflowToolConfigureButton {...props} />)@@ -1535,7 +1513,6 @@ describe('MethodSelector', () => {describe('Integration Tests', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCurrentWorkspaceManager.mockReturnValue(true)mockUseWorkflowToolDetailByAppID.mockImplementation((_appId: string, enabled: boolean) => ({data: enabled ? createMockWorkflowToolDetail() : undefined,isLoading: false,diff --git a/web/app/components/tools/workflow-tool/__tests__/index.spec.tsx b/web/app/components/tools/workflow-tool/__tests__/index.spec.tsxindex c0811ba6d5f..e3791bb174f 100644--- a/web/app/components/tools/workflow-tool/__tests__/index.spec.tsx+++ b/web/app/components/tools/workflow-tool/__tests__/index.spec.tsx@@ -89,21 +89,12 @@ describe('WorkflowToolDrawer', () => {await user.clear(screen.getByPlaceholderText('tools.createTool.toolNamePlaceHolder'))await user.type(screen.getByPlaceholderText('tools.createTool.toolNamePlaceHolder'), 'Created Tool')await user.click(screen.getByTestId('append-label'))- await user.click(screen.getByTestId('app-icon'))- await waitFor(() => {- expect(screen.getByPlaceholderText('Search emojis...')).toBeInTheDocument()- })- await user.click(screen.getByRole('button', { name: '#E4FBCC' }))- await user.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))- await waitFor(() => {- expect(screen.queryByPlaceholderText('Search emojis...')).not.toBeInTheDocument()- })await user.click(screen.getByRole('button', { name: 'common.operation.save' }))expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({workflow_app_id: 'workflow-app-1',label: 'Created Tool',- icon: { content: '🔧', background: '#E4FBCC' },+ icon: { content: '🔧', background: '#ffffff' },labels: ['label1', 'new-label'],}))})diff --git a/web/app/components/tools/workflow-tool/configure-button.tsx b/web/app/components/tools/workflow-tool/configure-button.tsxindex 58706962502..d1ce3a52a80 100644--- a/web/app/components/tools/workflow-tool/configure-button.tsx+++ b/web/app/components/tools/workflow-tool/configure-button.tsx@@ -13,7 +13,6 @@ type Props = Readonly<{published: booleanisLoading: booleanoutdated: boolean- isCurrentWorkspaceManager: booleanonConfigure: () => voiddisabledReason?: string}>@@ -23,7 +22,6 @@ const WorkflowToolConfigureButton = ({published,isLoading,outdated,- isCurrentWorkspaceManager,onConfigure,disabledReason,}: Props) => {@@ -36,46 +34,30 @@ const WorkflowToolConfigureButton = ({{(!published || !isLoading) && (<div className={cn('group rounded-lg bg-background-section-burn transition-colors',- disabled || !isCurrentWorkspaceManager ? 'cursor-not-allowed opacity-60 shadow-xs' : 'cursor-pointer',- !disabled && !published && isCurrentWorkspaceManager && 'hover:bg-state-accent-hover',+ disabled ? 'cursor-not-allowed opacity-60 shadow-xs' : 'cursor-pointer',+ !disabled && !published && 'hover:bg-state-accent-hover',)}>- {isCurrentWorkspaceManager- ? (- <div- className="flex items-center justify-start gap-2 p-2 pl-2.5"- onClick={() => {- if (!disabled && !published)- onConfigure()- }}- >- <span className={cn('relative i-ri-hammer-line size-4 text-text-secondary', !disabled && !published && 'group-hover:text-text-accent')} />- <div- title={t('common.workflowAsTool', { ns: 'workflow' }) || ''}- className={cn('shrink grow basis-0 truncate system-sm-medium text-text-secondary', !disabled && !published && 'group-hover:text-text-accent')}- >- {t('common.workflowAsTool', { ns: 'workflow' })}- </div>- {!published && (- <span className="shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary">- {t('common.configureRequired', { ns: 'workflow' })}- </span>- )}- </div>- )- : (- <div- className="flex items-center justify-start gap-2 p-2 pl-2.5"- >- <span className="i-ri-hammer-line size-4 text-text-tertiary" />- <div- title={t('common.workflowAsTool', { ns: 'workflow' }) || ''}- className="shrink grow basis-0 truncate system-sm-medium text-text-tertiary"- >- {t('common.workflowAsTool', { ns: 'workflow' })}- </div>- </div>- )}+ <div+ className="flex items-center justify-start gap-2 p-2 pl-2.5"+ onClick={() => {+ if (!disabled && !published)+ onConfigure()+ }}+ >+ <span className={cn('relative i-ri-hammer-line size-4 text-text-secondary', !disabled && !published && 'group-hover:text-text-accent')} />+ <div+ title={t('common.workflowAsTool', { ns: 'workflow' }) || ''}+ className={cn('shrink grow basis-0 truncate system-sm-medium text-text-secondary', !disabled && !published && 'group-hover:text-text-accent')}+ >+ {t('common.workflowAsTool', { ns: 'workflow' })}+ </div>+ {!published && (+ <span className="shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary">+ {t('common.configureRequired', { ns: 'workflow' })}+ </span>+ )}+ </div>{disabledReason && (<div className="mt-1 px-2.5 pb-2 text-xs leading-[18px] text-text-tertiary">{disabledReason}@@ -88,7 +70,7 @@ const WorkflowToolConfigureButton = ({size="small"className="w-[140px]"onClick={onConfigure}- disabled={!isCurrentWorkspaceManager || disabled}+ disabled={disabled}>{t('common.configure', { ns: 'workflow' })}{outdated && <StatusDot className="ml-1" status="warning" />}diff --git a/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.ts b/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.tsindex fd800fe5b00..741d7ebadbf 100644--- a/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.ts+++ b/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.ts@@ -4,13 +4,6 @@ import { act, renderHook } from '@testing-library/react'import { InputVarType } from '@/app/components/workflow/types'import { isParametersOutdated, useConfigureButton } from '../use-configure-button'-const mockIsCurrentWorkspaceManager = vi.fn(() => true)-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager(),- }),-}))-const mockCreateWorkflowToolProvider = vi.fn()const mockSaveWorkflowToolProvider = vi.fn()vi.mock('@/service/tools', () => ({@@ -197,7 +190,6 @@ describe('isParametersOutdated', () => {describe('useConfigureButton', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCurrentWorkspaceManager.mockReturnValue(true)mockUseWorkflowToolDetailByAppID.mockImplementation((_appId: string, enabled: boolean) => ({data: enabled ? createMockDetail() : undefined,isLoading: false,@@ -214,12 +206,6 @@ describe('useConfigureButton', () => {expect(result.current.payload).toMatchObject({ workflow_app_id: 'app-123' })})- it('should forward isCurrentWorkspaceManager from context', () => {- mockIsCurrentWorkspaceManager.mockReturnValue(false)- const { result } = renderHook(() => useConfigureButton(createDefaultOptions()))- expect(result.current.isCurrentWorkspaceManager).toBe(false)- })-it('should forward isLoading from query hook', () => {mockUseWorkflowToolDetailByAppID.mockReturnValue({ data: undefined, isLoading: true })const { result } = renderHook(() => useConfigureButton(createDefaultOptions({ published: true })))diff --git a/web/app/components/tools/workflow-tool/hooks/use-configure-button.ts b/web/app/components/tools/workflow-tool/hooks/use-configure-button.tsindex f4b6881f986..2e2d89e1506 100644--- a/web/app/components/tools/workflow-tool/hooks/use-configure-button.ts+++ b/web/app/components/tools/workflow-tool/hooks/use-configure-button.ts@@ -4,7 +4,6 @@ import type { PublishWorkflowParams } from '@/types/workflow'import { toast } from '@langgenius/dify-ui/toast'import { useEffect, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'-import { useAppContext } from '@/context/app-context'import { createWorkflowToolProvider, saveWorkflowToolProvider } from '@/service/tools'import { useInvalidateAllWorkflowTools, useInvalidateWorkflowToolDetailByAppID, useWorkflowToolDetailByAppID } from '@/service/use-tools'@@ -119,7 +118,6 @@ export function useConfigureButton(options: UseConfigureButtonOptions) {} = optionsconst { t } = useTranslation()- const { isCurrentWorkspaceManager } = useAppContext()// Data fetching via React Queryconst { data: detail, isLoading } = useWorkflowToolDetailByAppID(workflowAppId, enabled && published)@@ -209,7 +207,6 @@ export function useConfigureButton(options: UseConfigureButtonOptions) {isLoading,outdated,payload,- isCurrentWorkspaceManager,handleCreate,handleUpdate,}diff --git a/web/app/components/workflow-app/__tests__/index.spec.tsx b/web/app/components/workflow-app/__tests__/index.spec.tsxindex 880a62ca8d4..28810aa264f 100644--- a/web/app/components/workflow-app/__tests__/index.spec.tsx+++ b/web/app/components/workflow-app/__tests__/index.spec.tsx@@ -1,5 +1,6 @@import type { ReactNode } from 'react'import { render, screen, waitFor } from '@testing-library/react'+import { AppACLPermission } from '@/utils/permission'import WorkflowApp from '../index'const mockSetTriggerStatuses = vi.fn()@@ -17,6 +18,8 @@ let appStoreState: {appDetail?: {id: stringmode: string+ maintainer?: string+ permission_keys?: string[]}}@@ -38,6 +41,10 @@ let appContextState: {currentWorkspace: {id?: string}+ userProfile: {+ id: string+ }+ workspacePermissionKeys: string[]}let appTriggersState: {@@ -185,6 +192,7 @@ describe('WorkflowApp', () => {appDetail: {id: 'app-1',mode: 'workflow',+ permission_keys: [AppACLPermission.TestAndRun],},}workflowInitState = {@@ -206,6 +214,8 @@ describe('WorkflowApp', () => {appContextState = {isLoadingCurrentWorkspace: false,currentWorkspace: { id: 'workspace-1' },+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],}appTriggersState = {}searchParamsValue = null@@ -293,6 +303,27 @@ describe('WorkflowApp', () => {expect(mockSetInputs).not.toHaveBeenCalled()})+ it('should skip replay lookups when test/run permission is missing', async () => {+ searchParamsValue = 'run-1'+ appStoreState = {+ appDetail: {+ id: 'app-1',+ mode: 'workflow',+ permission_keys: [AppACLPermission.ViewLayout],+ },+ }++ render(<WorkflowApp />)++ await waitFor(() => {+ expect(screen.getByTestId('workflow-app-main')).toBeInTheDocument()+ })++ expect(mockGetWorkflowRunAndTraceUrl).not.toHaveBeenCalled()+ expect(mockFetchRunDetail).not.toHaveBeenCalled()+ expect(mockSetInputs).not.toHaveBeenCalled()+ })+it('should skip replay fetches when the resolved run url is empty', async () => {searchParamsValue = 'run-1'mockGetWorkflowRunAndTraceUrl.mockReturnValue({ runUrl: '' })diff --git a/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsxindex 898afffb694..aff1c32b19d 100644--- a/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsx+++ b/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsx@@ -45,6 +45,7 @@ const mockExportCheck = vi.fn()const mockAutoGenerateWebhookUrl = vi.fn()let workflowStoreState: WorkflowStoreState+let mockCanEdit = truelet eventSubscription: ((value: { type: string, payload: { data: Array<Record<string, unknown>> } }) => void) | null = nulllet lastGenerateNodeInput: Record<string, unknown> | null = null@@ -61,6 +62,16 @@ vi.mock('@/app/components/workflow/store', () => ({useStore: <T,>(selector: (state: WorkflowStoreState) => T) => selector(workflowStoreState),}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canImportExportDSL: boolean, canEdit: boolean } }) => T): T =>+ selector({+ accessControl: {+ canImportExportDSL: true,+ canEdit: mockCanEdit,+ },+ }),+}))+vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({eventEmitter: {@@ -296,6 +307,7 @@ describe('WorkflowChildren', () => {}eventSubscription = nulllastGenerateNodeInput = null+ mockCanEdit = truemockHandleSyncWorkflowDraft.mockImplementation((_force?: boolean, _notRefresh?: boolean, callback?: { onSuccess?: () => void }) => {callback?.onSuccess?.()})@@ -380,6 +392,20 @@ describe('WorkflowChildren', () => {expect(mockHandleOnboardingClose).toHaveBeenCalled()})+ it('should hide onboarding actions when workflow is readonly', () => {+ mockCanEdit = false+ workflowStoreState = {+ ...workflowStoreState,+ showOnboarding: true,+ }++ render(<WorkflowChildren />)++ expect(screen.queryByTestId('workflow-onboarding-modal')).not.toBeInTheDocument()+ expect(mockSetNodes).not.toHaveBeenCalled()+ expect(mockHandleSyncWorkflowDraft).not.toHaveBeenCalled()+ })+it('should create a start node, sync draft, and auto-generate webhook url after selecting a start node', async () => {const user = userEvent.setup()workflowStoreState = {diff --git a/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsxindex 956c95fa754..cc3f726f6b6 100644--- a/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsx+++ b/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsx@@ -1,8 +1,10 @@import type { ReactNode } from 'react'import type { WorkflowProps } from '@/app/components/workflow'import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { useStore as useAppStore } from '@/app/components/app/store'import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'import { BlockEnum } from '@/app/components/workflow/types'+import { AppACLPermission } from '@/utils/permission'import WorkflowMain from '../workflow-main'const mockSetFeatures = vi.fn()@@ -92,12 +94,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-vi.mock('@/app/components/app/store', () => ({- useStore: <T,>(selector: (state: { appDetail: { mode: string } }) => T) => selector({- appDetail: { mode: 'workflow' },- }),-}))-vi.mock('reactflow', () => ({useReactFlow: () => ({getNodes: () => [],@@ -224,6 +220,7 @@ vi.mock('@/app/components/workflow-app/hooks', () => ({useAvailableNodesMetaData: () => ({ nodes: [{ id: 'start' }], nodesMap: { start: { id: 'start' } } }),useConfigsMap: () => ({ flowId: 'app-1', flowType: 'app-flow', fileSettings: { enabled: true } }),useDSL: () => ({ exportCheck: hookFns.exportCheck, handleExportDSL: hookFns.handleExportDSL }),+ useDSLByCanEdit: () => ({ exportCheck: hookFns.exportCheck, handleExportDSL: hookFns.handleExportDSL }),useGetRunAndTraceUrl: () => ({ getWorkflowRunAndTraceUrl: hookFns.getWorkflowRunAndTraceUrl }),useInspectVarsCrud: () => ({hasNodeInspectVars: hookFns.hasNodeInspectVars,@@ -245,6 +242,10 @@ vi.mock('@/app/components/workflow-app/hooks', () => ({doSyncWorkflowDraft: hookFns.doSyncWorkflowDraft,syncWorkflowDraftWhenPageClose: hookFns.syncWorkflowDraftWhenPageClose,}),+ useNodesSyncDraftByCanEdit: () => ({+ doSyncWorkflowDraft: hookFns.doSyncWorkflowDraft,+ syncWorkflowDraftWhenPageClose: hookFns.syncWorkflowDraftWhenPageClose,+ }),useSetWorkflowVarsWithValue: () => ({fetchInspectVars: hookFns.fetchInspectVars,}),@@ -256,6 +257,13 @@ vi.mock('@/app/components/workflow-app/hooks', () => ({handleRun: hookFns.handleRun,handleStopRun: hookFns.handleStopRun,}),+ useWorkflowRunByCanEdit: () => ({+ handleBackupDraft: hookFns.handleBackupDraft,+ handleLoadBackupDraft: hookFns.handleLoadBackupDraft,+ handleRestoreFromPublishedWorkflow: hookFns.handleRestoreFromPublishedWorkflow,+ handleRun: hookFns.handleRun,+ handleStopRun: hookFns.handleStopRun,+ }),useWorkflowStartRun: () => ({handleStartWorkflowRun: hookFns.handleStartWorkflowRun,handleWorkflowStartRunInChatflow: hookFns.handleWorkflowStartRunInChatflow,@@ -265,6 +273,27 @@ vi.mock('@/app/components/workflow-app/hooks', () => ({handleWorkflowTriggerPluginRunInWorkflow: hookFns.handleWorkflowTriggerPluginRunInWorkflow,handleWorkflowRunAllTriggersInWorkflow: hookFns.handleWorkflowRunAllTriggersInWorkflow,}),+ useWorkflowStartRunByCanEdit: () => ({+ handleStartWorkflowRun: hookFns.handleStartWorkflowRun,+ handleWorkflowStartRunInChatflow: hookFns.handleWorkflowStartRunInChatflow,+ handleWorkflowStartRunInWorkflow: hookFns.handleWorkflowStartRunInWorkflow,+ handleWorkflowTriggerScheduleRunInWorkflow: hookFns.handleWorkflowTriggerScheduleRunInWorkflow,+ handleWorkflowTriggerWebhookRunInWorkflow: hookFns.handleWorkflowTriggerWebhookRunInWorkflow,+ handleWorkflowTriggerPluginRunInWorkflow: hookFns.handleWorkflowTriggerPluginRunInWorkflow,+ handleWorkflowRunAllTriggersInWorkflow: hookFns.handleWorkflowRunAllTriggersInWorkflow,+ }),+}))++vi.mock('@/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas', () => ({+ useWorkflowDraftGraphForCanvas: () => ({+ getWorkflowDraftGraphForCanvas: (graph?: { nodes?: unknown[], edges?: unknown[], viewport?: unknown }) => ({+ nodes: graph?.nodes?.length+ ? graph.nodes+ : [{ id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } }],+ edges: graph?.edges || [],+ viewport: graph?.viewport || { x: 0, y: 0, zoom: 1 },+ }),+ }),}))vi.mock('@/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas', () => ({@@ -297,6 +326,7 @@ describe('WorkflowMain', () => {collaborationListeners.workflowUpdate = nullcollaborationListeners.syncRequest = nullmockFetchWorkflowDraft.mockReset()+ useAppStore.setState({ appDetail: undefined })})it('should render the inner workflow context with children and forwarded graph props', () => {@@ -405,6 +435,30 @@ describe('WorkflowMain', () => {})})+ it('should pass view-layout ACL permission as comment-only workflow access', () => {+ useAppStore.setState({+ appDetail: {+ permission_keys: [AppACLPermission.ViewLayout],+ } as never,+ })++ render(+ <WorkflowMain+ nodes={[]}+ edges={[]}+ viewport={{ x: 0, y: 0, zoom: 1 }}+ />,+ )++ expect(capturedContextProps?.hooksStore).toMatchObject({+ accessControl: {+ canEdit: false,+ canComment: true,+ canRun: false,+ },+ })+ })+it('passes collaboration props and tracks cursors when collaboration is enabled', () => {collaborationRuntime.isEnabled = truecollaborationRuntime.isConnected = truediff --git a/web/app/components/workflow-app/components/workflow-children.tsx b/web/app/components/workflow-app/components/workflow-children.tsxindex a151dcae294..4ef93b079b2 100644--- a/web/app/components/workflow-app/components/workflow-children.tsx+++ b/web/app/components/workflow-app/components/workflow-children.tsx@@ -15,6 +15,7 @@ import {useDSL,usePanelInteractions,} from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'@@ -72,6 +73,8 @@ const WorkflowChildren = () => {const showImportDSLModal = useStore(s => s.showImportDSLModal)const setShowImportDSLModal = useStore(s => s.setShowImportDSLModal)const showOnboarding = useStore(s => s.showOnboarding)+ const canImportExportDSL = useHooksStore(s => s.accessControl.canImportExportDSL)+ const canEdit = useHooksStore(s => s.accessControl.canEdit)const setShowOnboarding = useStore(s => s.setShowOnboarding)const setHasSelectedStartNode = useStore(s => s.setHasSelectedStartNode)const setShouldAutoOpenStartNodeSelector = useStore(s => s.setShouldAutoOpenStartNodeSelector)@@ -99,6 +102,9 @@ const WorkflowChildren = () => {}, [handleOnboardingClose])const handleSelectStartNode = useCallback((nodeType: BlockEnum, toolConfig?: BlockDefaultValue) => {+ if (!canEdit)+ return+const nodeDefault = availableNodesMetaData.nodesMap?.[nodeType]if (!nodeDefault?.defaultValue)return@@ -152,7 +158,7 @@ const WorkflowChildren = () => {console.error('Failed to save node to draft')},})- }, [availableNodesMetaData, setShowOnboarding, setHasSelectedStartNode, reactFlowStore, handleSyncWorkflowDraft])+ }, [availableNodesMetaData, autoGenerateWebhookUrl, canEdit, handleSyncWorkflowDraft, reactFlowStore, setHasSelectedStartNode, setShouldAutoOpenStartNodeSelector, setShowOnboarding])return (<>@@ -161,7 +167,7 @@ const WorkflowChildren = () => {showFeaturesPanel && <Features />}{- showOnboarding && (+ canEdit && showOnboarding && (<WorkflowOnboardingModalisShow={showOnboarding}onClose={handleCloseOnboarding}@@ -170,7 +176,7 @@ const WorkflowChildren = () => {)}{- showImportDSLModal && (+ canImportExportDSL && showImportDSLModal && (<UpdateDSLModalonCancel={() => setShowImportDSLModal(false)}onBackup={exportCheck!}@@ -179,7 +185,7 @@ const WorkflowChildren = () => {)}{- secretEnvList.length > 0 && (+ canImportExportDSL && secretEnvList.length > 0 && (<DSLExportConfirmModalenvList={secretEnvList}onConfirm={handleExportDSL!}diff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsxindex 767927d9922..a2d3ba5c750 100644--- a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx+++ b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx@@ -46,6 +46,7 @@ const mockUpdatePublishedWorkflow = vi.fn()const mockResetWorkflowVersionHistory = vi.fn()const mockInvalidateAppTriggers = vi.fn()const mockFetchAppDetail = vi.fn()+const mockInvalidateQueries = vi.fn()const mockSetPublishedAt = vi.fn()const mockSetLastPublishedHasUserInput = vi.fn()@@ -86,6 +87,25 @@ vi.mock('@/app/components/workflow/store', () => ({useWorkflowStore: () => mockWorkflowStore,}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canReleaseAndVersion: boolean } }) => T): T =>+ selector({+ accessControl: {+ canReleaseAndVersion: true,+ },+ }),+}))++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useQueryClient: () => ({+ invalidateQueries: mockInvalidateQueries,+ }),+ }+})+vi.mock('@/app/components/base/features/hooks', () => ({useFeatures: (selector: (state: Record<string, unknown>) => unknown) => mockUseFeatures(selector),}))@@ -204,6 +224,7 @@ describe('FeaturesTrigger', () => {// Set up app store stateuseAppStore.setState({ appDetail: { id: 'app-id' } as unknown as App })mockFetchAppDetail.mockResolvedValue({ id: 'app-id' })+ mockInvalidateQueries.mockResolvedValue(undefined)mockPublishWorkflow.mockResolvedValue({ created_at: '2024-01-01T00:00:00Z' })})@@ -447,7 +468,7 @@ describe('FeaturesTrigger', () => {expect(mockSetLastPublishedHasUserInput).toHaveBeenCalledWith(true)expect(mockResetWorkflowVersionHistory).toHaveBeenCalled()expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'common.api.actionSuccess' })- expect(mockFetchAppDetail).toHaveBeenCalledWith({ url: '/apps', id: 'app-id' })+ expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['apps', 'detail', 'app-id'] })expect(useAppStore.getState().appDetail).toBeDefined()})})@@ -470,15 +491,14 @@ describe('FeaturesTrigger', () => {},},])- const { queryClient } = renderWithToast(<FeaturesTrigger />)- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ renderWithToast(<FeaturesTrigger />)// Actawait user.click(screen.getByRole('button', { name: 'publisher-publish' }))// Assertawait waitFor(() => {- expect(invalidateQueries).toHaveBeenCalledWith({+ expect(mockInvalidateQueries).toHaveBeenCalledWith({queryKey: consoleQuery.agent.get.key(),})})@@ -503,8 +523,7 @@ describe('FeaturesTrigger', () => {},},])- const { queryClient } = renderWithToast(<FeaturesTrigger />)- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ renderWithToast(<FeaturesTrigger />)// Actawait user.click(screen.getByRole('button', { name: 'publisher-publish' }))@@ -513,7 +532,7 @@ describe('FeaturesTrigger', () => {await waitFor(() => {expect(mockPublishWorkflow).toHaveBeenCalled()})- expect(invalidateQueries).not.toHaveBeenCalledWith({+ expect(mockInvalidateQueries).not.toHaveBeenCalledWith({queryKey: consoleQuery.agent.get.key(),})})@@ -579,7 +598,7 @@ describe('FeaturesTrigger', () => {// Arrangeconst user = userEvent.setup()const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)- mockFetchAppDetail.mockRejectedValue(new Error('fetch failed'))+ mockInvalidateQueries.mockRejectedValue(new Error('fetch failed'))renderWithToast(<FeaturesTrigger />)diff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsxindex a3b36fc0817..ab41536fd85 100644--- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx+++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx@@ -8,7 +8,6 @@ import type {import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { toast } from '@langgenius/dify-ui/toast'-import { RiApps2AddLine } from '@remixicon/react'import { useQueryClient } from '@tanstack/react-query'import {memo,@@ -29,6 +28,7 @@ import {useNodesSyncDraft,// useWorkflowRunValidation,} from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { hasValidRosterAgentBinding, isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'import {useStore,@@ -42,8 +42,8 @@ import {} from '@/app/components/workflow/types'import { useProviderContext } from '@/context/provider-context'import useTheme from '@/hooks/use-theme'-import { fetchAppDetail } from '@/service/apps'import { consoleQuery } from '@/service/client'+import { appDetailQueryKeyPrefix } from '@/service/use-apps'import { useInvalidateAppTriggers } from '@/service/use-tools'import { useInvalidateAppWorkflow, usePublishWorkflow, useResetWorkflowVersionHistory } from '@/service/use-workflow'@@ -55,8 +55,8 @@ const FeaturesTrigger = () => {const queryClient = useQueryClient()const appDetail = useAppStore(s => s.appDetail)const appID = appDetail?.id- const setAppDetail = useAppStore(s => s.setAppDetail)const { nodesReadOnly, getNodesReadOnly } = useNodesReadOnly()+ const canReleaseAndVersion = useHooksStore(s => s.accessControl.canReleaseAndVersion)const { plan, isFetchedPlan } = useProviderContext()const publishedAt = useStore(s => s.publishedAt)const draftUpdatedAt = useStore(s => s.draftUpdatedAt)@@ -134,13 +134,12 @@ const FeaturesTrigger = () => {const updateAppDetail = useCallback(async () => {try {- const res = await fetchAppDetail({ url: '/apps', id: appID! })- setAppDetail({ ...res })+ await queryClient.invalidateQueries({ queryKey: [...appDetailQueryKeyPrefix, appID!] })}catch (error) {console.error(error)}- }, [appID, setAppDetail])+ }, [appID, queryClient])const { mutateAsync: publishWorkflow } = usePublishWorkflow()// const { validateBeforeRun } = useWorkflowRunValidation()@@ -205,7 +204,7 @@ const FeaturesTrigger = () => {)}onClick={handleShowFeatures}>- <RiApps2AddLine className="mr-1 size-4 text-components-button-secondary-text" />+ <span className="mr-1 i-ri-apps-2-add-line size-4 text-components-button-secondary-text" />{t('common.features', { ns: 'workflow' })}</Button>)}@@ -213,7 +212,7 @@ const FeaturesTrigger = () => {{...{publishedAt,draftUpdatedAt,- disabled: nodesReadOnly || !hasWorkflowNodes,+ disabled: nodesReadOnly || !hasWorkflowNodes || !canReleaseAndVersion,toolPublished,inputs: variables,outputs: endVariables,@@ -225,7 +224,7 @@ const FeaturesTrigger = () => {missingStartNode: !startNode,hasTriggerNode,startNodeLimitExceeded,- publishDisabled: !hasWorkflowNodes || startNodeLimitExceeded,+ publishDisabled: !hasWorkflowNodes || startNodeLimitExceeded || !canReleaseAndVersion,hasHumanInputNode,}}/>diff --git a/web/app/components/workflow-app/components/workflow-main.tsx b/web/app/components/workflow-app/components/workflow-main.tsxindex 08fc2e8daf6..bfd0c3aa3d4 100644--- a/web/app/components/workflow-app/components/workflow-main.tsx+++ b/web/app/components/workflow-app/components/workflow-main.tsx@@ -21,18 +21,20 @@ import { useCollaboration } from '@/app/components/workflow/collaboration/hooks/import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-interactions'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { SupportUploadFileTypes } from '@/app/components/workflow/types'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { fetchWorkflowDraft } from '@/service/workflow'+import { getAppACLCapabilities } from '@/utils/permission'import {useAvailableNodesMetaData,useConfigsMap,- useDSL,+ useDSLByCanEdit,useGetRunAndTraceUrl,useInspectVarsCrud,- useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,useSetWorkflowVarsWithValue,useWorkflowRefreshDraft,- useWorkflowRun,- useWorkflowStartRun,+ useWorkflowRunByCanEdit,+ useWorkflowStartRunByCanEdit,} from '../hooks'import WorkflowChildren from './workflow-children'@@ -75,6 +77,16 @@ const WorkflowMain = ({const filteredCursors = Object.fromEntries(Object.entries(cursors).filter(([userId]) => userId !== myUserId),)+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const appACLCapabilities = useMemo(+ () => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }),+ [appDetail?.maintainer, appDetail?.permission_keys, currentUserId, workspacePermissionKeys],+ )useEffect(() => {if (!isCollaborationEnabled)@@ -138,7 +150,7 @@ const WorkflowMain = ({const {doSyncWorkflowDraft,syncWorkflowDraftWhenPageClose,- } = useNodesSyncDraft()+ } = useNodesSyncDraftByCanEdit(appACLCapabilities.canEdit)const { handleRefreshWorkflowDraft } = useWorkflowRefreshDraft()const { handleUpdateWorkflowCanvas } = useWorkflowUpdate()const {@@ -147,7 +159,7 @@ const WorkflowMain = ({handleRestoreFromPublishedWorkflow,handleRun,handleStopRun,- } = useWorkflowRun()+ } = useWorkflowRunByCanEdit(appACLCapabilities.canEdit)useEffect(() => {if (!appId || !isCollaborationEnabled)@@ -209,13 +221,13 @@ const WorkflowMain = ({handleWorkflowTriggerWebhookRunInWorkflow,handleWorkflowTriggerPluginRunInWorkflow,handleWorkflowRunAllTriggersInWorkflow,- } = useWorkflowStartRun()+ } = useWorkflowStartRunByCanEdit(appACLCapabilities.canEdit)const availableNodesMetaData = useAvailableNodesMetaData()const { getWorkflowRunAndTraceUrl } = useGetRunAndTraceUrl()const {exportCheck,handleExportDSL,- } = useDSL()+ } = useDSLByCanEdit(appACLCapabilities.canEdit)const configsMap = useConfigsMap()@@ -275,6 +287,13 @@ const WorkflowMain = ({invalidateSysVarValues,resetConversationVar,invalidateConversationVarValues,+ accessControl: {+ canEdit: appACLCapabilities.canEdit,+ canComment: appACLCapabilities.canComment,+ canRun: appACLCapabilities.canTestAndRun,+ canImportExportDSL: appACLCapabilities.canImportExportDSL,+ canReleaseAndVersion: appACLCapabilities.canReleaseAndVersion,+ },configsMap,}}, [@@ -312,6 +331,7 @@ const WorkflowMain = ({invalidateSysVarValues,resetConversationVar,invalidateConversationVarValues,+ appACLCapabilities,configsMap,])diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.tsindex 47ac39c60e2..4bc3c1a8fcb 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts@@ -1,6 +1,7 @@import { renderHook, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { BlockEnum } from '@/app/components/workflow/types'+import { AppACLPermission } from '@/utils/permission'import { useWorkflowInit } from '../use-workflow-init'@@ -21,6 +22,8 @@ let appStoreState: {id: stringname: stringmode: string+ permission_keys?: string[]+ maintainer?: string}}@@ -43,6 +46,14 @@ vi.mock('@/app/components/app/store', () => ({selector(appStoreState),}))+vi.mock('@/context/app-context', () => ({+ useSelector: <T>(selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => T): T =>+ selector({+ userProfile: { id: 'user-1' },+ workspacePermissionKeys: ['app.create_and_management'],+ }),+}))+vi.mock('../use-workflow-template', () => ({useWorkflowTemplate: () => ({nodes: appStoreState.appDetail.mode === 'workflow'@@ -98,7 +109,7 @@ describe('useWorkflowInit', () => {beforeEach(() => {vi.clearAllMocks()appStoreState = {- appDetail: { id: 'app-1', name: 'Test', mode: 'workflow' },+ appDetail: { id: 'app-1', name: 'Test', mode: 'workflow', permission_keys: [AppACLPermission.Edit] },}workflowConfigState = { data: null, isLoading: false }mockWorkflowStoreGetState.mockReturnValue({@@ -154,7 +165,7 @@ describe('useWorkflowInit', () => {it('should keep creating the first backend draft for advanced chat apps', async () => {appStoreState = {- appDetail: { id: 'app-1', name: 'Test', mode: 'advanced-chat' },+ appDetail: { id: 'app-1', name: 'Test', mode: 'advanced-chat', permission_keys: [AppACLPermission.Edit] },}mockFetchWorkflowDraft.mockReset()@@ -180,6 +191,33 @@ describe('useWorkflowInit', () => {expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('new-hash')})+ it('should keep readonly users local when the first workflow draft does not exist', async () => {+ appStoreState = {+ appDetail: { id: 'app-1', name: 'Test', mode: 'workflow', permission_keys: [AppACLPermission.ViewLayout] },+ }+ mockFetchWorkflowDraft+ .mockReset()+ .mockRejectedValueOnce(notExistError())++ const { result } = renderHook(() => useWorkflowInit())++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false)+ })++ expect(result.current.data?.graph.nodes).toEqual([+ { id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } },+ ])+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()+ expect(mockWorkflowStoreSetState).toHaveBeenCalledWith(expect.objectContaining({+ envSecrets: {},+ environmentVariables: [],+ conversationVariables: [],+ isWorkflowDataLoaded: true,+ }))+ expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('')+ })+it('should restore a local start placeholder when an existing workflow draft has an empty graph', async () => {mockFetchWorkflowDraft.mockReset().mockResolvedValue({...draftResponse,diff --git a/web/app/components/workflow-app/hooks/use-DSL.ts b/web/app/components/workflow-app/hooks/use-DSL.tsindex 2fb2df8a3b0..9110e53c506 100644--- a/web/app/components/workflow-app/hooks/use-DSL.ts+++ b/web/app/components/workflow-app/hooks/use-DSL.ts@@ -12,13 +12,17 @@ import { useEventEmitterContextContext } from '@/context/event-emitter'import { exportAppConfig } from '@/service/apps'import { fetchWorkflowDraft } from '@/service/workflow'import { downloadBlob } from '@/utils/download'-import { useNodesSyncDraft } from './use-nodes-sync-draft'+import {+ useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,+} from './use-nodes-sync-draft'-export const useDSL = () => {+type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']++const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const { t } = useTranslation()const { eventEmitter } = useEventEmitterContextContext()const [exporting, setExporting] = useState(false)- const { doSyncWorkflowDraft } = useNodesSyncDraft()const appDetail = useAppStore(s => s.appDetail)@@ -75,3 +79,15 @@ export const useDSL = () => {handleExportDSL,}}++export const useDSLByCanEdit = (canEdit: boolean) => {+ const { doSyncWorkflowDraft } = useNodesSyncDraftByCanEdit(canEdit)++ return useDSLBase(doSyncWorkflowDraft)+}++export const useDSL = () => {+ const { doSyncWorkflowDraft } = useNodesSyncDraft()++ return useDSLBase(doSyncWorkflowDraft)+}diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.tsindex f7bd2f4c2fb..980b2536546 100644--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts@@ -7,7 +7,7 @@ import { useStoreApi } from 'reactflow'import { useFeaturesStore } from '@/app/components/base/features/hooks'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'-import { useNodesReadOnly } from '@/app/components/workflow/hooks/use-workflow'+import { useNodesReadOnly, useNodesReadOnlyByCanEdit } from '@/app/components/workflow/hooks/use-workflow'import { useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { API_PREFIX } from '@/config'@@ -16,11 +16,10 @@ import { postWithKeepalive } from '@/service/fetch'import { syncWorkflowDraft } from '@/service/workflow'import { useWorkflowRefreshDraft } from '.'-export const useNodesSyncDraft = () => {+const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {const store = useStoreApi()const workflowStore = useWorkflowStore()const featuresStore = useFeaturesStore()- const { getNodesReadOnly } = useNodesReadOnly()const { handleRefreshWorkflowDraft } = useWorkflowRefreshDraft()const { data: isCollaborationEnabled } = useSuspenseQuery({...systemFeaturesQueryOptions(),@@ -181,3 +180,15 @@ export const useNodesSyncDraft = () => {syncWorkflowDraftWhenPageClose,}}++export const useNodesSyncDraftByCanEdit = (canEdit: boolean) => {+ const { getNodesReadOnly } = useNodesReadOnlyByCanEdit(canEdit)++ return useNodesSyncDraftBase(getNodesReadOnly)+}++export const useNodesSyncDraft = () => {+ const { getNodesReadOnly } = useNodesReadOnly()++ return useNodesSyncDraftBase(getNodesReadOnly)+}diff --git a/web/app/components/workflow-app/hooks/use-workflow-init.ts b/web/app/components/workflow-app/hooks/use-workflow-init.tsindex 7a4ccd63101..2845b97f46d 100644--- a/web/app/components/workflow-app/hooks/use-workflow-init.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-init.ts@@ -4,6 +4,7 @@ import type { FetchWorkflowDraftResponse } from '@/types/workflow'import {useCallback,useEffect,+ useMemo,useState,} from 'react'import { useStore as useAppStore } from '@/app/components/app/store'@@ -12,6 +13,7 @@ import {useWorkflowStore,} from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useWorkflowConfig } from '@/service/use-workflow'import {fetchNodesDefaultConfigs,@@ -20,9 +22,37 @@ import {syncWorkflowDraft,} from '@/service/workflow'import { AppModeEnum } from '@/types/app'+import { getAppACLCapabilities } from '@/utils/permission'import { useWorkflowDraftGraphForCanvas } from './use-workflow-draft-graph-for-canvas'import { useWorkflowTemplate } from './use-workflow-template'+const emptyAccount = {+ id: '',+ name: '',+ email: '',+}++const createLocalWorkflowDraft = (+ graph: FetchWorkflowDraftResponse['graph'],+): FetchWorkflowDraftResponse => ({+ id: '',+ graph,+ features: {+ retriever_resource: { enabled: true },+ },+ created_at: 0,+ created_by: emptyAccount,+ hash: '',+ updated_at: 0,+ updated_by: emptyAccount,+ tool_published: false,+ environment_variables: [],+ conversation_variables: [],+ version: '',+ marked_name: '',+ marked_comment: '',+})+const hasConnectedUserInput = (nodes: Node[] = [], edges: Edge[] = []): boolean => {const startNodeIds = nodes.filter(node => node?.data?.type === BlockEnum.Start)@@ -41,6 +71,13 @@ export const useWorkflowInit = () => {edges: edgesTemplate,} = useWorkflowTemplate()const appDetail = useAppStore(state => state.appDetail)!+ const currentUserId = useAppContextWithSelector(state => state.userProfile?.id)+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(appDetail.permission_keys, {+ currentUserId,+ resourceMaintainer: appDetail.maintainer,+ workspacePermissionKeys,+ }), [appDetail.maintainer, appDetail.permission_keys, currentUserId, workspacePermissionKeys])const { getWorkflowDraftGraphForCanvas } = useWorkflowDraftGraphForCanvas(appDetail.mode)const setSyncWorkflowDraftHash = useStore(s => s.setSyncWorkflowDraftHash)const [data, setData] = useState<FetchWorkflowDraftResponse>()@@ -86,6 +123,10 @@ export const useWorkflowInit = () => {error.json().then((err: any) => {if (err.code === 'draft_workflow_not_exist') {const isAdvancedChat = appDetail.mode === AppModeEnum.ADVANCED_CHAT+ const initialGraph = {+ nodes: isAdvancedChat ? nodesTemplate : [],+ edges: isAdvancedChat ? edgesTemplate : [],+ }workflowStore.setState({notInitialWorkflow: true,showOnboarding: false,@@ -94,13 +135,28 @@ export const useWorkflowInit = () => {hasShownOnboarding: !isAdvancedChat,})+ if (!appACLCapabilities.canEdit) {+ const initialData = createLocalWorkflowDraft({+ ...getWorkflowDraftGraphForCanvas(initialGraph, {+ localStartPlaceholderNodes: nodesTemplate,+ }),+ })+ setData(initialData)+ workflowStore.setState({+ envSecrets: {},+ environmentVariables: [],+ conversationVariables: [],+ isWorkflowDataLoaded: true,+ })+ setSyncWorkflowDraftHash(initialData.hash)+ setIsLoading(false)+ return+ }+syncWorkflowDraft({url: `/apps/${appDetail.id}/workflows/draft`,params: {- graph: {- nodes: isAdvancedChat ? nodesTemplate : [],- edges: isAdvancedChat ? edgesTemplate : [],- },+ graph: initialGraph,features: {retriever_resource: { enabled: true },},@@ -116,7 +172,7 @@ export const useWorkflowInit = () => {})}}- }, [appDetail, getWorkflowDraftGraphForCanvas, nodesTemplate, edgesTemplate, workflowStore, setSyncWorkflowDraftHash])+ }, [appACLCapabilities.canEdit, appDetail, getWorkflowDraftGraphForCanvas, nodesTemplate, edgesTemplate, workflowStore, setSyncWorkflowDraftHash])useEffect(() => {handleGetInitialWorkflowData()diff --git a/web/app/components/workflow-app/hooks/use-workflow-run.ts b/web/app/components/workflow-app/hooks/use-workflow-run.tsindex aa6b860acb7..d7a90e36605 100644--- a/web/app/components/workflow-app/hooks/use-workflow-run.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-run.ts@@ -26,7 +26,10 @@ import { stopWorkflowRun } from '@/service/workflow'import { AppModeEnum } from '@/types/app'import { useSetWorkflowVarsWithValue } from '../../workflow/hooks/use-fetch-workflow-inspect-vars'import { useConfigsMap } from './use-configs-map'-import { useNodesSyncDraft } from './use-nodes-sync-draft'+import {+ useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,+} from './use-nodes-sync-draft'import {createBaseWorkflowRunCallbacks,createFinalWorkflowRunCallbacks,@@ -96,12 +99,13 @@ const getWorkflowTracingCount = (workflowData: unknown) => {return Array.isArray(tracing) ? tracing.length : undefined}-export const useWorkflowRun = () => {+type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']++const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const store = useStoreApi()const workflowStore = useWorkflowStore()const reactflow = useReactFlow()const featuresStore = useFeaturesStore()- const { doSyncWorkflowDraft } = useNodesSyncDraft()const { handleUpdateWorkflowCanvas } = useWorkflowUpdate()const pathname = usePathname()const configsMap = useConfigsMap()@@ -515,3 +519,15 @@ export const useWorkflowRun = () => {handleRestoreFromPublishedWorkflow,}}++export const useWorkflowRunByCanEdit = (canEdit: boolean) => {+ const { doSyncWorkflowDraft } = useNodesSyncDraftByCanEdit(canEdit)++ return useWorkflowRunBase(doSyncWorkflowDraft)+}++export const useWorkflowRun = () => {+ const { doSyncWorkflowDraft } = useNodesSyncDraft()++ return useWorkflowRunBase(doSyncWorkflowDraft)+}diff --git a/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx b/web/app/components/workflow-app/hooks/use-workflow-start-run.tsxindex 516a653cd18..f5c58e2cd3a 100644--- a/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx+++ b/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx@@ -11,17 +11,23 @@ import {import {useIsChatMode,useNodesSyncDraft,+ useNodesSyncDraftByCanEdit,useWorkflowRun,+ useWorkflowRunByCanEdit,} from '.'-export const useWorkflowStartRun = () => {+type HandleRun = ReturnType<typeof useWorkflowRun>['handleRun']+type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']++const useWorkflowStartRunBase = (+ handleRun: HandleRun,+ doSyncWorkflowDraft: DoSyncWorkflowDraft,+) => {const store = useStoreApi()const workflowStore = useWorkflowStore()const featuresStore = useFeaturesStore()const isChatMode = useIsChatMode()const { handleCancelDebugAndPreviewPanel } = useWorkflowInteractions()- const { handleRun } = useWorkflowRun()- const { doSyncWorkflowDraft } = useNodesSyncDraft()const handleWorkflowStartRunInWorkflow = useCallback(async () => {const {@@ -303,3 +309,17 @@ export const useWorkflowStartRun = () => {handleWorkflowRunAllTriggersInWorkflow,}}++export const useWorkflowStartRunByCanEdit = (canEdit: boolean) => {+ const { handleRun } = useWorkflowRunByCanEdit(canEdit)+ const { doSyncWorkflowDraft } = useNodesSyncDraftByCanEdit(canEdit)++ return useWorkflowStartRunBase(handleRun, doSyncWorkflowDraft)+}++export const useWorkflowStartRun = () => {+ const { handleRun } = useWorkflowRun()+ const { doSyncWorkflowDraft } = useNodesSyncDraft()++ return useWorkflowStartRunBase(handleRun, doSyncWorkflowDraft)+}diff --git a/web/app/components/workflow-app/index.tsx b/web/app/components/workflow-app/index.tsxindex e45ebbac771..dd572c0b7e5 100644--- a/web/app/components/workflow-app/index.tsx+++ b/web/app/components/workflow-app/index.tsx@@ -24,6 +24,7 @@ import { useSearchParams } from '@/next/navigation'import { fetchRunDetail } from '@/service/log'import { useAppTriggers } from '@/service/use-tools'import { AppModeEnum } from '@/types/app'+import { getAppACLCapabilities } from '@/utils/permission'import WorkflowAppMain from './components/workflow-main'import { useGetRunAndTraceUrl } from './hooks/use-get-run-and-trace-url'@@ -44,11 +45,16 @@ const WorkflowAppWithAdditionalContext = () => {fileUploadConfigResponse,} = useWorkflowInit()const workflowStore = useWorkflowStore()- const { isLoadingCurrentWorkspace, currentWorkspace } = useAppContext()+ const { isLoadingCurrentWorkspace, currentWorkspace, userProfile, workspacePermissionKeys } = useAppContext()// Initialize trigger status at application levelconst { setTriggerStatuses } = useTriggerStatusStore()const appDetail = useAppStore(s => s.appDetail)+ const appACLCapabilities = useMemo(() => getAppACLCapabilities(appDetail?.permission_keys, {+ currentUserId: userProfile?.id,+ resourceMaintainer: appDetail?.maintainer,+ workspacePermissionKeys,+ }), [appDetail?.maintainer, appDetail?.permission_keys, userProfile?.id, workspacePermissionKeys])const appId = appDetail?.idconst isWorkflowMode = appDetail?.mode === AppModeEnum.WORKFLOWconst { data: triggersResponse } = useAppTriggers(isWorkflowMode ? appId : undefined, {@@ -98,7 +104,7 @@ const WorkflowAppWithAdditionalContext = () => {const replayRunId = searchParams.get('replayRunId')useEffect(() => {- if (!replayRunId)+ if (!replayRunId || !appACLCapabilities.canTestAndRun)returnconst { runUrl } = getWorkflowRunAndTraceUrl(replayRunId)if (!runUrl)@@ -127,7 +133,7 @@ const WorkflowAppWithAdditionalContext = () => {setShowInputsPanel(true)setShowDebugAndPreviewPanel(true)})- }, [replayRunId, workflowStore, getWorkflowRunAndTraceUrl])+ }, [appACLCapabilities.canTestAndRun, replayRunId, workflowStore, getWorkflowRunAndTraceUrl])if (!data || isLoading || isLoadingCurrentWorkspace || !currentWorkspace.id) {return (diff --git a/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsxindex 1f3ff385da5..37ee2cf0b30 100644--- a/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx+++ b/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx@@ -1,5 +1,6 @@import { ContextMenu } from '@langgenius/dify-ui/context-menu'import { fireEvent, screen, waitFor } from '@testing-library/react'+import { fullWorkflowAccessControl } from '../hooks-store'import { PanelContextmenu } from '../panel-contextmenu'import { BlockEnum } from '../types'import { createNode } from './fixtures'@@ -167,4 +168,26 @@ describe('PanelContextmenu', () => {expect(mockClose).toHaveBeenCalled()})})++ it('should hide add note when editing is denied but comments are allowed', async () => {+ mockUseWorkflowMoveMode.mockReturnValue({+ isCommentModeAvailable: true,+ })++ renderPanelContextmenu({+ initialStoreState: {+ contextMenuTarget: { type: 'panel' },+ },+ hooksStoreProps: {+ accessControl: {+ ...fullWorkflowAccessControl,+ canEdit: false,+ canComment: true,+ },+ },+ })++ expect(await screen.findByText('comments.actions.addComment')).toBeInTheDocument()+ expect(screen.queryByText('nodes.note.addNote')).not.toBeInTheDocument()+ })})diff --git a/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsxindex 39eff52fdc6..3ae8851a23f 100644--- a/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsx+++ b/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsx@@ -19,6 +19,15 @@ const mockHandleNodesDuplicate = vi.fn()const mockHandleNodesDelete = vi.fn()const mockHandleCreateSnippet = vi.fn()const mockCreateSnippetDialogRender = vi.fn()+const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['snippets.create_and_modify'] as string[],+}))++vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))vi.mock('@/app/components/snippets/hooks/use-create-snippet', async () => {const React = await vi.importActual<typeof import('react')>('react')@@ -135,6 +144,7 @@ describe('SelectionContextmenu', () => {mockHandleNodesDelete.mockReset()mockHandleCreateSnippet.mockReset()mockCreateSnippetDialogRender.mockReset()+ mockWorkspacePermissionKeys.value = ['snippets.create_and_modify']})it('should not render when selection context menu target is absent', () => {@@ -226,6 +236,24 @@ describe('SelectionContextmenu', () => {}))})+ it('should hide create snippet action without snippets create-and-modify permission', async () => {+ mockWorkspacePermissionKeys.value = []+ const nodes = [+ createNode({ id: 'n1', selected: true, width: 80, height: 40 }),+ createNode({ id: 'n2', selected: true, position: { x: 140, y: 0 }, width: 80, height: 40 }),+ ]+ const { store } = renderSelectionMenu({ nodes })++ act(() => {+ store.setState({ contextMenuTarget: { type: 'selection' } })+ })++ await waitFor(() => {+ expect(screen.getByRole('menuitem', { name: /common.copy/ })).toBeInTheDocument()+ })+ expect(screen.queryByRole('menuitem', { name: /Create Snippet|snippet\.createDialogTitle/ })).not.toBeInTheDocument()+ })+it('should add input fields for variable references outside of the selected graph', async () => {const nodes = [createNode({diff --git a/web/app/components/workflow/__tests__/workflow-test-env.spec.tsx b/web/app/components/workflow/__tests__/workflow-test-env.spec.tsxindex f47da870bb3..739fd01410e 100644--- a/web/app/components/workflow/__tests__/workflow-test-env.spec.tsx+++ b/web/app/components/workflow/__tests__/workflow-test-env.spec.tsx@@ -95,16 +95,9 @@ describe('renderWorkflowComponent', () => {expect(screen.getByTestId('hooks-reader'))!.toHaveTextContent('test-123')})- it('should throw when HooksStoreContext is not provided', () => {- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})- try {- expect(() => {- renderWorkflowComponent(React.createElement(HooksStoreReader))- }).toThrow('Missing HooksStoreContext.Provider')- }- finally {- consoleSpy.mockRestore()- }+ it('should provide HooksStoreContext with default store', () => {+ renderWorkflowComponent(React.createElement(HooksStoreReader))+ expect(screen.getByTestId('hooks-reader'))!.toHaveTextContent('none')})it('should forward extra render options (container)', () => {diff --git a/web/app/components/workflow/__tests__/workflow-test-env.tsx b/web/app/components/workflow/__tests__/workflow-test-env.tsxindex ff18b304e50..7c46887d3ef 100644--- a/web/app/components/workflow/__tests__/workflow-test-env.tsx+++ b/web/app/components/workflow/__tests__/workflow-test-env.tsx@@ -141,9 +141,7 @@ type StoreInstances = {function createStoresFromOptions(options: WorkflowProviderOptions): StoreInstances {const store = createTestWorkflowStore(options.initialStoreState)- const hooksStore = options.hooksStoreProps !== undefined- ? createTestHooksStore(options.hooksStoreProps)- : undefined+ const hooksStore = createTestHooksStore(options.hooksStoreProps)return { store, hooksStore }}diff --git a/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx b/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsxindex 943c3649ae1..b5949265cad 100644--- a/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx@@ -35,6 +35,7 @@ const mockCreateCustomCollection = vi.mocked(createCustomCollection)const mockInstallPackageFromMarketPlace = vi.fn()const mockCheckInstalled = vi.fn()const mockRefreshPluginList = vi.fn()+let mockWorkspacePermissionKeys: string[] = ['tool.manage']const mockUseGetLanguage = vi.mocked(useGetLanguage)const mockUseTheme = vi.mocked(useTheme)@@ -54,6 +55,12 @@ vi.mock('@/context/i18n', () => ({useGetLanguage: vi.fn(),}))+vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))+vi.mock('@/hooks/use-theme', () => ({default: vi.fn(),}))@@ -70,6 +77,10 @@ vi.mock('@/app/components/plugins/marketplace/hooks', () => ({useMarketplacePlugins: vi.fn(),}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission', () => ({+ default: () => ({ canInstallPlugin: true }),+}))+vi.mock('@/service/tools', () => ({createCustomCollection: vi.fn(),}))@@ -323,6 +334,7 @@ const renderToolPicker = (props: Partial<React.ComponentProps<typeof ToolPicker>describe('ToolPicker', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys = ['tool.manage']mockUseGetLanguage.mockReturnValue('en_US')mockUseTheme.mockReturnValue({ theme: Theme.light } as ReturnType<typeof useTheme>)@@ -345,8 +357,12 @@ describe('ToolPicker', () => {page: 0,} as ReturnType<typeof useMarketplacePlugins>)mockUseAllBuiltInTools.mockReturnValue({ data: builtInTools } as ReturnType<typeof useAllBuiltInTools>)- mockUseAllCustomTools.mockReturnValue({ data: customTools } as ReturnType<typeof useAllCustomTools>)- mockUseAllWorkflowTools.mockReturnValue({ data: workflowTools } as ReturnType<typeof useAllWorkflowTools>)+ mockUseAllCustomTools.mockImplementation((enabled = true) => ({+ data: enabled ? customTools : [],+ } as ReturnType<typeof useAllCustomTools>))+ mockUseAllWorkflowTools.mockImplementation((enabled = true) => ({+ data: enabled ? workflowTools : [],+ } as ReturnType<typeof useAllWorkflowTools>))mockUseAllMCPTools.mockReturnValue({ data: mcpTools } as ReturnType<typeof useAllMCPTools>)mockUseInvalidateAllBuiltInTools.mockReturnValue(mockInvalidateBuiltInTools)mockUseInvalidateAllCustomTools.mockReturnValue(mockInvalidateCustomTools)@@ -482,6 +498,24 @@ describe('ToolPicker', () => {expect(screen.queryByTestId('edit-custom-tool-modal')).not.toBeInTheDocument()})+ it('should keep custom and workflow tools usable but hide custom create action without tool.manage', () => {+ mockWorkspacePermissionKeys = []++ renderToolPicker({+ isShow: true,+ supportAddCustomTool: true,+ })++ expect(mockUseAllCustomTools).toHaveBeenCalledWith(true)+ expect(mockUseAllWorkflowTools).toHaveBeenCalledWith(true)+ expect(screen.getByText('Custom Provider')).toBeInTheDocument()+ expect(screen.getByText('Built-in Provider')).toBeInTheDocument()+ expect(screen.getByText('MCP Provider')).toBeInTheDocument()+ expect(Array.from(document.querySelectorAll('button')).some((button) => {+ return button.className.includes('bg-components-button-primary-bg')+ })).toBe(false)+ })+it('should invalidate all tool collections after featured install succeeds', async () => {const user = userEvent.setup()diff --git a/web/app/components/workflow/block-selector/featured-tools.tsx b/web/app/components/workflow/block-selector/featured-tools.tsxindex 61f8426028e..12a70f17e7c 100644--- a/web/app/components/workflow/block-selector/featured-tools.tsx+++ b/web/app/components/workflow/block-selector/featured-tools.tsx@@ -4,13 +4,14 @@ import type { ToolWithProvider } from '../types'import type { ToolDefaultValue, ToolValue } from './types'import type { Plugin } from '@/app/components/plugins/types'import type { Locale } from '@/i18n-config'+import { cn } from '@langgenius/dify-ui/cn'import { createPreviewCardHandle, PreviewCard, PreviewCardContent, PreviewCardTrigger } from '@langgenius/dify-ui/preview-card'-import { RiMoreLine } from '@remixicon/react'import { useLocalStorage } from 'foxact/use-local-storage'import { useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { ArrowDownDoubleLine, ArrowDownRoundFill, ArrowUpDoubleLine } from '@/app/components/base/icons/src/vender/solid/arrows'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 { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'import Action from '@/app/components/workflow/block-selector/market-place-plugin/action'@@ -124,7 +125,12 @@ const FeaturedTools = ({onClick={() => setIsCollapsed(prev => !prev)}><span className="system-xs-medium text-text-primary">{t('tabs.featuredTools', { ns: 'workflow' })}</span>- <ArrowDownRoundFill className={`ml-0.5 size-4 text-text-tertiary transition-transform ${isCollapsed ? '-rotate-90' : 'rotate-0'}`} />+ <span className={cn(+ 'i-custom-vender-solid-arrows-arrow-down-round-fill',+ 'ml-0.5 size-4 text-text-tertiary transition-transform',+ isCollapsed ? '-rotate-90' : 'rotate-0',+ )}+ /></button>{!isCollapsed && (@@ -190,13 +196,13 @@ const FeaturedTools = ({}}><div className="flex items-center px-1 text-text-tertiary transition-colors group-hover:text-text-secondary">- <RiMoreLine className="size-4 group-hover:hidden" />+ <span className="i-ri-more-line size-4 group-hover:hidden" />{isExpanded? (- <ArrowUpDoubleLine className="hidden size-4 group-hover:block" />+ <span className="i-custom-vender-solid-arrows-arrow-up-double-line hidden size-4 group-hover:block" />): (- <ArrowDownDoubleLine className="hidden size-4 group-hover:block" />+ <span className="i-custom-vender-solid-arrows-arrow-down-double-line hidden size-4 group-hover:block" />)}</div><div className="system-xs-regular">@@ -235,6 +241,7 @@ function FeaturedToolUninstalledItem({const installCountLabel = t('install', { ns: 'plugin', num: formatNumber(plugin.install_count || 0) })const [actionOpen, setActionOpen] = useState(false)const [isInstallModalOpen, setIsInstallModalOpen] = useState(false)+ const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()useEffect(() => {if (!actionOpen)@@ -266,16 +273,18 @@ function FeaturedToolUninstalledItem({<divclassName={`flex h-full items-center gap-1 system-xs-medium text-components-button-secondary-accent-text [&_.action-btn]:size-6 [&_.action-btn]:min-h-0 [&_.action-btn]:rounded-lg [&_.action-btn]:p-0 ${actionOpen ? '' : 'hidden group-hover:flex'}`}>- <button- type="button"- className="cursor-pointer rounded-md px-1.5 py-0.5 hover:bg-state-base-hover"- onClick={() => {- setActionOpen(false)- setIsInstallModalOpen(true)- }}- >- {t('installAction', { ns: 'plugin' })}- </button>+ {canInstallPlugin && (+ <button+ type="button"+ className="cursor-pointer rounded-md px-1.5 py-0.5 hover:bg-state-base-hover"+ onClick={() => {+ setActionOpen(false)+ setIsInstallModalOpen(true)+ }}+ >+ {t('installAction', { ns: 'plugin' })}+ </button>+ )}<Actionopen={actionOpen}onOpenChange={setActionOpen}@@ -304,18 +313,23 @@ function FeaturedToolUninstalledItem({/>): row}- {isInstallModalOpen && (- <InstallFromMarketplace- uniqueIdentifier={plugin.latest_package_identifier}- manifest={plugin}- onSuccess={async () => {- setIsInstallModalOpen(false)- await onInstallSuccess?.()- }}- onClose={() => {- setIsInstallModalOpen(false)- }}- />+ {isInstallModalOpen && canInstallPlugin && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ currentDifyVersion={currentDifyVersion}+ >+ <InstallFromMarketplace+ uniqueIdentifier={plugin.latest_package_identifier}+ manifest={plugin}+ onSuccess={async () => {+ setIsInstallModalOpen(false)+ await onInstallSuccess?.()+ }}+ onClose={() => {+ setIsInstallModalOpen(false)+ }}+ />+ </PluginInstallPermissionProvider>)}</>)diff --git a/web/app/components/workflow/block-selector/featured-triggers.tsx b/web/app/components/workflow/block-selector/featured-triggers.tsxindex 6f16d033994..917f46074fd 100644--- a/web/app/components/workflow/block-selector/featured-triggers.tsx+++ b/web/app/components/workflow/block-selector/featured-triggers.tsx@@ -4,13 +4,14 @@ import type { TriggerPluginActionPreviewPayload } from './trigger-plugin/action-import type { TriggerDefaultValue, TriggerWithProvider } from './types'import type { Plugin } from '@/app/components/plugins/types'import type { Locale } from '@/i18n-config'+import { cn } from '@langgenius/dify-ui/cn'import { createPreviewCardHandle, PreviewCard, PreviewCardContent, PreviewCardTrigger } from '@langgenius/dify-ui/preview-card'-import { RiMoreLine } from '@remixicon/react'import { useLocalStorage } from 'foxact/use-local-storage'import { useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { ArrowDownDoubleLine, ArrowDownRoundFill, ArrowUpDoubleLine } from '@/app/components/base/icons/src/vender/solid/arrows'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 { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'import Action from '@/app/components/workflow/block-selector/market-place-plugin/action'@@ -123,7 +124,12 @@ const FeaturedTriggers = ({onClick={() => setIsCollapsed(prev => !prev)}><span className="system-xs-medium text-text-primary">{t('tabs.featuredTools', { ns: 'workflow' })}</span>- <ArrowDownRoundFill className={`ml-0.5 size-4 text-text-tertiary transition-transform ${isCollapsed ? '-rotate-90' : 'rotate-0'}`} />+ <span className={cn(+ 'i-custom-vender-solid-arrows-arrow-down-round-fill',+ 'ml-0.5 size-4 text-text-tertiary transition-transform',+ isCollapsed ? '-rotate-90' : 'rotate-0',+ )}+ /></button>{!isCollapsed && (@@ -183,13 +189,13 @@ const FeaturedTriggers = ({}}><div className="flex items-center px-1 text-text-tertiary transition-colors group-hover:text-text-secondary">- <RiMoreLine className="size-4 group-hover:hidden" />+ <span className="i-ri-more-line size-4 group-hover:hidden" />{isExpanded? (- <ArrowUpDoubleLine className="hidden size-4 group-hover:block" />+ <span className="i-custom-vender-solid-arrows-arrow-up-double-line hidden size-4 group-hover:block" />): (- <ArrowDownDoubleLine className="hidden size-4 group-hover:block" />+ <span className="i-custom-vender-solid-arrows-arrow-down-double-line hidden size-4 group-hover:block" />)}</div><div className="system-xs-regular">@@ -233,6 +239,7 @@ function FeaturedTriggerUninstalledItem({const installCountLabel = t('install', { ns: 'plugin', num: formatNumber(plugin.install_count || 0) })const [actionOpen, setActionOpen] = useState(false)const [isInstallModalOpen, setIsInstallModalOpen] = useState(false)+ const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()useEffect(() => {if (!actionOpen)@@ -262,16 +269,18 @@ function FeaturedTriggerUninstalledItem({<divclassName={`flex h-full items-center gap-1 system-xs-medium text-components-button-secondary-accent-text [&_.action-btn]:size-6 [&_.action-btn]:min-h-0 [&_.action-btn]:rounded-lg [&_.action-btn]:p-0 ${actionOpen ? '' : 'hidden group-hover:flex'}`}>- <button- type="button"- className="cursor-pointer rounded-md px-1.5 py-0.5 hover:bg-state-base-hover"- onClick={() => {- setActionOpen(false)- setIsInstallModalOpen(true)- }}- >- {t('installAction', { ns: 'plugin' })}- </button>+ {canInstallPlugin && (+ <button+ type="button"+ className="cursor-pointer rounded-md px-1.5 py-0.5 hover:bg-state-base-hover"+ onClick={() => {+ setActionOpen(false)+ setIsInstallModalOpen(true)+ }}+ >+ {t('installAction', { ns: 'plugin' })}+ </button>+ )}<Actionopen={actionOpen}onOpenChange={setActionOpen}@@ -300,18 +309,23 @@ function FeaturedTriggerUninstalledItem({/>): row}- {isInstallModalOpen && (- <InstallFromMarketplace- uniqueIdentifier={plugin.latest_package_identifier}- manifest={plugin}- onSuccess={async () => {- setIsInstallModalOpen(false)- await onInstallSuccess?.()- }}- onClose={() => {- setIsInstallModalOpen(false)- }}- />+ {isInstallModalOpen && canInstallPlugin && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ currentDifyVersion={currentDifyVersion}+ >+ <InstallFromMarketplace+ uniqueIdentifier={plugin.latest_package_identifier}+ manifest={plugin}+ onSuccess={async () => {+ setIsInstallModalOpen(false)+ await onInstallSuccess?.()+ }}+ onClose={() => {+ setIsInstallModalOpen(false)+ }}+ />+ </PluginInstallPermissionProvider>)}</>)diff --git a/web/app/components/workflow/block-selector/market-place-plugin/__tests__/item-list.spec.tsx b/web/app/components/workflow/block-selector/market-place-plugin/__tests__/item-list.spec.tsxindex be251a54ffc..85640e132f1 100644--- a/web/app/components/workflow/block-selector/market-place-plugin/__tests__/item-list.spec.tsx+++ b/web/app/components/workflow/block-selector/market-place-plugin/__tests__/item-list.spec.tsx@@ -23,6 +23,13 @@ vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () =),}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission', () => ({+ default: () => ({+ canInstallPlugin: true,+ currentDifyVersion: '1.0.0',+ }),+}))+vi.mock('../action', () => ({default: ({ open, onOpenChange }: { open: boolean, onOpenChange: (open: boolean) => void }) => (<button type="button" onClick={() => onOpenChange(!open)}>diff --git a/web/app/components/workflow/block-selector/market-place-plugin/item.tsx b/web/app/components/workflow/block-selector/market-place-plugin/item.tsxindex fc2876e34c5..16316ffc8b5 100644--- a/web/app/components/workflow/block-selector/market-place-plugin/item.tsx+++ b/web/app/components/workflow/block-selector/market-place-plugin/item.tsx@@ -5,17 +5,16 @@ import { cn } from '@langgenius/dify-ui/cn'import { useBoolean } from 'ahooks'import * as React from 'react'import { useTranslation } from 'react-i18next'+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 { useLocale } from '@/context/i18n'import { formatNumber } from '@/utils/format'import Action from './action'-enum ActionType {- install = 'install',- download = 'download',- // viewDetail = 'viewDetail', // wait for marketplace api-}+type ActionType = 'install' | 'download'+type Props = Readonly<{payload: PluginonAction: (type: ActionType) => void@@ -33,6 +32,7 @@ const Item: FC<Props> = ({setTrue: showInstallModal,setFalse: hideInstallModal,}] = useBoolean(false)+ const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()return (<div className="group/plugin flex rounded-lg py-1 pr-1 pl-3 select-none hover:bg-state-base-hover">@@ -52,13 +52,15 @@ const Item: FC<Props> = ({</div>{/* Action */}<div className={cn(!open ? 'hidden' : 'flex', 'h-4 items-center space-x-1 system-xs-medium text-components-button-secondary-accent-text group-hover/plugin:flex')}>- <button- type="button"- className="cursor-pointer rounded-md border-0 bg-transparent px-1.5 py-0.5 hover:bg-state-base-hover"- onClick={showInstallModal}- >- {t('installAction', { ns: 'plugin' })}- </button>+ {canInstallPlugin && (+ <button+ type="button"+ className="cursor-pointer rounded-md border-0 bg-transparent px-1.5 py-0.5 hover:bg-state-base-hover"+ onClick={showInstallModal}+ >+ {t('installAction', { ns: 'plugin' })}+ </button>+ )}<Actionopen={open}onOpenChange={setOpen}@@ -67,13 +69,18 @@ const Item: FC<Props> = ({version={payload.latest_version}/></div>- {isShowInstallModal && (- <InstallFromMarketplace- uniqueIdentifier={payload.latest_package_identifier}- manifest={payload}- onSuccess={hideInstallModal}- onClose={hideInstallModal}- />+ {isShowInstallModal && canInstallPlugin && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ currentDifyVersion={currentDifyVersion}+ >+ <InstallFromMarketplace+ uniqueIdentifier={payload.latest_package_identifier}+ manifest={payload}+ onSuccess={hideInstallModal}+ onClose={hideInstallModal}+ />+ </PluginInstallPermissionProvider>)}</div></div>diff --git a/web/app/components/workflow/block-selector/rag-tool-recommendations/__tests__/list.spec.tsx b/web/app/components/workflow/block-selector/rag-tool-recommendations/__tests__/list.spec.tsxindex a7ff5ad084f..a9ffafca722 100644--- a/web/app/components/workflow/block-selector/rag-tool-recommendations/__tests__/list.spec.tsx+++ b/web/app/components/workflow/block-selector/rag-tool-recommendations/__tests__/list.spec.tsx@@ -25,6 +25,13 @@ vi.mock('@/app/components/workflow/nodes/_base/components/mcp-tool-availability'}),}))+vi.mock('@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission', () => ({+ default: () => ({+ canInstallPlugin: true,+ currentDifyVersion: '1.0.0',+ }),+}))+vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () => ({default: ({uniqueIdentifier,diff --git a/web/app/components/workflow/block-selector/rag-tool-recommendations/uninstalled-item.tsx b/web/app/components/workflow/block-selector/rag-tool-recommendations/uninstalled-item.tsxindex 768edc5ace5..0595fd292e8 100644--- a/web/app/components/workflow/block-selector/rag-tool-recommendations/uninstalled-item.tsx+++ b/web/app/components/workflow/block-selector/rag-tool-recommendations/uninstalled-item.tsx@@ -3,6 +3,8 @@ import type { Plugin } from '@/app/components/plugins/types'import { useBoolean } from 'ahooks'import * as React from 'react'import { useTranslation } from 'react-i18next'+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 { useLocale } from '@/context/i18n'import BlockIcon from '../../block-icon'@@ -24,6 +26,7 @@ const UninstalledItem = ({setTrue: showInstallModal,setFalse: hideInstallModal,}] = useBoolean(false)+ const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()return (<div className="flex h-8 items-center rounded-lg pr-2 pl-3 hover:bg-state-base-hover">@@ -41,19 +44,26 @@ const UninstalledItem = ({{payload.org}</span></div>- <div- className="cursor-pointer pl-1.5 system-xs-medium text-components-button-secondary-accent-text"- onClick={showInstallModal}- >- {t('installAction', { ns: 'plugin' })}- </div>- {isShowInstallModal && (- <InstallFromMarketplace- uniqueIdentifier={payload.latest_package_identifier}- manifest={payload}- onSuccess={hideInstallModal}- onClose={hideInstallModal}- />+ {canInstallPlugin && (+ <div+ className="cursor-pointer pl-1.5 system-xs-medium text-components-button-secondary-accent-text"+ onClick={showInstallModal}+ >+ {t('installAction', { ns: 'plugin' })}+ </div>+ )}+ {isShowInstallModal && canInstallPlugin && (+ <PluginInstallPermissionProvider+ canInstallPlugin={canInstallPlugin}+ currentDifyVersion={currentDifyVersion}+ >+ <InstallFromMarketplace+ uniqueIdentifier={payload.latest_package_identifier}+ manifest={payload}+ onSuccess={hideInstallModal}+ onClose={hideInstallModal}+ />+ </PluginInstallPermissionProvider>)}</div></div>diff --git a/web/app/components/workflow/block-selector/tool-picker.tsx b/web/app/components/workflow/block-selector/tool-picker.tsxindex 948b3cd65d9..eb7e60623d1 100644--- a/web/app/components/workflow/block-selector/tool-picker.tsx+++ b/web/app/components/workflow/block-selector/tool-picker.tsx@@ -18,6 +18,7 @@ import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import SearchBox from '@/app/components/plugins/marketplace/search-box'import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'+import { useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import AllTools from '@/app/components/workflow/block-selector/all-tools'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import {@@ -66,15 +67,18 @@ export function ToolPickerContent({const { t } = useTranslation()const [searchText, setSearchText] = useState('')const [tags, setTags] = useState<string[]>([])+ const canManageTools = useCanManageTools()const { data: enable_marketplace } = useSuspenseQuery({...systemFeaturesQueryOptions(),select: s => s.enable_marketplace,})const { data: buildInTools } = useAllBuiltInTools()- const { data: customTools } = useAllCustomTools()+ const shouldFetchCustomTools = scope !== 'plugins' && scope !== 'workflow'+ const { data: customTools } = useAllCustomTools(shouldFetchCustomTools)const invalidateCustomTools = useInvalidateAllCustomTools()- const { data: workflowTools } = useAllWorkflowTools()+ const shouldFetchWorkflowTools = scope !== 'plugins' && scope !== 'custom'+ const { data: workflowTools } = useAllWorkflowTools(shouldFetchWorkflowTools)const { data: mcpTools } = useAllMCPTools()const invalidateBuiltInTools = useInvalidateAllBuiltInTools()const invalidateWorkflowTools = useInvalidateAllWorkflowTools()@@ -130,13 +134,16 @@ export function ToolPickerContent({}] = useBoolean(false)const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {+ if (!canManageTools)+ return+await createCustomCollection(data)toast.success(t('api.actionSuccess', { ns: 'common' }))hideEditCustomCollectionModal()handleAddedCustomTool()}- if (isShowEditCollectionToolModal) {+ if (isShowEditCollectionToolModal && canManageTools) {return (<EditCustomToolModaldialogClassName="bg-background-overlay"@@ -156,7 +163,7 @@ export function ToolPickerContent({tags={tags}onTagsChange={setTags}placeholder={t('searchTools', { ns: 'plugin' })!}- supportAddCustomTool={supportAddCustomTool}+ supportAddCustomTool={supportAddCustomTool && canManageTools}onAddedCustomTool={handleAddedCustomTool}onShowAddCustomCollectionModal={showEditCustomCollectionModal}// The picker replaces the focused menu item inside an already-open popover.diff --git a/web/app/components/workflow/header/__tests__/run-and-history.spec.tsx b/web/app/components/workflow/header/__tests__/run-and-history.spec.tsxnew file mode 100644index 00000000000..98a426ef1dc--- /dev/null+++ b/web/app/components/workflow/header/__tests__/run-and-history.spec.tsx@@ -0,0 +1,77 @@+import { render, screen } from '@testing-library/react'+import RunAndHistory from '../run-and-history'++const mockState = vi.hoisted(() => ({+ canRun: true,+ nodesReadOnly: false,+}))+const mockRunMode = vi.hoisted(() => vi.fn())+const mockHandleWorkflowStartRunInChatflow = vi.hoisted(() => vi.fn())++vi.mock('../../hooks', () => ({+ useNodesReadOnly: () => ({ nodesReadOnly: mockState.nodesReadOnly }),+ useWorkflowStartRun: () => ({+ handleWorkflowStartRunInChatflow: mockHandleWorkflowStartRunInChatflow,+ }),+}))++vi.mock('../../hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canRun: boolean } }) => T): T =>+ selector({+ accessControl: {+ canRun: mockState.canRun,+ },+ }),+}))++vi.mock('../run-mode', () => ({+ default: ({ text, disabled }: { text?: string, disabled?: boolean }) => {+ mockRunMode({ text, disabled })++ return (+ <button type="button" disabled={disabled}>+ {text ?? 'workflow.common.run'}+ </button>+ )+ },+}))++vi.mock('../view-history', () => ({+ default: () => <button type="button">History</button>,+}))++vi.mock('../checklist', () => ({+ default: ({ disabled }: { disabled: boolean }) => (+ <button type="button" disabled={disabled}>+ Checklist+ </button>+ ),+}))++describe('RunAndHistory', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockState.canRun = true+ mockState.nodesReadOnly = false+ })++ it('should keep the test run button visible and disabled when workflow run permission is denied', () => {+ mockState.canRun = false++ render(<RunAndHistory showRunButton runButtonText="Test Run" />)++ expect(screen.getByRole('button', { name: 'Test Run' })).toBeDisabled()+ expect(mockRunMode).toHaveBeenCalledWith({+ text: 'Test Run',+ disabled: true,+ })+ })++ it('should keep the preview button visible and disabled when workflow run permission is denied', () => {+ mockState.canRun = false++ render(<RunAndHistory showPreviewButton />)++ expect(screen.getByRole('button', { name: 'workflow.common.debugAndPreview' })).toBeDisabled()+ })+})diff --git a/web/app/components/workflow/header/__tests__/run-mode.spec.tsx b/web/app/components/workflow/header/__tests__/run-mode.spec.tsxindex 7e2bc8d0b76..b92f8d12a45 100644--- a/web/app/components/workflow/header/__tests__/run-mode.spec.tsx+++ b/web/app/components/workflow/header/__tests__/run-mode.spec.tsx@@ -22,6 +22,7 @@ const hotkeyRegistrations = vi.hoisted(() => new Map<string, {let mockWarningNodes: Array<{ id: string }> = []let mockWorkflowRunningData: { result: { status: WorkflowRunningStatus }, task_id: string } | undefinedlet mockIsListening = false+let mockCanRun = truelet mockDynamicOptions = [{ type: TriggerType.UserInput, nodeId: 'start-node' },]@@ -47,6 +48,15 @@ vi.mock('@/app/components/workflow/store/workflow', () => ({selector({ workflowRunningData: mockWorkflowRunningData, isListening: mockIsListening }),}))+vi.mock('@/app/components/workflow/hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canRun: boolean } }) => T): T =>+ selector({+ accessControl: {+ canRun: mockCanRun,+ },+ }),+}))+vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()return {@@ -82,10 +92,6 @@ vi.mock('@/context/event-emitter', () => ({}),}))-vi.mock('@/app/components/base/icons/src/vender/line/mediaAndDevices', () => ({- StopCircle: () => <span data-testid="stop-circle" />,-}))-vi.mock('../test-run-menu', async (importOriginal) => {const actual = await importOriginal<typeof import('../test-run-menu')>()const TestRunMenuMock = ({ children, options, onSelect, ref }: { children: ReactNode, options: Array<{ type: TriggerType, nodeId?: string, relatedNodeIds?: string[] }>, onSelect: (option: { type: TriggerType, nodeId?: string, relatedNodeIds?: string[] }) => void, ref?: React.Ref<TestRunMenuRef> }) => {@@ -114,6 +120,7 @@ describe('RunMode', () => {mockWarningNodes = []mockWorkflowRunningData = undefinedmockIsListening = false+ mockCanRun = truehotkeyRegistrations.clear()mockDynamicOptions = [{ type: TriggerType.UserInput, nodeId: 'start-node' },@@ -152,7 +159,7 @@ describe('RunMode', () => {render(<RunMode />)expect(screen.getByText(/running/i))!.toBeInTheDocument()- fireEvent.click(screen.getByTestId('stop-circle').closest('button') as HTMLButtonElement)+ fireEvent.click(screen.getByRole('button', { name: 'workflow.debug.variableInspect.trigger.stop' }))expect(mockHandleStopRun).toHaveBeenCalledWith('task-1')})@@ -172,4 +179,19 @@ describe('RunMode', () => {expect.objectContaining({ ignoreInputs: true }),)})++ it('should keep the run trigger visible and disabled when workflow run permission is denied', () => {+ mockCanRun = false+ mockWorkflowRunningData = {+ result: { status: WorkflowRunningStatus.Running },+ task_id: 'task-1',+ }++ render(<RunMode />)++ expect(screen.getByRole('button', { name: /run/i })).toBeDisabled()+ expect(screen.queryByTestId('trigger-option')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'workflow.debug.variableInspect.trigger.stop' })).not.toBeInTheDocument()+ expect(mockHandleWorkflowStartRunInWorkflow).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/workflow/header/header-in-normal.tsx b/web/app/components/workflow/header/header-in-normal.tsxindex ea7c29affae..30fc8d24422 100644--- a/web/app/components/workflow/header/header-in-normal.tsx+++ b/web/app/components/workflow/header/header-in-normal.tsx@@ -11,6 +11,7 @@ import {useNodesReadOnly,useWorkflowRun,} from '../hooks'+import { useHooksStore } from '../hooks-store'import {useStore,useWorkflowStore,@@ -43,6 +44,7 @@ const HeaderInNormal = ({}: HeaderInNormalProps) => {const workflowStore = useWorkflowStore()const { nodesReadOnly } = useNodesReadOnly()+ const canReleaseAndVersion = useHooksStore(s => s.accessControl.canReleaseAndVersion)const { handleNodeSelect } = useNodesInteractions()const setShowWorkflowVersionHistoryPanel = useStore(s => s.setShowWorkflowVersionHistoryPanel)const setShowEnvPanel = useStore(s => s.setShowEnvPanel)@@ -94,7 +96,7 @@ const HeaderInNormal = ({</div>)}{components?.middle}- <VersionHistoryButton onClick={onStartRestoring} />+ {canReleaseAndVersion && <VersionHistoryButton onClick={onStartRestoring} />}</div></div>)diff --git a/web/app/components/workflow/header/run-and-history.tsx b/web/app/components/workflow/header/run-and-history.tsxindex c2e9cfceb96..2b221f1ce07 100644--- a/web/app/components/workflow/header/run-and-history.tsx+++ b/web/app/components/workflow/header/run-and-history.tsx@@ -1,33 +1,44 @@import type { ViewHistoryProps } from './view-history'import { cn } from '@langgenius/dify-ui/cn'-import {- RiPlayLargeLine,-} from '@remixicon/react'import { memo } from 'react'import { useTranslation } from 'react-i18next'import {useNodesReadOnly,useWorkflowStartRun,} from '../hooks'+import { useHooksStore } from '../hooks-store'import Checklist from './checklist'import RunMode from './run-mode'import ViewHistory from './view-history'-const PreviewMode = memo(() => {+const PreviewMode = memo(({+ disabled = false,+}: {+ disabled?: boolean+}) => {const { t } = useTranslation()const { handleWorkflowStartRunInChatflow } = useWorkflowStartRun()+ const canRun = useHooksStore(s => s.accessControl.canRun)+ const isDisabled = disabled || !canRunreturn (- <div+ <button+ type="button"+ disabled={isDisabled}className={cn('flex h-7 items-center rounded-md px-2.5 text-[13px] font-medium text-components-button-secondary-accent-text',- 'cursor-pointer hover:bg-state-accent-hover',+ isDisabled+ ? 'cursor-not-allowed opacity-50'+ : 'cursor-pointer hover:bg-state-accent-hover',)}- onClick={() => handleWorkflowStartRunInChatflow()}+ onClick={() => {+ if (!isDisabled)+ handleWorkflowStartRunInChatflow()+ }}>- <RiPlayLargeLine className="mr-1 size-4" />+ <span aria-hidden className="mr-1 i-ri-play-large-line size-4" />{t('common.debugAndPreview', { ns: 'workflow' })}- </div>+ </button>)})@@ -41,6 +52,7 @@ export type RunAndHistoryProps = {RunMode?: React.ComponentType<{text?: string+ disabled?: boolean}>}@@ -53,17 +65,18 @@ const RunAndHistory = ({components,}: RunAndHistoryProps) => {const { nodesReadOnly } = useNodesReadOnly()+ const canRun = useHooksStore(s => s.accessControl.canRun)const { RunMode: CustomRunMode } = components || {}return (<div className="flex h-8 items-center rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-0.5 shadow-xs">{showRunButton && (- CustomRunMode ? <CustomRunMode text={runButtonText} /> : <RunMode text={runButtonText} />+ CustomRunMode ? <CustomRunMode text={runButtonText} disabled={!canRun} /> : <RunMode text={runButtonText} disabled={!canRun} />)}{- showPreviewButton && <PreviewMode />+ showPreviewButton && <PreviewMode disabled={!canRun} />}<div className="mx-0.5 h-3.5 w-px bg-divider-regular"></div><ViewHistory {...viewHistoryProps} />diff --git a/web/app/components/workflow/header/run-mode.tsx b/web/app/components/workflow/header/run-mode.tsxindex 7b80025a48d..365481bea5f 100644--- a/web/app/components/workflow/header/run-mode.tsx+++ b/web/app/components/workflow/header/run-mode.tsx@@ -7,8 +7,8 @@ import * as React from 'react'import { useCallback, useRef } from 'react'import { useTranslation } from 'react-i18next'import { trackEvent } from '@/app/components/base/amplitude'-import { StopCircle } from '@/app/components/base/icons/src/vender/line/mediaAndDevices'import { useWorkflowRun, useWorkflowRunValidation, useWorkflowStartRun } from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { ShortcutKbd } from '@/app/components/workflow/shortcuts/shortcut-kbd'import { useStore } from '@/app/components/workflow/store/workflow'import { WorkflowRunningStatus } from '@/app/components/workflow/types'@@ -20,6 +20,7 @@ import TestRunMenu, { TriggerType } from './test-run-menu'type RunModeProps = {text?: string+ disabled?: boolean}const isWorkflowStopEvent = (value: EventEmitterValue) =>@@ -27,6 +28,7 @@ const isWorkflowStopEvent = (value: EventEmitterValue) =>const RunMode = ({text,+ disabled = false,}: RunModeProps) => {const { t } = useTranslation()const {@@ -40,6 +42,8 @@ const RunMode = ({const { warningNodes } = useWorkflowRunValidation()const workflowRunningData = useStore(s => s.workflowRunningData)const isListening = useStore(s => s.isListening)+ const canRun = useHooksStore(s => s.accessControl.canRun)+ const isRunDisabled = disabled || !canRunconst status = workflowRunningData?.result.statusconst isRunning = status === WorkflowRunningStatus.Running || isListening@@ -48,8 +52,11 @@ const RunMode = ({const testRunMenuRef = useRef<TestRunMenuRef>(null)const handleToggleTestRunMenu = useCallback(() => {+ if (isRunDisabled)+ return+testRunMenuRef.current?.toggle()- }, [])+ }, [isRunDisabled])useHotkey(TEST_RUN_MENU_HOTKEY, handleToggleTestRunMenu, {ignoreInputs: true,@@ -60,6 +67,9 @@ const RunMode = ({}, [handleStopRun, workflowRunningData?.task_id])const handleTriggerSelect = useCallback((option: TriggerOption) => {+ if (isRunDisabled)+ return+// Validate checklist before running any workflowlet isValid: boolean = truewarningNodes.forEach((node) => {@@ -95,7 +105,7 @@ const RunMode = ({handleWorkflowRunAllTriggersInWorkflow(targetNodeIds)trackEvent('app_start_action_time', { action_type: 'all' })}- }, [warningNodes, t, handleWorkflowStartRunInWorkflow, handleWorkflowTriggerScheduleRunInWorkflow, handleWorkflowTriggerWebhookRunInWorkflow, handleWorkflowTriggerPluginRunInWorkflow, handleWorkflowRunAllTriggersInWorkflow])+ }, [isRunDisabled, warningNodes, t, handleWorkflowStartRunInWorkflow, handleWorkflowTriggerScheduleRunInWorkflow, handleWorkflowTriggerWebhookRunInWorkflow, handleWorkflowTriggerPluginRunInWorkflow, handleWorkflowRunAllTriggersInWorkflow])const { eventEmitter } = useEventEmitterContextContext()eventEmitter?.useSubscription((v: EventEmitterValue) => {@@ -106,49 +116,67 @@ const RunMode = ({return (<div className="flex items-center gap-x-px">{- isRunning+ isRunDisabled? (<buttontype="button"className={cn(- 'flex h-7 cursor-not-allowed items-center gap-x-1 rounded-l-md bg-state-accent-hover px-1.5 system-xs-medium text-text-accent',+ 'flex h-7 cursor-not-allowed items-center gap-x-1 rounded-md px-1.5 system-xs-medium text-text-accent opacity-50',)}- disabled={true}+ disabled+ style={{ userSelect: 'none' }}>- <span className="mr-1 i-ri-loader-2-line size-4 animate-spin" />- {isListening ? t('common.listening', { ns: 'workflow' }) : t('common.running', { ns: 'workflow' })}+ <span aria-hidden className="mr-1 i-ri-play-large-line size-4" />+ {text ?? t('common.run', { ns: 'workflow' })}+ <ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} textColor="secondary" /></button>): (- <TestRunMenu- ref={testRunMenuRef}- options={dynamicOptions}- onSelect={handleTriggerSelect}- >- <button- type="button"- className={cn(- 'flex h-7 cursor-pointer items-center gap-x-1 rounded-md px-1.5 system-xs-medium text-text-accent hover:bg-state-accent-hover',- )}- style={{ userSelect: 'none' }}- >- <span aria-hidden className="mr-1 i-ri-play-large-line size-4" />- {text ?? t('common.run', { ns: 'workflow' })}- <ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} textColor="secondary" />- </button>- </TestRunMenu>+ isRunning+ ? (+ <button+ type="button"+ className={cn(+ 'flex h-7 cursor-not-allowed items-center gap-x-1 rounded-l-md bg-state-accent-hover px-1.5 system-xs-medium text-text-accent',+ )}+ disabled={true}+ >+ <span className="mr-1 i-ri-loader-2-line size-4 animate-spin" />+ {isListening ? t('common.listening', { ns: 'workflow' }) : t('common.running', { ns: 'workflow' })}+ </button>+ )+ : (+ <TestRunMenu+ ref={testRunMenuRef}+ options={dynamicOptions}+ onSelect={handleTriggerSelect}+ >+ <button+ type="button"+ className={cn(+ 'flex h-7 cursor-pointer items-center gap-x-1 rounded-md px-1.5 system-xs-medium text-text-accent hover:bg-state-accent-hover',+ )}+ style={{ userSelect: 'none' }}+ >+ <span aria-hidden className="mr-1 i-ri-play-large-line size-4" />+ {text ?? t('common.run', { ns: 'workflow' })}+ <ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} textColor="secondary" />+ </button>+ </TestRunMenu>+ ))}{- isRunning && (+ isRunning && !isRunDisabled && (<buttontype="button"+ aria-label={t('debug.variableInspect.trigger.stop', { ns: 'workflow' })}className={cn('flex size-7 items-center justify-center rounded-r-md bg-state-accent-active',)}onClick={handleStop}>- <StopCircle className="size-4 text-text-accent" />+ <span aria-hidden className="i-ri-stop-circle-line size-4 text-text-accent" /></button>)}diff --git a/web/app/components/workflow/hooks-store/provider.tsx b/web/app/components/workflow/hooks-store/provider.tsxindex 365e97eb14e..48288ebd56a 100644--- a/web/app/components/workflow/hooks-store/provider.tsx+++ b/web/app/components/workflow/hooks-store/provider.tsx@@ -18,12 +18,18 @@ export const HooksStoreContextProvider = ({ children, ...restProps }: HooksStoreconst storeRef = useRef<HooksStore | undefined>(undefined)const d3Selection = useStore(s => s.d3Selection)const d3Zoom = useStore(s => s.d3Zoom)+ const { accessControl } = restPropsuseEffect(() => {if (storeRef.current && d3Selection && d3Zoom)storeRef.current.getState().refreshAll(restProps)}, [d3Selection, d3Zoom])+ useEffect(() => {+ if (storeRef.current && accessControl)+ storeRef.current.getState().refreshAll({ accessControl })+ }, [accessControl])+if (!storeRef.current)storeRef.current = createHooksStore(restProps)diff --git a/web/app/components/workflow/hooks-store/store.ts b/web/app/components/workflow/hooks-store/store.tsindex c01e42dc4a1..d487ed27f0f 100644--- a/web/app/components/workflow/hooks-store/store.ts+++ b/web/app/components/workflow/hooks-store/store.ts@@ -27,6 +27,23 @@ export type SyncDraftCallback = {onError?: () => voidonSettled?: () => void}++export type WorkflowAccessControl = {+ canEdit: boolean+ canComment: boolean+ canRun: boolean+ canImportExportDSL: boolean+ canReleaseAndVersion: boolean+}++export const fullWorkflowAccessControl: WorkflowAccessControl = {+ canEdit: true,+ canComment: true,+ canRun: true,+ canImportExportDSL: true,+ canReleaseAndVersion: true,+}+type CommonHooksFnMap = {doSyncWorkflowDraft: (notRefreshWhenSyncError?: boolean,@@ -65,6 +82,7 @@ type CommonHooksFnMap = {invalidateSysVarValues: () => voidresetConversationVar: (varId: string) => Promise<void>invalidateConversationVarValues: () => void+ accessControl: WorkflowAccessControlconfigsMap?: {flowId: stringflowType: FlowType@@ -117,6 +135,7 @@ export const createHooksStore = ({resetConversationVar = async () => noop(),invalidateConversationVarValues = noop,configsMap,+ accessControl = fullWorkflowAccessControl,}: Partial<Shape>) => {return createStore<Shape>(set => ({refreshAll: props => set(state => ({ ...state, ...props })),@@ -155,6 +174,7 @@ export const createHooksStore = ({resetConversationVar,invalidateConversationVarValues,configsMap,+ accessControl,}))}diff --git a/web/app/components/workflow/hooks/__tests__/use-node-plugin-installation.spec.ts b/web/app/components/workflow/hooks/__tests__/use-node-plugin-installation.spec.tsindex 4577055098c..57652c54cce 100644--- a/web/app/components/workflow/hooks/__tests__/use-node-plugin-installation.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-node-plugin-installation.spec.ts@@ -13,6 +13,13 @@ const mockInvalidToolsByType = vi.fn()const mockTriggerPlugins = vi.fn()const mockInvalidateTriggers = vi.fn()const mockInvalidDataSourceList = vi.fn()+let mockWorkspacePermissionKeys = ['plugin.install']++vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ workspacePermissionKeys: mockWorkspacePermissionKeys,+ }),+}))vi.mock('@/service/use-tools', () => ({useAllBuiltInTools: (enabled: boolean) => mockBuiltInTools(enabled),@@ -86,6 +93,7 @@ const matchedDataSource = {describe('useNodePluginInstallation', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys = ['plugin.install']mockBuiltInTools.mockReturnValue({ data: undefined, isLoading: false })mockCustomTools.mockReturnValue({ data: undefined, isLoading: false })mockWorkflowTools.mockReturnValue({ data: undefined, isLoading: false })@@ -169,6 +177,17 @@ describe('useNodePluginInstallation', () => {expect(result.current.shouldDim).toBe(false)})+ it('should not allow installing missing tool plugins without plugin install permission', () => {+ mockWorkspacePermissionKeys = []+ mockBuiltInTools.mockReturnValue({ data: [], isLoading: false })++ const { result } = renderWorkflowHook(() => useNodePluginInstallation(makeToolNode()))++ expect(result.current.isMissing).toBe(true)+ expect(result.current.uniqueIdentifier).toBe('[email protected]')+ expect(result.current.canInstall).toBe(false)+ })+it('should flag missing trigger plugins and invalidate trigger data after installation', () => {mockTriggerPlugins.mockReturnValue({ data: [matchedTriggerProvider], isLoading: false })diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow-panel-interactions.spec.tsx b/web/app/components/workflow/hooks/__tests__/use-workflow-panel-interactions.spec.tsxindex 9ff61f70f92..30ad040f050 100644--- a/web/app/components/workflow/hooks/__tests__/use-workflow-panel-interactions.spec.tsx+++ b/web/app/components/workflow/hooks/__tests__/use-workflow-panel-interactions.spec.tsx@@ -1,6 +1,6 @@import { act } from '@testing-library/react'import { renderWorkflowHook } from '../../__tests__/workflow-test-env'-import { ControlMode } from '../../types'+import { ControlMode, WorkflowRunningStatus } from '../../types'import {useWorkflowInteractions,useWorkflowMoveMode,@@ -107,4 +107,64 @@ describe('useWorkflowMoveMode', () => {expect(store.getState().controlMode).toBe(ControlMode.Pointer)expect(mockHandleSelectionCancel).not.toHaveBeenCalled()})++ it('switches to comment mode when nodes are read-only', () => {+ runtimeState.nodesReadOnly = true+ const { result, store } = renderWorkflowHook(() => useWorkflowMoveMode(), {+ initialStoreState: {+ controlMode: ControlMode.Pointer,+ },+ })++ act(() => {+ result.current.handleModeComment()+ })++ expect(store.getState().controlMode).toBe(ControlMode.Comment)+ expect(mockHandleSelectionCancel).toHaveBeenCalledTimes(1)+ expect(result.current.canUseCommentMode).toBe(true)+ })++ it('does not switch to comment mode while workflow operation is blocked', () => {+ const { result, store } = renderWorkflowHook(() => useWorkflowMoveMode(), {+ initialStoreState: {+ controlMode: ControlMode.Pointer,+ workflowRunningData: {+ result: { status: WorkflowRunningStatus.Running },+ } as never,+ },+ })++ act(() => {+ result.current.handleModeComment()+ })++ expect(result.current.canUseCommentMode).toBe(false)+ expect(store.getState().controlMode).toBe(ControlMode.Pointer)+ expect(mockHandleSelectionCancel).not.toHaveBeenCalled()+ })++ it('does not switch to comment mode when commenting is denied', () => {+ const { result, store } = renderWorkflowHook(() => useWorkflowMoveMode(), {+ initialStoreState: {+ controlMode: ControlMode.Pointer,+ },+ hooksStoreProps: {+ accessControl: {+ canEdit: true,+ canComment: false,+ canRun: true,+ canImportExportDSL: true,+ canReleaseAndVersion: true,+ },+ },+ })++ act(() => {+ result.current.handleModeComment()+ })++ expect(store.getState().controlMode).toBe(ControlMode.Pointer)+ expect(mockHandleSelectionCancel).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow.spec.tsindex d9ed2437126..99c1a0d57b3 100644--- a/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts@@ -9,6 +9,7 @@ import {useIsNodeInIteration,useIsNodeInLoop,useNodesReadOnly,+ useNodesReadOnlyByCanEdit,useWorkflow,useWorkflowReadOnly,} from '../use-workflow'@@ -125,8 +126,41 @@ describe('useWorkflowReadOnly', () => {// ---------------------------------------------------------------------------describe('useNodesReadOnly', () => {+ it('should use the default HooksStoreContext from the workflow test helper', () => {+ const { result } = renderWorkflowHook(() => useNodesReadOnly())+ expect(result.current.nodesReadOnly).toBe(false)+ expect(result.current.getNodesReadOnly()).toBe(false)+ })++ it('should return true when explicit edit permission is denied before HooksStoreContext is available', () => {+ const { result } = renderWorkflowHook(() => useNodesReadOnlyByCanEdit(false))+ expect(result.current.nodesReadOnly).toBe(true)+ expect(result.current.getNodesReadOnly()).toBe(true)+ })++ it('should return false when edit permission is allowed by HooksStoreContext', () => {+ const { result } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {},+ })+ expect(result.current.nodesReadOnly).toBe(false)+ })++ it('should expose getNodesReadOnly that reads from store state', () => {+ const { result, store } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {},+ })++ expect(result.current.getNodesReadOnly()).toBe(false)++ act(() => {+ store.setState({ isRestoring: true })+ })+ expect(result.current.getNodesReadOnly()).toBe(true)+ })+it('should return true when status is Running', () => {const { result } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {},initialStoreState: {workflowRunningData: baseRunningData(),},@@ -136,6 +170,7 @@ describe('useNodesReadOnly', () => {it('should return true when status is Paused', () => {const { result } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {},initialStoreState: {workflowRunningData: baseRunningData({ result: { status: WorkflowRunningStatus.Paused } }),},@@ -145,6 +180,7 @@ describe('useNodesReadOnly', () => {it('should return true when historyWorkflowData is present', () => {const { result } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {},initialStoreState: {historyWorkflowData: { id: 'run-1', status: 'succeeded' },},@@ -154,6 +190,7 @@ describe('useNodesReadOnly', () => {it('should return true when isRestoring is true', () => {const { result } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {},initialStoreState: { isRestoring: true },})expect(result.current.nodesReadOnly).toBe(true)@@ -170,18 +207,25 @@ describe('useNodesReadOnly', () => {})it('should return false when none of the conditions are met', () => {- const { result } = renderWorkflowHook(() => useNodesReadOnly())+ const { result } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {},+ })expect(result.current.nodesReadOnly).toBe(false)})- it('should expose getNodesReadOnly that reads from store state', () => {- const { result, store } = renderWorkflowHook(() => useNodesReadOnly())-- expect(result.current.getNodesReadOnly()).toBe(false)-- act(() => {- store.setState({ isRestoring: true })+ it('should return true when edit permission is denied by HooksStoreContext', () => {+ const { result } = renderWorkflowHook(() => useNodesReadOnly(), {+ hooksStoreProps: {+ accessControl: {+ canEdit: false,+ canComment: true,+ canRun: true,+ canImportExportDSL: true,+ canReleaseAndVersion: true,+ },+ },})+ expect(result.current.nodesReadOnly).toBe(true)expect(result.current.getNodesReadOnly()).toBe(true)})})diff --git a/web/app/components/workflow/hooks/use-node-plugin-installation.ts b/web/app/components/workflow/hooks/use-node-plugin-installation.tsindex 55f8982efe3..1ac2e496b30 100644--- a/web/app/components/workflow/hooks/use-node-plugin-installation.ts+++ b/web/app/components/workflow/hooks/use-node-plugin-installation.ts@@ -3,6 +3,7 @@ import type { ToolNodeType } from '../nodes/tool/types'import type { PluginTriggerNodeType } from '../nodes/trigger-plugin/types'import type { CommonNodeType } from '../types'import { useCallback, useMemo } from 'react'+import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'import { CollectionType } from '@/app/components/tools/types'import { useInvalidDataSourceList } from '@/service/use-pipeline'import {@@ -42,7 +43,7 @@ const NOOP_INSTALLATION: InstallationState = {shouldDim: false,}-const useToolInstallation = (data: ToolNodeType, enabled: boolean): InstallationState => {+const useToolInstallation = (data: ToolNodeType, enabled: boolean, canInstallPlugin: boolean): InstallationState => {const isBuiltIn = enabled && data.provider_type === CollectionType.builtInconst isCustom = enabled && data.provider_type === CollectionType.customconst isWorkflow = enabled && data.provider_type === CollectionType.workflow@@ -108,7 +109,7 @@ const useToolInstallation = (data: ToolNodeType, enabled: boolean): Installation}, [collection, plugin_id, provider_id, provider_name])const uniqueIdentifier = data.plugin_unique_identifier || data.plugin_id || data.provider_id- const canInstall = Boolean(data.plugin_unique_identifier)+ const canInstall = Boolean(data.plugin_unique_identifier) && canInstallPluginconst onInstallSuccess = useCallback(() => {if (invalidateTools)@@ -127,7 +128,7 @@ const useToolInstallation = (data: ToolNodeType, enabled: boolean): Installation}}-const useTriggerInstallation = (data: PluginTriggerNodeType, enabled: boolean): InstallationState => {+const useTriggerInstallation = (data: PluginTriggerNodeType, enabled: boolean, canInstallPlugin: boolean): InstallationState => {const triggerPluginsQuery = useAllTriggerPlugins(enabled)const invalidateTriggers = useInvalidateAllTriggerPlugins()@@ -143,7 +144,7 @@ const useTriggerInstallation = (data: PluginTriggerNodeType, enabled: boolean):}, [plugin_id, provider_id, provider_name, triggerProviders])const uniqueIdentifier = data.plugin_unique_identifier || data.plugin_id || data.provider_id- const canInstall = Boolean(data.plugin_unique_identifier)+ const canInstall = Boolean(data.plugin_unique_identifier) && canInstallPluginconst onInstallSuccess = useCallback(() => {invalidateTriggers()@@ -161,7 +162,7 @@ const useTriggerInstallation = (data: PluginTriggerNodeType, enabled: boolean):}}-const useDataSourceInstallation = (data: DataSourceNodeType, _enabled: boolean): InstallationState => {+const useDataSourceInstallation = (data: DataSourceNodeType, _enabled: boolean, canInstallPlugin: boolean): InstallationState => {const dataSourceList = useStore(s => s.dataSourceList)const invalidateDataSourceList = useInvalidDataSourceList()@@ -174,7 +175,7 @@ const useDataSourceInstallation = (data: DataSourceNodeType, _enabled: boolean):}, [dataSourceList, plugin_id, plugin_unique_identifier, provider_name])const uniqueIdentifier = data.plugin_unique_identifier || data.plugin_id- const canInstall = Boolean(data.plugin_unique_identifier)+ const canInstall = Boolean(data.plugin_unique_identifier) && canInstallPluginconst onInstallSuccess = useCallback(() => {invalidateDataSourceList()@@ -198,10 +199,11 @@ export const useNodePluginInstallation = (data: CommonNodeType): InstallationStaconst isTool = data.type === BlockEnum.Toolconst isTrigger = data.type === BlockEnum.TriggerPluginconst isDataSource = data.type === BlockEnum.DataSource+ const { canInstallPlugin } = useWorkspacePluginInstallPermission()- const toolInstallation = useToolInstallation(data as ToolNodeType, isTool)- const triggerInstallation = useTriggerInstallation(data as PluginTriggerNodeType, isTrigger)- const dataSourceInstallation = useDataSourceInstallation(data as DataSourceNodeType, isDataSource)+ const toolInstallation = useToolInstallation(data as ToolNodeType, isTool, canInstallPlugin)+ const triggerInstallation = useTriggerInstallation(data as PluginTriggerNodeType, isTrigger, canInstallPlugin)+ const dataSourceInstallation = useDataSourceInstallation(data as DataSourceNodeType, isDataSource, canInstallPlugin)if (isTool)return toolInstallationdiff --git a/web/app/components/workflow/hooks/use-workflow-panel-interactions.ts b/web/app/components/workflow/hooks/use-workflow-panel-interactions.tsindex 89f8a9a4454..c3ebeba2300 100644--- a/web/app/components/workflow/hooks/use-workflow-panel-interactions.ts+++ b/web/app/components/workflow/hooks/use-workflow-panel-interactions.ts@@ -1,8 +1,9 @@import { useSuspenseQuery } from '@tanstack/react-query'import { useCallback } from 'react'import { systemFeaturesQueryOptions } from '@/features/system-features/client'+import { useHooksStore } from '../hooks-store'import { useStore, useWorkflowStore } from '../store'-import { ControlMode } from '../types'+import { ControlMode, WorkflowRunningStatus } from '../types'import { useEdgesInteractionsWithoutSync } from './use-edges-interactions-without-sync'import { useNodesInteractionsWithoutSync } from './use-nodes-interactions-without-sync'import { useSelectionInteractions } from './use-selection-interactions'@@ -29,12 +30,23 @@ export const useWorkflowInteractions = () => {export const useWorkflowMoveMode = () => {const setControlMode = useStore(s => s.setControlMode)+ const workflowRunningData = useStore(s => s.workflowRunningData)+ const historyWorkflowData = useStore(s => s.historyWorkflowData)+ const isRestoring = useStore(s => s.isRestoring)+ const canComment = useHooksStore(s => s.accessControl.canComment)const { getNodesReadOnly } = useNodesReadOnly()const { handleSelectionCancel } = useSelectionInteractions()const { data: isCommentModeAvailable } = useSuspenseQuery({...systemFeaturesQueryOptions(),select: s => s.enable_collaboration_mode,})+ const isCommentModeOperationBlocked = !!(+ workflowRunningData?.result.status === WorkflowRunningStatus.Running+ || workflowRunningData?.result.status === WorkflowRunningStatus.Paused+ || historyWorkflowData+ || isRestoring+ )+ const canUseCommentMode = !!(canComment && !isCommentModeOperationBlocked && isCommentModeAvailable)const handleModePointer = useCallback(() => {if (getNodesReadOnly())@@ -52,17 +64,18 @@ export const useWorkflowMoveMode = () => {}, [getNodesReadOnly, handleSelectionCancel, setControlMode])const handleModeComment = useCallback(() => {- if (getNodesReadOnly() || !isCommentModeAvailable)+ if (!canUseCommentMode)returnsetControlMode(ControlMode.Comment)handleSelectionCancel()- }, [getNodesReadOnly, handleSelectionCancel, isCommentModeAvailable, setControlMode])+ }, [canUseCommentMode, handleSelectionCancel, setControlMode])return {handleModePointer,handleModeHand,handleModeComment,isCommentModeAvailable,+ canUseCommentMode,}}diff --git a/web/app/components/workflow/hooks/use-workflow.ts b/web/app/components/workflow/hooks/use-workflow.tsindex bf568f0fb6c..8bfa148f9fc 100644--- a/web/app/components/workflow/hooks/use-workflow.ts+++ b/web/app/components/workflow/hooks/use-workflow.ts@@ -26,6 +26,7 @@ import { useNodesMetaData } from '.'import {SUPPORT_OUTPUT_VARS_NODE,} from '../constants'+import { useHooksStore } from '../hooks-store'import { findUsedVarNodes, getNodeOutputVars, updateNodeVars } from '../nodes/_base/components/variable/utils'import { CUSTOM_NOTE_NODE } from '../note-node/constants'@@ -437,7 +438,7 @@ export const useWorkflowReadOnly = () => {}}-export const useNodesReadOnly = () => {+const useNodesReadOnlyBase = (canEdit: boolean) => {const workflowStore = useWorkflowStore()const canvasReadOnly = useStore(s => s.canvasReadOnly)const workflowRunningData = useStore(s => s.workflowRunningData)@@ -454,16 +455,18 @@ export const useNodesReadOnly = () => {return !!(canvasReadOnly+ || !canEdit|| workflowRunningData?.result.status === WorkflowRunningStatus.Running|| workflowRunningData?.result.status === WorkflowRunningStatus.Paused|| historyWorkflowData|| isRestoring)- }, [workflowStore])+ }, [workflowStore, canEdit])return {nodesReadOnly: !!(canvasReadOnly+ || !canEdit|| workflowRunningData?.result.status === WorkflowRunningStatus.Running|| workflowRunningData?.result.status === WorkflowRunningStatus.Paused|| historyWorkflowData@@ -473,6 +476,16 @@ export const useNodesReadOnly = () => {}}+export const useNodesReadOnlyByCanEdit = (canEdit: boolean) => {+ return useNodesReadOnlyBase(canEdit)+}++export const useNodesReadOnly = () => {+ const canEdit = useHooksStore(s => s.accessControl.canEdit)++ return useNodesReadOnlyBase(canEdit)+}+export const useIsNodeInIteration = (iterationId: string) => {const collaborativeWorkflow = useCollaborativeWorkflow()diff --git a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsxindex 4a54d759bc7..19cb4ea0e4b 100644--- a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx+++ b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx@@ -131,7 +131,10 @@ describe('node actions menu details', () => {handleNodesCopy,} as unknown as ReturnType<typeof useNodesInteractions>)mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: false } as ReturnType<typeof useNodesReadOnly>)- mockUseHooksStore.mockImplementation((selector: any) => selector({ configsMap: { flowType: FlowType.appFlow } }))+ mockUseHooksStore.mockImplementation((selector: any) => selector({+ configsMap: { flowType: FlowType.appFlow },+ accessControl: { canRun: true },+ }))mockUseNodes.mockReturnValue([{ id: 'start', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } as any }] as any)mockUseAllWorkflowTools.mockReturnValue({ data: [] } as any)})diff --git a/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsxindex 6b6bdeb9331..44704d037bc 100644--- a/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx+++ b/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx@@ -130,6 +130,19 @@ describe('NodeActionsDropdown', () => {expect(store.getState().pendingSingleRun).toEqual({ nodeId: 'node-1', action: 'run' })})+ it('should hide single-run actions when nodes are readonly', async () => {+ const user = userEvent.setup()+ mockUseNodesReadOnly.mockReturnValueOnce({+ nodesReadOnly: true,+ } as ReturnType<typeof useNodesReadOnly>)++ renderComponent()++ await user.click(screen.getByRole('button', { name: 'common.operation.more' }))++ expect(screen.queryByText('workflow.panel.runThisStep')).not.toBeInTheDocument()+ })+it('should hide the help link when showHelpLink is false', async () => {const user = userEvent.setup()renderComponent(false)diff --git a/web/app/components/workflow/node-actions-menu/use-node-actions-menu-model.ts b/web/app/components/workflow/node-actions-menu/use-node-actions-menu-model.tsindex 579b3406c9d..db184749303 100644--- a/web/app/components/workflow/node-actions-menu/use-node-actions-menu-model.ts+++ b/web/app/components/workflow/node-actions-menu/use-node-actions-menu-model.ts@@ -7,6 +7,7 @@ import {useNodesInteractions,useNodesReadOnly,} from '@/app/components/workflow/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'import { canRunBySingle } from '@/app/components/workflow/utils'@@ -35,11 +36,12 @@ export function useNodeActionsMenuModel({} = useNodesInteractions()const workflowStore = useWorkflowStore()const { nodesReadOnly } = useNodesReadOnly()+ const canRunWorkflow = useHooksStore(s => s.accessControl.canRun)const nodeMetaData = useNodeMetaData({ id, data } as Node)const { data: workflowTools } = useAllWorkflowTools()const isChildNode = !!(data.isInIteration || data.isInLoop)- const canRun = canRunBySingle(data.type, isChildNode)+ const canRun = canRunWorkflow && !nodesReadOnly && canRunBySingle(data.type, isChildNode)const isSingleRunning = data._singleRunningStatus === NodeRunningStatus.Runningconst canChangeBlock = !nodeMetaData.isTypeFixed && !nodeMetaData.isUndeletable && !nodesReadOnlyconst sourceHandle = useMemo(() => {diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/node-control.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/node-control.spec.tsxindex 62d74b64da1..95d1cd74069 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/node-control.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/node-control.spec.tsx@@ -1,15 +1,19 @@+import type React from 'react'import type { CommonNodeType } from '../../../../types'import { fireEvent, screen } from '@testing-library/react'import { renderWorkflowComponent } from '../../../../__tests__/workflow-test-env'+import { fullWorkflowAccessControl } from '../../../../hooks-store'import { BlockEnum, NodeRunningStatus } from '../../../../types'import NodeControl from '../node-control'const {mockHandleNodeSelect,mockCanRunBySingle,+ mockUseNodesReadOnly,} = vi.hoisted(() => ({mockHandleNodeSelect: vi.fn(),mockCanRunBySingle: vi.fn(() => true),+ mockUseNodesReadOnly: vi.fn(() => false),}))let mockPluginInstallLocked = false@@ -21,6 +25,7 @@ vi.mock('../../../../hooks', async () => {useNodesInteractions: () => ({handleNodeSelect: mockHandleNodeSelect,}),+ useNodesReadOnly: mockUseNodesReadOnly,}})@@ -51,6 +56,14 @@ function NodeControlHarness({ id, data }: { id: string, data: CommonNodeType, se)}+function renderNodeControl(ui: React.ReactElement, accessControl = fullWorkflowAccessControl) {+ return renderWorkflowComponent(ui, {+ hooksStoreProps: {+ accessControl,+ },+ })+}+const makeData = (overrides: Partial<CommonNodeType> = {}): CommonNodeType => ({type: BlockEnum.Code,title: 'Node',@@ -67,12 +80,13 @@ describe('NodeControl', () => {vi.clearAllMocks()mockPluginInstallLocked = falsemockCanRunBySingle.mockReturnValue(true)+ mockUseNodesReadOnly.mockReturnValue(false)})// Run/stop behavior should be driven by the workflow store, not CSS classes.describe('Single Run Actions', () => {it('should trigger a single run through the workflow store', () => {- const { store } = renderWorkflowComponent(+ const { store } = renderNodeControl(<NodeControlHarness id="node-1" data={makeData()} />,)@@ -84,7 +98,7 @@ describe('NodeControl', () => {})it('should trigger stop when the node is already single-running', () => {- const { store } = renderWorkflowComponent(+ const { store } = renderNodeControl(<NodeControlHarnessid="node-2"data={makeData({@@ -106,7 +120,7 @@ describe('NodeControl', () => {it('should keep the panel operator available when the plugin is install-locked', () => {mockPluginInstallLocked = true- renderWorkflowComponent(+ renderNodeControl(<NodeControlHarnessid="node-3"data={makeData({@@ -121,7 +135,7 @@ describe('NodeControl', () => {it('should hide the run control when single-node execution is not supported', () => {mockCanRunBySingle.mockReturnValue(false)- renderWorkflowComponent(+ renderNodeControl(<NodeControlHarnessid="node-4"data={makeData()}@@ -131,5 +145,32 @@ describe('NodeControl', () => {expect(screen.queryByRole('button', { name: 'workflow.panel.runThisStep' })).not.toBeInTheDocument()expect(screen.getByRole('button', { name: 'open panel' })).toBeInTheDocument()})++ it('should hide the run control when workflow run permission is missing', () => {+ renderNodeControl(+ <NodeControlHarness id="node-5" data={makeData()} />,+ {+ canEdit: false,+ canComment: true,+ canRun: false,+ canImportExportDSL: false,+ canReleaseAndVersion: false,+ },+ )++ expect(screen.queryByRole('button', { name: 'workflow.panel.runThisStep' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'open panel' })).toBeInTheDocument()+ })++ it('should hide the run control when nodes are read-only', () => {+ mockUseNodesReadOnly.mockReturnValue(true)++ renderNodeControl(+ <NodeControlHarness id="node-6" data={makeData()} />,+ )++ expect(screen.queryByRole('button', { name: 'workflow.panel.runThisStep' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'open panel' })).toBeInTheDocument()+ })})})diff --git a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsxindex 9d1d8eec0a9..9ef2dafd8e5 100644--- a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx+++ b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx@@ -46,7 +46,7 @@ const NotFoundWarn = (props: {<TooltipTriggerrender={<div><span className="i-ri-error-warning-fill size-4 text-text-destructive" aria-hidden="true" /></div>}/>- <TooltipContent className="w-[180px]">+ <TooltipContent className="w-45"><div className="space-y-1 text-xs"><h3 className="font-semibold text-text-primary">{title}@@ -208,7 +208,7 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =><SwitchPluginVersionuniqueIdentifier={value.plugin_unique_identifier}tooltip={(- <div className="w-[180px] space-y-1 text-xs">+ <div className="w-45 space-y-1 text-xs"><h3 className="font-semibold text-text-primary">{t('nodes.agent.unsupportedStrategy', { ns: 'workflow' })}</h3>@@ -231,12 +231,12 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>sideOffset={0}popupClassName="border-none bg-transparent p-0 shadow-none backdrop-blur-none">- <div className="w-[388px] overflow-hidden rounded-md border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow">+ <div className="w-97 overflow-hidden rounded-md border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow"><header className="flex gap-1 p-2"><SearchInput placeholder={t('nodes.agent.strategy.searchPlaceholder', { ns: 'workflow' })} value={query} onValueChange={setQuery} className="w-full" /><ViewTypeSelect viewType={viewType} onChange={setViewType} /></header>- <main className="relative flex w-full flex-col overflow-hidden md:max-h-[300px] xl:max-h-[400px] 2xl:max-h-[564px]" ref={wrapElemRef}>+ <main className="relative flex w-full flex-col overflow-hidden md:max-h-75 xl:max-h-100 2xl:max-h-141" ref={wrapElemRef}><Toolstools={filteredTools}viewType={viewType}diff --git a/web/app/components/workflow/nodes/_base/components/install-plugin-button.tsx b/web/app/components/workflow/nodes/_base/components/install-plugin-button.tsxindex dd2611b395b..560b64a6213 100644--- a/web/app/components/workflow/nodes/_base/components/install-plugin-button.tsx+++ b/web/app/components/workflow/nodes/_base/components/install-plugin-button.tsx@@ -1,10 +1,10 @@import type { ComponentProps, MouseEventHandler } from 'react'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'-import { RiInstallLine, RiLoader2Line } from '@remixicon/react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import checkTaskStatus from '@/app/components/plugins/install-plugin/base/check-task-status'+import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'import { TaskStatus } from '@/app/components/plugins/types'import { useCheckInstalled, useInstallPackageFromMarketPlace } from '@/service/use-plugins'@@ -23,6 +23,7 @@ export const InstallPluginButton = (props: InstallPluginButtonProps) => {...rest} = propsconst { t } = useTranslation()+ const { canInstallPlugin } = useWorkspacePluginInstallPermission()const identifiers = Array.from(new Set([uniqueIdentifier, ...extraIdentifiers].filter((item): item is string => Boolean(item)),))@@ -83,7 +84,7 @@ export const InstallPluginButton = (props: InstallPluginButtonProps) => {},})}- if (!manifest.data)+ if (!canInstallPlugin || !manifest.data)return nullconst identifierSet = new Set(identifiers)const isInstalled = manifest.data.plugins.some(plugin => (@@ -102,7 +103,7 @@ export const InstallPluginButton = (props: InstallPluginButtonProps) => {className={cn('flex items-center', className)}>{!isLoading ? t('nodes.agent.pluginInstaller.install', { ns: 'workflow' }) : t('nodes.agent.pluginInstaller.installing', { ns: 'workflow' })}- {!isLoading ? <RiInstallLine className="ml-1 size-3.5" /> : <RiLoader2Line className="ml-1 size-3.5 animate-spin" />}+ {!isLoading ? <span className="ml-1 i-ri-install-line size-3.5" /> : <span className="ml-1 i-ri-loader-2-line size-3.5 animate-spin" />}</Button>)}diff --git a/web/app/components/workflow/nodes/_base/components/node-control.tsx b/web/app/components/workflow/nodes/_base/components/node-control.tsxindex 2932e8d599f..926f3820b12 100644--- a/web/app/components/workflow/nodes/_base/components/node-control.tsx+++ b/web/app/components/workflow/nodes/_base/components/node-control.tsx@@ -11,10 +11,12 @@ import { useTranslation } from 'react-i18next'import {Stop,} from '@/app/components/base/icons/src/vender/line/mediaAndDevices'+import { useHooksStore } from '@/app/components/workflow/hooks-store'import { NodeActionsDropdown } from '@/app/components/workflow/node-actions-menu'import { useWorkflowStore } from '@/app/components/workflow/store'import {useNodesInteractions,+ useNodesReadOnly,} from '../../../hooks'import { NodeRunningStatus } from '../../../types'import { canRunBySingle } from '../../../utils'@@ -29,7 +31,9 @@ const NodeControl: FC<NodeControlProps> = ({}) => {const { t } = useTranslation()const { handleNodeSelect } = useNodesInteractions()+ const nodesReadOnly = useNodesReadOnly()const workflowStore = useWorkflowStore()+ const canRun = useHooksStore(s => s.accessControl.canRun)const isSingleRunning = data._singleRunningStatus === NodeRunningStatus.Runningconst isChildNode = !!(data.isInIteration || data.isInLoop)@@ -48,7 +52,7 @@ const NodeControl: FC<NodeControlProps> = ({onClick={e => e.stopPropagation()}>{- canRunBySingle(data.type, isChildNode) && (+ canRun && !nodesReadOnly && canRunBySingle(data.type, isChildNode) && (<buttontype="button"aria-label={isSingleRunning ? t('debug.variableInspect.trigger.stop', { ns: 'workflow' }) : t('panel.runThisStep', { ns: 'workflow' })}diff --git a/web/app/components/workflow/nodes/_base/components/option-card.tsx b/web/app/components/workflow/nodes/_base/components/option-card.tsxindex 4bb860aba6d..c90a8c76f94 100644--- a/web/app/components/workflow/nodes/_base/components/option-card.tsx+++ b/web/app/components/workflow/nodes/_base/components/option-card.tsx@@ -50,7 +50,7 @@ const OptionCard: FC<Props> = ({className={cn('flex h-8 cursor-default items-center rounded-md border border-components-option-card-option-border bg-components-option-card-option-bg px-2 system-sm-regular text-text-secondary',(!selected && !disabled) && 'cursor-pointer hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',- selected && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg system-sm-medium shadow-xs',+ (selected && !disabled) && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg system-sm-medium shadow-xs',disabled && 'text-text-disabled',variants({ align }),className,diff --git a/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx b/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsxindex 4220d65be5c..0a1a7fd3ad8 100644--- a/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx+++ b/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx@@ -3,13 +3,13 @@import type { FC, ReactNode } from 'react'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'-import { RiArrowLeftRightLine, RiExternalLinkLine } from '@remixicon/react'import { useBoolean } from 'ahooks'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import Badge from '@/app/components/base/badge'import { Badge as Badge2, BadgeState } from '@/app/components/base/badge/index'import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'+import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'import { pluginManifestToCardPluginProps } from '@/app/components/plugins/install-plugin/utils'import PluginMutationModel from '@/app/components/plugins/plugin-mutation-model'import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'@@ -34,6 +34,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {version: stringpluginUniqueIden: string}>()+ const { canUpdatePlugin } = useWorkspacePluginInstallPermission()const pluginDetails = useCheckInstalled({pluginIds: [pluginId!],enabled: true,@@ -64,7 +65,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {const { t } = useTranslation()// Guard against null/undefined uniqueIdentifier to prevent app crash- if (!uniqueIdentifier || !pluginId)+ if (!uniqueIdentifier || !pluginId || !canUpdatePlugin)return nullconst content = (@@ -99,7 +100,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {<span className="system-xs-regular text-xs text-text-accent">{t('nodes.agent.installPlugin.changelog', { ns: 'workflow' })}</span>- <RiExternalLinkLine className="size-3 text-text-accent" />+ <span className="i-ri-external-link-line size-3 text-text-accent" /></Link>)}/>@@ -127,7 +128,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {text={(<><div>{pluginDetail.version}</div>- <RiArrowLeftRightLine className="ml-1 size-3 text-text-tertiary" />+ <span className="ml-1 i-ri-arrow-left-right-line size-3 text-text-tertiary" /></>)}hasRedCornerMark={true}diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsxindex be30d075213..97c055a8534 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx@@ -16,6 +16,8 @@ const mockHandleSingleRun = vi.fn()const mockHandleStop = vi.fn()const mockHandleRunWithParams = vi.fn()let mockShowMessageLogModal = false+let mockNodesReadOnly = false+let mockCanRun = truelet mockBuiltInTools = [{id: 'provider/tool',name: 'Tool',@@ -115,7 +117,7 @@ vi.mock('@/app/components/workflow/hooks', () => ({},}),useNodesReadOnly: () => ({- nodesReadOnly: false,+ nodesReadOnly: mockNodesReadOnly,}),useToolIcon: () => undefined,useWorkflowHistory: () => ({@@ -128,11 +130,14 @@ vi.mock('@/app/components/workflow/hooks', () => ({}))vi.mock('@/app/components/workflow/hooks-store', () => ({- useHooksStore: (selector: (state: { configsMap: { flowId: string, flowType: string } }) => unknown) => selector({+ useHooksStore: (selector: (state: { configsMap: { flowId: string, flowType: string }, accessControl: { canRun: boolean } }) => unknown) => selector({configsMap: {flowId: 'flow-1',flowType: 'app',},+ accessControl: {+ canRun: mockCanRun,+ },}),}))@@ -298,6 +303,8 @@ describe('workflow-panel index', () => {beforeEach(() => {vi.clearAllMocks()mockShowMessageLogModal = false+ mockNodesReadOnly = false+ mockCanRun = truemockBuiltInTools = [{id: 'provider/tool',name: 'Tool',@@ -351,6 +358,42 @@ describe('workflow-panel index', () => {}))})+ it('should hide the single-run action when nodes are readonly even with run permission', () => {+ mockNodesReadOnly = true++ renderWorkflowComponent(+ <BasePanel id="node-1" data={createData() as never}>+ <div>panel-child</div>+ </BasePanel>,+ {+ initialStoreState: {+ nodePanelWidth: 480,+ otherPanelWidth: 200,+ },+ },+ )++ expect(screen.queryByRole('button', { name: 'workflow.panel.runThisStep' })).not.toBeInTheDocument()+ })++ it('should hide the single-run action when run permission is missing', () => {+ mockCanRun = false++ renderWorkflowComponent(+ <BasePanel id="node-1" data={createData() as never}>+ <div>panel-child</div>+ </BasePanel>,+ {+ initialStoreState: {+ nodePanelWidth: 480,+ otherPanelWidth: 200,+ },+ },+ )++ expect(screen.queryByRole('button', { name: 'workflow.panel.runThisStep' })).not.toBeInTheDocument()+ })+it('should render the special result panel when logs request it', () => {mockLogsState.showSpecialResultPanel = truediff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsxindex 51a7756e460..7a420b258e7 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx@@ -267,6 +267,7 @@ const BasePanel: FC<BasePanelProps> = ({} = useNodesMetaData()const configsMap = useHooksStore(s => s.configsMap)+ const canRun = useHooksStore(s => s.accessControl.canRun)const {isShowSingleRun,hideSingleRun,@@ -580,7 +581,7 @@ const BasePanel: FC<BasePanelProps> = ({)}<div className="flex shrink-0 items-center text-text-tertiary">{- isSupportSingleRun && !nodesReadOnly && (+ isSupportSingleRun && canRun && !nodesReadOnly && (<Tooltip disabled={isSingleRunning}><TooltipTriggerrender={(diff --git a/web/app/components/workflow/nodes/data-source/node.tsx b/web/app/components/workflow/nodes/data-source/node.tsxindex 81ad58ee7d9..4a9dc0ce653 100644--- a/web/app/components/workflow/nodes/data-source/node.tsx+++ b/web/app/components/workflow/nodes/data-source/node.tsx@@ -23,7 +23,7 @@ const Node: FC<NodeProps<DataSourceNodeType>> = ({return (<div className="relative mb-1 px-3 py-1">- <div className="pointer-events-auto absolute top-[-32px] right-3 z-40">+ <div className="pointer-events-auto absolute -top-8 right-3 z-40"><InstallPluginButtonsize="small"extraIdentifiers={[diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsxindex ea1514fc965..db88f1a67ca 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx@@ -86,9 +86,11 @@ const renderWithProviders = (ui: ReactNode) => {useSelector: vi.fn(),isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],}),isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],}}><HooksStoreContext.Provider value={hooksStore}>diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsxindex 30c6db59230..0ca263206bd 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx@@ -52,6 +52,7 @@ const createMember = (overrides: Partial<Member>): Member => ({avatar_url: 'avatar.png',status: 'active',role: 'normal',+ roles: [],created_at: '2026-01-01T00:00:00Z',last_active_at: '2026-01-02T00:00:00Z',last_login_at: '2026-01-03T00:00:00Z',diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-item.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-item.spec.tsxindex 72f995787b2..4c759906877 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-item.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-item.spec.tsx@@ -13,6 +13,7 @@ describe('human-input/delivery-method/recipient/email-item', () => {avatar_url: 'avatar.png',status: 'active',role: 'normal',+ roles: [],created_at: '2026-01-01T00:00:00Z',last_active_at: '2026-01-02T00:00:00Z',last_login_at: '2026-01-03T00:00:00Z',@@ -45,6 +46,7 @@ describe('human-input/delivery-method/recipient/email-item', () => {avatar_url: null,status: 'pending',role: 'normal',+ roles: [],created_at: '2026-01-01T00:00:00Z',last_active_at: '2026-01-02T00:00:00Z',last_login_at: '2026-01-03T00:00:00Z',diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-list.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-list.spec.tsxindex e33ab459583..b794f23be21 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-list.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-list.spec.tsx@@ -10,6 +10,7 @@ const createMember = (overrides: Partial<Member>): Member => ({avatar_url: 'owner.png',status: 'active',role: 'normal',+ roles: [],created_at: '2026-01-01T00:00:00Z',last_active_at: '2026-01-02T00:00:00Z',last_login_at: '2026-01-03T00:00:00Z',diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsxindex 8d54e3babae..0f7e1eca1d7 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsx@@ -38,6 +38,7 @@ const members: Member[] = [{avatar_url: 'avatar.png',status: 'active',role: 'normal',+ roles: [],created_at: '2026-01-01T00:00:00Z',last_active_at: '2026-01-02T00:00:00Z',last_login_at: '2026-01-03T00:00:00Z',diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsxindex aec46ee2c7a..c5b424f0f98 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx@@ -14,6 +14,7 @@ import {} from '@/models/datasets'import { AccountProfileQueryProvider, createAccountProfileQueryClient } from '@/test/account-profile-query'import { RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'+import { DatasetACLPermission, getDatasetACLCapabilities } from '@/utils/permission'import { DatasetsDetailContext } from '../../../datasets-detail-store/provider'import { createDatasetsDetailStore } from '../../../datasets-detail-store/store'import { BlockEnum, VarType } from '../../../types'@@ -58,6 +59,7 @@ const createDataset = (overrides: Partial<DataSet> = {}): DataSet => ({data_source_type: DataSourceType.FILE,indexing_technique: 'high_quality' as DataSet['indexing_technique'],created_by: 'user-1',+ maintainer: 'user-1',updated_by: 'user-1',updated_at: 1690000000,app_count: 0,@@ -128,8 +130,9 @@ const createCondition = (overrides: Partial<MetadataFilteringCondition> = {}): M})vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: { userProfile: { id: string } }) => unknown) => selector({+ useSelector: (selector: (state: { userProfile: { id: string }, workspacePermissionKeys: string[] }) => unknown) => selector({userProfile: { id: 'user-1' },+ workspacePermissionKeys: [],}),useAppContext: () => ({userProfile: {@@ -139,6 +142,24 @@ vi.mock('@/context/app-context', () => ({}))vi.mock('@/utils/permission', () => ({+ DatasetACLPermission: {+ Readonly: 'dataset.acl.readonly',+ Edit: 'dataset.acl.edit',+ Use: 'dataset.acl.use',+ },+ getDatasetACLCapabilities: vi.fn(() => ({+ canReadonly: false,+ canEdit: true,+ canImportExportDSL: false,+ canPipelineTest: false,+ canDocumentDownload: false,+ canRetrievalRecall: false,+ canUse: true,+ canDeleteFile: false,+ canPipelineRelease: false,+ canDelete: false,+ canAccessConfig: false,+ })),hasEditPermissionForDataset: (userId: string,datasetConfig: { createdBy: string, partialMemberList: string[], permission: DatasetPermission },@@ -287,6 +308,19 @@ describe('knowledge-retrieval path', () => {beforeEach(() => {vi.clearAllMocks()mockHasEditPermissionForDataset.mockReturnValue(true)+ vi.mocked(getDatasetACLCapabilities).mockReturnValue({+ canReadonly: false,+ canEdit: true,+ canImportExportDSL: false,+ canPipelineTest: false,+ canDocumentDownload: false,+ canRetrievalRecall: false,+ canUse: true,+ canDeleteFile: false,+ canPipelineRelease: false,+ canDelete: false,+ canAccessConfig: false,+ })})describe('Dataset controls', () => {@@ -372,6 +406,42 @@ describe('knowledge-retrieval path', () => {expect(onChange).toHaveBeenCalledWith([])})++ it('should hide dataset settings when ACL does not grant edit even if legacy dataset permission allows it', () => {+ const dataset = createDataset({+ permission: DatasetPermission.allTeamMembers,+ permission_keys: [DatasetACLPermission.Use],+ })+ mockHasEditPermissionForDataset.mockReturnValue(true)+ vi.mocked(getDatasetACLCapabilities).mockReturnValue({+ canReadonly: false,+ canEdit: false,+ canImportExportDSL: false,+ canPipelineTest: false,+ canDocumentDownload: false,+ canRetrievalRecall: false,+ canUse: true,+ canDeleteFile: false,+ canPipelineRelease: false,+ canDelete: false,+ canAccessConfig: false,+ })++ render(+ <DatasetList+ list={[dataset]}+ onChange={vi.fn()}+ />,+ )++ const datasetItem = getDatasetItem()++ expect(within(datasetItem).queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()+ expect(getDatasetACLCapabilities).toHaveBeenCalledWith(dataset.permission_keys, expect.objectContaining({+ currentUserId: 'user-1',+ resourceMaintainer: dataset.maintainer,+ }))+ })})describe('Retrieval settings', () => {diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsxindex 029c856a036..b68e2d1e7a7 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsx@@ -6,7 +6,7 @@ import * as React from 'react'import { useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useSelector as useAppContextSelector } from '@/context/app-context'-import { hasEditPermissionForDataset } from '@/utils/permission'+import { getDatasetACLCapabilities } from '@/utils/permission'import Item from './dataset-item'type Props = Readonly<{@@ -29,7 +29,8 @@ const DatasetList: FC<Props> = ({settingsModalHeight,}) => {const { t } = useTranslation()- const userProfile = useAppContextSelector(s => s.userProfile)+ const currentUserId = useAppContextSelector(s => s.userProfile?.id)+ const workspacePermissionKeys = useAppContextSelector(s => s.workspacePermissionKeys)const handleRemove = useCallback((index: number) => {return () => {@@ -51,17 +52,17 @@ const DatasetList: FC<Props> = ({const formattedList = useMemo(() => {return list.map((item) => {- const datasetConfig = {- createdBy: item.created_by,- partialMemberList: item.partial_member_list || [],- permission: item.permission,- }+ const datasetACLCapabilities = getDatasetACLCapabilities(item.permission_keys, {+ currentUserId,+ resourceMaintainer: item.maintainer,+ workspacePermissionKeys,+ })return {...item,- editable: hasEditPermissionForDataset(userProfile?.id || '', datasetConfig),+ editable: datasetACLCapabilities.canEdit,}})- }, [list, userProfile?.id])+ }, [currentUserId, list, workspacePermissionKeys])return (<div className="space-y-1">diff --git a/web/app/components/workflow/nodes/tool/node.tsx b/web/app/components/workflow/nodes/tool/node.tsxindex fa6fea24c21..023be76cc7c 100644--- a/web/app/components/workflow/nodes/tool/node.tsx+++ b/web/app/components/workflow/nodes/tool/node.tsx@@ -35,7 +35,7 @@ const Node: FC<NodeProps<ToolNodeType>> = ({return (<div className="relative mb-1 px-3 py-1">{showInstallButton && (- <div className="pointer-events-auto absolute top-[-32px] right-3 z-40">+ <div className="pointer-events-auto absolute -top-8 right-3 z-40"><InstallPluginButtonsize="small"className="font-medium! text-text-accent!"diff --git a/web/app/components/workflow/nodes/trigger-plugin/node.tsx b/web/app/components/workflow/nodes/trigger-plugin/node.tsxindex 49fb0fd68cd..57733121fad 100644--- a/web/app/components/workflow/nodes/trigger-plugin/node.tsx+++ b/web/app/components/workflow/nodes/trigger-plugin/node.tsx@@ -64,7 +64,7 @@ const Node: FC<NodeProps<PluginTriggerNodeType>> = ({return (<div className="relative mb-1 px-3 py-1">{showInstallButton && (- <div className="pointer-events-auto absolute top-[-32px] right-3 z-40">+ <div className="pointer-events-auto absolute -top-8 right-3 z-40"><InstallPluginButtonsize="small"extraIdentifiers={[@@ -87,7 +87,7 @@ const Node: FC<NodeProps<PluginTriggerNodeType>> = ({><divtitle={key}- className="max-w-[100px] shrink-0 truncate text-xs font-medium text-text-tertiary uppercase"+ className="max-w-25 shrink-0 truncate text-xs font-medium text-text-tertiary uppercase">{key}</div>diff --git a/web/app/components/workflow/operator/__tests__/control.spec.tsx b/web/app/components/workflow/operator/__tests__/control.spec.tsxindex 3a31c8f7217..23118185d4d 100644--- a/web/app/components/workflow/operator/__tests__/control.spec.tsx+++ b/web/app/components/workflow/operator/__tests__/control.spec.tsx@@ -10,16 +10,22 @@ type WorkflowStoreState = {const {mockHandleAddNote,mockHandleLayout,+ mockHandleModeComment,mockHandleModeHand,mockHandleModePointer,} = vi.hoisted(() => ({mockHandleAddNote: vi.fn(),mockHandleLayout: vi.fn(),+ mockHandleModeComment: vi.fn(),mockHandleModeHand: vi.fn(),mockHandleModePointer: vi.fn(),}))let mockNodesReadOnly = false+let mockCanComment = true+let mockCanEdit = true+let mockCanUseCommentMode = true+let mockIsCommentModeAvailable = truelet mockStoreState: WorkflowStoreStatevi.mock('../../hooks', () => ({@@ -30,6 +36,9 @@ vi.mock('../../hooks', () => ({useWorkflowMoveMode: () => ({handleModePointer: mockHandleModePointer,handleModeHand: mockHandleModeHand,+ handleModeComment: mockHandleModeComment,+ isCommentModeAvailable: mockIsCommentModeAvailable,+ canUseCommentMode: mockCanUseCommentMode,}),useWorkflowOrganize: () => ({handleLayout: mockHandleLayout,@@ -46,6 +55,16 @@ vi.mock('../../store', () => ({useStore: (selector: (state: WorkflowStoreState) => unknown) => selector(mockStoreState),}))+vi.mock('../../hooks-store', () => ({+ useHooksStore: <T,>(selector: (state: { accessControl: { canComment: boolean, canEdit: boolean } }) => T): T =>+ selector({+ accessControl: {+ canComment: mockCanComment,+ canEdit: mockCanEdit,+ },+ }),+}))+vi.mock('../add-block', () => ({default: () => <div data-testid="add-block" />,}))@@ -68,6 +87,10 @@ describe('Control', () => {beforeEach(() => {vi.clearAllMocks()mockNodesReadOnly = false+ mockCanComment = true+ mockCanEdit = true+ mockCanUseCommentMode = true+ mockIsCommentModeAvailable = truemockStoreState = {controlMode: ControlMode.Pointer,}@@ -103,15 +126,19 @@ describe('Control', () => {fireEvent.click(screen.getByTestId('workflow.nodes.note.addNote').firstElementChild as HTMLElement)fireEvent.click(screen.getByTestId('workflow.common.pointerMode').firstElementChild as HTMLElement)fireEvent.click(screen.getByTestId('workflow.common.handMode').firstElementChild as HTMLElement)+ fireEvent.click(screen.getByTestId('workflow.common.commentMode').firstElementChild as HTMLElement)fireEvent.click(screen.getByTestId('workflow.panel.organizeBlocks').firstElementChild as HTMLElement)expect(mockHandleAddNote).toHaveBeenCalledTimes(1)expect(mockHandleModePointer).toHaveBeenCalledTimes(1)expect(mockHandleModeHand).toHaveBeenCalledTimes(1)+ expect(mockHandleModeComment).toHaveBeenCalledTimes(1)expect(mockHandleLayout).toHaveBeenCalledTimes(1)})- it('should block note creation when the workflow is read only', () => {+ it('should block note creation when editing is not allowed', () => {+ mockCanEdit = false+ mockCanComment = truemockNodesReadOnly = truerender(<Control />)@@ -120,5 +147,32 @@ describe('Control', () => {expect(mockHandleAddNote).not.toHaveBeenCalled()})++ it('should keep comment mode enabled for readonly layout users who can comment', () => {+ mockNodesReadOnly = true+ mockCanUseCommentMode = true++ render(<Control />)++ const commentButton = screen.getByTestId('workflow.common.commentMode').firstElementChild as HTMLButtonElement+ expect(commentButton).toBeEnabled()++ fireEvent.click(commentButton)++ expect(mockHandleModeComment).toHaveBeenCalledTimes(1)+ })++ it('should disable comment mode when comment operation is blocked', () => {+ mockCanUseCommentMode = false++ render(<Control />)++ const commentButton = screen.getByTestId('workflow.common.commentMode').firstElementChild as HTMLButtonElement+ expect(commentButton).toBeDisabled()++ fireEvent.click(commentButton)++ expect(mockHandleModeComment).not.toHaveBeenCalled()+ })})})diff --git a/web/app/components/workflow/operator/control.tsx b/web/app/components/workflow/operator/control.tsxindex 74baf76afd4..228ffd37447 100644--- a/web/app/components/workflow/operator/control.tsx+++ b/web/app/components/workflow/operator/control.tsx@@ -34,6 +34,7 @@ const Control = () => {handleModeHand,handleModeComment,isCommentModeAvailable,+ canUseCommentMode,} = useWorkflowMoveMode()const { handleLayout } = useWorkflowOrganize()const { handleAddNote } = useOperator()@@ -103,11 +104,11 @@ const Control = () => {<buttontype="button"aria-label={t('common.commentMode', { ns: 'workflow' })}- disabled={nodesReadOnly}+ disabled={!canUseCommentMode}className={cn('ml-px flex size-8 cursor-pointer items-center justify-center rounded-lg',controlMode === ControlMode.Comment ? 'bg-state-accent-active text-text-accent' : 'hover:bg-state-base-hover hover:text-text-secondary',- `${nodesReadOnly && 'cursor-not-allowed text-text-disabled hover:bg-transparent hover:text-text-disabled'}`,+ `${!canUseCommentMode && 'cursor-not-allowed text-text-disabled hover:bg-transparent hover:text-text-disabled'}`,)}onClick={handleModeComment}>diff --git a/web/app/components/workflow/panel-contextmenu.tsx b/web/app/components/workflow/panel-contextmenu.tsxindex 5ceb7b843f1..2e620e26909 100644--- a/web/app/components/workflow/panel-contextmenu.tsx+++ b/web/app/components/workflow/panel-contextmenu.tsx@@ -17,10 +17,12 @@ import {useWorkflowMoveMode,useWorkflowStartRun,} from './hooks'+import { useHooksStore } from './hooks-store'import AddBlock from './operator/add-block'import { useOperator } from './operator/hooks'import { ShortcutKbd } from './shortcuts/shortcut-kbd'import { useStore } from './store'+import { WorkflowRunningStatus } from './types'export function PanelContextmenu({onClose,@@ -34,6 +36,9 @@ export function PanelContextmenu({const pendingComment = useStore(s => s.pendingComment)const setCommentPlacing = useStore(s => s.setCommentPlacing)const setCommentQuickAdd = useStore(s => s.setCommentQuickAdd)+ const workflowRunningData = useStore(s => s.workflowRunningData)+ const historyWorkflowData = useStore(s => s.historyWorkflowData)+ const isRestoring = useStore(s => s.isRestoring)const { handleNodesPaste } = useNodesInteractions()const {handleStartWorkflowRun,@@ -42,7 +47,16 @@ export function PanelContextmenu({const { handleAddNote } = useOperator()const { isCommentModeAvailable } = useWorkflowMoveMode()const { exportCheck } = useDSL()+ const accessControl = useHooksStore(s => s.accessControl)const isChatMode = useIsChatMode()+ const workflowOperationReadOnly = !!(+ workflowRunningData?.result.status === WorkflowRunningStatus.Running+ || workflowRunningData?.result.status === WorkflowRunningStatus.Paused+ || historyWorkflowData+ || isRestoring+ )+ const canEditWorkflow = accessControl.canEdit && !workflowOperationReadOnly+ const canCommentWorkflow = accessControl.canComment && !workflowOperationReadOnlyconst renderAddBlockTrigger = useCallback(() => {return (@@ -78,26 +92,30 @@ export function PanelContextmenu({sideOffset={4}><ContextMenuGroup>- <AddBlock- renderTrigger={renderAddBlockTrigger}- renderTriggerAsButtonRoot- onClose={onClose}- offset={{- mainAxis: -36,- crossAxis: -4,- }}- />- <ContextMenuItem- className="justify-between gap-4 px-3 text-text-secondary"- onClick={(e) => {- e.stopPropagation()- handleAddNote()- onClose()- }}- >- {t('nodes.note.addNote', { ns: 'workflow' })}- </ContextMenuItem>- {isCommentModeAvailable && (+ {canEditWorkflow && (+ <AddBlock+ renderTrigger={renderAddBlockTrigger}+ renderTriggerAsButtonRoot+ onClose={onClose}+ offset={{+ mainAxis: -36,+ crossAxis: -4,+ }}+ />+ )}+ {canEditWorkflow && (+ <ContextMenuItem+ className="justify-between gap-4 px-3 text-text-secondary"+ onClick={(e) => {+ e.stopPropagation()+ handleAddNote()+ onClose()+ }}+ >+ {t('nodes.note.addNote', { ns: 'workflow' })}+ </ContextMenuItem>+ )}+ {canCommentWorkflow && isCommentModeAvailable && (<ContextMenuItemdisabled={!!pendingComment}className={cn(@@ -116,48 +134,58 @@ export function PanelContextmenu({{t('comments.actions.addComment', { ns: 'workflow' })}</ContextMenuItem>)}- <ContextMenuItem- className="justify-between gap-4 px-3 text-text-secondary"- onClick={handleRunAction}- >- {isChatMode ? t('common.debugAndPreview', { ns: 'workflow' }) : t('common.run', { ns: 'workflow' })}- {!isChatMode && <ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} />}- </ContextMenuItem>- </ContextMenuGroup>- <ContextMenuSeparator />- <ContextMenuGroup>- <ContextMenuItem- disabled={!clipboardElements.length}- className={cn(- 'justify-between gap-4 px-3 text-text-secondary',- !clipboardElements.length && 'cursor-not-allowed opacity-50',- )}- onClick={() => {- if (clipboardElements.length) {- handleNodesPaste()- onClose()- }- }}- >- {t('common.pasteHere', { ns: 'workflow' })}- <ShortcutKbd shortcut="workflow.paste" />- </ContextMenuItem>- </ContextMenuGroup>- <ContextMenuSeparator />- <ContextMenuGroup>- <ContextMenuItem- className="justify-between gap-4 px-3 text-text-secondary"- onClick={() => exportCheck?.()}- >- {t('export', { ns: 'app' })}- </ContextMenuItem>- <ContextMenuItem- className="justify-between gap-4 px-3 text-text-secondary"- onClick={() => setShowImportDSLModal(true)}- >- {t('importApp', { ns: 'app' })}- </ContextMenuItem>+ {accessControl.canRun && (+ <ContextMenuItem+ className="justify-between gap-4 px-3 text-text-secondary"+ onClick={handleRunAction}+ >+ {isChatMode ? t('common.debugAndPreview', { ns: 'workflow' }) : t('common.run', { ns: 'workflow' })}+ {!isChatMode && <ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} />}+ </ContextMenuItem>+ )}</ContextMenuGroup>+ {canEditWorkflow && (+ <>+ <ContextMenuSeparator />+ <ContextMenuGroup>+ <ContextMenuItem+ disabled={!clipboardElements.length}+ className={cn(+ 'justify-between gap-4 px-3 text-text-secondary',+ !clipboardElements.length && 'cursor-not-allowed opacity-50',+ )}+ onClick={() => {+ if (clipboardElements.length) {+ handleNodesPaste()+ onClose()+ }+ }}+ >+ {t('common.pasteHere', { ns: 'workflow' })}+ <ShortcutKbd shortcut="workflow.paste" />+ </ContextMenuItem>+ </ContextMenuGroup>+ </>+ )}+ {accessControl.canImportExportDSL && (+ <>+ <ContextMenuSeparator />+ <ContextMenuGroup>+ <ContextMenuItem+ className="justify-between gap-4 px-3 text-text-secondary"+ onClick={() => exportCheck?.()}+ >+ {t('export', { ns: 'app' })}+ </ContextMenuItem>+ <ContextMenuItem+ className="justify-between gap-4 px-3 text-text-secondary"+ onClick={() => setShowImportDSLModal(true)}+ >+ {t('importApp', { ns: 'app' })}+ </ContextMenuItem>+ </ContextMenuGroup>+ </>+ )}</ContextMenuContent>)}diff --git a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsxindex 41174d97a1e..667b0e9a67f 100644--- a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx+++ b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx@@ -299,5 +299,31 @@ describe('InputsPanel', () => {expect(screen.getByRole('button', { name: 'workflow.singleRun.startRun' })).toBeDisabled()})++ it('should disable the run button and skip execution when test/run permission is missing', async () => {+ const user = userEvent.setup()+ const onRun = vi.fn()+ const handleRun = vi.fn()++ renderInputsPanel(createStartNode(), {+ hooksStoreProps: createHooksStoreProps({+ handleRun,+ accessControl: {+ canEdit: true,+ canComment: true,+ canRun: false,+ canImportExportDSL: true,+ canReleaseAndVersion: true,+ },+ }),+ }, onRun)++ await user.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))++ expect(screen.getByRole('button', { name: 'workflow.singleRun.startRun' })).toBeDisabled()+ expect(mockCheckInputsForm).not.toHaveBeenCalled()+ expect(onRun).not.toHaveBeenCalled()+ expect(handleRun).not.toHaveBeenCalled()+ })})})diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.tsindex fb045c47233..cadf5f6733c 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts@@ -11,6 +11,9 @@ const mockSetLoopTimes = vi.fn()const mockSubmitHumanInputForm = vi.fn()const mockSseGet = vi.fn()const mockGetNodes = vi.fn((): any[] => [])+const mockHooksStoreState = vi.hoisted(() => ({+ canRun: true,+}))let mockWorkflowRunningData: any = null@@ -49,7 +52,12 @@ vi.mock('../../../../hooks', () => ({}))vi.mock('../../../../hooks-store', () => ({- useHooksStore: () => null,+ useHooksStore: (selector: (state: { configsMap: null, accessControl: { canRun: boolean } }) => unknown) => selector({+ configsMap: null,+ accessControl: {+ canRun: mockHooksStoreState.canRun,+ },+ }),}))vi.mock('../../../../store', () => ({@@ -67,6 +75,7 @@ vi.mock('../../../../store', () => ({const resetMocksAndWorkflowState = () => {vi.clearAllMocks()mockWorkflowRunningData = null+ mockHooksStoreState.canRun = true}describe('useChat – handleSend', () => {@@ -87,6 +96,20 @@ describe('useChat – handleSend', () => {expect(bodyParams.query).toBe('hello')})+ it('should return false and skip handleRun when test/run permission is missing', () => {+ mockHooksStoreState.canRun = false+ const { result } = renderHook(() => useChat({}))++ let returned: unknown+ act(() => {+ returned = result.current.handleSend({ query: 'hello', inputs: {} }, {})+ })++ expect(returned).toBe(false)+ expect(mockHandleRun).not.toHaveBeenCalled()+ expect(result.current.chatList).toHaveLength(0)+ })+it('should show notification and return false when already responding', () => {mockHandleRun.mockImplementation(() => {})diff --git a/web/app/components/workflow/panel/debug-and-preview/hooks.ts b/web/app/components/workflow/panel/debug-and-preview/hooks.tsindex 24f643ec870..463eff19221 100644--- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts+++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts@@ -68,6 +68,7 @@ export const useChat = (const isRespondingRef = useRef(false)const workflowEventsAbortControllerRef = useRef<AbortController | null>(null)const configsMap = useHooksStore(s => s.configsMap)+ const canRun = useHooksStore(s => s.accessControl.canRun)const invalidAllLastRun = useInvalidAllLastRun(configsMap?.flowType, configsMap?.flowId)const { fetchInspectVars } = useSetWorkflowVarsWithValue()const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])@@ -259,6 +260,9 @@ export const useChat = (onGetSuggestedQuestions,}: SendCallback,) => {+ if (canRun === false)+ return false+if (isRespondingRef.current) {toast.info(t('errorMessage.waitForResponse', { ns: 'appDebug' }))return false@@ -665,7 +669,7 @@ export const useChat = (},},)- }, [threadMessages, chatTree.length, updateCurrentQAOnTree, handleResponding, formSettings?.inputsForm, handleRun, t, workflowStore, fetchInspectVars, invalidAllLastRun, config?.suggested_questions_after_answer?.enabled])+ }, [canRun, threadMessages, chatTree.length, updateCurrentQAOnTree, handleResponding, formSettings?.inputsForm, handleRun, t, workflowStore, fetchInspectVars, invalidAllLastRun, config?.suggested_questions_after_answer?.enabled])const handleSubmitHumanInputForm = async (formToken: string, formData: HumanInputFormSubmitData) => {await submitHumanInputForm(formToken, formData)diff --git a/web/app/components/workflow/panel/inputs-panel.tsx b/web/app/components/workflow/panel/inputs-panel.tsxindex 6a40a755396..f76ce322df9 100644--- a/web/app/components/workflow/panel/inputs-panel.tsx+++ b/web/app/components/workflow/panel/inputs-panel.tsx@@ -34,6 +34,7 @@ const InputsPanel = ({ onRun }: Props) => {const workflowStore = useWorkflowStore()const inputs = useStore(s => s.inputs)const fileSettings = useHooksStore(s => s.configsMap?.fileSettings)+ const canRunWorkflow = useHooksStore(s => s.accessControl.canRun)const nodes = useNodes<StartNodeType>()const files = useStore(s => s.files)const workflowRunningData = useStore(s => s.workflowRunningData)@@ -92,16 +93,19 @@ const InputsPanel = ({ onRun }: Props) => {}}+ const canRun = useMemo(() => {+ const canUploadReady = !(files?.some(item => (item.transfer_method as any) === TransferMethod.local_file && !item.upload_file_id))+ return canRunWorkflow && canUploadReady+ }, [canRunWorkflow, files])+const doRun = useCallback(() => {+ if (!canRun)+ returnif (!checkInputsForm(initialInputs, variables as any))returnonRun()handleRun({ inputs: getProcessedInputs(initialInputs, variables as any), files })- }, [files, handleRun, initialInputs, onRun, variables, checkInputsForm])-- const canRun = useMemo(() => {- return !(files?.some(item => (item.transfer_method as any) === TransferMethod.local_file && !item.upload_file_id))- }, [files])+ }, [canRun, files, handleRun, initialInputs, onRun, variables, checkInputsForm])return (<>diff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsxindex 545becd1cfc..b28901a8f95 100644--- a/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsx@@ -61,6 +61,7 @@ describe('VersionHistoryItem', () => {latestVersionId="latest-version"onClick={onClick}handleClickActionMenuItem={vi.fn()}+ canImportExportDSLisLast={false}/>,)@@ -91,6 +92,7 @@ describe('VersionHistoryItem', () => {latestVersionId="version-1"onClick={onClick}handleClickActionMenuItem={handleClickActionMenuItem}+ canImportExportDSLisLast={false}/>,)@@ -127,6 +129,35 @@ describe('VersionHistoryItem', () => {)})+ it('should hide export from the context menu when import/export DSL permission is missing', async () => {+ const user = userEvent.setup()++ render(+ <VersionHistoryItem+ item={createVersionHistory()}+ currentVersion={null}+ latestVersionId="version-1"+ onClick={vi.fn()}+ handleClickActionMenuItem={vi.fn()}+ canImportExportDSL={false}+ isLast={false}+ />,+ )++ const title = screen.getByText('Release 1')+ const itemContainer = title.closest('.group')+ if (!itemContainer)+ throw new Error('Expected version history item container')++ fireEvent.mouseEnter(itemContainer)++ const triggerButton = await screen.findByRole('button')+ await user.click(triggerButton)++ expect(screen.queryByText('app.export')).not.toBeInTheDocument()+ expect(screen.getByText('workflow.versionHistory.copyId')).toBeInTheDocument()+ })+it('should ignore clicks when the item is already selected', async () => {const user = userEvent.setup()const onClick = vi.fn()@@ -139,6 +170,7 @@ describe('VersionHistoryItem', () => {latestVersionId="other-version"onClick={onClick}handleClickActionMenuItem={vi.fn()}+ canImportExportDSLisLast/>,)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 5a633f36bcc..56890f01d6a 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@@ -39,6 +39,7 @@ describe('ActionMenu', () => {<ActionMenuisNamedVersionisShowDelete+ canImportExportDSLopensetOpen={setOpen}handleClickActionMenuItem={handleClickActionMenuItem}@@ -69,6 +70,7 @@ describe('ActionMenu', () => {<ActionMenuisNamedVersionisShowDelete+ canImportExportDSLopensetOpen={vi.fn()}handleClickActionMenuItem={handleClickActionMenuItem}diff --git a/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/use-action-menu.spec.tsx b/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/use-action-menu.spec.tsxindex e08bc787d7a..78944e6cc79 100644--- a/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/use-action-menu.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/use-action-menu.spec.tsx@@ -6,6 +6,7 @@ describe('useActionMenu', () => {it('returns restore, edit, export, copy and delete operations for app workflows', () => {const { result } = renderWorkflowHook(() => useActionMenu({isNamedVersion: true,+ canImportExportDSL: true,isShowDelete: false,open: false,setOpen: vi.fn(),@@ -27,6 +28,7 @@ describe('useActionMenu', () => {it('omits export for pipelines and renames the edit action for unnamed versions', () => {const { result } = renderWorkflowHook(() => useActionMenu({isNamedVersion: false,+ canImportExportDSL: true,isShowDelete: true,open: false,setOpen: vi.fn(),@@ -52,4 +54,21 @@ describe('useActionMenu', () => {},])})++ it('omits export when import/export DSL permission is missing', () => {+ const { result } = renderWorkflowHook(() => useActionMenu({+ isNamedVersion: true,+ canImportExportDSL: false,+ isShowDelete: false,+ open: false,+ setOpen: vi.fn(),+ handleClickActionMenuItem: vi.fn(),+ }))++ expect(result.current.options.map(item => item.key)).toEqual([+ VersionHistoryContextMenuOptions.restore,+ VersionHistoryContextMenuOptions.edit,+ VersionHistoryContextMenuOptions.copyId,+ ])+ })})diff --git a/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx b/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsxindex 81f04f31ea8..5d96a761edd 100644--- a/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx+++ b/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx@@ -15,6 +15,7 @@ import useActionMenu from './use-action-menu'export type ActionMenuProps = {isShowDelete: booleanisNamedVersion: boolean+ canImportExportDSL: booleanopen: booleansetOpen: React.Dispatch<React.SetStateAction<boolean>>handleClickActionMenuItem: (operation: VersionHistoryContextMenuOptions) => voiddiff --git a/web/app/components/workflow/panel/version-history-panel/action-menu/use-action-menu.ts b/web/app/components/workflow/panel/version-history-panel/action-menu/use-action-menu.tsindex 765816427a4..94b94aa2516 100644--- a/web/app/components/workflow/panel/version-history-panel/action-menu/use-action-menu.ts+++ b/web/app/components/workflow/panel/version-history-panel/action-menu/use-action-menu.ts@@ -9,6 +9,7 @@ import { VersionHistoryContextMenuOptions } from '../../../types'const useActionMenu = (props: ActionMenuProps) => {const {isNamedVersion,+ canImportExportDSL,} = propsconst { t } = useTranslation()const pipelineId = useStore(s => s.pipelineId)@@ -37,7 +38,7 @@ const useActionMenu = (props: ActionMenuProps) => {name: t('versionHistory.nameThisVersion', { ns: 'workflow' }),},// todo: pipeline support export specific version DSL- ...(!pipelineId+ ...(canImportExportDSL && !pipelineId? [{key: VersionHistoryContextMenuOptions.exportDSL,name: t('export', { ns: 'app' }),@@ -49,7 +50,7 @@ const useActionMenu = (props: ActionMenuProps) => {name: t('versionHistory.copyId', { ns: 'workflow' }),},]- }, [isNamedVersion, pipelineId, shouldShowUpgrade, t])+ }, [canImportExportDSL, isNamedVersion, pipelineId, shouldShowUpgrade, shouldShowUpgrade, t])return {deleteOperation,diff --git a/web/app/components/workflow/panel/version-history-panel/index.tsx b/web/app/components/workflow/panel/version-history-panel/index.tsxindex 05c7dce7290..384e945168f 100644--- a/web/app/components/workflow/panel/version-history-panel/index.tsx+++ b/web/app/components/workflow/panel/version-history-panel/index.tsx@@ -60,6 +60,7 @@ export const VersionHistoryPanel = ({const setCurrentVersion = useStore(s => s.setCurrentVersion)const userProfile = useAppContextSelector(s => s.userProfile)const configsMap = useHooksStore(s => s.configsMap)+ const canImportExportDSL = useHooksStore(s => s.accessControl.canImportExportDSL)const invalidAllLastRun = useInvalidAllLastRun(configsMap?.flowType, configsMap?.flowId)const {deleteAllInspectVars,@@ -138,10 +139,12 @@ export const VersionHistoryPanel = ({setIsRestorePlanUpgradeModalOpen(true)break}+ if (!canImportExportDSL)+ returnhandleExportDSL?.(false, item.id)break}- }, [canUseWorkflowVersionAction, t, handleExportDSL])+ }, [canUseWorkflowVersionAction, canImportExportDSL, t, handleExportDSL])const handleCancel = useCallback((operation: VersionHistoryContextMenuOptions) => {switch (operation) {@@ -307,6 +310,7 @@ export const VersionHistoryPanel = ({latestVersionId={latestVersionId || ''}onClick={handleVersionClick}handleClickActionMenuItem={handleClickActionMenuItem.bind(null, item)}+ canImportExportDSL={canImportExportDSL}isLast={isLast}/>)diff --git a/web/app/components/workflow/panel/version-history-panel/version-history-item.tsx b/web/app/components/workflow/panel/version-history-panel/version-history-item.tsxindex 98e4d4f4806..e0c19ee589d 100644--- a/web/app/components/workflow/panel/version-history-panel/version-history-item.tsx+++ b/web/app/components/workflow/panel/version-history-panel/version-history-item.tsx@@ -14,6 +14,7 @@ type VersionHistoryItemProps = {latestVersionId: stringonClick: (item: VersionHistory) => voidhandleClickActionMenuItem: (operation: VersionHistoryContextMenuOptions) => void+ canImportExportDSL: booleanisLast: booleanhideActionMenu?: boolean}@@ -43,6 +44,7 @@ const VersionHistoryItem: React.FC<VersionHistoryItemProps> = ({latestVersionId,onClick,handleClickActionMenuItem,+ canImportExportDSL,isLast,hideActionMenu,}) => {@@ -133,6 +135,7 @@ const VersionHistoryItem: React.FC<VersionHistoryItemProps> = ({<ActionMenuisShowDelete={!isLatest}isNamedVersion={!!item.marked_name}+ canImportExportDSL={canImportExportDSL}open={open}setOpen={setOpen}handleClickActionMenuItem={handleClickActionMenuItem}diff --git a/web/app/components/workflow/run/agent-log/__tests__/agent-log-item.spec.tsx b/web/app/components/workflow/run/agent-log/__tests__/agent-log-item.spec.tsxindex d444eb6c627..50ac08b682c 100644--- a/web/app/components/workflow/run/agent-log/__tests__/agent-log-item.spec.tsx+++ b/web/app/components/workflow/run/agent-log/__tests__/agent-log-item.spec.tsx@@ -41,6 +41,7 @@ const createAppContextValue = (): AppContextValue => {langGeniusVersionInfo: initialLangGeniusVersionInfo,isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],}const useSelector: AppContextValue['useSelector'] = selector => selector(value)value = {diff --git a/web/app/components/workflow/run/agent-log/__tests__/agent-result-panel.spec.tsx b/web/app/components/workflow/run/agent-log/__tests__/agent-result-panel.spec.tsxindex 8cd7d349f65..7953bfc52a1 100644--- a/web/app/components/workflow/run/agent-log/__tests__/agent-result-panel.spec.tsx+++ b/web/app/components/workflow/run/agent-log/__tests__/agent-result-panel.spec.tsx@@ -38,6 +38,7 @@ const createAppContextValue = (): AppContextValue => {langGeniusVersionInfo: initialLangGeniusVersionInfo,isLoadingCurrentWorkspace: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],}const useSelector: AppContextValue['useSelector'] = selector => selector(value)value = {diff --git a/web/app/components/workflow/selection-contextmenu.tsx b/web/app/components/workflow/selection-contextmenu.tsxindex 2470d5e1b65..dffbd31a5e1 100644--- a/web/app/components/workflow/selection-contextmenu.tsx+++ b/web/app/components/workflow/selection-contextmenu.tsx@@ -13,7 +13,9 @@ import {import { useTranslation } from 'react-i18next'import { useStore as useReactFlowStore } from 'reactflow'import { useCreateSnippetFromSelection } from '@/app/components/snippets/hooks/use-create-snippet-from-selection'+import { canCreateAndModifySnippets } from '@/app/components/snippets/utils/permission'import { useCollaborativeWorkflow } from '@/app/components/workflow/hooks/use-collaborative-workflow'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useNodesInteractions, useNodesReadOnly, useNodesSyncDraft } from './hooks'import { useWorkflowHistory, WorkflowHistoryEvent } from './hooks/use-workflow-history'import { ShortcutKbd } from './shortcuts/shortcut-kbd'@@ -233,6 +235,7 @@ export function SelectionContextmenu({}) {const { t } = useTranslation()const { getNodesReadOnly } = useNodesReadOnly()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)const { handleNodesCopy, handleNodesDelete, handleNodesDuplicate } = useNodesInteractions()const isSelectionContextMenu = useStore(s => s.contextMenuTarget?.type === 'selection')@@ -256,7 +259,8 @@ export function SelectionContextmenu({selectedNodes,onClose,})- const canCreateSnippet = selectedNodes.every(node => !unsupportedSnippetNodeTypes.has(node.data.type))+ const canCreateSnippet = canCreateAndModifySnippets(workspacePermissionKeys)+ && selectedNodes.every(node => !unsupportedSnippetNodeTypes.has(node.data.type))const handleCopyNodes = useCallback(() => {handleNodesCopy()diff --git a/web/app/components/workflow/workflow-generator/apply.ts b/web/app/components/workflow/workflow-generator/apply.tsindex a4e77335512..c8946a41cec 100644--- a/web/app/components/workflow/workflow-generator/apply.ts+++ b/web/app/components/workflow/workflow-generator/apply.ts@@ -89,7 +89,7 @@ export const applyToNewApp = async ({instruction,appName,icon,-}: ApplyToNewAppParams): Promise<{ appId: string, appMode: AppModeEnum }> => {+}: ApplyToNewAppParams): Promise<{ appId: string, appMode: AppModeEnum, permissionKeys?: string[] }> => {const appMode = MODE_TO_APP_MODE[mode]const name = (appName ?? '').trim() || deriveAppName(instruction)const appIcon = (icon ?? '').trim() || '🤖'@@ -131,7 +131,7 @@ export const applyToNewApp = async ({throw syncErr}- return { appId: app.id, appMode }+ return { appId: app.id, appMode, permissionKeys: app.permission_keys }}type ApplyToCurrentAppParams = {diff --git a/web/app/components/workflow/workflow-generator/index.tsx b/web/app/components/workflow/workflow-generator/index.tsxindex e7824ae0d9b..102b6de08b7 100644--- a/web/app/components/workflow/workflow-generator/index.tsx+++ b/web/app/components/workflow/workflow-generator/index.tsx@@ -26,7 +26,6 @@ import { ModelTypeEnum } from '@/app/components/header/account-setting/model-proimport { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'import WorkflowPreview from '@/app/components/workflow/workflow-preview'-import { useAppContext } from '@/context/app-context'import { useRouter } from '@/next/navigation'import { generateWorkflow } from '@/service/debug'import { fetchWorkflowDraft } from '@/service/workflow'@@ -111,7 +110,6 @@ const RecoveryDialog = ({ open, onOpenChange, title, description, cancelLabel, cconst WorkflowGeneratorModal: React.FC = () => {const { t } = useTranslation('workflow')const router = useRouter()- const { isCurrentWorkspaceEditor } = useAppContext()const isOpen = useWorkflowGeneratorStore(s => s.isOpen)const mode = useWorkflowGeneratorStore(s => s.mode)@@ -356,7 +354,7 @@ const WorkflowGeneratorModal: React.FC = () => {returnsetApplyingTrue()try {- const { appId, appMode } = await applyToNewApp({+ const { appId, appMode, permissionKeys } = await applyToNewApp({mode,graph: current.graph as GeneratedGraph,instruction,@@ -365,7 +363,7 @@ const WorkflowGeneratorModal: React.FC = () => {})toast.success(t('workflowGenerator.applied'))closeGenerator()- router.push(getRedirectionPath(isCurrentWorkspaceEditor, { id: appId, mode: appMode }))+ router.push(getRedirectionPath({ id: appId, mode: appMode, permission_keys: permissionKeys }))}catch (e: unknown) {if (e instanceof WorkflowApplyOrphanError) {@@ -382,7 +380,7 @@ const WorkflowGeneratorModal: React.FC = () => {finally {setApplyingFalse()}- }, [current, instruction, mode, router, isCurrentWorkspaceEditor, closeGenerator, t, isApplying, setApplyingTrue, setApplyingFalse])+ }, [current, instruction, mode, router, closeGenerator, t, isApplying, setApplyingTrue, setApplyingFalse])const handleApplyToCurrentConfirmed = useCallback(async () => {if (!current?.graph || !currentAppId || isApplying)diff --git a/web/app/education-apply/education-apply-page.tsx b/web/app/education-apply/education-apply-page.tsxindex aaa2e66e6e7..61f232b5739 100644--- a/web/app/education-apply/education-apply-page.tsx+++ b/web/app/education-apply/education-apply-page.tsx@@ -27,6 +27,7 @@ import {useEducationAdd,useInvalidateEducationStatus,} from '@/service/use-education'+import { BillingPermission, hasPermission } from '@/utils/permission'import DifyLogo from '../components/base/logo/dify-logo'import AppliedEducationContent from './applied-education-content'import RoleSelector from './role-selector'@@ -52,7 +53,7 @@ const EducationApplyAgeContent = () => {mutateAsync: educationAdd,} = useEducationAdd({ onSuccess: noop })const { onPlanInfoChanged, isEducationAccount, plan } = useProviderContext()- const { currentWorkspace, isCurrentWorkspaceManager } = useAppContext()+ const { currentWorkspace, workspacePermissionKeys } = useAppContext()const updateEducationStatus = useInvalidateEducationStatus()const docLink = useDocLink()const { handleEducationDiscount } = useEducationDiscount()@@ -64,8 +65,9 @@ const EducationApplyAgeContent = () => {const searchParams = useSearchParams()const token = searchParams.get('token')+ const canManageBilling = hasPermission(workspacePermissionKeys, BillingPermission.Manage)const appliedEducationCase = (() => {- if (!isCurrentWorkspaceManager)+ if (!canManageBilling)return AppliedEducationCase.noPaymentPermissionif (plan.type === Plan.sandbox)diff --git a/web/context/__tests__/app-context-provider.spec.tsx b/web/context/__tests__/app-context-provider.spec.tsxnew file mode 100644index 00000000000..0e55cd8459e--- /dev/null+++ b/web/context/__tests__/app-context-provider.spec.tsx@@ -0,0 +1,179 @@+import { render, screen } from '@testing-library/react'+import { useAppContext, useSelector } from '../app-context'+import { AppContextProvider } from '../app-context-provider'++const mockInvalidateQueries = vi.hoisted(() => vi.fn())+const mockPermissionKeysState = vi.hoisted(() => ({+ isPending: false,+ permissionKeys: ['app.create_and_management'],+}))+const mockCurrentWorkspaceResponse = vi.hoisted(() => ({+ id: 'workspace-1',+ name: 'Workspace',+ plan: 'sandbox',+ status: 'normal',+ created_at: 1704067200,+ role: 'editor',+ trial_credits: 200,+ trial_credits_used: 0,+ next_credit_reset_date: 1706745600,+ custom_config: {},+}))++vi.mock('@tanstack/react-query', () => ({+ useQueryClient: () => ({+ invalidateQueries: mockInvalidateQueries,+ }),+ useSuspenseQuery: (options: { queryKey?: readonly unknown[] }) => {+ if (options.queryKey?.[0] === 'system-features') {+ return {+ data: {+ branding: {+ enabled: false,+ },+ },+ }+ }++ return {+ data: {+ profile: {+ id: 'user-1',+ name: 'User',+ email: '[email protected]',+ avatar: '',+ avatar_url: '',+ is_password_set: true,+ },+ meta: {+ currentVersion: '1.0.0',+ currentEnv: 'cloud',+ },+ },+ }+ },+ useQuery: (options: { select?: (workspace: typeof mockCurrentWorkspaceResponse) => unknown }) => ({+ data: options.select ? options.select(mockCurrentWorkspaceResponse) : mockCurrentWorkspaceResponse,+ isFetching: false,+ isPending: false,+ }),+}))++vi.mock('@/features/system-features/client', () => ({+ systemFeaturesQueryOptions: () => ({+ queryKey: ['system-features'],+ }),+}))++vi.mock('@/features/account-profile/client', () => ({+ userProfileQueryOptions: () => ({+ queryKey: ['user-profile'],+ }),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ workspaces: {+ current: {+ post: {+ key: () => ['current-workspace'],+ queryOptions: (options: Record<string, unknown>) => ({+ queryKey: ['current-workspace'],+ ...options,+ }),+ },+ },+ },+ },+}))++vi.mock('@/service/access-control/use-permission-keys', () => ({+ useWorkspacePermissionKeys: () => ({+ data: {+ workspace: {+ permission_keys: mockPermissionKeysState.permissionKeys,+ },+ app: {+ default_permission_keys: [],+ overrides: [],+ },+ dataset: {+ default_permission_keys: [],+ overrides: [],+ },+ },+ isPending: mockPermissionKeysState.isPending,+ }),+}))++vi.mock('@/service/use-common', () => ({+ useLangGeniusVersion: () => ({+ data: {+ version: '1.0.1',+ release_date: '',+ release_notes: '',+ can_auto_update: false,+ },+ }),+}))++vi.mock('@/app/components/base/amplitude', () => ({+ setUserId: vi.fn(),+ setUserProperties: vi.fn(),+}))++vi.mock('@/app/components/base/amplitude/registration-tracking', () => ({+ flushRegistrationSuccess: vi.fn(),+}))++vi.mock('@/app/components/base/zendesk/utils', () => ({+ setZendeskConversationFields: vi.fn(),+}))++vi.mock('@/app/components/header/maintenance-notice', () => ({+ default: () => null,+}))++function AppContextProbe() {+ const context = useAppContext()+ const selectedWorkspacePermissionKeys = useSelector(state => state.workspacePermissionKeys)++ return (+ <>+ <span>+ keys:+ {selectedWorkspacePermissionKeys.join(',')}+ </span>+ <span>+ loading:+ {String(context.isLoadingWorkspacePermissionKeys)}+ </span>+ <span>+ role:+ {context.currentWorkspace.role}+ </span>+ </>+ )+}++describe('AppContextProvider', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockPermissionKeysState.isPending = false+ mockPermissionKeysState.permissionKeys = ['app.create_and_management']+ })++ describe('Workspace Permission Keys', () => {+ it('should provide current workspace permission keys from my-permissions', () => {+ render(+ <AppContextProvider>+ <AppContextProbe />+ </AppContextProvider>,+ )++ expect(screen.getByText('keys:app.create_and_management')).toBeInTheDocument()+ expect(screen.getByText('loading:false')).toBeInTheDocument()+ expect(screen.getByText('role:editor')).toBeInTheDocument()+ })+ })+})diff --git a/web/context/app-context-provider.tsx b/web/context/app-context-provider.tsxindex d974ad916bc..2091f0818c2 100644--- a/web/context/app-context-provider.tsx+++ b/web/context/app-context-provider.tsx@@ -21,6 +21,7 @@ import {import { env } from '@/env'import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'+import { useWorkspacePermissionKeys } from '@/service/access-control/use-permission-keys'import { consoleQuery } from '@/service/client'import {useLangGeniusVersion,@@ -31,6 +32,7 @@ type AppContextProviderProps = {}const workspaceRoles = new Set<ICurrentWorkspace['role']>(['owner', 'admin', 'editor', 'dataset_operator', 'normal'])+const emptyWorkspacePermissionKeys: string[] = []const resolveWorkspaceRole = (role: PostWorkspacesCurrentResponse['role']): ICurrentWorkspace['role'] => {if (role && workspaceRoles.has(role as ICurrentWorkspace['role']))@@ -71,6 +73,7 @@ export const AppContextProvider: FC<AppContextProviderProps> = ({ children }) =>const currentWorkspaceQuery = useQuery(consoleQuery.workspaces.current.post.queryOptions({select: normalizeCurrentWorkspace,}))+ const workspacePermissionKeysQuery = useWorkspacePermissionKeys()const langGeniusVersionQuery = useLangGeniusVersion(userProfileResp?.meta.currentVersion,!systemFeatures.branding.enabled,@@ -184,7 +187,9 @@ export const AppContextProvider: FC<AppContextProviderProps> = ({ children }) =>isCurrentWorkspaceDatasetOperator,mutateCurrentWorkspace,isLoadingCurrentWorkspace: currentWorkspaceQuery.isPending,+ isLoadingWorkspacePermissionKeys: workspacePermissionKeysQuery.isPending,isValidatingCurrentWorkspace: currentWorkspaceQuery.isFetching,+ workspacePermissionKeys: workspacePermissionKeysQuery.data?.workspace.permission_keys ?? emptyWorkspacePermissionKeys,}}><div className="flex h-full flex-col overflow-hidden">diff --git a/web/context/app-context.ts b/web/context/app-context.tsindex 50df95e71ef..5b8fcf22e69 100644--- a/web/context/app-context.ts+++ b/web/context/app-context.ts@@ -17,7 +17,9 @@ export type AppContextValue = {langGeniusVersionInfo: LangGeniusVersionResponseuseSelector: typeof useSelectorisLoadingCurrentWorkspace: boolean+ isLoadingWorkspacePermissionKeys?: booleanisValidatingCurrentWorkspace: boolean+ workspacePermissionKeys: string[]}export const userProfilePlaceholder = {@@ -64,7 +66,9 @@ export const AppContext = createContext<AppContextValue>({langGeniusVersionInfo: initialLangGeniusVersionInfo,useSelector,isLoadingCurrentWorkspace: false,+ isLoadingWorkspacePermissionKeys: false,isValidatingCurrentWorkspace: false,+ workspacePermissionKeys: [],})export function useSelector<T>(selector: (value: AppContextValue) => T): T {diff --git a/web/context/debug-configuration.ts b/web/context/debug-configuration.tsindex 48e34fbe5ee..a5f80f06840 100644--- a/web/context/debug-configuration.ts+++ b/web/context/debug-configuration.ts@@ -30,6 +30,7 @@ import { AppModeEnum, ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod }type IDebugConfiguration = {readonly?: boolean+ canTestAndRun?: booleanappId: stringisAPIKeySet: booleanisTrailFinished: boolean@@ -110,6 +111,7 @@ type IDebugConfiguration = {const DebugConfigurationContext = createContext<IDebugConfiguration>({readonly: false,+ canTestAndRun: false,appId: '',isAPIKeySet: false,isTrailFinished: false,diff --git a/web/context/external-knowledge-api-context.tsx b/web/context/external-knowledge-api-context.tsxindex 64f23a3085a..854aab47660 100644--- a/web/context/external-knowledge-api-context.tsx+++ b/web/context/external-knowledge-api-context.tsx@@ -15,14 +15,18 @@ const ExternalKnowledgeApiContext = createContext<ExternalKnowledgeApiContextTyptype ExternalKnowledgeApiProviderProps = {children: ReactNode+ enabled?: boolean}-export const ExternalKnowledgeApiProvider: FC<ExternalKnowledgeApiProviderProps> = ({ children }) => {- const { data, refetch, isLoading } = useExternalKnowledgeApiList()+export const ExternalKnowledgeApiProvider: FC<ExternalKnowledgeApiProviderProps> = ({ children, enabled = true }) => {+ const { data, refetch, isLoading } = useExternalKnowledgeApiList({ enabled })const mutateExternalKnowledgeApis = useCallback(() => {+ if (!enabled)+ return Promise.resolve(undefined)+return refetch().then(res => res.data)- }, [refetch])+ }, [enabled, refetch])const contextValue = useMemo<ExternalKnowledgeApiContextType>(() => ({externalKnowledgeApiList: data?.data || [],diff --git a/web/context/web-app-context.tsx b/web/context/web-app-context.tsxindex 2adaf16f593..e04e0b5dc27 100644--- a/web/context/web-app-context.tsx+++ b/web/context/web-app-context.tsx@@ -55,8 +55,13 @@ export const useWebAppStore = create<WebAppStore>(set => ({const getShareCodeFromRedirectUrl = (redirectUrl: string | null): string | null => {if (!redirectUrl || redirectUrl.length === 0)return null- const url = new URL(`${window.location.origin}${decodeURIComponent(redirectUrl)}`)- return url.pathname.split('/').pop() || null+ try {+ const url = new URL(decodeURIComponent(redirectUrl), 'https://dify.local')+ return url.pathname.split('/').pop() || null+ }+ catch {+ return null+ }}const getShareCodeFromPathname = (pathname: string): string | null => {const code = pathname.split('/').pop() || nulldiff --git a/web/contract/console/access-control.ts b/web/contract/console/access-control.tsnew file mode 100644index 00000000000..d1fb8306ae2--- /dev/null+++ b/web/contract/console/access-control.ts@@ -0,0 +1,182 @@+import type { AccessControlTemplateLanguage } from '@/i18n-config/language'+import type {+ GetAccessPolicyDetailResponse,+ GetAppAccessPolicyByAppIdResponse,+ GetAppUserAccessSettingsResponse,+ GetDatasetAccessPolicyByDatasetIdResponse,+ GetDatasetUserAccessSettingsResponse,+ ResourceOpenScope,+} from '@/models/access-control'+import { type } from '@orpc/contract'+import { base } from '../base'++const appAccessRulesContract = base+ .route({+ path: '/workspaces/current/rbac/apps/{appId}/access-policy',+ method: 'GET',+ })+ .input(type<{+ params: {+ appId: string+ }+ query: {+ language: AccessControlTemplateLanguage+ }+ }>())+ .output(type<GetAppAccessPolicyByAppIdResponse>())++const appUserAccessSettingsContract = base+ .route({+ path: '/workspaces/current/rbac/apps/{appId}/user-access-policies',+ method: 'GET',+ })+ .input(type<{+ params: {+ appId: string+ }+ query: {+ language: AccessControlTemplateLanguage+ }+ }>())+ .output(type<GetAppUserAccessSettingsResponse>())++const updateAppUserAccessSettingsContract = base+ .route({+ path: '/workspaces/current/rbac/apps/{appId}/users/{accountId}/access-policies',+ method: 'PUT',+ })+ .input(type<{+ params: {+ appId: string+ accountId: string+ }+ body: {+ access_policy_ids: string[]+ }+ }>())+ .output(type<GetAccessPolicyDetailResponse>())++const removeAppAccessPolicyMemberBindingsContract = base+ .route({+ path: '/workspaces/current/rbac/apps/{appId}/access-policies/{policyId}/member-bindings',+ method: 'DELETE',+ })+ .input(type<{+ params: {+ appId: string+ policyId: string+ }+ body: {+ account_ids: string[]+ }+ }>())+ .output(type<unknown>())++const updateAppOpenScopeContract = base+ .route({+ path: '/workspaces/current/rbac/apps/{appId}/whitelist',+ method: 'PUT',+ })+ .input(type<{+ params: {+ appId: string+ }+ body: {+ scope: ResourceOpenScope+ }+ }>())+ .output(type<unknown>())++const datasetAccessRulesContract = base+ .route({+ path: '/workspaces/current/rbac/datasets/{datasetId}/access-policy',+ method: 'GET',+ })+ .input(type<{+ params: {+ datasetId: string+ }+ query: {+ language: AccessControlTemplateLanguage+ }+ }>())+ .output(type<GetDatasetAccessPolicyByDatasetIdResponse>())++const datasetUserAccessSettingsContract = base+ .route({+ path: '/workspaces/current/rbac/datasets/{datasetId}/user-access-policies',+ method: 'GET',+ })+ .input(type<{+ params: {+ datasetId: string+ }+ query: {+ language: AccessControlTemplateLanguage+ }+ }>())+ .output(type<GetDatasetUserAccessSettingsResponse>())++const updateDatasetUserAccessSettingsContract = base+ .route({+ path: '/workspaces/current/rbac/datasets/{datasetId}/users/{accountId}/access-policies',+ method: 'PUT',+ })+ .input(type<{+ params: {+ datasetId: string+ accountId: string+ }+ body: {+ access_policy_ids: string[]+ }+ }>())+ .output(type<GetAccessPolicyDetailResponse>())++const removeDatasetAccessPolicyMemberBindingsContract = base+ .route({+ path: '/workspaces/current/rbac/datasets/{datasetId}/access-policies/{policyId}/member-bindings',+ method: 'DELETE',+ })+ .input(type<{+ params: {+ datasetId: string+ policyId: string+ }+ body: {+ account_ids: string[]+ }+ }>())+ .output(type<unknown>())++const updateDatasetOpenScopeContract = base+ .route({+ path: '/workspaces/current/rbac/datasets/{datasetId}/whitelist',+ method: 'PUT',+ })+ .input(type<{+ params: {+ datasetId: string+ }+ body: {+ scope: ResourceOpenScope+ }+ }>())+ .output(type<unknown>())++export const rbacAccessConfigContract = {+ apps: {+ accessRules: appAccessRulesContract,+ userAccessSettings: appUserAccessSettingsContract,+ updateUserAccessSettings: updateAppUserAccessSettingsContract,+ removeMemberBindings: removeAppAccessPolicyMemberBindingsContract,+ updateOpenScope: updateAppOpenScopeContract,+ },+ datasets: {+ accessRules: datasetAccessRulesContract,+ userAccessSettings: datasetUserAccessSettingsContract,+ updateUserAccessSettings: updateDatasetUserAccessSettingsContract,+ removeMemberBindings: removeDatasetAccessPolicyMemberBindingsContract,+ updateOpenScope: updateDatasetOpenScopeContract,+ },+}diff --git a/web/contract/router.ts b/web/contract/router.tsindex 662857332ca..2f9b5de318d 100644--- a/web/contract/router.ts+++ b/web/contract/router.ts@@ -1,6 +1,7 @@import type { InferContractRouterInputs } from '@orpc/contract'import { contract as communityContract } from '@dify/contracts/api/console/orpc.gen'import { contract as enterpriseContract } from '@dify/contracts/enterprise/orpc.gen'+import { rbacAccessConfigContract } from './console/access-control'import {appDeleteContract,appListContract,@@ -152,6 +153,7 @@ export const consoleRouterContract = {checkInstalled: pluginCheckInstalledContract,latestVersions: pluginLatestVersionsContract,},+ rbacAccessConfig: rbacAccessConfigContract,snippets: {list: listCustomizedSnippetsContract,create: createCustomizedSnippetContract,diff --git a/web/eslint.constants.mjs b/web/eslint.constants.mjsindex 3a7b858ef90..b6180b932c6 100644--- a/web/eslint.constants.mjs+++ b/web/eslint.constants.mjs@@ -1,6 +1,7 @@export const GENERATED_IGNORES = ['storybook-static/','.next/',+ '.vinext/','next/','next-env.d.ts','dist/',diff --git a/web/features/system-features/config.ts b/web/features/system-features/config.tsindex 1161ac64184..1b0c88a9ea2 100644--- a/web/features/system-features/config.ts+++ b/web/features/system-features/config.ts@@ -48,6 +48,7 @@ export const defaultSystemFeatures = {plugin_manager: {enabled: false,},+ rbac_enabled: false,enable_creators_platform: false,enable_trial_app: false,enable_explore_banner: false,diff --git a/web/features/tag-management/__tests__/dataset-card-tags.spec.tsx b/web/features/tag-management/__tests__/dataset-card-tags.spec.tsxindex 59c26c64cd0..8b3cec572df 100644--- a/web/features/tag-management/__tests__/dataset-card-tags.spec.tsx+++ b/web/features/tag-management/__tests__/dataset-card-tags.spec.tsx@@ -3,23 +3,29 @@ import { fireEvent, render, screen } from '@testing-library/react'import { describe, expect, it, vi } from 'vitest'import { DatasetCardTags } from '../components/dataset-card-tags'+const renderTagSelector = vi.hoisted(() => vi.fn())+vi.mock('@/features/tag-management/components/tag-selector', () => ({- TagSelector: ({ value, onOpenTagManagement }: {+ TagSelector: (props: {value: Tag[]onOpenTagManagement?: () => void- }) => (- <div role="group" aria-label="Tag selector mock">- <div>{value.map(tag => tag.id).join(',')}</div>- <div>- {value.length}- {' '}- tags+ canBindOrUnbindTags?: boolean+ }) => {+ renderTagSelector(props)+ return (+ <div role="group" aria-label="Tag selector mock">+ <div>{props.value.map(tag => tag.id).join(',')}</div>+ <div>+ {props.value.length}+ {' '}+ tags+ </div>+ <button onClick={props.onOpenTagManagement}>+ Open Management+ </button></div>- <button onClick={onOpenTagManagement}>- Open Management- </button>- </div>- ),+ )+ },}))describe('DatasetCardTags', () => {@@ -62,6 +68,14 @@ describe('DatasetCardTags', () => {expect(screen.getByRole('group', { name: 'Tag selector mock' })).toBeInTheDocument()})+ it('should pass tag binding permission to TagSelector', () => {+ render(<DatasetCardTags {...defaultProps} canBindOrUnbindTags={true} />)++ expect(renderTagSelector).toHaveBeenCalledWith(expect.objectContaining({+ canBindOrUnbindTags: true,+ }))+ })+it('should render with empty tags', () => {render(<DatasetCardTags {...defaultProps} tags={[]} />)expect(screen.getByText('0 tags')).toBeInTheDocument()diff --git a/web/features/tag-management/__tests__/tag-filter.spec.tsx b/web/features/tag-management/__tests__/tag-filter.spec.tsxindex 9d6f8088e36..8660f412b1e 100644--- a/web/features/tag-management/__tests__/tag-filter.spec.tsx+++ b/web/features/tag-management/__tests__/tag-filter.spec.tsx@@ -7,10 +7,20 @@ const { mockUseQueryData } = vi.hoisted(() => ({mockUseQueryData: { current: [] as Tag[] },}))+const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['app.tag.manage', 'dataset.tag.manage'] as string[],+}))+vi.mock('@tanstack/react-query', () => ({useQuery: () => ({ data: mockUseQueryData.current }),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))+const mockTags: Tag[] = [{ id: 'tag-1', name: 'Frontend', type: 'app', binding_count: 3 },{ id: 'tag-2', name: 'Backend', type: 'app', binding_count: 5 },@@ -37,6 +47,7 @@ describe('TagFilter', () => {beforeEach(() => {vi.clearAllMocks()mockUseQueryData.current = mockTags+ mockWorkspacePermissionKeys.value = ['app.tag.manage', 'dataset.tag.manage']})describe('Rendering', () => {@@ -204,6 +215,18 @@ describe('TagFilter', () => {expect(onOpenTagManagement).toHaveBeenCalledTimes(1)})++ it('should hide tag management action without tag management permission', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys.value = []++ render(<TagFilter {...defaultProps} />)++ await user.click(screen.getByText(i18n.placeholder))++ expect(screen.queryByRole('button', { name: i18n.manageTags })).not.toBeInTheDocument()+ expect(screen.getByRole('option', { name: /Frontend/i })).toBeInTheDocument()+ })})describe('Search', () => {diff --git a/web/features/tag-management/__tests__/tag-management-modal.spec.tsx b/web/features/tag-management/__tests__/tag-management-modal.spec.tsxindex d9afcca54f7..01c58082401 100644--- a/web/features/tag-management/__tests__/tag-management-modal.spec.tsx+++ b/web/features/tag-management/__tests__/tag-management-modal.spec.tsx@@ -28,6 +28,10 @@ const { mockUseQueryData, createTag } = vi.hoisted(() => ({createTag: vi.fn(),}))+const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['app.tag.manage', 'dataset.tag.manage', 'snippets.management'] as string[],+}))+vi.mock('@tanstack/react-query', () => ({useQuery: () => ({ data: mockUseQueryData.current }),useMutation: (mutationOptions: { mutationFn: (input: unknown) => Promise<unknown> }) => ({@@ -40,6 +44,12 @@ vi.mock('@tanstack/react-query', () => ({}),}))+vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))+vi.mock('@/service/client', () => ({consoleQuery: {tags: {@@ -89,6 +99,7 @@ describe('TagManagementModal', () => {beforeEach(() => {vi.clearAllMocks()mockUseQueryData.current = mockTags+ mockWorkspacePermissionKeys.value = ['app.tag.manage', 'dataset.tag.manage', 'snippets.management']vi.mocked(createTag).mockResolvedValue({ id: 'new-tag', name: 'NewTag', type: 'app', binding_count: 0 })})@@ -133,6 +144,15 @@ describe('TagManagementModal', () => {// The Modal component hides content when isShow is falseexpect(screen.queryByText(i18n.manageTags)).not.toBeInTheDocument()})++ it('should not render content without tag management permission', () => {+ mockWorkspacePermissionKeys.value = []++ render(<TagManagementModal {...defaultProps} />)++ expect(screen.queryByText(i18n.manageTags)).not.toBeInTheDocument()+ expect(screen.queryByRole('textbox', { name: i18n.addNew })).not.toBeInTheDocument()+ })})describe('User Interactions', () => {diff --git a/web/features/tag-management/__tests__/tag-search-content.spec.tsx b/web/features/tag-management/__tests__/tag-search-content.spec.tsxindex 30b3cef8ad6..45aa3054c4e 100644--- a/web/features/tag-management/__tests__/tag-search-content.spec.tsx+++ b/web/features/tag-management/__tests__/tag-search-content.spec.tsx@@ -11,6 +11,16 @@ const { onValueChangeSpy } = vi.hoisted(() => ({onValueChangeSpy: vi.fn(),}))+const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['app.tag.manage', 'dataset.tag.manage'] as string[],+}))++vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (state: { workspacePermissionKeys: string[] }) => unknown) => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))+const i18n = {selectorPlaceholder: 'common.tag.selectorPlaceholder',operationClear: 'common.operation.clear',@@ -91,6 +101,7 @@ const PanelHarness = ({describe('TagSearchContent', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys.value = ['app.tag.manage', 'dataset.tag.manage']})it('renders search, selected tags, unselected tags, and management action', () => {@@ -191,8 +202,31 @@ describe('TagSearchContent', () => {expect(onOpenTagManagement).toHaveBeenCalledTimes(1)})+ it('hides tag management action without tag management permission', () => {+ mockWorkspacePermissionKeys.value = []++ render(<PanelHarness />)++ expect(screen.queryByRole('button', { name: i18n.manageTags })).not.toBeInTheDocument()+ expect(screen.getByRole('option', { name: /Frontend/i })).toBeInTheDocument()+ })+it('renders knowledge tags when the panel type is knowledge', () => {render(<PanelHarness type="knowledge" value={[]} />)expect(screen.getByRole('option', { name: /KnowledgeDB/i })).toBeInTheDocument()})++ it('renders snippet management action with snippets management permission', () => {+ mockWorkspacePermissionKeys.value = ['snippets.management']++ render(+ <PanelHarness+ type="snippet"+ value={[]}+ tagList={[{ id: 'snippet-tag-1', name: 'Reusable', type: 'snippet', binding_count: 1 }]}+ />,+ )++ expect(screen.getByRole('button', { name: i18n.manageTags })).toBeInTheDocument()+ })})diff --git a/web/features/tag-management/__tests__/tag-selector.spec.tsx b/web/features/tag-management/__tests__/tag-selector.spec.tsxindex f33470825bc..190425b83df 100644--- a/web/features/tag-management/__tests__/tag-selector.spec.tsx+++ b/web/features/tag-management/__tests__/tag-selector.spec.tsx@@ -29,6 +29,16 @@ const { mockUseQueryData, createTag, bindTag, unBindTag } = vi.hoisted(() => {}})+const mockWorkspacePermissionKeys = vi.hoisted(() => ({+ value: ['app.tag.manage', 'dataset.tag.manage', 'snippets.management'] as string[],+}))++vi.mock('@/context/app-context', () => ({+ useSelector: <T,>(selector: (state: { workspacePermissionKeys: string[] }) => T): T => selector({+ workspacePermissionKeys: mockWorkspacePermissionKeys.value,+ }),+}))+vi.mock('@tanstack/react-query', () => ({useQuery: () => ({ data: mockUseQueryData.current }),useMutation: (mutationOptions: { mutationFn: (input: unknown) => Promise<unknown> }) => ({@@ -100,6 +110,7 @@ const defaultProps = {describe('TagSelector', () => {beforeEach(() => {vi.clearAllMocks()+ mockWorkspacePermissionKeys.value = ['app.tag.manage', 'dataset.tag.manage', 'snippets.management']mockUseQueryData.current = appTagsvi.mocked(createTag).mockResolvedValue({ id: 'new-tag', name: 'NewTag', type: 'app', binding_count: 0 })vi.mocked(bindTag).mockResolvedValue(undefined)@@ -240,4 +251,58 @@ describe('TagSelector', () => {})expect(bindTag).not.toHaveBeenCalled()})++ it('does not open the tag selector when neither tag management nor binding capability is available', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys.value = []++ render(<TagSelector {...defaultProps} />)++ await user.click(screen.getByRole('combobox', { name: /Frontend/i }))++ expect(screen.queryByRole('combobox', { name: i18n.selectorPlaceholder })).not.toBeInTheDocument()+ })++ it('opens the tag selector with binding capability even without workspace tag management permission', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys.value = []++ render(<TagSelector {...defaultProps} canBindOrUnbindTags />)++ await user.click(screen.getByRole('combobox', { name: /Frontend/i }))++ expect(await screen.findByRole('combobox', { name: i18n.selectorPlaceholder })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: i18n.manageTags })).not.toBeInTheDocument()+ })++ it('does not create new tags when only binding capability is available', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys.value = []++ render(<TagSelector {...defaultProps} canBindOrUnbindTags />)++ await user.click(screen.getByRole('combobox', { name: /Frontend/i }))+ await user.type(await screen.findByRole('combobox', { name: i18n.selectorPlaceholder }), 'BrandNewTag')++ expect(screen.queryByRole('option', { name: /BrandNewTag/i })).not.toBeInTheDocument()+ expect(createTag).not.toHaveBeenCalled()+ })++ it('opens snippet tag selector with snippets management permission', async () => {+ const user = userEvent.setup()+ mockWorkspacePermissionKeys.value = ['snippets.management']+ mockUseQueryData.current = [{ id: 'snippet-tag-1', name: 'Reusable', type: 'snippet', binding_count: 1 }]++ render(+ <TagSelector+ targetId="snippet-1"+ type="snippet"+ value={[{ id: 'snippet-tag-1', name: 'Reusable', type: 'snippet', binding_count: 1 }]}+ />,+ )++ await user.click(screen.getByRole('combobox', { name: /Reusable/i }))++ expect(await screen.findByRole('combobox', { name: i18n.selectorPlaceholder })).toBeInTheDocument()+ })})diff --git a/web/features/tag-management/components/__tests__/app-card-tags.spec.tsx b/web/features/tag-management/components/__tests__/app-card-tags.spec.tsxindex d34224f2948..dd9ba09a88c 100644--- a/web/features/tag-management/components/__tests__/app-card-tags.spec.tsx+++ b/web/features/tag-management/components/__tests__/app-card-tags.spec.tsx@@ -13,6 +13,7 @@ vi.mock('@/features/tag-management/components/tag-selector', () => ({targetId: stringtype: stringvalue: Tag[]+ canBindOrUnbindTags?: boolean}) => {renderTagSelector(props)@@ -47,6 +48,7 @@ describe('AppCardTags', () => {targetId: 'app-1',type: 'app',value: tags,+ canBindOrUnbindTags: undefined,}))})@@ -91,5 +93,13 @@ describe('AppCardTags', () => {value: [],}))})++ it('should forward app ACL tag binding capability', () => {+ render(<AppCardTags appId="app-1" tags={tags} canBindOrUnbindTags={false} />)++ expect(renderTagSelector).toHaveBeenCalledWith(expect.objectContaining({+ canBindOrUnbindTags: false,+ }))+ })})})diff --git a/web/features/tag-management/components/app-card-tags.tsx b/web/features/tag-management/components/app-card-tags.tsxindex 44b65bb8342..67a3ca81d83 100644--- a/web/features/tag-management/components/app-card-tags.tsx+++ b/web/features/tag-management/components/app-card-tags.tsx@@ -4,6 +4,7 @@ import { TagSelector } from '@/features/tag-management/components/tag-selector'type AppCardTagsProps = {appId: stringtags: Tag[]+ canBindOrUnbindTags?: booleanonOpenTagManagement?: () => voidonTagsChange?: () => void}@@ -11,6 +12,7 @@ type AppCardTagsProps = {export const AppCardTags = ({appId,tags,+ canBindOrUnbindTags,onOpenTagManagement = () => {},onTagsChange,}: AppCardTagsProps) => {@@ -21,6 +23,7 @@ export const AppCardTags = ({type="app"targetId={appId}value={tags}+ canBindOrUnbindTags={canBindOrUnbindTags}onOpenTagManagement={onOpenTagManagement}onTagsChange={onTagsChange}/>diff --git a/web/features/tag-management/components/dataset-card-tags.tsx b/web/features/tag-management/components/dataset-card-tags.tsxindex 53e605389c5..c33382b36bc 100644--- a/web/features/tag-management/components/dataset-card-tags.tsx+++ b/web/features/tag-management/components/dataset-card-tags.tsx@@ -10,6 +10,7 @@ type DatasetCardTagsProps = {onClick: (e: MouseEvent) => voidonOpenTagManagement?: () => voidonTagsChange?: () => void+ canBindOrUnbindTags?: boolean}export const DatasetCardTags = ({@@ -19,6 +20,7 @@ export const DatasetCardTags = ({onClick,onOpenTagManagement = () => {},onTagsChange,+ canBindOrUnbindTags,}: DatasetCardTagsProps) => (<divclassName={cn('group/tag-area w-full px-3', !embeddingAvailable && 'opacity-30')}@@ -32,6 +34,10 @@ export const DatasetCardTags = ({value={tags}onOpenTagManagement={onOpenTagManagement}onTagsChange={onTagsChange}+ canBindOrUnbindTags={canBindOrUnbindTags}+ />+ <div+ className="pointer-events-none absolute top-0 right-0 h-full w-20 bg-tag-selector-mask-bg group-focus-within/tag-area:hidden group-hover/tag-area:hidden"/><divclassName="pointer-events-none absolute top-0 right-0 h-full w-20 bg-tag-selector-mask-bg group-focus-within/tag-area:hidden group-hover/tag-area:hidden"diff --git a/web/features/tag-management/components/tag-management-modal.tsx b/web/features/tag-management/components/tag-management-modal.tsxindex 49d6b540d44..d21e26bca54 100644--- a/web/features/tag-management/components/tag-management-modal.tsx+++ b/web/features/tag-management/components/tag-management-modal.tsx@@ -5,7 +5,10 @@ import { toast } from '@langgenius/dify-ui/toast'import { useMutation, useQuery } from '@tanstack/react-query'import { useState } from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { consoleQuery } from '@/service/client'+import { hasPermission } from '@/utils/permission'+import { getTagManagePermissionKey } from '../utils'import { TagItemEditor } from './tag-item-editor'type TagManagementModalProps = {@@ -16,18 +19,22 @@ type TagManagementModalProps = {}export const TagManagementModal = ({ show, type, onClose, onTagsChange }: TagManagementModalProps) => {const { t } = useTranslation()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canManageTags = hasPermission(workspacePermissionKeys, getTagManagePermissionKey(type))const { data: tagList = [] } = useQuery(consoleQuery.tags.list.queryOptions({input: {query: {type,},},- enabled: show,+ enabled: show && canManageTags,}))const createTagMutation = useMutation(consoleQuery.tags.create.mutationOptions())const [name, setName] = useState<string>('')const createNewTag = () => {+ if (!canManageTags)+ returnif (!name)returnif (createTagMutation.isPending)@@ -53,6 +60,9 @@ export const TagManagementModal = ({ show, type, onClose, onTagsChange }: TagManonClose()}+ if (!canManageTags)+ return null+return (<Dialog open={show} onOpenChange={open => !open && handleClose()}><DialogContent className="w-150 max-w-150 rounded-xl p-8">diff --git a/web/features/tag-management/components/tag-search-content.tsx b/web/features/tag-management/components/tag-search-content.tsxindex 9811fca568e..ec7935acfe0 100644--- a/web/features/tag-management/components/tag-search-content.tsx+++ b/web/features/tag-management/components/tag-search-content.tsx@@ -3,6 +3,9 @@ import type { TagType } from '@/contract/console/tags'import { ComboboxEmpty, ComboboxInput, ComboboxInputGroup, ComboboxItem, ComboboxItemIndicator, ComboboxItemText, ComboboxList, ComboboxSeparator, useComboboxFilteredItems } from '@langgenius/dify-ui/combobox'import { Fragment } from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'+import { getTagManagePermissionKey } from '../utils'import { isCreateTagOption } from './tag-combobox-item'type TagSearchContentProps = {@@ -21,6 +24,8 @@ export const TagSearchContent = ({onClose,}: TagSearchContentProps) => {const { t } = useTranslation()+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canManageTags = hasPermission(workspacePermissionKeys, getTagManagePermissionKey(type))const filteredItems = useComboboxFilteredItems<TagComboboxItem>()const realItemCount = filteredItems.filter(tag => !isCreateTagOption(tag)).lengthconst placeholder = t('tag.selectorPlaceholder', { ns: 'common' }) || ''@@ -84,22 +89,26 @@ export const TagSearchContent = ({<div className="system-xs-regular text-text-tertiary">{t('tag.noTag', { ns: 'common' })}</div></div></ComboboxEmpty>- <ComboboxSeparator />- <div className="p-1">- <button- type="button"- className="flex w-full cursor-pointer touch-manipulation items-center gap-x-1 rounded-lg px-2 py-1.5 text-left outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"- onClick={() => {- onOpenTagManagement?.()- onClose?.()- }}- >- <span className="i-custom-vender-line-financeAndECommerce-tag-01 size-4 text-text-tertiary" aria-hidden="true" />- <span className="min-w-0 grow truncate px-1 system-md-regular text-text-secondary">- {t('tag.manageTags', { ns: 'common' })}- </span>- </button>- </div>+ {canManageTags && (+ <>+ <ComboboxSeparator />+ <div className="p-1">+ <button+ type="button"+ className="flex w-full cursor-pointer touch-manipulation items-center gap-x-1 rounded-lg px-2 py-1.5 text-left outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"+ onClick={() => {+ onOpenTagManagement?.()+ onClose?.()+ }}+ >+ <span className="i-custom-vender-line-financeAndECommerce-tag-01 size-4 text-text-tertiary" aria-hidden="true" />+ <span className="min-w-0 grow truncate px-1 system-md-regular text-text-secondary">+ {t('tag.manageTags', { ns: 'common' })}+ </span>+ </button>+ </div>+ </>+ )}</div>)}diff --git a/web/features/tag-management/components/tag-selector.tsx b/web/features/tag-management/components/tag-selector.tsxindex 999596a363b..fc6210c2732 100644--- a/web/features/tag-management/components/tag-selector.tsx+++ b/web/features/tag-management/components/tag-selector.tsx@@ -8,8 +8,11 @@ import { toast } from '@langgenius/dify-ui/toast'import { useMutation, useQuery } from '@tanstack/react-query'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { consoleQuery } from '@/service/client'+import { hasPermission } from '@/utils/permission'import { useApplyTagBindingsMutation } from '../hooks/use-tag-mutations'+import { getTagManagePermissionKey } from '../utils'import { isCreateTagOption } from './tag-combobox-item'import { TagSearchContent } from './tag-search-content'import { TagTrigger } from './tag-trigger'@@ -43,6 +46,7 @@ type TagSelectorProps = TagSelectorRootProps & TagSelectorContentProps & {targetId: stringtype: TagTypevalue: Tag[]+ canBindOrUnbindTags?: booleanonOpenTagManagement?: () => voidonTagsChange?: () => void}@@ -51,6 +55,7 @@ export const TagSelector = ({targetId,type,value,+ canBindOrUnbindTags,onOpenTagManagement = () => {},onTagsChange,placement = 'bottom-start',@@ -66,6 +71,9 @@ export const TagSelector = ({const [open, setOpen] = useState(false)const [draftTags, setDraftTags] = useState<Tag[]>(value)const [inputValue, setInputValue] = useState('')+ const workspacePermissionKeys = useAppContextWithSelector(state => state.workspacePermissionKeys)+ const canManageTags = hasPermission(workspacePermissionKeys, getTagManagePermissionKey(type))+const applyTagBindingsMutation = useApplyTagBindingsMutation()const {isPending: isCreatingTag,@@ -109,7 +117,7 @@ export const TagSelector = ({nextItems.push(tag)}- if (inputValue && nextItems.every(tag => tag.name !== inputValue)) {+ if (canManageTags && inputValue && nextItems.every(tag => tag.name !== inputValue)) {nextItems.push({id: `__create_tag__:${inputValue}`,name: inputValue,@@ -120,7 +128,7 @@ export const TagSelector = ({}return nextItems- }, [inputValue, tagList, type, value])+ }, [canManageTags, inputValue, tagList, type, value])const applyTagBindings = useCallback(() => {const draftTagIds = draftTags.map(tag => tag.id)@@ -167,7 +175,7 @@ export const TagSelector = ({}, [applyTagBindings, value])const createNewTag = useCallback((name: string) => {- if (!name || isCreatingTag)+ if (!canManageTags || !name || isCreatingTag)returncreateTag({@@ -184,7 +192,7 @@ export const TagSelector = ({toast.error(t('tag.failed', { ns: 'common' }))},})- }, [createTag, isCreatingTag, t, type])+ }, [canManageTags, createTag, isCreatingTag, t, type])const handleValueChange = useCallback((nextTags: TagComboboxItem[]) => {const createOption = nextTags.find(isCreateTagOption)@@ -212,6 +220,7 @@ export const TagSelector = ({isItemEqualToValue={isSameTag}><ComboboxTrigger+ disabled={!canManageTags && !canBindOrUnbindTags}aria-label={triggerLabel}className={cn('block h-auto w-full rounded-lg border-0 bg-transparent p-0 text-left hover:bg-transparent focus:outline-hidden focus-visible:bg-transparent focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-base-hover data-popup-open:hover:bg-state-base-hover',diff --git a/web/features/tag-management/utils.ts b/web/features/tag-management/utils.tsnew file mode 100644index 00000000000..bc88569ade9--- /dev/null+++ b/web/features/tag-management/utils.ts@@ -0,0 +1,13 @@+import type { TagType } from '@/contract/console/tags'+import type { PermissionKey } from '@/models/access-control'+import { SnippetPermission } from '@/app/components/snippets/utils/permission'++export const getTagManagePermissionKey = (type: TagType): PermissionKey => {+ if (type === 'app')+ return 'app.tag.manage'++ if (type === 'snippet')+ return SnippetPermission.Management++ return 'dataset.tag.manage'+}diff --git a/web/hooks/use-credential-permissions.ts b/web/hooks/use-credential-permissions.tsnew file mode 100644index 00000000000..5766e7282b9--- /dev/null+++ b/web/hooks/use-credential-permissions.ts@@ -0,0 +1,11 @@+import { useSelector as useAppContextSelector } from '@/context/app-context'+import { hasPermission } from '@/utils/permission'++export const useCredentialPermissions = () => {+ const workspacePermissionKeys = useAppContextSelector(state => state.workspacePermissionKeys)++ return {+ canUseCredential: hasPermission(workspacePermissionKeys, ['credential.use', 'credential.manage']),+ canManageCredential: hasPermission(workspacePermissionKeys, 'credential.manage'),+ }+}diff --git a/web/hooks/use-import-dsl.ts b/web/hooks/use-import-dsl.tsindex 7fdb0255976..387fb2c37df 100644--- a/web/hooks/use-import-dsl.ts+++ b/web/hooks/use-import-dsl.ts@@ -13,7 +13,6 @@ import {import { useTranslation } from 'react-i18next'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'-import { useSelector } from '@/context/app-context'import { DSLImportStatus } from '@/models/app'import { useRouter } from '@/next/navigation'import {@@ -42,7 +41,6 @@ export const useImportDSL = () => {const { t } = useTranslation()const [isFetching, setIsFetching] = useState(false)const { handleCheckPluginDependencies } = usePluginDependencies()- const isCurrentWorkspaceEditor = useSelector(s => s.isCurrentWorkspaceEditor)const { push } = useRouter()const invalidateAppList = useInvalidateAppList()const [versions, setVersions] = useState<{ importedVersion: string, systemVersion: string }>()@@ -74,6 +72,7 @@ export const useImportDSL = () => {app_mode,imported_dsl_version,current_dsl_version,+ permission_keys,} = responseif (status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS) {@@ -93,7 +92,7 @@ export const useImportDSL = () => {setNeedRefresh('1')invalidateAppList()await handleCheckPluginDependencies(app_id)- getRedirection(isCurrentWorkspaceEditor, { id: app_id, mode: app_mode }, push)+ getRedirection({ id: app_id, mode: app_mode, permission_keys }, push)}else if (status === DSLImportStatus.PENDING) {setVersions({@@ -115,7 +114,7 @@ export const useImportDSL = () => {finally {setIsFetching(false)}- }, [t, handleCheckPluginDependencies, isCurrentWorkspaceEditor, push, isFetching, setNeedRefresh, invalidateAppList])+ }, [isFetching, t, setNeedRefresh, handleCheckPluginDependencies, push, setNeedRefresh, invalidateAppList])const handleImportDSLConfirm = useCallback(async ({@@ -134,7 +133,7 @@ export const useImportDSL = () => {import_id: importIdRef.current,})- const { status, app_id, app_mode } = response+ const { status, app_id, app_mode, permission_keys } = responseif (!app_id)return@@ -144,7 +143,7 @@ export const useImportDSL = () => {await handleCheckPluginDependencies(app_id)setNeedRefresh('1')invalidateAppList()- getRedirection(isCurrentWorkspaceEditor, { id: app_id!, mode: app_mode }, push)+ getRedirection({ id: app_id, mode: app_mode, permission_keys }, push)}else if (status === DSLImportStatus.FAILED) {toast.error(t('newApp.appCreateFailed', { ns: 'app' }))@@ -158,7 +157,7 @@ export const useImportDSL = () => {finally {setIsFetching(false)}- }, [t, handleCheckPluginDependencies, isCurrentWorkspaceEditor, push, isFetching, setNeedRefresh, invalidateAppList])+ }, [isFetching, t, handleCheckPluginDependencies, setNeedRefresh, push, setNeedRefresh, invalidateAppList])return {handleImportDSL,diff --git a/web/i18n-config/language.ts b/web/i18n-config/language.tsindex 343a634abcd..f3b5062e3b2 100644--- a/web/i18n-config/language.ts+++ b/web/i18n-config/language.ts@@ -23,6 +23,14 @@ const DOC_LANGUAGE: Record<string, DocLanguage | undefined> = {'en-US': 'en',}+export type AccessControlTemplateLanguage = 'zh' | 'ja' | 'en'++const ACCESS_CONTROL_TEMPLATE_LANGUAGE: Record<string, AccessControlTemplateLanguage> = {+ 'zh-Hans': 'zh',+ 'ja-JP': 'ja',+ 'en-US': 'en',+}+export const localeMap: Record<Locale, string> = {'en-US': 'en','en_US': 'en',@@ -64,6 +72,10 @@ export const getPricingPageLanguage = (locale: string) => {return PRICING_PAGE_LANGUAGE[locale] || ''}+export const getAccessControlTemplateLanguage = (locale: string): AccessControlTemplateLanguage => {+ return ACCESS_CONTROL_TEMPLATE_LANGUAGE[locale] || 'en'+}+export const NOTICE_I18N = {title: {en_US: 'Important Notice',diff --git a/web/i18n-config/resources.ts b/web/i18n-config/resources.tsindex 4a3fa9a4eac..16c0ad39bee 100644--- a/web/i18n-config/resources.ts+++ b/web/i18n-config/resources.ts@@ -20,6 +20,8 @@ import type explore from '../i18n/en-US/explore.json'import type layout from '../i18n/en-US/layout.json'import type login from '../i18n/en-US/login.json'import type oauth from '../i18n/en-US/oauth.json'+import type permissionKeys from '../i18n/en-US/permission-keys.json'+import type permission from '../i18n/en-US/permission.json'import type pipeline from '../i18n/en-US/pipeline.json'import type pluginTags from '../i18n/en-US/plugin-tags.json'import type pluginTrigger from '../i18n/en-US/plugin-trigger.json'@@ -56,6 +58,8 @@ export type Resources = {layout: typeof layoutlogin: typeof loginoauth: typeof oauth+ permission: typeof permission+ permissionKeys: typeof permissionKeyspipeline: typeof pipelineplugin: typeof pluginpluginTags: typeof pluginTags@@ -92,6 +96,8 @@ export const namespaces = ['layout','login','oauth',+ 'permission',+ 'permissionKeys','pipeline','plugin','pluginTags',diff --git a/web/i18n/ar-TN/app.json b/web/i18n/ar-TN/app.jsonindex d02064948c6..3a295fe102a 100644--- a/web/i18n/ar-TN/app.json+++ b/web/i18n/ar-TN/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "المخرجات الهيكلية هي ميزة تضمن أن يولد النموذج دائمًا استجابات تلتزم بـ JSON Schema الذي قدمته","studio.allApps": "كل التطبيقات","studio.apps": "تطبيقات",- "studio.filters.allCreators": "جميع المبدعين",- "studio.filters.creators": "المبدعين",+ "studio.filters.allCreators": "جميع المنشئين",+ "studio.filters.creators": "المنشئون","studio.filters.reset": "إعادة تعيين","studio.filters.searchCreators": "بحث عن المبدع...","studio.filters.types": "أنواع",diff --git a/web/i18n/ar-TN/common.json b/web/i18n/ar-TN/common.jsonindex 5939821a64f..f28682d7171 100644--- a/web/i18n/ar-TN/common.json+++ b/web/i18n/ar-TN/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "تبديل مساحة العمل","mcpPage.description": "اتصل بخوادم MCP وأدرها لمنح تطبيقاتك إمكانية الوصول إلى الأدوات والخدمات الخارجية.",- "members.admin": "المسؤول","members.adminTip": "يمكنه بناء التطبيقات وإدارة إعدادات الفريق","members.alreadyInTeam": "موجود بالفعل في الفريق","members.alreadyInTeamTip": "هؤلاء المستخدمون لديهم بالفعل إمكانية الوصول إلى مساحة العمل هذه.","members.builder": "باني","members.builderTip": "يمكنه بناء وتعديل تطبيقاته الخاصة",- "members.datasetOperator": "مسؤول المعرفة","members.datasetOperatorTip": "يمكنه إدارة قاعدة المعرفة فقط","members.deleteMember": "حذف العضو","members.disInvite": "إلغاء الدعوة",- "members.editor": "محرر","members.editorTip": "يمكنه بناء وتعديل التطبيقات","members.email": "البريد الإلكتروني","members.emailInvalid": "تنسيق البريد الإلكتروني غير صالح",@@ -272,14 +269,12 @@"members.invite": "إضافة","members.inviteTeamMember": "إضافة عضو فريق","members.inviteTeamMemberTip": "يمكنهم الوصول إلى بيانات فريقك مباشرة بعد تسجيل الدخول.",- "members.invitedAsRole": "تمت الدعوة كمستخدم {{role}}",+ "members.invitedAsRole": "تمت الدعوة كـ {{role}}","members.lastActive": "آخر نشاط","members.name": "الاسم","members.noNewInvitationsSent": "لم يتم إرسال دعوات جديدة",- "members.normal": "عادي","members.normalTip": "يمكنه استخدام التطبيقات فقط، ولا يمكنه بناء التطبيقات","members.ok": "موافق",- "members.owner": "المالك","members.pending": "قيد الانتظار...","members.removeFromTeam": "إزالة من الفريق","members.removeFromTeamTip": "سيتم إزالة وصول الفريق",@@ -605,9 +600,6 @@"placeholder.input": "يرجى الإدخال","placeholder.search": "بحث...","placeholder.select": "يرجى التحديد",- "plugin.serpapi.apiKey": "مفتاح API",- "plugin.serpapi.apiKeyPlaceholder": "أدخل مفتاح API الخاص بك",- "plugin.serpapi.keyFrom": "احصل على مفتاح SerpAPI الخاص بك من صفحة حساب SerpAPI","promptEditor.context.item.desc": "إدراج قالب السياق","promptEditor.context.item.title": "السياق","promptEditor.context.modal.add": "إضافة سياق ",diff --git a/web/i18n/de-DE/app.json b/web/i18n/de-DE/app.jsonindex 5705010310f..08d7b86f085 100644--- a/web/i18n/de-DE/app.json+++ b/web/i18n/de-DE/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "Strukturierte Ausgaben ist eine Funktion, die sicherstellt, dass das Modell immer Antworten generiert, die Ihrem bereitgestellten JSON-Schema entsprechen.","studio.allApps": "Alle Apps","studio.apps": "Anwendungen",- "studio.filters.allCreators": "Alle Schöpfer",- "studio.filters.creators": "Schöpfer",+ "studio.filters.allCreators": "Alle Ersteller",+ "studio.filters.creators": "Ersteller","studio.filters.reset": "Zurücksetzen","studio.filters.searchCreators": "Suchersteller...","studio.filters.types": "Typen",diff --git a/web/i18n/de-DE/common.json b/web/i18n/de-DE/common.jsonindex 93ba27276d5..c4744db342e 100644--- a/web/i18n/de-DE/common.json+++ b/web/i18n/de-DE/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Workspace wechseln","mcpPage.description": "Verbinde und verwalte MCP-Server, damit deine Apps auf externe Tools und Dienste zugreifen können.",- "members.admin": "Admin","members.adminTip": "Kann Apps erstellen & Team-Einstellungen verwalten","members.alreadyInTeam": "Bereits im Team","members.alreadyInTeamTip": "Diese Benutzer haben bereits Zugriff auf diesen Arbeitsbereich.","members.builder": "Bauherr","members.builderTip": "Kann eigene Apps erstellen und bearbeiten",- "members.datasetOperator": "Wissensadministrator","members.datasetOperatorTip": "Kann die Wissensdatenbank nur verwalten","members.deleteMember": "Mitglied löschen","members.disInvite": "Einladung widerrufen",- "members.editor": "Editor","members.editorTip": "Kann Apps erstellen & bearbeiten","members.email": "E-Mail","members.emailInvalid": "Ungültiges E-Mail-Format",@@ -272,14 +269,12 @@"members.invite": "Hinzufügen","members.inviteTeamMember": "Teammitglied hinzufügen","members.inviteTeamMemberTip": "Sie können direkt nach der Anmeldung auf Ihre Teamdaten zugreifen.",- "members.invitedAsRole": "Eingeladen als {{role}}-Benutzer",+ "members.invitedAsRole": "Eingeladen als {{role}}","members.lastActive": "ZULETZT AKTIV","members.name": "NAME","members.noNewInvitationsSent": "Keine neuen Einladungen gesendet",- "members.normal": "Normal","members.normalTip": "Kann nur Apps verwenden, kann keine Apps erstellen","members.ok": "OK",- "members.owner": "Eigentümer","members.pending": "Ausstehend...","members.removeFromTeam": "Vom Team entfernen","members.removeFromTeamTip": "Wird den Teamzugang entfernen",@@ -605,9 +600,6 @@"placeholder.input": "Bitte eingeben","placeholder.search": "Suchen...","placeholder.select": "Bitte auswählen",- "plugin.serpapi.apiKey": "API-Schlüssel",- "plugin.serpapi.apiKeyPlaceholder": "Geben Sie Ihren API-Schlüssel ein",- "plugin.serpapi.keyFrom": "Holen Sie Ihren SerpAPI-Schlüssel von der SerpAPI-Kontoseite","promptEditor.context.item.desc": "Kontextvorlage einfügen","promptEditor.context.item.title": "Kontext","promptEditor.context.modal.add": "Kontext hinzufügen",diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.jsonindex 023b35a5ae7..a58816d826a 100644--- a/web/i18n/en-US/common.json+++ b/web/i18n/en-US/common.json@@ -249,17 +249,18 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Switch workspace","mcpPage.description": "Connect and manage MCP servers to give your apps access to external tools and services.",- "members.admin": "Admin","members.adminTip": "Can build apps & manage team settings","members.alreadyInTeam": "Already in team","members.alreadyInTeamTip": "These users already have access to this workspace.",+ "members.assignRoles": "Assign Roles",+ "members.assignRolesModal.description": "Select roles to assign to this member. All permissions from selected roles will be combined.",+ "members.assignRolesModal.selectedCount": "{{count}} selected",+ "members.assignRolesModal.title": "Assign Roles","members.builder": "Builder","members.builderTip": "Can build & edit own apps",- "members.datasetOperator": "Knowledge Admin","members.datasetOperatorTip": "Only can manage the knowledge base","members.deleteMember": "Delete Member","members.disInvite": "Cancel the invitation",- "members.editor": "Editor","members.editorTip": "Can build & edit apps","members.email": "Email","members.emailInvalid": "Invalid Email Format",@@ -272,18 +273,41 @@"members.invite": "Add","members.inviteTeamMember": "Add team member","members.inviteTeamMemberTip": "They can access your team data directly after signing in.",- "members.invitedAsRole": "Invited as {{role}} user",+ "members.invitedAsRole": "Invited as {{role}}","members.lastActive": "LAST ACTIVE",+ "members.memberActions": "Member actions",+ "members.memberDetails.assign": "Assign",+ "members.memberDetails.assignedRoles": "Assigned Roles",+ "members.memberDetails.customGroup": "CUSTOMIZED",+ "members.memberDetails.generalGroup": "GENERAL",+ "members.memberDetails.openAria": "Open member details for {{name}}",+ "members.memberDetails.permissions.assignRoles": "Assign roles",+ "members.memberDetails.permissions.createApps": "Create apps",+ "members.memberDetails.permissions.createDatasets": "Create knowledge",+ "members.memberDetails.permissions.editApps": "Edit apps",+ "members.memberDetails.permissions.editDatasets": "Edit knowledge",+ "members.memberDetails.permissions.inviteMembers": "Invite members",+ "members.memberDetails.permissions.manageBilling": "Manage billing",+ "members.memberDetails.permissions.manageDatasets": "Manage knowledge",+ "members.memberDetails.permissions.removeMembers": "Remove members",+ "members.memberDetails.permissions.transferOwnership": "Transfer ownership",+ "members.memberDetails.permissions.useApps": "Use apps",+ "members.memberDetails.permissions.workspaceSettings": "Workspace settings",+ "members.memberDetails.removeRoleAria": "Remove {{role}} role",+ "members.memberDetails.roleActionsAria": "Open actions for {{role}} role",+ "members.memberDetails.roleNoPermissionSummary": "Current role has no permissions.",+ "members.memberDetails.rolePermissionSummary": "{{role}} can <permissionList>{{permissions}}</permissionList>",+ "members.memberDetails.title": "Member Details","members.name": "NAME","members.noNewInvitationsSent": "No new invitations sent","members.normal": "Normal","members.normalTip": "Only can use apps, can not build apps","members.ok": "OK",- "members.owner": "Owner","members.pending": "Pending...","members.removeFromTeam": "Remove from team","members.removeFromTeamTip": "Will remove team access","members.role": "ROLES",+ "members.selectRole": "Select a role","members.sendInvite": "Send Invite","members.setAdmin": "Set as administrator","members.setBuilder": "Set as builder",@@ -557,6 +581,7 @@"operation.lineBreak": "Line break","operation.log": "Log","operation.more": "More",+ "operation.moreActions": "More actions","operation.no": "No","operation.noSearchCount": "0 {{content}}","operation.noSearchResults": "No {{content}} were found",@@ -605,9 +630,6 @@"placeholder.input": "Please enter","placeholder.search": "Search...","placeholder.select": "Please select",- "plugin.serpapi.apiKey": "API Key",- "plugin.serpapi.apiKeyPlaceholder": "Enter your API key",- "plugin.serpapi.keyFrom": "Get your SerpAPI key from SerpAPI Account Page","promptEditor.context.item.desc": "Insert context template","promptEditor.context.item.title": "Context","promptEditor.context.modal.add": "Add Context ",@@ -670,6 +692,7 @@"provider.saveFailed": "Save api key failed","provider.validatedError": "Validation failed: ","provider.validating": "Validating key...",+ "settings.ResourceAccess": "Resource Access","settings.account": "My account","settings.accountGroup": "GENERAL","settings.agentStrategy": "Agent Strategy",@@ -689,6 +712,9 @@"settings.plugin": "Integrations","settings.preferences": "Preferences","settings.provider": "Model Provider",+ "settings.resourceAccess": "Resource Access",+ "settings.resourceAccessDescription": "Configure permission rules that apps and knowledge bases can use. Permission rules can be assigned to members in specific resource access configurations.",+ "settings.rolesAndPermissions": "Roles & Permissions","settings.settings": "Settings","settings.swaggerAPIAsTool": "Swagger API as Tool","settings.trigger": "Trigger",diff --git a/web/i18n/en-US/dataset-settings.json b/web/i18n/en-US/dataset-settings.jsonindex 053996e769e..d4a3ec361a7 100644--- a/web/i18n/en-US/dataset-settings.json+++ b/web/i18n/en-US/dataset-settings.json@@ -27,6 +27,7 @@"form.numberOfKeywords": "Number of Keywords","form.onSearchResults": "No members match your search query.\nTry your search again.","form.permissions": "Permissions",+ "form.permissionsAccessConfig": "Go to access configuration","form.permissionsAllMember": "All team members","form.permissionsInvitedMembers": "Partial team members","form.permissionsOnlyMe": "Only me",diff --git a/web/i18n/en-US/permission-keys.json b/web/i18n/en-US/permission-keys.jsonnew file mode 100644index 00000000000..8bd6ac7fd15--- /dev/null+++ b/web/i18n/en-US/permission-keys.json@@ -0,0 +1,50 @@+{+ "api_extension.manage": "Manage API extension configuration",+ "app.access_config": "Configure app access permissions",+ "app.acl.access_config": "Configure app access permissions",+ "app.acl.delete": "Delete app",+ "app.acl.edit": "Edit and orchestrate app",+ "app.acl.import_export_dsl": "Import / export DSL",+ "app.acl.monitor": "Monitoring and operations",+ "app.acl.preview": "Preview app",+ "app.acl.release_and_version": "App publishing and version management",+ "app.acl.test_and_run": "Test and use app",+ "app.acl.view_layout": "Read-only orchestration page",+ "app.create_and_management": "Create apps and manage apps you created",+ "app.tag.manage": "Manage app tags",+ "app_library.access": "Access App Library",+ "billing.manage": "Change subscription plans",+ "billing.subscription.manage": "Manage billing and subscriptions in the billing portal",+ "billing.view": "Access Billing settings",+ "credential.manage": "Manage credentials",+ "credential.use": "Use credentials",+ "customization.manage": "Manage customization",+ "data_source.manage": "Manage data source configuration",+ "dataset.access_config": "Configure knowledge base access permissions",+ "dataset.acl.access_config": "Configure knowledge base access permissions",+ "dataset.acl.delete": "Delete knowledge base",+ "dataset.acl.delete_file": "Delete knowledge base files",+ "dataset.acl.document_download": "Download documents",+ "dataset.acl.edit": "Edit knowledge base",+ "dataset.acl.import_export_dsl": "Import / export knowledge pipeline DSL",+ "dataset.acl.pipeline_release": "Knowledge pipeline publishing and version management",+ "dataset.acl.pipeline_test": "Pipeline testing",+ "dataset.acl.preview": "Preview knowledge base",+ "dataset.acl.readonly": "Read-only knowledge base",+ "dataset.acl.retrieval_recall": "Knowledge base retrieval",+ "dataset.acl.use": "Add documents to knowledge base",+ "dataset.api_key.manage": "Manage knowledge base API keys",+ "dataset.create_and_management": "Create knowledge bases and manage knowledge bases you created",+ "dataset.external.connect": "Connect external knowledge bases",+ "dataset.tag.manage": "Manage knowledge base tags",+ "mcp.manage": "Manage MCP",+ "plugin.debug": "Debug plugins",+ "plugin.install": "Install and update plugins",+ "plugin.manage": "Manage plugins",+ "plugin.plugin_preferences": "Manage plugin preferences",+ "snippets.create_and_modify": "Create and modify snippets",+ "snippets.management": "Manage snippets",+ "tool.manage": "Manage tools",+ "workspace.member.manage": "Manage members",+ "workspace.role.manage": "Manage role permissions and resource access rules"+}diff --git a/web/i18n/en-US/permission.json b/web/i18n/en-US/permission.jsonnew file mode 100644index 00000000000..fed93cc71b9--- /dev/null+++ b/web/i18n/en-US/permission.json@@ -0,0 +1,104 @@+{+ "accessRule.actions": "Actions",+ "accessRule.addMemberAria": "Add {{name}}",+ "accessRule.addMembersTitle": "Add members",+ "accessRule.allPermittedMembers": "All members with role permissions",+ "accessRule.allPermittedMembersDescription": "Members with matching role permissions can access this resource.",+ "accessRule.appDescription": "Control who this app is open to. Members still need role permissions to view or operate it.",+ "accessRule.appTitle": "App Access Rules",+ "accessRule.changeOpenScopeDescription": "Changing the open scope will reset all individual permission settings for this resource. You'll need to add member-specific permissions again after switching.",+ "accessRule.changeOpenScopeTitle": "Change resource open scope?",+ "accessRule.collapseSection": "Collapse {{title}}",+ "accessRule.copied": "Access rule copied successfully",+ "accessRule.created": "Access rule created successfully",+ "accessRule.datasetDescription": "Control who this knowledge base is open to. Members still need role permissions to view or operate it.",+ "accessRule.datasetTitle": "Knowledge Base Access Rules",+ "accessRule.defaultPermission": "By role permissions",+ "accessRule.deleteDescription": "This access rule will be permanently deleted and removed from the resource authorization list.",+ "accessRule.deleteTitle": "Delete \"{{name}}\"?",+ "accessRule.deleted": "Access rule deleted successfully",+ "accessRule.exceptionPermissionFor": "Exception permission for {{name}}",+ "accessRule.expandSection": "Expand {{title}}",+ "accessRule.individualPermissionSettings": "Individual permission settings",+ "accessRule.individualPermissionSettingsTip": "Set permission exceptions for specific collaborators or groups. These settings override the default access level.",+ "accessRule.lockedSummary_one": "· {{count}} locked",+ "accessRule.lockedSummary_other": "· {{count}} locked",+ "accessRule.maintainer": "Maintainer",+ "accessRule.member": "Member",+ "accessRule.newPermissionSet": "New permission set",+ "accessRule.noAvailableMembers": "No members available to add",+ "accessRule.noDescription": "No description",+ "accessRule.noRoles": "No roles",+ "accessRule.noRules": "No access rules",+ "accessRule.noUserAccessSettings": "No individual permission settings",+ "accessRule.permission": "Permission",+ "accessRule.resourceOpenScope": "Resource open scope",+ "accessRule.resourceOpenScopeDescription": "Choose who this resource is open to. Role permissions still decide what each member can do.",+ "accessRule.specificMembersOnly": "Specific members only",+ "accessRule.specificMembersOnlyDescription": "Only selected members can access this resource.",+ "accessRule.summary_one": "{{count}} permission set",+ "accessRule.summary_other": "{{count}} permission sets",+ "accessRule.updated": "Access rule updated successfully",+ "common.duplicateAction": "Duplicate",+ "group.app": "Applications",+ "group.app_acl": "App access permissions",+ "group.billing": "Billing",+ "group.credential": "Credentials",+ "group.dataset": "Knowledge bases",+ "group.dataset_acl": "Knowledge base access permissions",+ "group.plugin": "Plugins",+ "group.tool_mcp": "Tools and MCP",+ "group.workspace": "Workspace",+ "permissionList.clearAll": "Clear all",+ "permissionList.collapseGroup": "Collapse group",+ "permissionList.expandGroup": "Expand group",+ "permissionList.noPermissionsFound": "No permissions found",+ "permissionList.selectAll": "Select all",+ "permissionSet.descriptionLabel": "Description",+ "permissionSet.descriptionPlaceholder": "Describe what this permission set grants",+ "permissionSet.learnMore": "Learn more about permissions",+ "permissionSet.modal.create.app.description": "Create an app permission set that can be referenced in access rules for quick authorization.",+ "permissionSet.modal.create.app.title": "Create App permission set",+ "permissionSet.modal.create.dataset.description": "Create a knowledge base permission set that can be referenced in access rules for quick authorization.",+ "permissionSet.modal.create.dataset.title": "Create Knowledge Base permission set",+ "permissionSet.modal.edit.app.description": "Modify the name, description, and permissions granted for this permission set.",+ "permissionSet.modal.edit.app.title": "Edit App permission set",+ "permissionSet.modal.edit.dataset.description": "Modify the name, description, and permissions granted for this permission set.",+ "permissionSet.modal.edit.dataset.title": "Edit Knowledge Base permission set",+ "permissionSet.modal.view.app.description": "View the name, description, and permissions granted for this permission set.",+ "permissionSet.modal.view.app.title": "View App permission set",+ "permissionSet.modal.view.dataset.description": "View the name, description, and permissions granted for this permission set.",+ "permissionSet.modal.view.dataset.title": "View Knowledge Base permission set",+ "permissionSet.nameLabel": "Permission set name",+ "permissionSet.namePlaceholder": "e.g. Can export DSL",+ "permissionSet.permissions": "Permissions",+ "role.addRole": "Create roles",+ "role.copyMembersDescription_one": "\"{{name}}\" is assigned to {{count}} member. Do you want the new role copy to include the same member?",+ "role.copyMembersDescription_other": "\"{{name}}\" is assigned to {{count}} members. Do you want the new role copy to include the same members?",+ "role.copyMembersLoading": "Loading member assignments...",+ "role.copyMembersTitle": "Copy member assignments?",+ "role.created": "Role created successfully",+ "role.deleteDescription": "This role will be permanently deleted and removed from any members or access rules that use it.",+ "role.deleteTitle": "Delete \"{{name}}\"?",+ "role.deleted": "Role deleted successfully",+ "role.duplicated": "Role duplicated successfully",+ "role.groups.builtin": "System Roles",+ "role.groups.custom": "Custom Roles",+ "role.loading": "Loading roles...",+ "role.modal.create.description": "Create a role and assign permissions",+ "role.modal.create.title": "Create Role",+ "role.modal.descriptionLabel": "Description",+ "role.modal.descriptionPlaceholder": "Describe what this role is responsible for",+ "role.modal.edit.description": "Edit role details and permissions",+ "role.modal.edit.title": "Edit Role",+ "role.modal.nameLabel": "Role name",+ "role.modal.namePlaceholder": "e.g. Marketing Lead",+ "role.modal.view.description": "View role details and permissions",+ "role.modal.view.title": "View Role",+ "role.noDescription": "No description",+ "role.noMatchingRoles": "No matching roles",+ "role.searchPlaceholder": "Search roles...",+ "role.updated": "Role updated successfully",+ "role.workspaceRoles.description": "Create roles and define what each role can do in this workspace.",+ "role.workspaceRoles.title": "Workspace Roles"+}diff --git a/web/i18n/en-US/plugin.json b/web/i18n/en-US/plugin.jsonindex 398452ec85f..7cdcd08236e 100644--- a/web/i18n/en-US/plugin.json+++ b/web/i18n/en-US/plugin.json@@ -245,6 +245,7 @@"pluginInfoModal.title": "Integration info","pluginPublishGuide": "Integration publishing guide","privilege.admins": "Admins",+ "privilege.configurePermissionsInSettings": "Go to Settings > Roles & Permissions to configure plugin permissions.","privilege.everyone": "Everyone","privilege.noDebugPermissionTooltip": "You don't have permission to debug integrations","privilege.noInstallPermissionTooltip": "You don't have permission to install and manage integrations",diff --git a/web/i18n/es-ES/common.json b/web/i18n/es-ES/common.jsonindex 4dfd491cde6..f915fd3faf2 100644--- a/web/i18n/es-ES/common.json+++ b/web/i18n/es-ES/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Cambiar espacio de trabajo","mcpPage.description": "Conecta y gestiona servidores MCP para dar a tus apps acceso a herramientas y servicios externos.",- "members.admin": "Administrador","members.adminTip": "Puede crear aplicaciones y administrar configuraciones del equipo","members.alreadyInTeam": "Ya está en el equipo","members.alreadyInTeamTip": "Estos usuarios ya tienen acceso a este espacio de trabajo.","members.builder": "Constructor","members.builderTip": "Puede crear y editar sus propias aplicaciones",- "members.datasetOperator": "Administrador de Conocimiento","members.datasetOperatorTip": "Solo puede administrar la base de conocimiento","members.deleteMember": "Eliminar miembro","members.disInvite": "Cancelar la invitación",- "members.editor": "Editor","members.editorTip": "Puede crear y editar aplicaciones","members.email": "Correo electrónico","members.emailInvalid": "Formato de correo electrónico inválido",@@ -272,14 +269,12 @@"members.invite": "Agregar","members.inviteTeamMember": "Agregar miembro del equipo","members.inviteTeamMemberTip": "Pueden acceder a tus datos del equipo directamente después de iniciar sesión.",- "members.invitedAsRole": "Invitado como usuario {{role}}",+ "members.invitedAsRole": "Invitado como {{role}}","members.lastActive": "ÚLTIMA ACTIVIDAD","members.name": "NOMBRE","members.noNewInvitationsSent": "No se han enviado nuevas invitaciones",- "members.normal": "Normal","members.normalTip": "Solo puede usar aplicaciones, no puede crear aplicaciones","members.ok": "OK",- "members.owner": "Propietario","members.pending": "Pendiente...","members.removeFromTeam": "Eliminar del espacio de trabajo","members.removeFromTeamTip": "Se eliminará el acceso al equipo",@@ -605,9 +600,6 @@"placeholder.input": "Por favor ingresa","placeholder.search": "Buscar...","placeholder.select": "Por favor selecciona",- "plugin.serpapi.apiKey": "Clave API",- "plugin.serpapi.apiKeyPlaceholder": "Ingresa tu clave API",- "plugin.serpapi.keyFrom": "Obtén tu clave API de SerpAPI en la página de cuenta de SerpAPI","promptEditor.context.item.desc": "Insertar plantilla de contexto","promptEditor.context.item.title": "Contexto","promptEditor.context.modal.add": "Agregar Contexto ",diff --git a/web/i18n/fa-IR/common.json b/web/i18n/fa-IR/common.jsonindex 3fbd841354e..10f74e2afc4 100644--- a/web/i18n/fa-IR/common.json+++ b/web/i18n/fa-IR/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "تغییر فضای کاری","mcpPage.description": "سرورهای MCP را وصل و مدیریت کنید تا برنامههای شما به ابزارها و سرویسهای خارجی دسترسی داشته باشند.",- "members.admin": "مدیر","members.adminTip": "میتواند برنامهها را بسازد و تنظیمات تیم را مدیریت کند","members.alreadyInTeam": "در حال حاضر در تیم است","members.alreadyInTeamTip": "این کاربران از قبل به این فضای کاری دسترسی دارند.","members.builder": "سازنده","members.builderTip": "میتواند برنامههای خود را بسازد و ویرایش کند",- "members.datasetOperator": "مدیر دانش","members.datasetOperatorTip": "فقط میتواند پایگاه دانش را مدیریت کند","members.deleteMember": "حذف عضو","members.disInvite": "لغو دعوت",- "members.editor": "ویرایشگر","members.editorTip": "میتواند برنامهها را بسازد و ویرایش کند","members.email": "ایمیل","members.emailInvalid": "فرمت ایمیل نامعتبر است",@@ -272,14 +269,12 @@"members.invite": "افزودن","members.inviteTeamMember": "افزودن عضو تیم","members.inviteTeamMemberTip": "آنها میتوانند پس از ورود به سیستم، مستقیماً به دادههای تیم شما دسترسی پیدا کنند.",- "members.invitedAsRole": "به عنوان کاربر {{role}} دعوت شده",+ "members.invitedAsRole": "به عنوان {{role}} دعوت شده","members.lastActive": "آخرین فعالیت","members.name": "نام","members.noNewInvitationsSent": "هیچ دعوتنامه جدیدی ارسال نشد",- "members.normal": "عادی","members.normalTip": "فقط میتواند از برنامهها استفاده کند، نمیتواند برنامه بسازد","members.ok": "تایید",- "members.owner": "مالک","members.pending": "در انتظار...","members.removeFromTeam": "حذف از تیم","members.removeFromTeamTip": "دسترسی تیم را حذف میکند",@@ -605,9 +600,6 @@"placeholder.input": "لطفا وارد کنید","placeholder.search": "جستجو...","placeholder.select": "لطفا انتخاب کنید",- "plugin.serpapi.apiKey": "کلید API",- "plugin.serpapi.apiKeyPlaceholder": "کلید API خود را وارد کنید",- "plugin.serpapi.keyFrom": "کلید SerpAPI خود را از صفحه حساب SerpAPI دریافت کنید","promptEditor.context.item.desc": "درج الگوی زمینه","promptEditor.context.item.title": "زمینه","promptEditor.context.modal.add": "افزودن زمینه",diff --git a/web/i18n/fr-FR/common.json b/web/i18n/fr-FR/common.jsonindex b10d5a216b0..9f1a640874d 100644--- a/web/i18n/fr-FR/common.json+++ b/web/i18n/fr-FR/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Changer d’espace de travail","mcpPage.description": "Connectez et gérez des serveurs MCP pour donner à vos apps accès à des outils et services externes.",- "members.admin": "Administrateur","members.adminTip": "Peut construire des applications & gérer les paramètres de l'équipe","members.alreadyInTeam": "Déjà dans l’équipe","members.alreadyInTeamTip": "Ces utilisateurs ont déjà accès à cet espace de travail.","members.builder": "Constructeur","members.builderTip": "Peut créer et modifier ses propres applications",- "members.datasetOperator": "Administrateur des connaissances","members.datasetOperatorTip": "Seul peut gérer la base de connaissances","members.deleteMember": "Supprimer Membre","members.disInvite": "Annuler l'invitation",- "members.editor": "Éditeur","members.editorTip": "Peut construire des applications, mais ne peut pas gérer les paramètres de l'équipe","members.email": "Courrier électronique","members.emailInvalid": "Format de courriel invalide",@@ -272,14 +269,12 @@"members.invite": "Ajouter","members.inviteTeamMember": "Ajouter un membre de l'équipe","members.inviteTeamMemberTip": "Ils peuvent accéder directement à vos données d'équipe après s'être connectés.",- "members.invitedAsRole": "Invité en tant qu'utilisateur {{role}}",+ "members.invitedAsRole": "Invité en tant que {{role}}","members.lastActive": "DERNIÈRE ACTIVITÉ","members.name": "NOM","members.noNewInvitationsSent": "Aucune nouvelle invitation envoyée",- "members.normal": "Normal","members.normalTip": "Peut seulement utiliser des applications, ne peut pas construire des applications","members.ok": "D'accord",- "members.owner": "Propriétaire","members.pending": "En attente...","members.removeFromTeam": "Retirer de l'équipe","members.removeFromTeamTip": "Supprimera l'accès de l'équipe",@@ -605,9 +600,6 @@"placeholder.input": "Veuillez entrer","placeholder.search": "Rechercher...","placeholder.select": "Veuillez sélectionner",- "plugin.serpapi.apiKey": "Clé API",- "plugin.serpapi.apiKeyPlaceholder": "Entrez votre clé API",- "plugin.serpapi.keyFrom": "Obtenez votre clé SerpAPI depuis la page de compte SerpAPI","promptEditor.context.item.desc": "Insérez le modèle de contexte","promptEditor.context.item.title": "Contexte","promptEditor.context.modal.add": "Ajouter Contexte",diff --git a/web/i18n/hi-IN/app.json b/web/i18n/hi-IN/app.jsonindex 7d2bba9000e..ea4b2f070d4 100644--- a/web/i18n/hi-IN/app.json+++ b/web/i18n/hi-IN/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "संरचित आउटपुट एक विशेषता है जो यह सुनिश्चित करती है कि मॉडल हमेशा आपके प्रदान किए गए JSON स्कीमा के अनुसार प्रतिक्रियाएँ生成 करेगा।","studio.allApps": "सभी ऐप्स","studio.apps": "ऐप्स",- "studio.filters.allCreators": "सभी रचनाकार",- "studio.filters.creators": "रचनाकारों",+ "studio.filters.allCreators": "सभी निर्माता",+ "studio.filters.creators": "निर्माता","studio.filters.reset": "रीसेट करें","studio.filters.searchCreators": "निर्माता खोजें...","studio.filters.types": "प्रकार",diff --git a/web/i18n/hi-IN/common.json b/web/i18n/hi-IN/common.jsonindex 3031cecc279..a254bee5b07 100644--- a/web/i18n/hi-IN/common.json+++ b/web/i18n/hi-IN/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "वर्कस्पेस बदलें","mcpPage.description": "MCP सर्वर कनेक्ट और प्रबंधित करें ताकि आपके ऐप्स बाहरी टूल और सेवाओं तक पहुँच सकें।",- "members.admin": "प्रशासक","members.adminTip": "ऐप्स बना सकते हैं और टीम सेटिंग्स का प्रबंधन कर सकते हैं","members.alreadyInTeam": "पहले से टीम में हैं","members.alreadyInTeamTip": "इन उपयोगकर्ताओं के पास पहले से इस वर्कस्पेस की पहुंच है।","members.builder": "निर्माता","members.builderTip": "अपने स्वयं के ऐप्स बना और संपादित कर सकते हैं",- "members.datasetOperator": "ज्ञान व्यवस्थापक","members.datasetOperatorTip": "केवल नॉलेज बेस प्रबंधित कर सकते हैं","members.deleteMember": "सदस्य को हटाएं","members.disInvite": "आमंत्रण रद्द करें",- "members.editor": "संपादक","members.editorTip": "ऐप्स बना और संपादित कर सकते हैं","members.email": "ईमेल","members.emailInvalid": "अवैध ईमेल प्रारूप",@@ -272,14 +269,12 @@"members.invite": "जोड़ें","members.inviteTeamMember": "टीम सदस्य जोड़ें","members.inviteTeamMemberTip": "वे साइन इन करने के बाद सीधे आपकी टीम डेटा तक पहुंच सकते हैं।",- "members.invitedAsRole": "{{role}} उपयोगकर्ता के रूप में आमंत्रित किया गया",+ "members.invitedAsRole": "{{role}} के रूप में आमंत्रित किया गया","members.lastActive": "अंतिम सक्रियता","members.name": "नाम","members.noNewInvitationsSent": "कोई नया आमंत्रण नहीं भेजा गया",- "members.normal": "सामान्य","members.normalTip": "केवल ऐप्स का उपयोग कर सकते हैं, ऐप्स नहीं बना सकते","members.ok": "ठीक है",- "members.owner": "मालिक","members.pending": "लंबित...","members.removeFromTeam": "टीम से हटाएं","members.removeFromTeamTip": "टीम पहुंच को हटा देगा",@@ -605,9 +600,6 @@"placeholder.input": "कृपया दर्ज करें","placeholder.search": "खोजें...","placeholder.select": "कृपया चयन करें",- "plugin.serpapi.apiKey": "एपीआई कुंजी",- "plugin.serpapi.apiKeyPlaceholder": "अपनी एपीआई कुंजी दर्ज करें",- "plugin.serpapi.keyFrom": "SerpAPI खाता पृष्ठ से अपनी SerpAPI कुंजी प्राप्त करें","promptEditor.context.item.desc": "संदर्भ टेम्पलेट डालें","promptEditor.context.item.title": "संदर्भ","promptEditor.context.modal.add": "संदर्भ जोड़ें",diff --git a/web/i18n/id-ID/app.json b/web/i18n/id-ID/app.jsonindex 64582d2c18a..f1a27e2f9c1 100644--- a/web/i18n/id-ID/app.json+++ b/web/i18n/id-ID/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "Output Terstruktur adalah fitur yang memastikan model akan selalu menghasilkan respons yang mematuhi Skema JSON yang Anda sediakan","studio.allApps": "Semua Aplikasi","studio.apps": "Aplikasi",- "studio.filters.allCreators": "Semua pencipta",- "studio.filters.creators": "Pencipta",+ "studio.filters.allCreators": "Semua pembuat",+ "studio.filters.creators": "Pembuat","studio.filters.reset": "Setel ulang","studio.filters.searchCreators": "Penelusuran pencipta...","studio.filters.types": "Jenis",diff --git a/web/i18n/id-ID/common.json b/web/i18n/id-ID/common.jsonindex 57939b12a99..8b5a1dc5a39 100644--- a/web/i18n/id-ID/common.json+++ b/web/i18n/id-ID/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Ganti workspace","mcpPage.description": "Hubungkan dan kelola server MCP agar aplikasi Anda dapat mengakses alat dan layanan eksternal.",- "members.admin": "Admin","members.adminTip": "Dapat membangun aplikasi & mengelola pengaturan tim","members.alreadyInTeam": "Sudah ada di tim","members.alreadyInTeamTip": "Pengguna ini sudah memiliki akses ke ruang kerja ini.","members.builder": "Pembangun","members.builderTip": "Dapat membangun & mengedit aplikasi sendiri",- "members.datasetOperator": "Admin Pengetahuan","members.datasetOperatorTip": "Hanya dapat mengelola basis pengetahuan","members.deleteMember": "Hapus Anggota","members.disInvite": "Batalkan undangan",- "members.editor": "Editor","members.editorTip": "Dapat membangun & mengedit aplikasi","members.email": "Email","members.emailInvalid": "Format Email Tidak Valid",@@ -272,14 +269,12 @@"members.invite": "Tambah","members.inviteTeamMember": "Tambahkan anggota tim","members.inviteTeamMemberTip": "Mereka dapat mengakses data tim Anda langsung setelah masuk.",- "members.invitedAsRole": "Diundang sebagai pengguna {{role}}",+ "members.invitedAsRole": "Diundang sebagai {{role}}","members.lastActive": "TERAKHIR AKTIF","members.name": "NAMA","members.noNewInvitationsSent": "Tidak ada undangan baru yang dikirim",- "members.normal": "Biasa","members.normalTip": "Hanya dapat menggunakan aplikasi, tidak dapat membuat aplikasi","members.ok": "OKE",- "members.owner": "Pemilik","members.pending": "Tertunda...","members.removeFromTeam": "Hapus dari tim","members.removeFromTeamTip": "Akan menghapus akses tim",@@ -605,9 +600,6 @@"placeholder.input": "Silakan masuk","placeholder.search": "Cari...","placeholder.select": "Silakan pilih",- "plugin.serpapi.apiKey": "Kunci API",- "plugin.serpapi.apiKeyPlaceholder": "Masukkan kunci API Anda",- "plugin.serpapi.keyFrom": "Dapatkan kunci SerpAPI Anda dari Halaman Akun SerpAPI","promptEditor.context.item.desc": "Sisipkan templat konteks","promptEditor.context.item.title": "Konteks","promptEditor.context.modal.add": "Tambahkan Konteks",diff --git a/web/i18n/it-IT/common.json b/web/i18n/it-IT/common.jsonindex fe662ee06c2..6e3b1454ae8 100644--- a/web/i18n/it-IT/common.json+++ b/web/i18n/it-IT/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Cambia workspace","mcpPage.description": "Connetti e gestisci server MCP per dare alle tue app accesso a strumenti e servizi esterni.",- "members.admin": "Admin","members.adminTip": "Può creare app e gestire le impostazioni del team","members.alreadyInTeam": "Già nel team","members.alreadyInTeamTip": "Questi utenti hanno già accesso a questo spazio di lavoro.","members.builder": "Builder","members.builderTip": "Può creare e modificare le proprie app",- "members.datasetOperator": "Admin della Conoscenza","members.datasetOperatorTip": "Può solo gestire la base di conoscenza","members.deleteMember": "Elimina Membro","members.disInvite": "Annulla l'invito",- "members.editor": "Editor","members.editorTip": "Può creare e modificare app","members.email": "Email","members.emailInvalid": "Formato Email non valido",@@ -272,14 +269,12 @@"members.invite": "Aggiungi","members.inviteTeamMember": "Aggiungi membro del team","members.inviteTeamMemberTip": "Potranno accedere ai dati del tuo team direttamente dopo aver effettuato l'accesso.",- "members.invitedAsRole": "Invitato come utente {{role}}",+ "members.invitedAsRole": "Invitato come {{role}}","members.lastActive": "ULTIMA ATTIVITÀ","members.name": "NOME","members.noNewInvitationsSent": "Nessun nuovo invito inviato",- "members.normal": "Normale","members.normalTip": "Può solo usare le app, non può crearle","members.ok": "OK",- "members.owner": "Proprietario","members.pending": "In attesa...","members.removeFromTeam": "Rimuovi dal team","members.removeFromTeamTip": "Rimuoverà l'accesso al team",@@ -605,9 +600,6 @@"placeholder.input": "Per favore inserisci","placeholder.search": "Cerca...","placeholder.select": "Per favore seleziona",- "plugin.serpapi.apiKey": "API Key",- "plugin.serpapi.apiKeyPlaceholder": "Inserisci la tua API key",- "plugin.serpapi.keyFrom": "Ottieni la tua API key dalla pagina dell'account SerpAPI","promptEditor.context.item.desc": "Inserisci modello di contesto","promptEditor.context.item.title": "Contesto","promptEditor.context.modal.add": "Aggiungi Contesto ",diff --git a/web/i18n/ja-JP/app.json b/web/i18n/ja-JP/app.jsonindex d1f608c287a..d2f338a84de 100644--- a/web/i18n/ja-JP/app.json+++ b/web/i18n/ja-JP/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "構造化出力は、モデルが常に指定された JSON スキーマに準拠した応答を生成することを保証する機能です。","studio.allApps": "すべてのアプリ","studio.apps": "アプリ",- "studio.filters.allCreators": "すべてのクリエイター",- "studio.filters.creators": "クリエイター",+ "studio.filters.allCreators": "すべての作成者",+ "studio.filters.creators": "作成者","studio.filters.reset": "リセット","studio.filters.searchCreators": "クリエイターを検索...","studio.filters.types": "種類",diff --git a/web/i18n/ja-JP/common.json b/web/i18n/ja-JP/common.jsonindex 698fa5fc9eb..7b8b37a8f56 100644--- a/web/i18n/ja-JP/common.json+++ b/web/i18n/ja-JP/common.json@@ -249,17 +249,18 @@"mainNav.workspace.sort.openMenu": "ワークスペースを並べ替え","mainNav.workspace.switchWorkspace": "ワークスペースを切り替え","mcpPage.description": "MCP サーバーを接続・管理して、アプリから外部ツールやサービスにアクセスできるようにします。",- "members.admin": "管理者","members.adminTip": "アプリの構築およびチーム設定の管理ができます","members.alreadyInTeam": "すでにチームに参加済み","members.alreadyInTeamTip": "これらのユーザーはすでにこのワークスペースにアクセスできます。",+ "members.assignRoles": "ロールを割り当て",+ "members.assignRolesModal.description": "このメンバーに割り当てるロールを選択します。選択したロールのすべての権限が結合されます。",+ "members.assignRolesModal.selectedCount": "{{count}} 件選択済み",+ "members.assignRolesModal.title": "ロールを割り当て","members.builder": "ビルダー","members.builderTip": "独自のアプリを作成・編集できる",- "members.datasetOperator": "ナレッジ管理員","members.datasetOperatorTip": "ナレッジベースのみを管理できる","members.deleteMember": "メンバーを削除","members.disInvite": "招待をキャンセル",- "members.editor": "エディター","members.editorTip": "アプリの構築ができますが、チーム設定の管理はできません","members.email": "メール","members.emailInvalid": "無効なメール形式",@@ -272,18 +273,40 @@"members.invite": "招待","members.inviteTeamMember": "チームメンバーを招待する","members.inviteTeamMemberTip": "彼らはサインイン後、直接あなたのチームデータにアクセスできます。",- "members.invitedAsRole": "{{role}}ユーザーとして招待されました",+ "members.invitedAsRole": "{{role}}として招待されました","members.lastActive": "最終アクティブ",+ "members.memberActions": "メンバー操作",+ "members.memberDetails.assign": "割り当て",+ "members.memberDetails.assignedRoles": "割り当て済みロール",+ "members.memberDetails.customGroup": "カスタム",+ "members.memberDetails.generalGroup": "一般",+ "members.memberDetails.openAria": "{{name}} のメンバー詳細を開く",+ "members.memberDetails.permissions.assignRoles": "ロールを割り当て",+ "members.memberDetails.permissions.createApps": "アプリを作成",+ "members.memberDetails.permissions.createDatasets": "ナレッジを作成",+ "members.memberDetails.permissions.editApps": "アプリを編集",+ "members.memberDetails.permissions.editDatasets": "ナレッジを編集",+ "members.memberDetails.permissions.inviteMembers": "メンバーを招待",+ "members.memberDetails.permissions.manageBilling": "請求を管理",+ "members.memberDetails.permissions.manageDatasets": "ナレッジを管理",+ "members.memberDetails.permissions.removeMembers": "メンバーを削除",+ "members.memberDetails.permissions.transferOwnership": "所有権を移転",+ "members.memberDetails.permissions.useApps": "アプリを使用",+ "members.memberDetails.permissions.workspaceSettings": "ワークスペース設定",+ "members.memberDetails.removeRoleAria": "{{role}} ロールを削除",+ "members.memberDetails.roleActionsAria": "{{role}} ロールの操作を開く",+ "members.memberDetails.roleNoPermissionSummary": "現在のロールには権限がありません。",+ "members.memberDetails.rolePermissionSummary": "{{role}} は <permissionList>{{permissions}}</permissionList> できます",+ "members.memberDetails.title": "メンバー詳細","members.name": "名前","members.noNewInvitationsSent": "新しい招待は送信されませんでした",- "members.normal": "通常","members.normalTip": "アプリの使用のみが可能で、アプリの構築はできません","members.ok": "OK",- "members.owner": "オーナー","members.pending": "保留中...","members.removeFromTeam": "チームから削除","members.removeFromTeamTip": "チームへのアクセスが削除されます","members.role": "ロール",+ "members.selectRole": "ロールを選択してください","members.sendInvite": "招待を送る","members.setAdmin": "管理者に設定","members.setBuilder": "ビルダーに設定",@@ -557,6 +580,7 @@"operation.lineBreak": "改行","operation.log": "ログ","operation.more": "もっと",+ "operation.moreActions": "その他の操作","operation.no": "いいえ","operation.noSearchCount": "0件の{{content}}","operation.noSearchResults": "{{content}}は見つかりませんでした",@@ -605,9 +629,6 @@"placeholder.input": "入力してください","placeholder.search": "検索...","placeholder.select": "選択してください",- "plugin.serpapi.apiKey": "API キー",- "plugin.serpapi.apiKeyPlaceholder": "API キーを入力してください",- "plugin.serpapi.keyFrom": "SerpAPI アカウントページから SerpAPI キーを取得してください","promptEditor.context.item.desc": "コンテキストテンプレートを挿入","promptEditor.context.item.title": "コンテキスト","promptEditor.context.modal.add": "コンテキストを追加",@@ -670,6 +691,7 @@"provider.saveFailed": "API キーの保存に失敗しました","provider.validatedError": "検証に失敗しました:","provider.validating": "キーの検証中...",+ "settings.ResourceAccess": "リソースアクセス","settings.account": "マイアカウント","settings.accountGroup": "アカウント","settings.agentStrategy": "エージェント戦略",@@ -689,6 +711,9 @@"settings.plugin": "インテグレーション","settings.preferences": "ユーザー設定","settings.provider": "モデルプロバイダー",+ "settings.resourceAccess": "リソースアクセス",+ "settings.resourceAccessDescription": "アプリとナレッジベースで使用できる権限ルールを設定します。権限ルールは、具体的なリソースアクセス設定でメンバーに割り当てられます。",+ "settings.rolesAndPermissions": "ロールと権限","settings.settings": "設定","settings.swaggerAPIAsTool": "Swagger API をツールとして利用","settings.trigger": "トリガー",diff --git a/web/i18n/ja-JP/permission-keys.json b/web/i18n/ja-JP/permission-keys.jsonnew file mode 100644index 00000000000..d91764df177--- /dev/null+++ b/web/i18n/ja-JP/permission-keys.json@@ -0,0 +1,50 @@+{+ "api_extension.manage": "API拡張設定を管理",+ "app.access_config": "アプリアクセス権限を設定",+ "app.acl.access_config": "アプリアクセス権限を設定",+ "app.acl.delete": "アプリを削除",+ "app.acl.edit": "アプリの編集とオーケストレーション",+ "app.acl.import_export_dsl": "DSLのインポート / エクスポート",+ "app.acl.monitor": "監視と運用",+ "app.acl.preview": "アプリをプレビュー",+ "app.acl.release_and_version": "アプリ公開とバージョン管理",+ "app.acl.test_and_run": "アプリのテストと使用",+ "app.acl.view_layout": "オーケストレーションページの読み取り専用",+ "app.create_and_management": "アプリの作成と、自分が作成したアプリの管理",+ "app.tag.manage": "アプリタグを管理",+ "app_library.access": "アプリライブラリにアクセス",+ "billing.manage": "サブスクリプションプランを変更",+ "billing.subscription.manage": "請求ポータルで請求とサブスクリプションを管理",+ "billing.view": "設定の請求ページにアクセス",+ "credential.manage": "認証情報を管理",+ "credential.use": "認証情報を使用",+ "customization.manage": "カスタマイズを管理",+ "data_source.manage": "データソース設定を管理",+ "dataset.access_config": "ナレッジベースのアクセス権限を設定",+ "dataset.acl.access_config": "ナレッジベースのアクセス権限を設定",+ "dataset.acl.delete": "ナレッジベースを削除",+ "dataset.acl.delete_file": "ナレッジベースファイルを削除",+ "dataset.acl.document_download": "ドキュメントをダウンロード",+ "dataset.acl.edit": "ナレッジベースを編集",+ "dataset.acl.import_export_dsl": "ナレッジパイプライン DSL のインポート / エクスポート",+ "dataset.acl.pipeline_release": "ナレッジパイプライン公開とバージョン管理",+ "dataset.acl.pipeline_test": "パイプラインテスト",+ "dataset.acl.preview": "ナレッジベースをプレビュー",+ "dataset.acl.readonly": "ナレッジベースの読み取り専用",+ "dataset.acl.retrieval_recall": "ナレッジベース検索リコール",+ "dataset.acl.use": "ナレッジベースにドキュメントを追加",+ "dataset.api_key.manage": "ナレッジベース API キーを管理",+ "dataset.create_and_management": "ナレッジベースの作成と、自分が作成したナレッジベースの管理",+ "dataset.external.connect": "外部ナレッジベースに接続",+ "dataset.tag.manage": "ナレッジベースタグを管理",+ "mcp.manage": "MCPを管理",+ "plugin.debug": "プラグインをデバッグ",+ "plugin.install": "プラグインのインストールと更新",+ "plugin.manage": "プラグインを管理",+ "plugin.plugin_preferences": "プラグイン設定を管理",+ "snippets.create_and_modify": "スニペットの作成と変更",+ "snippets.management": "スニペットを管理",+ "tool.manage": "ツールを管理",+ "workspace.member.manage": "メンバーを管理",+ "workspace.role.manage": "ロール権限とリソースアクセスルールを管理"+}diff --git a/web/i18n/ja-JP/permission.json b/web/i18n/ja-JP/permission.jsonnew file mode 100644index 00000000000..5a30f5c4d2e--- /dev/null+++ b/web/i18n/ja-JP/permission.json@@ -0,0 +1,104 @@+{+ "accessRule.actions": "アクション",+ "accessRule.addMemberAria": "{{name}} を追加",+ "accessRule.addMembersTitle": "メンバーを追加",+ "accessRule.allPermittedMembers": "ロール権限を持つすべてのメンバー",+ "accessRule.allPermittedMembersDescription": "一致するロール権限を持つメンバーは、このリソースにアクセスできます。",+ "accessRule.appDescription": "このアプリを公開する対象を制御します。メンバーが表示または操作するには、引き続きロール権限が必要です。",+ "accessRule.appTitle": "アプリアクセスルール",+ "accessRule.changeOpenScopeDescription": "公開範囲を変更すると、このリソースのすべての個別権限設定がリセットされます。切り替え後、メンバー固有の権限を再度追加する必要があります。",+ "accessRule.changeOpenScopeTitle": "リソースの公開範囲を変更しますか?",+ "accessRule.collapseSection": "{{title}} を折りたたむ",+ "accessRule.copied": "アクセスルールをコピーしました",+ "accessRule.created": "アクセスルールを作成しました",+ "accessRule.datasetDescription": "このナレッジベースを公開する対象を制御します。メンバーが表示または操作するには、引き続きロール権限が必要です。",+ "accessRule.datasetTitle": "ナレッジベースアクセスルール",+ "accessRule.defaultPermission": "ロール権限に従う",+ "accessRule.deleteDescription": "このアクセスルールは完全に削除され、リソースの認可リストから削除されます。",+ "accessRule.deleteTitle": "「{{name}}」を削除しますか?",+ "accessRule.deleted": "アクセスルールを削除しました",+ "accessRule.exceptionPermissionFor": "{{name}} の例外権限",+ "accessRule.expandSection": "{{title}} を展開",+ "accessRule.individualPermissionSettings": "個別権限設定",+ "accessRule.individualPermissionSettingsTip": "特定の共同編集者またはグループに権限の例外を設定します。これらの設定はデフォルトのアクセスレベルを上書きします。",+ "accessRule.lockedSummary_one": "· {{count}} 件ロック済み",+ "accessRule.lockedSummary_other": "· {{count}} 件ロック済み",+ "accessRule.maintainer": "メンテナー",+ "accessRule.member": "メンバー",+ "accessRule.newPermissionSet": "新しい権限セット",+ "accessRule.noAvailableMembers": "追加できるメンバーがいません",+ "accessRule.noDescription": "説明なし",+ "accessRule.noRoles": "ロールなし",+ "accessRule.noRules": "アクセスルールがありません",+ "accessRule.noUserAccessSettings": "個別権限設定がありません",+ "accessRule.permission": "権限",+ "accessRule.resourceOpenScope": "リソース公開範囲",+ "accessRule.resourceOpenScopeDescription": "このリソースを公開する対象を選択します。各メンバーが実行できる操作はロール権限で決まります。",+ "accessRule.specificMembersOnly": "指定メンバーのみ",+ "accessRule.specificMembersOnlyDescription": "選択されたメンバーのみがこのリソースにアクセスできます。",+ "accessRule.summary_one": "{{count}} 件の権限セット",+ "accessRule.summary_other": "{{count}} 件の権限セット",+ "accessRule.updated": "アクセスルールを更新しました",+ "common.duplicateAction": "複製",+ "group.app": "アプリ",+ "group.app_acl": "アプリアクセス権限",+ "group.billing": "請求",+ "group.credential": "認証情報",+ "group.dataset": "ナレッジベース",+ "group.dataset_acl": "ナレッジベースアクセス権限",+ "group.plugin": "プラグイン",+ "group.tool_mcp": "ツールとMCP",+ "group.workspace": "ワークスペース",+ "permissionList.clearAll": "すべてクリア",+ "permissionList.collapseGroup": "グループを折りたたむ",+ "permissionList.expandGroup": "グループを展開",+ "permissionList.noPermissionsFound": "権限が見つかりません",+ "permissionList.selectAll": "すべて選択",+ "permissionSet.descriptionLabel": "説明",+ "permissionSet.descriptionPlaceholder": "この権限セットが付与する内容を説明",+ "permissionSet.learnMore": "権限について詳しく見る",+ "permissionSet.modal.create.app.description": "アクセスルールで参照できるアプリ権限セットを作成し、すばやく認可します。",+ "permissionSet.modal.create.app.title": "アプリ権限セットを作成",+ "permissionSet.modal.create.dataset.description": "アクセスルールで参照できるナレッジベース権限セットを作成し、すばやく認可します。",+ "permissionSet.modal.create.dataset.title": "ナレッジベース権限セットを作成",+ "permissionSet.modal.edit.app.description": "この権限セットの名前、説明、付与される権限を変更します。",+ "permissionSet.modal.edit.app.title": "アプリ権限セットを編集",+ "permissionSet.modal.edit.dataset.description": "この権限セットの名前、説明、付与される権限を変更します。",+ "permissionSet.modal.edit.dataset.title": "ナレッジベース権限セットを編集",+ "permissionSet.modal.view.app.description": "この権限セットの名前、説明、付与される権限を表示します。",+ "permissionSet.modal.view.app.title": "アプリ権限セットを表示",+ "permissionSet.modal.view.dataset.description": "この権限セットの名前、説明、付与される権限を表示します。",+ "permissionSet.modal.view.dataset.title": "ナレッジベース権限セットを表示",+ "permissionSet.nameLabel": "権限セット名",+ "permissionSet.namePlaceholder": "例: DSL をエクスポート可能",+ "permissionSet.permissions": "権限",+ "role.addRole": "ロールを作成",+ "role.copyMembersDescription_one": "「{{name}}」は {{count}} 人のメンバーに割り当てられています。新しいロールのコピーに同じメンバーを含めますか?",+ "role.copyMembersDescription_other": "「{{name}}」は {{count}} 人のメンバーに割り当てられています。新しいロールのコピーに同じメンバーを含めますか?",+ "role.copyMembersLoading": "割り当て済みメンバーを読み込み中...",+ "role.copyMembersTitle": "メンバーの割り当てもコピーしますか?",+ "role.created": "ロールを作成しました",+ "role.deleteDescription": "このロールは完全に削除され、それを使用するメンバーまたはアクセスルールから削除されます。",+ "role.deleteTitle": "「{{name}}」を削除しますか?",+ "role.deleted": "ロールを削除しました",+ "role.duplicated": "ロールを複製しました",+ "role.groups.builtin": "システムロール",+ "role.groups.custom": "カスタムロール",+ "role.loading": "ロールを読み込み中...",+ "role.modal.create.description": "ロールを作成して権限を割り当てます",+ "role.modal.create.title": "ロールを作成",+ "role.modal.descriptionLabel": "説明",+ "role.modal.descriptionPlaceholder": "このロールの責任範囲を説明",+ "role.modal.edit.description": "ロールの詳細と権限を編集します",+ "role.modal.edit.title": "ロールを編集",+ "role.modal.nameLabel": "ロール名",+ "role.modal.namePlaceholder": "例: マーケティング責任者",+ "role.modal.view.description": "ロールの詳細と権限を表示します",+ "role.modal.view.title": "ロールを表示",+ "role.noDescription": "説明なし",+ "role.noMatchingRoles": "一致するロールが見つかりません",+ "role.searchPlaceholder": "ロールを検索...",+ "role.updated": "ロールを更新しました",+ "role.workspaceRoles.description": "ロールを作成し、このワークスペースで各ロールが実行できる操作を定義します。",+ "role.workspaceRoles.title": "ワークスペースロール"+}diff --git a/web/i18n/ko-KR/app.json b/web/i18n/ko-KR/app.jsonindex 9e79d569480..a1995c21b46 100644--- a/web/i18n/ko-KR/app.json+++ b/web/i18n/ko-KR/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "구조화된 출력은 모델이 제공한 JSON 스키마를 항상 준수하는 응답을 생성하도록 보장하는 기능입니다.","studio.allApps": "모든 앱","studio.apps": "앱",- "studio.filters.allCreators": "모든 크리에이터",- "studio.filters.creators": "크리에이터",+ "studio.filters.allCreators": "모든 작성자",+ "studio.filters.creators": "작성자","studio.filters.reset": "초기화","studio.filters.searchCreators": "작성자 검색...","studio.filters.types": "형?",diff --git a/web/i18n/ko-KR/common.json b/web/i18n/ko-KR/common.jsonindex cb776d64f9f..64db784d138 100644--- a/web/i18n/ko-KR/common.json+++ b/web/i18n/ko-KR/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "워크스페이스 전환","mcpPage.description": "MCP 서버를 연결하고 관리하여 앱이 외부 도구와 서비스에 접근할 수 있도록 하세요.",- "members.admin": "관리자","members.adminTip": "앱 빌드 및 팀 설정 관리 가능","members.alreadyInTeam": "이미 팀에 있습니다","members.alreadyInTeamTip": "이 사용자들은 이미 이 작업 공간에 액세스할 수 있습니다.","members.builder": "빌더","members.builderTip": "자신의 앱을 구축 및 편집할 수 있습니다.",- "members.datasetOperator": "지식 관리자","members.datasetOperatorTip": "기술 자료만 관리할 수 있습니다.","members.deleteMember": "멤버 삭제","members.disInvite": "초대 취소",- "members.editor": "편집자","members.editorTip": "앱 빌드만 가능하고 팀 설정 관리 불가능","members.email": "이메일","members.emailInvalid": "유효하지 않은 이메일 형식",@@ -272,14 +269,12 @@"members.invite": "초대","members.inviteTeamMember": "팀 멤버 초대","members.inviteTeamMemberTip": "로그인 후에 바로 팀 데이터에 액세스할 수 있습니다.",- "members.invitedAsRole": "{{role}} 사용자로 초대되었습니다",+ "members.invitedAsRole": "{{role}}로 초대되었습니다","members.lastActive": "최근 활동","members.name": "이름","members.noNewInvitationsSent": "새 초대가 전송되지 않았습니다",- "members.normal": "일반","members.normalTip": "앱 사용만 가능하고 앱 빌드는 불가능","members.ok": "확인",- "members.owner": "소유자","members.pending": "대기 중...","members.removeFromTeam": "팀에서 제거","members.removeFromTeamTip": "팀 액세스가 제거됩니다",@@ -605,9 +600,6 @@"placeholder.input": "입력해주세요","placeholder.search": "검색...","placeholder.select": "선택해주세요",- "plugin.serpapi.apiKey": "API 키",- "plugin.serpapi.apiKeyPlaceholder": "API 키를 입력하세요",- "plugin.serpapi.keyFrom": "SerpAPI 계정 페이지에서 SerpAPI 키를 가져오세요","promptEditor.context.item.desc": "컨텍스트 템플릿을 삽입합니다.","promptEditor.context.item.title": "컨텍스트","promptEditor.context.modal.add": "컨텍스트 추가",diff --git a/web/i18n/nl-NL/common.json b/web/i18n/nl-NL/common.jsonindex 494f92ab164..8c03f8fd4d2 100644--- a/web/i18n/nl-NL/common.json+++ b/web/i18n/nl-NL/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Werkruimte wisselen","mcpPage.description": "Verbind en beheer MCP-servers zodat je apps toegang krijgen tot externe tools en services.",- "members.admin": "Admin","members.adminTip": "Can build apps & manage team settings","members.alreadyInTeam": "Al in het team","members.alreadyInTeamTip": "Deze gebruikers hebben al toegang tot deze werkruimte.","members.builder": "Builder","members.builderTip": "Can build & edit own apps",- "members.datasetOperator": "Knowledge Admin","members.datasetOperatorTip": "Only can manage the knowledge base","members.deleteMember": "Delete Member","members.disInvite": "Cancel the invitation",- "members.editor": "Editor","members.editorTip": "Can build & edit apps","members.email": "Email","members.emailInvalid": "Invalid Email Format",@@ -272,14 +269,12 @@"members.invite": "Add","members.inviteTeamMember": "Add team member","members.inviteTeamMemberTip": "They can access your team data directly after signing in.",- "members.invitedAsRole": "Invited as {{role}} user",+ "members.invitedAsRole": "Uitgenodigd als {{role}}","members.lastActive": "LAST ACTIVE","members.name": "NAME","members.noNewInvitationsSent": "Geen nieuwe uitnodigingen verzonden",- "members.normal": "Normal","members.normalTip": "Only can use apps, can not build apps","members.ok": "OK",- "members.owner": "Owner","members.pending": "Pending...","members.removeFromTeam": "Remove from team","members.removeFromTeamTip": "Will remove team access",@@ -605,9 +600,6 @@"placeholder.input": "Please enter","placeholder.search": "Search...","placeholder.select": "Please select",- "plugin.serpapi.apiKey": "API Key",- "plugin.serpapi.apiKeyPlaceholder": "Enter your API key",- "plugin.serpapi.keyFrom": "Get your SerpAPI key from SerpAPI Account Page","promptEditor.context.item.desc": "Insert context template","promptEditor.context.item.title": "Context","promptEditor.context.modal.add": "Add Context ",diff --git a/web/i18n/pl-PL/app.json b/web/i18n/pl-PL/app.jsonindex 26b910983d4..58156671cf7 100644--- a/web/i18n/pl-PL/app.json+++ b/web/i18n/pl-PL/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "Strukturalne wyniki to funkcja, która zapewnia, że model zawsze generuje odpowiedzi zgodne z dostarczonym schematem JSON.","studio.allApps": "Wszystkie aplikacje","studio.apps": "Aplikacje",- "studio.filters.allCreators": "Wszyscy twórcy",- "studio.filters.creators": "Twórcy",+ "studio.filters.allCreators": "Wszyscy autorzy",+ "studio.filters.creators": "Autorzy","studio.filters.reset": "Zresetuj","studio.filters.searchCreators": "Szukaj twórcy...","studio.filters.types": "Typy",diff --git a/web/i18n/pl-PL/common.json b/web/i18n/pl-PL/common.jsonindex 35a30b811e6..b156c28448f 100644--- a/web/i18n/pl-PL/common.json+++ b/web/i18n/pl-PL/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Przełącz obszar roboczy","mcpPage.description": "Łącz i zarządzaj serwerami MCP, aby aplikacje mogły korzystać z zewnętrznych narzędzi i usług.",- "members.admin": "Admin","members.adminTip": "Może tworzyć aplikacje i zarządzać ustawieniami zespołu","members.alreadyInTeam": "Już w zespole","members.alreadyInTeamTip": "Ci użytkownicy mają już dostęp do tego obszaru roboczego.","members.builder": "Budowniczy","members.builderTip": "Może tworzyć i edytować własne aplikacje",- "members.datasetOperator": "Wiedza Admin","members.datasetOperatorTip": "Może zarządzać tylko bazą wiedzy","members.deleteMember": "Usuń członka","members.disInvite": "Anuluj zaproszenie",- "members.editor": "Edytor","members.editorTip": "Może tworzyć i edytować aplikacje, ale nie zarządzać ustawieniami zespołu","members.email": "Email","members.emailInvalid": "Nieprawidłowy format e-maila",@@ -272,14 +269,12 @@"members.invite": "Dodaj","members.inviteTeamMember": "Dodaj członka zespołu","members.inviteTeamMemberTip": "Mogą uzyskać bezpośredni dostęp do danych Twojego zespołu po zalogowaniu.",- "members.invitedAsRole": "Zaproszony jako użytkownik typu {{role}}",+ "members.invitedAsRole": "Zaproszony jako {{role}}","members.lastActive": "OSTATNIA AKTYWNOŚĆ","members.name": "NAZWA","members.noNewInvitationsSent": "Nie wysłano nowych zaproszeń",- "members.normal": "Normalny","members.normalTip": "Może tylko korzystać z aplikacji, nie może tworzyć aplikacji","members.ok": "OK",- "members.owner": "Właściciel","members.pending": "Oczekujący...","members.removeFromTeam": "Usuń z zespołu","members.removeFromTeamTip": "Usunie dostęp do zespołu",@@ -605,9 +600,6 @@"placeholder.input": "Proszę wprowadzić","placeholder.search": "Szukaj...","placeholder.select": "Proszę wybrać",- "plugin.serpapi.apiKey": "Klucz API",- "plugin.serpapi.apiKeyPlaceholder": "Wprowadź swój klucz API",- "plugin.serpapi.keyFrom": "Pobierz swój klucz SerpAPI ze strony konta SerpAPI","promptEditor.context.item.desc": "Wstaw szablon kontekstu","promptEditor.context.item.title": "Kontekst","promptEditor.context.modal.add": "Dodaj Kontekst ",diff --git a/web/i18n/pt-BR/common.json b/web/i18n/pt-BR/common.jsonindex 5c640313016..ce04750e3c5 100644--- a/web/i18n/pt-BR/common.json+++ b/web/i18n/pt-BR/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Trocar workspace","mcpPage.description": "Conecte e gerencie servidores MCP para dar aos seus apps acesso a ferramentas e serviços externos.",- "members.admin": "Admin","members.adminTip": "Pode criar aplicativos e gerenciar configurações da equipe","members.alreadyInTeam": "Já está na equipe","members.alreadyInTeamTip": "Estes usuários já têm acesso a este espaço de trabalho.","members.builder": "Construtor","members.builderTip": "Pode criar e editar seus próprios aplicativos",- "members.datasetOperator": "Administrador de conhecimento","members.datasetOperatorTip": "Só pode gerenciar a base de dados de conhecimento","members.deleteMember": "Excluir Membro","members.disInvite": "Cancelar o convite",- "members.editor": "Editor","members.editorTip": "Pode editar aplicativos, mas não pode gerenciar configurações da equipe","members.email": "E-mail","members.emailInvalid": "Formato de e-mail inválido",@@ -272,14 +269,12 @@"members.invite": "Adicionar","members.inviteTeamMember": "Adicionar membro da equipe","members.inviteTeamMemberTip": "Eles podem acessar os dados da sua equipe diretamente após fazer login.",- "members.invitedAsRole": "Convidado como usuário {{role}}",+ "members.invitedAsRole": "Convidado como {{role}}","members.lastActive": "ÚLTIMA ATIVIDADE","members.name": "NOME","members.noNewInvitationsSent": "Nenhum novo convite enviado",- "members.normal": "Normal","members.normalTip": "Só pode usar aplicativos, não pode criar aplicativos","members.ok": "OK",- "members.owner": "Proprietário","members.pending": "Pendente...","members.removeFromTeam": "Remover da equipe","members.removeFromTeamTip": "Removerá o acesso da equipe",@@ -605,9 +600,6 @@"placeholder.input": "Por favor, insira","placeholder.search": "Pesquisar...","placeholder.select": "Por favor, selecione",- "plugin.serpapi.apiKey": "Chave da API",- "plugin.serpapi.apiKeyPlaceholder": "Insira sua chave da API",- "plugin.serpapi.keyFrom": "Obtenha sua chave da SerpAPI na página da conta da SerpAPI","promptEditor.context.item.desc": "Inserir modelo de contexto","promptEditor.context.item.title": "Contexto","promptEditor.context.modal.add": "Adicionar Contexto",diff --git a/web/i18n/ro-RO/common.json b/web/i18n/ro-RO/common.jsonindex 3a15cf1b603..50216e7108b 100644--- a/web/i18n/ro-RO/common.json+++ b/web/i18n/ro-RO/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Schimbă spațiul de lucru","mcpPage.description": "Conectează și administrează servere MCP pentru a oferi aplicațiilor acces la instrumente și servicii externe.",- "members.admin": "Administrator","members.adminTip": "Poate construi aplicații și gestiona setările echipei","members.alreadyInTeam": "Deja în echipă","members.alreadyInTeamTip": "Acești utilizatori au deja acces la acest spațiu de lucru.","members.builder": "Constructor","members.builderTip": "Poate construi și edita propriile aplicații",- "members.datasetOperator": "Administrator de cunoștințe","members.datasetOperatorTip": "Numai poate gestiona baza de cunoștințe","members.deleteMember": "Șterge membru","members.disInvite": "Anulează invitația",- "members.editor": "Editor","members.editorTip": "Poate construi aplicații, dar nu poate gestiona setările echipei","members.email": "Email","members.emailInvalid": "Format de email invalid",@@ -272,14 +269,12 @@"members.invite": "Adaugă","members.inviteTeamMember": "Adaugă membru în echipă","members.inviteTeamMemberTip": "Pot accesa direct datele echipei dvs. după autentificare.",- "members.invitedAsRole": "Invitat ca utilizator {{role}}",+ "members.invitedAsRole": "Invitat ca {{role}}","members.lastActive": "ULTIMA ACTIVITATE","members.name": "NUME","members.noNewInvitationsSent": "Nu au fost trimise invitații noi",- "members.normal": "Normal","members.normalTip": "Poate doar utiliza aplicații, nu poate construi aplicații","members.ok": "OK",- "members.owner": "Proprietar","members.pending": "În așteptare...","members.removeFromTeam": "Elimină din echipă","members.removeFromTeamTip": "Va elimina accesul la echipă",@@ -605,9 +600,6 @@"placeholder.input": "Vă rugăm să introduceți","placeholder.search": "Caută...","placeholder.select": "Vă rugăm să selectați",- "plugin.serpapi.apiKey": "Cheie API",- "plugin.serpapi.apiKeyPlaceholder": "Introduceți cheia dvs. API",- "plugin.serpapi.keyFrom": "Obțineți cheia dvs. SerpAPI din pagina contului SerpAPI","promptEditor.context.item.desc": "Inserați șablon de context","promptEditor.context.item.title": "Context","promptEditor.context.modal.add": "Adăugați context ",diff --git a/web/i18n/ru-RU/common.json b/web/i18n/ru-RU/common.jsonindex e99d38def6d..23b8625b756 100644--- a/web/i18n/ru-RU/common.json+++ b/web/i18n/ru-RU/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Переключить рабочую область","mcpPage.description": "Подключайте и управляйте MCP-серверами, чтобы приложения могли обращаться к внешним инструментам и сервисам.",- "members.admin": "Администратор","members.adminTip": "Может создавать приложения и управлять настройками команды","members.alreadyInTeam": "Уже в команде","members.alreadyInTeamTip": "Эти пользователи уже имеют доступ к этому рабочему пространству.","members.builder": "Разработчик","members.builderTip": "Может создавать и редактировать собственные приложения",- "members.datasetOperator": "Администратор знаний","members.datasetOperatorTip": "Может управлять только базой знаний","members.deleteMember": "Удалить участника","members.disInvite": "Отменить приглашение",- "members.editor": "Редактор","members.editorTip": "Может создавать и редактировать приложения","members.email": "Электронная почта","members.emailInvalid": "Неверный формат электронной почты",@@ -272,14 +269,12 @@"members.invite": "Добавить","members.inviteTeamMember": "Добавить участника команды","members.inviteTeamMemberTip": "Они могут получить доступ к данным вашей команды сразу после входа в систему.",- "members.invitedAsRole": "Приглашен как пользователь с ролью {{role}}",+ "members.invitedAsRole": "Приглашен как {{role}}","members.lastActive": "ПОСЛЕДНЯЯ АКТИВНОСТЬ","members.name": "ИМЯ","members.noNewInvitationsSent": "Новые приглашения не отправлены",- "members.normal": "Обычный","members.normalTip": "Может только использовать приложения, не может создавать приложения","members.ok": "ОК",- "members.owner": "Владелец","members.pending": "Ожидание...","members.removeFromTeam": "Удалить из команды","members.removeFromTeamTip": "Удалить доступ к команде",@@ -605,9 +600,6 @@"placeholder.input": "Пожалуйста, введите","placeholder.search": "Поиск...","placeholder.select": "Пожалуйста, выберите",- "plugin.serpapi.apiKey": "Ключ API",- "plugin.serpapi.apiKeyPlaceholder": "Введите свой ключ API",- "plugin.serpapi.keyFrom": "Получите свой ключ SerpAPI на странице учетной записи SerpAPI","promptEditor.context.item.desc": "Вставить шаблон контекста","promptEditor.context.item.title": "Контекст","promptEditor.context.modal.add": "Добавить контекст ",diff --git a/web/i18n/sl-SI/common.json b/web/i18n/sl-SI/common.jsonindex af24887d274..b1a1726d195 100644--- a/web/i18n/sl-SI/common.json+++ b/web/i18n/sl-SI/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Preklopi delovni prostor","mcpPage.description": "Povežite in upravljajte strežnike MCP, da aplikacijam omogočite dostop do zunanjih orodij in storitev.",- "members.admin": "Administrator","members.adminTip": "Lahko ustvarja aplikacije in upravlja nastavitve ekipe","members.alreadyInTeam": "Že v ekipi","members.alreadyInTeamTip": "Ti uporabniki že imajo dostop do tega delovnega prostora.","members.builder": "Graditelj","members.builderTip": "Lahko ustvarja in ureja lastne aplikacije",- "members.datasetOperator": "Skrbnik znanja","members.datasetOperatorTip": "Lahko upravlja samo bazo znanja","members.deleteMember": "Izbriši člana","members.disInvite": "Prekliči povabilo",- "members.editor": "Urednik","members.editorTip": "Lahko ustvarja in ureja aplikacije","members.email": "E-pošta","members.emailInvalid": "Neveljaven format e-pošte",@@ -272,14 +269,12 @@"members.invite": "Dodaj","members.inviteTeamMember": "Dodaj člana ekipe","members.inviteTeamMemberTip": "Do vaših podatkov bo lahko dostopal takoj po prijavi.",- "members.invitedAsRole": "Povabljen kot uporabnik {{role}}",+ "members.invitedAsRole": "Povabljen kot {{role}}","members.lastActive": "NAZADNJE AKTIVEN","members.name": "IME","members.noNewInvitationsSent": "Nova povabila niso bila poslana",- "members.normal": "Običajni uporabnik","members.normalTip": "Lahko uporablja samo aplikacije, ne more ustvarjati aplikacij","members.ok": "V redu",- "members.owner": "Lastnik","members.pending": "V teku...","members.removeFromTeam": "Odstrani iz ekipe","members.removeFromTeamTip": "Odstranjen bo dostop do ekipe",@@ -605,9 +600,6 @@"placeholder.input": "Vnesite prosim","placeholder.search": "Išči...","placeholder.select": "Izberite prosim",- "plugin.serpapi.apiKey": "API ključ",- "plugin.serpapi.apiKeyPlaceholder": "Vnesite ključ API",- "plugin.serpapi.keyFrom": "Pridobite svoj ključ SerpAPI na strani računa SerpAPI","promptEditor.context.item.desc": "Vstavljanje predloge konteksta","promptEditor.context.item.title": "Kontekstu","promptEditor.context.modal.add": "Dodajanje konteksta",diff --git a/web/i18n/th-TH/common.json b/web/i18n/th-TH/common.jsonindex 41c5ed7ad80..d05b8b38a08 100644--- a/web/i18n/th-TH/common.json+++ b/web/i18n/th-TH/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "สลับพื้นที่ทำงาน","mcpPage.description": "เชื่อมต่อและจัดการเซิร์ฟเวอร์ MCP เพื่อให้แอปของคุณเข้าถึงเครื่องมือและบริการภายนอกได้",- "members.admin": "ผู้ดูแลระบบ","members.adminTip": "สามารถสร้างแอพและจัดการการตั้งค่าทีมได้","members.alreadyInTeam": "อยู่ในทีมแล้ว","members.alreadyInTeamTip": "ผู้ใช้เหล่านี้มีสิทธิ์เข้าถึงพื้นที่ทำงานนี้อยู่แล้ว","members.builder": "ผู้สร้าง","members.builderTip": "สามารถสร้างและแก้ไขแอปของตัวเองได้",- "members.datasetOperator": "ผู้ดูแลระบบความรู้","members.datasetOperatorTip": "สามารถจัดการฐานความรู้ได้เท่านั้น","members.deleteMember": "ลบสมาชิก","members.disInvite": "ยกเลิกคําเชิญ",- "members.editor": "บรรณาธิการ","members.editorTip": "สามารถสร้างและแก้ไขแอปได้","members.email": "อีเมล","members.emailInvalid": "รูปแบบอีเมลไม่ถูกต้อง",@@ -272,14 +269,12 @@"members.invite": "เพิ่ม","members.inviteTeamMember": "เพิ่มสมาชิกในทีม","members.inviteTeamMemberTip": "พวกเขาสามารถเข้าถึงข้อมูลทีมของคุณได้โดยตรงหลังจากลงชื่อเข้าใช้",- "members.invitedAsRole": "ได้รับเชิญให้เป็นผู้ใช้ {{role}}",+ "members.invitedAsRole": "ได้รับเชิญให้เป็น {{role}}","members.lastActive": "ใช้งานล่าสุด","members.name": "ชื่อ","members.noNewInvitationsSent": "ไม่มีการส่งคำเชิญใหม่",- "members.normal": "ปกติ","members.normalTip": "ใช้ได้เฉพาะแอพ สร้างแอพไม่ได้","members.ok": "ตกลง, ได้",- "members.owner": "เจ้าของ","members.pending": "รอ ","members.removeFromTeam": "ลบออกจากทีม","members.removeFromTeamTip": "จะลบการเข้าถึงของทีม",@@ -605,9 +600,6 @@"placeholder.input": "กรุณากรอก","placeholder.search": "ค้นหา...","placeholder.select": "กรุณาเลือก",- "plugin.serpapi.apiKey": "คีย์ API",- "plugin.serpapi.apiKeyPlaceholder": "ป้อนคีย์ API ของคุณ",- "plugin.serpapi.keyFrom": "รับคีย์ SerpAPI ของคุณจากหน้าบัญชี SerpAPI","promptEditor.context.item.desc": "แทรกเทมเพลตบริบท","promptEditor.context.item.title": "บริบท","promptEditor.context.modal.add": "เพิ่มบริบท",diff --git a/web/i18n/tr-TR/app.json b/web/i18n/tr-TR/app.jsonindex 10263d5f22d..ffb77396d3c 100644--- a/web/i18n/tr-TR/app.json+++ b/web/i18n/tr-TR/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "Yapılandırılmış Çıktılar, modelin sağladığınız JSON Şemasına uyacak şekilde her zaman yanıtlar üretmesini sağlayan bir özelliktir.","studio.allApps": "Tüm Uygulamalar","studio.apps": "Uygulamalar",- "studio.filters.allCreators": "Tüm yaratıcılar",- "studio.filters.creators": "Yaratıcılar",+ "studio.filters.allCreators": "Tüm oluşturanlar",+ "studio.filters.creators": "Oluşturanlar","studio.filters.reset": "Sıfırla","studio.filters.searchCreators": "Yaratıcıyı ara...","studio.filters.types": "Türler",diff --git a/web/i18n/tr-TR/common.json b/web/i18n/tr-TR/common.jsonindex 93f9bd14f42..5b0fb47bdb8 100644--- a/web/i18n/tr-TR/common.json+++ b/web/i18n/tr-TR/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Çalışma alanını değiştir","mcpPage.description": "Uygulamalarınıza harici araç ve servislere erişim vermek için MCP sunucularını bağlayın ve yönetin.",- "members.admin": "Yönetici","members.adminTip": "Uygulama oluşturabilir ve takım ayarlarını yönetebilir","members.alreadyInTeam": "Zaten ekipte","members.alreadyInTeamTip": "Bu kullanıcıların bu çalışma alanına zaten erişimi var.","members.builder": "Oluşturucu","members.builderTip": "Kendi uygulamalarını oluşturup düzenleyebilir",- "members.datasetOperator": "Bilgi Yöneticisi","members.datasetOperatorTip": "Sadece bilgi tabanını yönetebilir","members.deleteMember": "Üyeyi Sil","members.disInvite": "Davetiyeyi iptal et",- "members.editor": "Editör","members.editorTip": "Uygulama oluşturabilir ve düzenleyebilir","members.email": "E-posta","members.emailInvalid": "Geçersiz E-posta Formatı",@@ -272,14 +269,12 @@"members.invite": "Ekle","members.inviteTeamMember": "Takım Üyesi Ekle","members.inviteTeamMemberTip": "Giriş yaptıktan sonra takım verilerinize doğrudan erişebilirler.",- "members.invitedAsRole": "{{role}} kullanıcısı olarak davet edildi",+ "members.invitedAsRole": "{{role}} olarak davet edildi","members.lastActive": "SON AKTİF","members.name": "İSİM","members.noNewInvitationsSent": "Yeni davet gönderilmedi",- "members.normal": "Normal","members.normalTip": "Sadece uygulamaları kullanabilir, uygulama oluşturamaz","members.ok": "Tamam",- "members.owner": "Sahibi","members.pending": "Beklemede...","members.removeFromTeam": "Takımdan Kaldır","members.removeFromTeamTip": "Takım erişimi kaldırılacak",@@ -605,9 +600,6 @@"placeholder.input": "Lütfen girin","placeholder.search": "Ara...","placeholder.select": "Lütfen seçin",- "plugin.serpapi.apiKey": "API Anahtarı",- "plugin.serpapi.apiKeyPlaceholder": "API anahtarınızı girin",- "plugin.serpapi.keyFrom": "SerpAPI Hesap Sayfasından SerpAPI anahtarınızı alın","promptEditor.context.item.desc": "Bağlam şablonunu ekle","promptEditor.context.item.title": "Bağlam","promptEditor.context.modal.add": "Bağlam Ekle",diff --git a/web/i18n/uk-UA/app.json b/web/i18n/uk-UA/app.jsonindex c2673359135..2bdcb3b71bb 100644--- a/web/i18n/uk-UA/app.json+++ b/web/i18n/uk-UA/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "Структуровані виходи - це функція, яка забезпечує, що модель завжди генеруватиме відповіді, що відповідають наданій вами схемі JSON.","studio.allApps": "Усі застосунки","studio.apps": "програми",- "studio.filters.allCreators": "Всі творці",- "studio.filters.creators": "Творці",+ "studio.filters.allCreators": "Усі автори",+ "studio.filters.creators": "Автори","studio.filters.reset": "Скинути","studio.filters.searchCreators": "Творець пошуку...","studio.filters.types": "Типи",diff --git a/web/i18n/uk-UA/common.json b/web/i18n/uk-UA/common.jsonindex ff458338d3d..9c10c3a9610 100644--- a/web/i18n/uk-UA/common.json+++ b/web/i18n/uk-UA/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Перемкнути робочий простір","mcpPage.description": "Підключайте й керуйте MCP-серверами, щоб ваші застосунки мали доступ до зовнішніх інструментів і сервісів.",- "members.admin": "Адміністратор","members.adminTip": "Може створювати програми та керувати налаштуваннями команди","members.alreadyInTeam": "Уже в команді","members.alreadyInTeamTip": "Ці користувачі вже мають доступ до цього робочого простору.","members.builder": "Будівник","members.builderTip": "Може створювати та редагувати власні програми",- "members.datasetOperator": "Адміністратор знань","members.datasetOperatorTip": "Тільки може управляти базою знань","members.deleteMember": "Видалити учасника","members.disInvite": "Скасувати запрошення",- "members.editor": "Редактор","members.editorTip": "Може створювати програми, але не може керувати налаштуваннями команди","members.email": "Електронна пошта","members.emailInvalid": "Недійсний формат електронної пошти",@@ -272,14 +269,12 @@"members.invite": "Додати","members.inviteTeamMember": "Додати учасника команди","members.inviteTeamMemberTip": "Вони зможуть отримати доступ до даних вашої команди безпосередньо після входу.",- "members.invitedAsRole": "Запрошено як користувача {{role}}",+ "members.invitedAsRole": "Запрошено як {{role}}","members.lastActive": "ОСТАННЯ АКТИВНІСТЬ","members.name": "ІМ'Я","members.noNewInvitationsSent": "Нові запрошення не надіслано",- "members.normal": "Звичайний","members.normalTip": "Може лише використовувати програми, не може створювати програми","members.ok": "ОК",- "members.owner": "Власник","members.pending": "В очікуванні...","members.removeFromTeam": "Видалити з команди","members.removeFromTeamTip": "Буде видалено доступ до команди",@@ -605,9 +600,6 @@"placeholder.input": "Будь ласка, введіть текст","placeholder.search": "Пошук...","placeholder.select": "Будь ласка, оберіть параметр",- "plugin.serpapi.apiKey": "Ключ API",- "plugin.serpapi.apiKeyPlaceholder": "Введіть свій ключ API",- "plugin.serpapi.keyFrom": "Отримайте свій ключ SerpAPI зі сторінки облікового запису SerpAPI","promptEditor.context.item.desc": "Вставити шаблон контексту","promptEditor.context.item.title": "Контекст","promptEditor.context.modal.add": "Додати контекст",diff --git a/web/i18n/vi-VN/app.json b/web/i18n/vi-VN/app.jsonindex d8f997069be..41ca574c10b 100644--- a/web/i18n/vi-VN/app.json+++ b/web/i18n/vi-VN/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "Đầu ra có cấu trúc là một tính năng đảm bảo rằng mô hình sẽ luôn tạo ra các phản hồi tuân theo sơ đồ JSON mà bạn cung cấp.","studio.allApps": "Tất cả ứng dụng","studio.apps": "Ứng dụng",- "studio.filters.allCreators": "Tất cả người sáng tạo",- "studio.filters.creators": "Người sáng tạo",+ "studio.filters.allCreators": "Tất cả người tạo",+ "studio.filters.creators": "Người tạo","studio.filters.reset": "Đặt lại","studio.filters.searchCreators": "Tìm kiếm người tạo...","studio.filters.types": "Các loại",diff --git a/web/i18n/vi-VN/common.json b/web/i18n/vi-VN/common.jsonindex 3d344ce5767..6f9566bf197 100644--- a/web/i18n/vi-VN/common.json+++ b/web/i18n/vi-VN/common.json@@ -249,17 +249,14 @@"mainNav.workspace.sort.openMenu": "Sort workspaces","mainNav.workspace.switchWorkspace": "Chuyển workspace","mcpPage.description": "Kết nối và quản lý máy chủ MCP để ứng dụng của bạn truy cập các công cụ và dịch vụ bên ngoài.",- "members.admin": "Quản trị viên","members.adminTip": "Có thể xây dựng ứng dụng và quản lý cài đặt nhóm","members.alreadyInTeam": "Đã ở trong nhóm","members.alreadyInTeamTip": "Những người dùng này đã có quyền truy cập vào không gian làm việc này.","members.builder": "Chủ thầu","members.builderTip": "Có thể xây dựng và chỉnh sửa ứng dụng của riêng mình",- "members.datasetOperator": "Quản trị viên kiến thức","members.datasetOperatorTip": "Chỉ có thể quản lý cơ sở kiến thức","members.deleteMember": "Xóa thành viên","members.disInvite": "Hủy lời mời",- "members.editor": "Biên tập viên","members.editorTip": "Có thể xây dựng ứng dụng, không thể quản lý cài đặt nhóm","members.email": "Email","members.emailInvalid": "Định dạng Email không hợp lệ",@@ -276,10 +273,8 @@"members.lastActive": "HOẠT ĐỘNG GẦN ĐÂY","members.name": "TÊN","members.noNewInvitationsSent": "Không có lời mời mới nào được gửi",- "members.normal": "Bình thường","members.normalTip": "Chỉ có thể sử dụng ứng dụng, không thể xây dựng ứng dụng","members.ok": "OK",- "members.owner": "Chủ sở hữu","members.pending": "Đang chờ...","members.removeFromTeam": "Xóa khỏi nhóm","members.removeFromTeamTip": "Sẽ xóa quyền truy cập nhóm",@@ -605,9 +600,6 @@"placeholder.input": "Vui lòng nhập","placeholder.search": "Tìm kiếm...","placeholder.select": "Vui lòng chọn",- "plugin.serpapi.apiKey": "Khóa API",- "plugin.serpapi.apiKeyPlaceholder": "Nhập khóa API của bạn",- "plugin.serpapi.keyFrom": "Nhận khóa SerpAPI của bạn từ Trang tài khoản SerpAPI","promptEditor.context.item.desc": "Chèn mẫu bối cảnh","promptEditor.context.item.title": "Bối cảnh","promptEditor.context.modal.add": "Thêm Bối cảnh",diff --git a/web/i18n/zh-Hans/app.json b/web/i18n/zh-Hans/app.jsonindex efb8bb866aa..640b54e0987 100644--- a/web/i18n/zh-Hans/app.json+++ b/web/i18n/zh-Hans/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "结构化输出是一项功能,可确保模型始终生成符合您提供的 JSON 模式的响应","studio.allApps": "所有应用","studio.apps": "应用程序",- "studio.filters.allCreators": "所有创作者",- "studio.filters.creators": "创作者",+ "studio.filters.allCreators": "所有创建者",+ "studio.filters.creators": "创建者","studio.filters.reset": "重置","studio.filters.searchCreators": "搜索创作者...","studio.filters.types": "类型",diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.jsonindex b7903ed354f..ec6c72cc701 100644--- a/web/i18n/zh-Hans/common.json+++ b/web/i18n/zh-Hans/common.json@@ -249,17 +249,18 @@"mainNav.workspace.sort.openMenu": "排序工作空间","mainNav.workspace.switchWorkspace": "切换工作空间","mcpPage.description": "连接并管理 MCP 服务器,让你的应用可以访问外部工具与服务。",- "members.admin": "管理员","members.adminTip": "能够建立应用程序和管理团队设置","members.alreadyInTeam": "已在团队中","members.alreadyInTeamTip": "以下用户已经可以访问此工作空间。",+ "members.assignRoles": "分配角色",+ "members.assignRolesModal.description": "为该成员选择要分配的角色,所选角色的权限将被合并。",+ "members.assignRolesModal.selectedCount": "已选 {{count}} 项",+ "members.assignRolesModal.title": "分配角色","members.builder": "构建器","members.builderTip": "可以构建和编辑自己的应用程序",- "members.datasetOperator": "知识库管理员","members.datasetOperatorTip": "只能管理知识库","members.deleteMember": "删除成员","members.disInvite": "取消邀请",- "members.editor": "编辑","members.editorTip": "能够建立并编辑应用程序,不能管理团队设置","members.email": "邮箱","members.emailInvalid": "邮箱格式无效",@@ -272,18 +273,40 @@"members.invite": "添加","members.inviteTeamMember": "添加团队成员","members.inviteTeamMemberTip": "对方在登录后可以访问你的团队数据。",- "members.invitedAsRole": "邀请为{{role}}用户",+ "members.invitedAsRole": "邀请为{{role}}","members.lastActive": "上次活动时间",+ "members.memberActions": "成员操作",+ "members.memberDetails.assign": "分配",+ "members.memberDetails.assignedRoles": "已分配角色",+ "members.memberDetails.customGroup": "自定义",+ "members.memberDetails.generalGroup": "通用",+ "members.memberDetails.openAria": "打开 {{name}} 的成员详情",+ "members.memberDetails.permissions.assignRoles": "分配角色",+ "members.memberDetails.permissions.createApps": "创建应用",+ "members.memberDetails.permissions.createDatasets": "创建知识库",+ "members.memberDetails.permissions.editApps": "编辑应用",+ "members.memberDetails.permissions.editDatasets": "编辑知识库",+ "members.memberDetails.permissions.inviteMembers": "邀请成员",+ "members.memberDetails.permissions.manageBilling": "管理订阅",+ "members.memberDetails.permissions.manageDatasets": "管理知识库",+ "members.memberDetails.permissions.removeMembers": "移除成员",+ "members.memberDetails.permissions.transferOwnership": "转移所有权",+ "members.memberDetails.permissions.useApps": "使用应用",+ "members.memberDetails.permissions.workspaceSettings": "工作空间设置",+ "members.memberDetails.removeRoleAria": "移除 {{role}} 角色",+ "members.memberDetails.roleActionsAria": "打开 {{role}} 角色操作",+ "members.memberDetails.roleNoPermissionSummary": "当前角色没有任何权限。",+ "members.memberDetails.rolePermissionSummary": "{{role}} 可以<permissionList>{{permissions}}</permissionList>",+ "members.memberDetails.title": "成员详情","members.name": "姓名","members.noNewInvitationsSent": "没有新的邀请发送",- "members.normal": "成员","members.normalTip": "只能使用应用程序,不能建立应用程序","members.ok": "好的",- "members.owner": "所有者","members.pending": "待定...","members.removeFromTeam": "移出团队","members.removeFromTeamTip": "将取消团队访问","members.role": "角色",+ "members.selectRole": "请选择角色","members.sendInvite": "发送邀请","members.setAdmin": "设为管理员","members.setBuilder": "Set as builder(设置为构建器)",@@ -557,6 +580,7 @@"operation.lineBreak": "换行","operation.log": "日志","operation.more": "更多",+ "operation.moreActions": "更多操作","operation.no": "否","operation.noSearchCount": "0 个 {{content}}","operation.noSearchResults": "没有找到{{content}}",@@ -605,9 +629,6 @@"placeholder.input": "请输入","placeholder.search": "搜索...","placeholder.select": "请选择",- "plugin.serpapi.apiKey": "API Key",- "plugin.serpapi.apiKeyPlaceholder": "输入你的 API 密钥",- "plugin.serpapi.keyFrom": "从 SerpAPI 帐户页面获取您的 SerpAPI 密钥","promptEditor.context.item.desc": "插入上下文模板","promptEditor.context.item.title": "上下文","promptEditor.context.modal.add": "添加上下文",@@ -670,6 +691,7 @@"provider.saveFailed": "API 密钥保存失败","provider.validatedError": "校验失败:","provider.validating": "验证密钥中...",+ "settings.ResourceAccess": "访问权限规则","settings.account": "我的账户","settings.accountGroup": "通用","settings.agentStrategy": "Agent 策略",@@ -689,6 +711,9 @@"settings.plugin": "集成","settings.preferences": "偏好设置","settings.provider": "模型供应商",+ "settings.resourceAccess": "访问权限",+ "settings.resourceAccessDescription": "配置应用和知识库可使用的权限规则。权限规则可在具体资源访问配置中分配给成员。",+ "settings.rolesAndPermissions": "角色与权限","settings.settings": "设置","settings.swaggerAPIAsTool": "Swagger API 作为工具","settings.trigger": "触发器",diff --git a/web/i18n/zh-Hans/dataset-settings.json b/web/i18n/zh-Hans/dataset-settings.jsonindex 7c3698a9ffc..24028be1690 100644--- a/web/i18n/zh-Hans/dataset-settings.json+++ b/web/i18n/zh-Hans/dataset-settings.json@@ -27,6 +27,7 @@"form.numberOfKeywords": "关键词数量","form.onSearchResults": "没有成员匹配您的搜索查询。\n请尝试其他关键词。","form.permissions": "可见权限",+ "form.permissionsAccessConfig": "前往访问配置","form.permissionsAllMember": "所有团队成员","form.permissionsInvitedMembers": "部分团队成员","form.permissionsOnlyMe": "只有我",diff --git a/web/i18n/zh-Hans/permission-keys.json b/web/i18n/zh-Hans/permission-keys.jsonnew file mode 100644index 00000000000..08154da397a--- /dev/null+++ b/web/i18n/zh-Hans/permission-keys.json@@ -0,0 +1,50 @@+{+ "api_extension.manage": "管理API扩展",+ "app.access_config": "配置应用访问权限",+ "app.acl.access_config": "配置应用访问权限",+ "app.acl.delete": "删除应用",+ "app.acl.edit": "编辑与编排应用",+ "app.acl.import_export_dsl": "导入 / 导出 DSL",+ "app.acl.monitor": "监测与运维",+ "app.acl.preview": "预览应用",+ "app.acl.release_and_version": "应用发布与版本管理",+ "app.acl.test_and_run": "测试与使用应用",+ "app.acl.view_layout": "编排页只读",+ "app.create_and_management": "创建和管理自己创建的应用",+ "app.tag.manage": "管理应用标签",+ "app_library.access": "访问应用库",+ "billing.manage": "更换订阅套餐",+ "billing.subscription.manage": "在账单门户管理账单与订阅方案",+ "billing.view": "在设置中访问账单页面",+ "credential.manage": "管理凭据",+ "credential.use": "使用凭据",+ "customization.manage": "管理定制",+ "data_source.manage": "管理数据来源",+ "dataset.access_config": "配置知识库访问权限",+ "dataset.acl.access_config": "配置知识库访问权限",+ "dataset.acl.delete": "删除知识库",+ "dataset.acl.delete_file": "删除知识库文件",+ "dataset.acl.document_download": "文档下载",+ "dataset.acl.edit": "知识库编辑",+ "dataset.acl.import_export_dsl": "从 DSL 导入 / 导出知识流水线 DSL",+ "dataset.acl.pipeline_release": "知识库流水线发布与版本管理",+ "dataset.acl.pipeline_test": "流水线测试",+ "dataset.acl.preview": "预览知识库",+ "dataset.acl.readonly": "知识库只读",+ "dataset.acl.retrieval_recall": "知识库检索召回",+ "dataset.acl.use": "向知识库新增文件",+ "dataset.api_key.manage": "管理知识库 API Key",+ "dataset.create_and_management": "创建和管理自己创建的知识库",+ "dataset.external.connect": "连接外部知识库",+ "dataset.tag.manage": "管理知识库标签",+ "mcp.manage": "管理MCP",+ "plugin.debug": "调试插件",+ "plugin.install": "安装与更新插件",+ "plugin.manage": "管理插件",+ "plugin.plugin_preferences": "管理插件偏好",+ "snippets.create_and_modify": "创建和修改 Snippets",+ "snippets.management": "管理 Snippets",+ "tool.manage": "管理工具",+ "workspace.member.manage": "管理成员",+ "workspace.role.manage": "管理角色权限与访问权限规则"+}diff --git a/web/i18n/zh-Hans/permission.json b/web/i18n/zh-Hans/permission.jsonnew file mode 100644index 00000000000..4229276f1ac--- /dev/null+++ b/web/i18n/zh-Hans/permission.json@@ -0,0 +1,104 @@+{+ "accessRule.actions": "操作",+ "accessRule.addMemberAria": "添加 {{name}}",+ "accessRule.addMembersTitle": "添加成员",+ "accessRule.allPermittedMembers": "全部成员",+ "accessRule.allPermittedMembersDescription": "所有具备对应角色权限的成员均可访问",+ "accessRule.appDescription": "设置谁可以访问此应用,以及个别成员的权限例外",+ "accessRule.appTitle": "应用访问规则",+ "accessRule.changeOpenScopeDescription": "更改开放范围会重置此资源的所有个人权限设置。切换后,你需要重新添加成员专属权限。",+ "accessRule.changeOpenScopeTitle": "更改资源开放范围?",+ "accessRule.collapseSection": "折叠 {{title}}",+ "accessRule.copied": "访问规则已复制",+ "accessRule.created": "访问规则已创建",+ "accessRule.datasetDescription": "控制此知识库对哪些成员开放。成员仍需具备角色权限才能查看或操作此知识库。",+ "accessRule.datasetTitle": "知识库访问规则",+ "accessRule.defaultPermission": "按角色权限",+ "accessRule.deleteDescription": "此访问规则将被永久删除,并从资源授权列表中移除。",+ "accessRule.deleteTitle": "删除“{{name}}”?",+ "accessRule.deleted": "访问规则已删除",+ "accessRule.exceptionPermissionFor": "{{name}} 的例外权限",+ "accessRule.expandSection": "展开 {{title}}",+ "accessRule.individualPermissionSettings": "个人权限设置",+ "accessRule.individualPermissionSettingsTip": "为指定协作者或群组设置权限例外。这些设置会覆盖默认访问级别。",+ "accessRule.lockedSummary_one": "· {{count}} 个锁定",+ "accessRule.lockedSummary_other": "· {{count}} 个锁定",+ "accessRule.maintainer": "维护者",+ "accessRule.member": "成员",+ "accessRule.newPermissionSet": "新建权限集",+ "accessRule.noAvailableMembers": "暂无可添加成员",+ "accessRule.noDescription": "无描述",+ "accessRule.noRoles": "暂无角色",+ "accessRule.noRules": "暂无访问规则",+ "accessRule.noUserAccessSettings": "暂无个人权限设置",+ "accessRule.permission": "权限",+ "accessRule.resourceOpenScope": "访问范围",+ "accessRule.resourceOpenScopeDescription": "选择此资源对哪些成员开放。角色权限仍决定每位成员可执行的操作。",+ "accessRule.specificMembersOnly": "指定成员",+ "accessRule.specificMembersOnlyDescription": "仅被添加到下方列表的成员可访问",+ "accessRule.summary_one": "{{count}} 个权限集",+ "accessRule.summary_other": "{{count}} 个权限集",+ "accessRule.updated": "访问规则已更新",+ "common.duplicateAction": "创建副本",+ "group.app": "应用",+ "group.app_acl": "应用访问权限",+ "group.billing": "账单",+ "group.credential": "凭据",+ "group.dataset": "知识库",+ "group.dataset_acl": "知识库访问权限",+ "group.plugin": "插件",+ "group.tool_mcp": "工具与MCP",+ "group.workspace": "工作空间",+ "permissionList.clearAll": "清除全部",+ "permissionList.collapseGroup": "折叠分组",+ "permissionList.expandGroup": "展开分组",+ "permissionList.noPermissionsFound": "未找到权限",+ "permissionList.selectAll": "全选",+ "permissionSet.descriptionLabel": "描述",+ "permissionSet.descriptionPlaceholder": "描述此权限集授予的能力",+ "permissionSet.learnMore": "了解更多权限说明",+ "permissionSet.modal.create.app.description": "创建可在访问规则中引用的应用权限集,以便快速授权。",+ "permissionSet.modal.create.app.title": "创建应用权限集",+ "permissionSet.modal.create.dataset.description": "创建可在访问规则中引用的知识库权限集,以便快速授权。",+ "permissionSet.modal.create.dataset.title": "创建知识库权限集",+ "permissionSet.modal.edit.app.description": "修改此权限集的名称、描述和授予的权限。",+ "permissionSet.modal.edit.app.title": "编辑应用权限集",+ "permissionSet.modal.edit.dataset.description": "修改此权限集的名称、描述和授予的权限。",+ "permissionSet.modal.edit.dataset.title": "编辑知识库权限集",+ "permissionSet.modal.view.app.description": "查看此权限集的名称、描述和授予的权限。",+ "permissionSet.modal.view.app.title": "查看应用权限集",+ "permissionSet.modal.view.dataset.description": "查看此权限集的名称、描述和授予的权限。",+ "permissionSet.modal.view.dataset.title": "查看知识库权限集",+ "permissionSet.nameLabel": "权限集名称",+ "permissionSet.namePlaceholder": "例如:可导出 DSL",+ "permissionSet.permissions": "权限",+ "role.addRole": "创建角色",+ "role.copyMembersDescription_one": "“{{name}}”已分配给 {{count}} 个成员。是否让新角色副本包含相同成员?",+ "role.copyMembersDescription_other": "“{{name}}”已分配给 {{count}} 个成员。是否让新角色副本包含相同成员?",+ "role.copyMembersLoading": "正在查询已绑定成员...",+ "role.copyMembersTitle": "复制成员绑定?",+ "role.created": "角色已创建",+ "role.deleteDescription": "此角色将被永久删除,并从使用它的成员或访问规则中移除。",+ "role.deleteTitle": "删除“{{name}}”?",+ "role.deleted": "角色已删除",+ "role.duplicated": "角色已复制",+ "role.groups.builtin": "系统角色",+ "role.groups.custom": "自定义角色",+ "role.loading": "角色加载中...",+ "role.modal.create.description": "创建角色并分配权限",+ "role.modal.create.title": "创建角色",+ "role.modal.descriptionLabel": "描述",+ "role.modal.descriptionPlaceholder": "描述该角色负责的事项",+ "role.modal.edit.description": "编辑角色详情和权限",+ "role.modal.edit.title": "编辑角色",+ "role.modal.nameLabel": "角色名称",+ "role.modal.namePlaceholder": "例如:市场负责人",+ "role.modal.view.description": "查看角色详情和权限",+ "role.modal.view.title": "查看角色",+ "role.noDescription": "无描述",+ "role.noMatchingRoles": "未找到匹配角色",+ "role.searchPlaceholder": "搜索角色...",+ "role.updated": "角色已更新",+ "role.workspaceRoles.description": "创建角色并定义每个角色在此工作空间中可以执行的操作。",+ "role.workspaceRoles.title": "工作空间角色"+}diff --git a/web/i18n/zh-Hans/plugin.json b/web/i18n/zh-Hans/plugin.jsonindex 131ea9e3a0f..504815bdb71 100644--- a/web/i18n/zh-Hans/plugin.json+++ b/web/i18n/zh-Hans/plugin.json@@ -245,6 +245,7 @@"pluginInfoModal.title": "集成信息","pluginPublishGuide": "集成发布指南","privilege.admins": "管理员",+ "privilege.configurePermissionsInSettings": "前往设置 > 角色与权限中配置插件权限。","privilege.everyone": "所有人","privilege.noDebugPermissionTooltip": "你没有调试集成的权限","privilege.noInstallPermissionTooltip": "你没有安装和管理集成的权限",diff --git a/web/i18n/zh-Hant/app.json b/web/i18n/zh-Hant/app.jsonindex d2519f8d5e3..b989a327960 100644--- a/web/i18n/zh-Hant/app.json+++ b/web/i18n/zh-Hant/app.json@@ -246,8 +246,8 @@"structOutput.structuredTip": "結構化輸出是一項功能,確保模型始終生成符合您提供的 JSON 架構的響應。","studio.allApps": "所有應用","studio.apps": "應用程式",- "studio.filters.allCreators": "所有創作者",- "studio.filters.creators": "創作者",+ "studio.filters.allCreators": "所有創建者",+ "studio.filters.creators": "創建者","studio.filters.reset": "重置","studio.filters.searchCreators": "搜尋創作者...","studio.filters.types": "類型",diff --git a/web/i18n/zh-Hant/common.json b/web/i18n/zh-Hant/common.jsonindex 0dab2a8b720..9a9aae7746b 100644--- a/web/i18n/zh-Hant/common.json+++ b/web/i18n/zh-Hant/common.json@@ -249,17 +249,18 @@"mainNav.workspace.sort.openMenu": "排序工作區","mainNav.workspace.switchWorkspace": "切換工作區","mcpPage.description": "連接並管理 MCP 伺服器,讓你的應用可以存取外部工具和服務。",- "members.admin": "管理員","members.adminTip": "能夠建立應用程式和管理團隊設定","members.alreadyInTeam": "已在團隊中","members.alreadyInTeamTip": "以下使用者已經可以存取此工作區。",+ "members.assignRoles": "分配角色",+ "members.assignRolesModal.description": "為該成員選擇要分配的角色,所選角色的權限將被合併。",+ "members.assignRolesModal.selectedCount": "已選 {{count}} 項",+ "members.assignRolesModal.title": "分配角色","members.builder": "建築工人","members.builderTip": "可以構建和編輯自己的應用程式",- "members.datasetOperator": "知識管理員","members.datasetOperatorTip": "只能管理知識庫","members.deleteMember": "刪除成員","members.disInvite": "取消邀請",- "members.editor": "編輯","members.editorTip": "能夠建立並編輯應用程式,不能管理團隊設定","members.email": "郵箱","members.emailInvalid": "郵箱格式無效",@@ -272,18 +273,40 @@"members.invite": "新增","members.inviteTeamMember": "新增團隊成員","members.inviteTeamMemberTip": "對方在登入後可以訪問你的團隊資料。",- "members.invitedAsRole": "邀請為{{role}}使用者",+ "members.invitedAsRole": "邀請為{{role}}","members.lastActive": "上次活動時間",+ "members.memberActions": "成員操作",+ "members.memberDetails.assign": "分配",+ "members.memberDetails.assignedRoles": "已分配角色",+ "members.memberDetails.customGroup": "自訂",+ "members.memberDetails.generalGroup": "通用",+ "members.memberDetails.openAria": "開啟 {{name}} 的成員詳情",+ "members.memberDetails.permissions.assignRoles": "分配角色",+ "members.memberDetails.permissions.createApps": "建立應用",+ "members.memberDetails.permissions.createDatasets": "建立知識庫",+ "members.memberDetails.permissions.editApps": "編輯應用",+ "members.memberDetails.permissions.editDatasets": "編輯知識庫",+ "members.memberDetails.permissions.inviteMembers": "邀請成員",+ "members.memberDetails.permissions.manageBilling": "管理訂閱",+ "members.memberDetails.permissions.manageDatasets": "管理知識庫",+ "members.memberDetails.permissions.removeMembers": "移除成員",+ "members.memberDetails.permissions.transferOwnership": "轉移所有權",+ "members.memberDetails.permissions.useApps": "使用應用",+ "members.memberDetails.permissions.workspaceSettings": "工作空間設定",+ "members.memberDetails.removeRoleAria": "移除 {{role}} 角色",+ "members.memberDetails.roleActionsAria": "開啟 {{role}} 角色操作",+ "members.memberDetails.roleNoPermissionSummary": "目前角色沒有任何權限。",+ "members.memberDetails.rolePermissionSummary": "{{role}} 可以<permissionList>{{permissions}}</permissionList>",+ "members.memberDetails.title": "成員詳情","members.name": "姓名","members.noNewInvitationsSent": "沒有新的邀請送出",- "members.normal": "成員","members.normalTip": "只能使用應用程式,不能建立應用程式","members.ok": "好的",- "members.owner": "所有者","members.pending": "待定...","members.removeFromTeam": "移出團隊","members.removeFromTeamTip": "將取消團隊訪問","members.role": "角色",+ "members.selectRole": "請選擇角色","members.sendInvite": "傳送邀請","members.setAdmin": "設為管理員","members.setBuilder": "Set as builder(設置為建構器)",@@ -557,6 +580,7 @@"operation.lineBreak": "換行","operation.log": "日誌","operation.more": "更多",+ "operation.moreActions": "更多操作","operation.no": "不","operation.noSearchCount": "0 {{content}}","operation.noSearchResults": "未找到 {{content}}",@@ -605,9 +629,6 @@"placeholder.input": "請輸入","placeholder.search": "搜尋...","placeholder.select": "請選擇",- "plugin.serpapi.apiKey": "API Key",- "plugin.serpapi.apiKeyPlaceholder": "輸入你的 API 金鑰",- "plugin.serpapi.keyFrom": "從 SerpAPI 帳戶頁面獲取您的 SerpAPI 金鑰","promptEditor.context.item.desc": "插入上下文模板","promptEditor.context.item.title": "上下文","promptEditor.context.modal.add": "新增上下文",@@ -670,6 +691,7 @@"provider.saveFailed": "API 金鑰儲存失敗","provider.validatedError": "校驗失敗:","provider.validating": "驗證金鑰中...",+ "settings.ResourceAccess": "訪問權限規則","settings.account": "我的賬戶","settings.accountGroup": "賬戶","settings.agentStrategy": "Agent 策略",@@ -689,6 +711,9 @@"settings.plugin": "集成","settings.preferences": "偏好設定","settings.provider": "模型供應商",+ "settings.resourceAccess": "訪問權限",+ "settings.resourceAccessDescription": "配置應用和知識庫可使用的權限規則。權限規則可在具體資源訪問配置中分配給成員。",+ "settings.rolesAndPermissions": "角色與權限","settings.settings": "設定","settings.swaggerAPIAsTool": "Swagger API 作為工具","settings.trigger": "觸發器",diff --git a/web/i18n/zh-Hant/permission-keys.json b/web/i18n/zh-Hant/permission-keys.jsonnew file mode 100644index 00000000000..08830764bf1--- /dev/null+++ b/web/i18n/zh-Hant/permission-keys.json@@ -0,0 +1,50 @@+{+ "api_extension.manage": "管理API擴充配置",+ "app.access_config": "配置應用訪問權限",+ "app.acl.access_config": "配置應用訪問權限",+ "app.acl.delete": "刪除應用",+ "app.acl.edit": "編輯與編排應用",+ "app.acl.import_export_dsl": "匯入 / 匯出 DSL",+ "app.acl.monitor": "監測與維運",+ "app.acl.preview": "預覽應用",+ "app.acl.release_and_version": "應用發布與版本管理",+ "app.acl.test_and_run": "測試與使用應用",+ "app.acl.view_layout": "編排頁唯讀",+ "app.create_and_management": "建立與管理自己建立的應用",+ "app.tag.manage": "管理應用標籤",+ "app_library.access": "訪問應用庫",+ "billing.manage": "更換訂閱套餐",+ "billing.subscription.manage": "在帳單入口網站管理帳單與訂閱方案",+ "billing.view": "在設定中訪問帳單頁面",+ "credential.manage": "管理憑據",+ "credential.use": "使用憑據",+ "customization.manage": "管理自訂",+ "data_source.manage": "管理資料來源配置",+ "dataset.access_config": "配置知識庫訪問權限",+ "dataset.acl.access_config": "配置知識庫訪問權限",+ "dataset.acl.delete": "刪除知識庫",+ "dataset.acl.delete_file": "刪除知識庫檔案",+ "dataset.acl.document_download": "文件下載",+ "dataset.acl.edit": "知識庫編輯",+ "dataset.acl.import_export_dsl": "從 DSL 匯入 / 匯出知識流水線 DSL",+ "dataset.acl.pipeline_release": "知識庫流水線發布與版本管理",+ "dataset.acl.pipeline_test": "流水線測試",+ "dataset.acl.preview": "預覽知識庫",+ "dataset.acl.readonly": "知識庫唯讀",+ "dataset.acl.retrieval_recall": "知識庫檢索召回",+ "dataset.acl.use": "向知識庫新增檔案",+ "dataset.api_key.manage": "管理知識庫 API Key",+ "dataset.create_and_management": "建立與管理自己建立的知識庫",+ "dataset.external.connect": "連接外部知識庫",+ "dataset.tag.manage": "管理知識庫標籤",+ "mcp.manage": "管理MCP",+ "plugin.debug": "調試插件",+ "plugin.install": "安裝與更新插件",+ "plugin.manage": "管理插件",+ "plugin.plugin_preferences": "管理插件偏好設定",+ "snippets.create_and_modify": "建立和修改 Snippets",+ "snippets.management": "管理 Snippets",+ "tool.manage": "管理工具",+ "workspace.member.manage": "管理成員",+ "workspace.role.manage": "管理角色權限與訪問權限規則"+}diff --git a/web/i18n/zh-Hant/permission.json b/web/i18n/zh-Hant/permission.jsonnew file mode 100644index 00000000000..098c432bd10--- /dev/null+++ b/web/i18n/zh-Hant/permission.json@@ -0,0 +1,104 @@+{+ "accessRule.actions": "操作",+ "accessRule.addMemberAria": "新增 {{name}}",+ "accessRule.addMembersTitle": "新增成員",+ "accessRule.allPermittedMembers": "全部成員",+ "accessRule.allPermittedMembersDescription": "所有具備對應角色權限的成員均可訪問",+ "accessRule.appDescription": "設定誰可以訪問此應用,以及個別成員的權限例外",+ "accessRule.appTitle": "應用訪問規則",+ "accessRule.changeOpenScopeDescription": "更改開放範圍會重置此資源的所有個人權限設定。切換後,你需要重新新增成員專屬權限。",+ "accessRule.changeOpenScopeTitle": "更改資源開放範圍?",+ "accessRule.collapseSection": "折疊 {{title}}",+ "accessRule.copied": "訪問規則已複製",+ "accessRule.created": "訪問規則已建立",+ "accessRule.datasetDescription": "控制此知識庫對哪些成員開放。成員仍需具備角色權限才能查看或操作此知識庫。",+ "accessRule.datasetTitle": "知識庫訪問規則",+ "accessRule.defaultPermission": "按角色權限",+ "accessRule.deleteDescription": "此訪問規則將被永久刪除,並從資源授權列表中移除。",+ "accessRule.deleteTitle": "刪除「{{name}}」?",+ "accessRule.deleted": "訪問規則已刪除",+ "accessRule.exceptionPermissionFor": "{{name}} 的例外權限",+ "accessRule.expandSection": "展開 {{title}}",+ "accessRule.individualPermissionSettings": "個人權限設定",+ "accessRule.individualPermissionSettingsTip": "為指定協作者或群組設定權限例外。這些設定會覆蓋預設存取層級。",+ "accessRule.lockedSummary_one": "· {{count}} 個鎖定",+ "accessRule.lockedSummary_other": "· {{count}} 個鎖定",+ "accessRule.maintainer": "維護者",+ "accessRule.member": "成員",+ "accessRule.newPermissionSet": "新增權限集",+ "accessRule.noAvailableMembers": "暫無可新增成員",+ "accessRule.noDescription": "無描述",+ "accessRule.noRoles": "暫無角色",+ "accessRule.noRules": "暫無訪問規則",+ "accessRule.noUserAccessSettings": "暫無個人權限設定",+ "accessRule.permission": "權限",+ "accessRule.resourceOpenScope": "訪問範圍",+ "accessRule.resourceOpenScopeDescription": "選擇此資源對哪些成員開放。角色權限仍決定每位成員可執行的操作。",+ "accessRule.specificMembersOnly": "指定成員",+ "accessRule.specificMembersOnlyDescription": "僅被新增到下方列表的成員可訪問",+ "accessRule.summary_one": "{{count}} 個權限集",+ "accessRule.summary_other": "{{count}} 個權限集",+ "accessRule.updated": "訪問規則已更新",+ "common.duplicateAction": "建立副本",+ "group.app": "應用",+ "group.app_acl": "應用訪問權限",+ "group.billing": "帳單",+ "group.credential": "憑據",+ "group.dataset": "知識庫",+ "group.dataset_acl": "知識庫訪問權限",+ "group.plugin": "插件",+ "group.tool_mcp": "工具與MCP",+ "group.workspace": "工作空間",+ "permissionList.clearAll": "清除全部",+ "permissionList.collapseGroup": "折疊分組",+ "permissionList.expandGroup": "展開分組",+ "permissionList.noPermissionsFound": "未找到權限",+ "permissionList.selectAll": "全選",+ "permissionSet.descriptionLabel": "描述",+ "permissionSet.descriptionPlaceholder": "描述此權限集授予的能力",+ "permissionSet.learnMore": "了解更多權限說明",+ "permissionSet.modal.create.app.description": "建立可在訪問規則中引用的應用權限集,以便快速授權。",+ "permissionSet.modal.create.app.title": "建立應用權限集",+ "permissionSet.modal.create.dataset.description": "建立可在訪問規則中引用的知識庫權限集,以便快速授權。",+ "permissionSet.modal.create.dataset.title": "建立知識庫權限集",+ "permissionSet.modal.edit.app.description": "修改此權限集的名稱、描述和授予的權限。",+ "permissionSet.modal.edit.app.title": "編輯應用權限集",+ "permissionSet.modal.edit.dataset.description": "修改此權限集的名稱、描述和授予的權限。",+ "permissionSet.modal.edit.dataset.title": "編輯知識庫權限集",+ "permissionSet.modal.view.app.description": "查看此權限集的名稱、描述和授予的權限。",+ "permissionSet.modal.view.app.title": "查看應用權限集",+ "permissionSet.modal.view.dataset.description": "查看此權限集的名稱、描述和授予的權限。",+ "permissionSet.modal.view.dataset.title": "查看知識庫權限集",+ "permissionSet.nameLabel": "權限集名稱",+ "permissionSet.namePlaceholder": "例如:可匯出 DSL",+ "permissionSet.permissions": "權限",+ "role.addRole": "建立角色",+ "role.copyMembersDescription_one": "「{{name}}」已分配給 {{count}} 個成員。是否讓新角色副本包含相同成員?",+ "role.copyMembersDescription_other": "「{{name}}」已分配給 {{count}} 個成員。是否讓新角色副本包含相同成員?",+ "role.copyMembersLoading": "正在查詢已綁定成員...",+ "role.copyMembersTitle": "複製成員綁定?",+ "role.created": "角色已建立",+ "role.deleteDescription": "此角色將被永久刪除,並從使用它的成員或訪問規則中移除。",+ "role.deleteTitle": "刪除「{{name}}」?",+ "role.deleted": "角色已刪除",+ "role.duplicated": "角色已複製",+ "role.groups.builtin": "系統角色",+ "role.groups.custom": "自訂角色",+ "role.loading": "角色載入中...",+ "role.modal.create.description": "建立角色並分配權限",+ "role.modal.create.title": "建立角色",+ "role.modal.descriptionLabel": "描述",+ "role.modal.descriptionPlaceholder": "描述該角色負責的事項",+ "role.modal.edit.description": "編輯角色詳情和權限",+ "role.modal.edit.title": "編輯角色",+ "role.modal.nameLabel": "角色名稱",+ "role.modal.namePlaceholder": "例如:市場負責人",+ "role.modal.view.description": "查看角色詳情和權限",+ "role.modal.view.title": "查看角色",+ "role.noDescription": "無描述",+ "role.noMatchingRoles": "未找到匹配角色",+ "role.searchPlaceholder": "搜尋角色...",+ "role.updated": "角色已更新",+ "role.workspaceRoles.description": "建立角色並定義每個角色在此工作空間中可以執行的操作。",+ "role.workspaceRoles.title": "工作空間角色"+}diff --git a/web/models/access-control.ts b/web/models/access-control.tsindex f09db659613..db13e9159e0 100644--- a/web/models/access-control.ts+++ b/web/models/access-control.ts@@ -1,3 +1,5 @@+import type { AccessControlTemplateLanguage } from '@/i18n-config/language'+export const SubjectType = {GROUP: 'group',ACCOUNT: 'account',@@ -32,3 +34,237 @@ export type SubjectGroup = { subjectId: string, subjectType: SubjectType, groupDexport type SubjectAccount = { subjectId: string, subjectType: SubjectType, accountData: AccessControlAccount }export type Subject = SubjectGroup | SubjectAccount++type Permission = {+ key: string+ name: string+ description: string+}+export type PermissionGroup = {+ group_key: string+ group_name: string+ description: string+ permissions: Permission[]+}++export type PermissionGroups = {+ groups: PermissionGroup[]+}++export type PermissionKey = string++type RoleType = 'workspace' | 'app' | 'dataset'++export type RoleCategory = 'global_system_default' | 'global_custom'++export type Role = {+ id: string+ tenant_id: string+ type: RoleType+ category: RoleCategory+ name: string+ description: string+ is_builtin: boolean+ permission_keys: PermissionKey[]+ role_tag: 'owner' | '' // Used for identifying the unique owner role, which has some special handlings+}++type Pagination = {+ total_count: number+ per_page: number+ current_page: number+ total_pages: number+}++type PaginationParameters = {+ page?: number+ limit?: number+ reverse?: boolean+}++export type RoleListRequest = PaginationParameters & {+ include_owner?: 1 | 0+ language?: AccessControlTemplateLanguage+}++export type RoleListResponse = {+ data: Role[]+ pagination: Pagination+}++export type CreateRoleRequest = {+ name: string+ description?: string+ permission_keys?: PermissionKey[]+}++export type UpdateRolesRequest = {+ id: string+ name: string+ description?: string+ permission_keys?: PermissionKey[]+}++export type CopyWorkspaceRoleRequest = {+ roleId: string+ copy_member: boolean+}++export type WorkspaceAccessRulesRequest = {+ language?: AccessControlTemplateLanguage+} & PaginationParameters++export type AccessPolicyResourceType = 'app' | 'dataset'++type AccessPolicyCategory = 'global_system_default' | 'global_custom'++export type AccessPolicy = {+ id: string+ tenant_id: string+ resource_type: AccessPolicyResourceType+ policy_key: string+ name: string+ description: string+ permission_keys: PermissionKey[]+ is_builtin: boolean+ category: AccessPolicyCategory+ created_at: string+ updated_at: string+}++export type CreateAccessPolicyRequest = {+ name: string+ description?: string+ permission_keys?: PermissionKey[]+}++export type UpdateAccessPolicyRequest = {+ id: string+ name: string+ description?: string+ permission_keys?: PermissionKey[]+}++type Bindings = {+ roles: Array<{+ role_id: string+ role_name: string+ binding_id: string+ is_locked: boolean+ role_tag: 'owner' | '' // Used for identifying the unique owner role, which has some special handlings+ }>+ accounts: Array<{+ account_id: string+ account_name: string+ binding_id: string+ is_locked: boolean+ avatar?: string+ }>+}++export type AccessPolicyWithBindings = {+ policy: AccessPolicy+} & Bindings++export type GetAppAccessPolicyByAppIdResponse = {+ app_id: string+ items: AccessPolicyWithBindings[]+}++export type GetDatasetAccessPolicyByDatasetIdResponse = {+ dataset_id: string+ items: AccessPolicyWithBindings[]+}++export type GetAppAccessPoliciesResponse = {+ items: AccessPolicyWithBindings[]+ pagination: Pagination+}++export type GetDatasetAccessPoliciesResponse = {+ items: AccessPolicyWithBindings[]+ pagination: Pagination+}++export type RolesOfMemberResponse = {+ account_id: string+ roles: Role[]+}++export type UpdateRolesOfMemberRequest = {+ memberId: string+ roleIds: string[]+}++type WorkspacePermissionKeys = {+ permission_keys: string[]+}++type ResourcePermissionKeys = {+ default_permission_keys: string[]+ overrides: Array<{+ resource_id: string+ permission_keys: string[]+ }>+}++export type PermissionKeysResponse = {+ workspace: WorkspacePermissionKeys+ app: ResourcePermissionKeys+ dataset: ResourcePermissionKeys+}++export type GetMembersOfRoleRequest = {+ roleId: string+} & PaginationParameters++type Account = {+ account_id: string+ account_name: string+ email?: string+ avatar?: string+}++export type ResourceUserAccessSetting = {+ account: Account+ roles: Omit<Role, 'tenant_id' | 'description' | 'role_tag'>[]+ access_policies: Omit<AccessPolicy, 'created_at' | 'updated_at'>[]+}++type ResourceUserAccessSettingsResponse = {+ data: ResourceUserAccessSetting[]+ scope: ResourceOpenScope+}++export type GetMembersOfRoleResponse = {+ data: Account[]+ pagination: Pagination+}++export type GetAppUserAccessSettingsResponse = ResourceUserAccessSettingsResponse++export type GetDatasetUserAccessSettingsResponse = ResourceUserAccessSettingsResponse++type UpdateResourceUserAccessSettingsRequest = {+ accountId: string+ accessPolicyIds: string[]+}++export type UpdateAppUserAccessSettingsRequest = UpdateResourceUserAccessSettingsRequest++export type UpdateDatasetUserAccessSettingsRequest = UpdateResourceUserAccessSettingsRequest++type RemoveResourceAccessPolicyMemberBindingsRequest = {+ accessPolicyId: string+ accountIds: string[]+}++export type RemoveAppAccessPolicyMemberBindingsRequest = RemoveResourceAccessPolicyMemberBindingsRequest++export type RemoveDatasetAccessPolicyMemberBindingsRequest = RemoveResourceAccessPolicyMemberBindingsRequest++export type GetAccessPolicyDetailResponse = {+ access_policies: Pick<AccessPolicy, 'id' | 'name' | 'resource_type' | 'policy_key' | 'permission_keys'>[]+}++export type ResourceOpenScope = 'all' | 'specific'diff --git a/web/models/app.ts b/web/models/app.tsindex d14dc1cd6cd..6f6b5a346b9 100644--- a/web/models/app.ts+++ b/web/models/app.ts@@ -45,6 +45,7 @@ export type DSLImportResponse = {imported_dsl_version?: stringerror: stringleaked_dependencies: Dependency[]+ permission_keys: string[]}export type UpdateAppSiteCodeResponse = { app_id: string } & SiteConfigdiff --git a/web/models/common.ts b/web/models/common.tsindex d41de93ab0c..5549fee8f48 100644--- a/web/models/common.ts+++ b/web/models/common.ts@@ -1,4 +1,5 @@import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'+import type { Role } from './access-control'import type { I18nText } from '@/i18n-config/language'import type { Model } from '@/types/app'@@ -42,6 +43,7 @@ export type Member = Pick<GetAccountProfileResponse, 'id' | 'name' | 'email' | 'created_at?: stringstatus: 'pending' | 'active' | 'banned' | 'closed'role: 'owner' | 'admin' | 'editor' | 'normal' | 'dataset_operator'+ roles: Role[]}const ProviderName = {diff --git a/web/models/datasets.ts b/web/models/datasets.tsindex 7ca206864b5..a0ce36a0bdc 100644--- a/web/models/datasets.ts+++ b/web/models/datasets.ts@@ -60,6 +60,7 @@ export type DataSet = {indexing_technique: IndexingTypeauthor_name?: stringcreated_by: string+ maintainer?: stringupdated_by: stringupdated_at: numberapp_count: number@@ -96,6 +97,8 @@ export type DataSet = {enable_api: boolean // Indicates if the service API is enabledis_multimodal: boolean // Indicates if the dataset supports multimodalsummary_index_setting?: SummaryIndexSetting+ /** ACL permission keys */+ permission_keys?: string[]}export type ExternalAPIItem = {diff --git a/web/plugins/eslint/namespaces.js b/web/plugins/eslint/namespaces.jsindex 68d41d5a4f9..a968e1e74ab 100644--- a/web/plugins/eslint/namespaces.js+++ b/web/plugins/eslint/namespaces.js@@ -23,6 +23,7 @@ const NAMESPACES = ['layout','login','oauth',+ 'permission','pipeline','plugin','pluginTags',diff --git a/web/service/__tests__/use-explore.spec.tsx b/web/service/__tests__/use-explore.spec.tsxnew file mode 100644index 00000000000..6db3d634235--- /dev/null+++ b/web/service/__tests__/use-explore.spec.tsx@@ -0,0 +1,87 @@+import type { ReactNode } from 'react'+import type { App } from '@/models/explore'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderHook, waitFor } from '@testing-library/react'+import { AppModeEnum } from '@/types/app'+import { fetchAppList } from '../explore'+import { useExploreAppList } from '../use-explore'++vi.mock('@/context/i18n', () => ({+ useLocale: () => 'en-US',+}))++vi.mock('../explore', () => ({+ fetchAppList: vi.fn(),+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++const createApp = (appId: string, position: number): App => ({+ app: {+ id: appId,+ mode: AppModeEnum.CHAT,+ icon_type: 'emoji',+ icon: 'robot',+ icon_background: '#fff',+ icon_url: '',+ name: appId,+ description: '',+ use_icon_as_answer_icon: false,+ },+ app_id: appId,+ description: '',+ copyright: '',+ privacy_policy: null,+ custom_disclaimer: null,+ categories: [],+ position,+ is_listed: true,+ install_count: 0,+ installed: false,+ editable: false,+ is_agent: false,+ can_trial: false,+})++describe('useExploreAppList', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(fetchAppList).mockResolvedValue({+ categories: [],+ recommended_apps: [+ createApp('app-2', 2),+ createApp('app-1', 1),+ ],+ })+ })++ // Explore app list can now be disabled by callers.+ describe('Queries', () => {+ it('should not fetch app list when disabled', () => {+ renderHook(() => useExploreAppList({ enabled: false }), { wrapper: createWrapper() })++ expect(fetchAppList).not.toHaveBeenCalled()+ })++ it('should fetch localized app list and sort recommended apps by position', async () => {+ const { result } = renderHook(() => useExploreAppList({ enabled: true }), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(fetchAppList).toHaveBeenCalledWith('en-US')+ })+ await waitFor(() => {+ expect(result.current.data?.allList.map(app => app.app_id)).toEqual(['app-1', 'app-2'])+ })+ })+ })+})diff --git a/web/service/__tests__/use-plugins.spec.tsx b/web/service/__tests__/use-plugins.spec.tsxindex ce69fa4b958..015614c4a50 100644--- a/web/service/__tests__/use-plugins.spec.tsx+++ b/web/service/__tests__/use-plugins.spec.tsx@@ -38,6 +38,7 @@ vi.mock('@/context/app-context', () => ({useAppContext: () => ({isCurrentWorkspaceManager: true,isCurrentWorkspaceOwner: false,+ workspacePermissionKeys: ['plugin.install'],}),}))diff --git a/web/service/__tests__/use-tools.spec.tsx b/web/service/__tests__/use-tools.spec.tsxnew file mode 100644index 00000000000..f2c11f2ac97--- /dev/null+++ b/web/service/__tests__/use-tools.spec.tsx@@ -0,0 +1,54 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderHook, waitFor } from '@testing-library/react'+import { get } from '../base'+import { useAppTriggers, useMCPServerDetail } from '../use-tools'++vi.mock('../base', () => ({+ get: vi.fn(),+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('use-tools query options', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(get).mockResolvedValue({ data: [] })+ })++ // MCP server detail supports an explicit enabled flag.+ describe('MCP Server Detail', () => {+ it('should not fetch server detail when disabled', () => {+ renderHook(() => useMCPServerDetail('app-1', false), { wrapper: createWrapper() })++ expect(get).not.toHaveBeenCalled()+ })++ it('should fetch server detail when enabled', async () => {+ renderHook(() => useMCPServerDetail('app-1'), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/apps/app-1/server')+ })+ })+ })++ // App trigger callers can override default query options such as enabled.+ describe('App Triggers', () => {+ it('should respect caller-provided enabled option', () => {+ renderHook(() => useAppTriggers('app-1', { enabled: false }), { wrapper: createWrapper() })++ expect(get).not.toHaveBeenCalled()+ })+ })+})diff --git a/web/service/access-control/__tests__/use-app-access-config.spec.tsx b/web/service/access-control/__tests__/use-app-access-config.spec.tsxnew file mode 100644index 00000000000..879fba01e45--- /dev/null+++ b/web/service/access-control/__tests__/use-app-access-config.spec.tsx@@ -0,0 +1,167 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook } from '@testing-library/react'+import {+ useAppAccessRules,+ useAppUserAccessSettings,+ useRemoveAppAccessPolicyMemberBindings,+ useUpdateAppOpenScope,+ useUpdateAppUserAccessSettings,+} from '../use-app-access-config'++const mocks = vi.hoisted(() => ({+ accessRulesQueryOptions: vi.fn(() => ({+ queryKey: ['rbac-access-config', 'apps', 'access-rules'],+ queryFn: vi.fn().mockResolvedValue({ app_id: 'app-1', items: [] }),+ })),+ accessRulesKey: vi.fn(() => ['rbac-access-config', 'apps', 'access-rules']),+ userAccessSettingsQueryOptions: vi.fn(() => ({+ queryKey: ['rbac-access-config', 'apps', 'user-access-settings'],+ queryFn: vi.fn().mockResolvedValue({ data: [], scope: 'specific' }),+ })),+ userAccessSettingsKey: vi.fn(() => ['rbac-access-config', 'apps', 'user-access-settings']),+ userAccessSettingsQueryKey: vi.fn(() => ['rbac-access-config', 'apps', 'user-access-settings', 'app-1']),+ updateOpenScope: vi.fn().mockResolvedValue({}),+ updateUserAccessSettings: vi.fn().mockResolvedValue({}),+ removeMemberBindings: vi.fn().mockResolvedValue({}),+}))++vi.mock('@/service/client', () => ({+ consoleClient: {+ rbacAccessConfig: {+ apps: {+ updateOpenScope: mocks.updateOpenScope,+ updateUserAccessSettings: mocks.updateUserAccessSettings,+ removeMemberBindings: mocks.removeMemberBindings,+ },+ },+ },+ consoleQuery: {+ rbacAccessConfig: {+ apps: {+ accessRules: {+ key: mocks.accessRulesKey,+ queryOptions: mocks.accessRulesQueryOptions,+ },+ userAccessSettings: {+ key: mocks.userAccessSettingsKey,+ queryKey: mocks.userAccessSettingsQueryKey,+ queryOptions: mocks.userAccessSettingsQueryOptions,+ },+ },+ },+ },+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('use-app-access-config', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ // Queries load app-specific access policies from the RBAC app route.+ describe('Queries', () => {+ it('should fetch access rules for an app id', () => {+ renderHook(() => useAppAccessRules('app-1', 'zh'), { wrapper: createWrapper() })++ expect(mocks.accessRulesQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ appId: 'app-1',+ },+ query: {+ language: 'zh',+ },+ },+ })+ })+ })++ // User access settings configure which access policies apply to app users.+ describe('User Access Settings', () => {+ it('should fetch user access settings for an app id', () => {+ renderHook(() => useAppUserAccessSettings('app-1', 'en'), { wrapper: createWrapper() })++ expect(mocks.userAccessSettingsQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ appId: 'app-1',+ },+ query: {+ language: 'en',+ },+ },+ })+ })++ it('should update user access settings for an app id', async () => {+ const { result } = renderHook(() => useUpdateAppUserAccessSettings('app-1'), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync({ accountId: 'account-1', accessPolicyIds: ['policy-1', 'policy-2'] })+ })++ expect(mocks.updateUserAccessSettings).toHaveBeenCalledWith({+ params: {+ appId: 'app-1',+ accountId: 'account-1',+ },+ body: {+ access_policy_ids: ['policy-1', 'policy-2'],+ },+ })+ expect(mocks.userAccessSettingsKey).toHaveBeenCalled()+ expect(mocks.accessRulesKey).toHaveBeenCalled()+ })++ it('should remove app access policy member bindings for account ids', async () => {+ const { result } = renderHook(() => useRemoveAppAccessPolicyMemberBindings('app-1'), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync({ accessPolicyId: 'policy-1', accountIds: ['account-1'] })+ })++ expect(mocks.removeMemberBindings).toHaveBeenCalledWith({+ params: {+ appId: 'app-1',+ policyId: 'policy-1',+ },+ body: {+ account_ids: ['account-1'],+ },+ })+ expect(mocks.userAccessSettingsKey).toHaveBeenCalled()+ expect(mocks.accessRulesKey).toHaveBeenCalled()+ })++ it('should update open scope for an app id', async () => {+ const { result } = renderHook(() => useUpdateAppOpenScope('app-1'), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync('all')+ })++ expect(mocks.updateOpenScope).toHaveBeenCalledWith({+ params: {+ appId: 'app-1',+ },+ body: {+ scope: 'all',+ },+ })+ expect(mocks.userAccessSettingsKey).toHaveBeenCalled()+ })+ })+})diff --git a/web/service/access-control/__tests__/use-app-access-control.spec.tsx b/web/service/access-control/__tests__/use-app-access-control.spec.tsxnew file mode 100644index 00000000000..bcf4ebcfaf2--- /dev/null+++ b/web/service/access-control/__tests__/use-app-access-control.spec.tsx@@ -0,0 +1,108 @@+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 {+ useAppWhiteListSubjects,+ useGetUserCanAccessApp,+ useSearchForWhiteListCandidates,+} from '../use-app-access-control'++const mockSystemFeatures = vi.hoisted(() => ({+ webappAuthEnabled: false,+}))++vi.mock('@/service/base', () => ({+ get: vi.fn(),+ request: vi.fn(),+}))++vi.mock('@/service/share', () => ({+ getUserCanAccess: vi.fn(),+}))++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 },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('use-app-access-control', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockSystemFeatures.webappAuthEnabled = false+ vi.mocked(get).mockResolvedValue({ groups: [], members: [] })+ vi.mocked(getUserCanAccess).mockResolvedValue({ result: true })+ })++ // Queries build the enterprise whitelist endpoints from app and filter inputs.+ describe('Queries', () => {+ it('should fetch app whitelist subjects when enabled', async () => {+ renderHook(() => useAppWhiteListSubjects('app-1', true), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/enterprise/webapp/app/subjects?appId=app-1')+ })+ })++ it('should search whitelist candidates with encoded query params', async () => {+ vi.mocked(get).mockResolvedValue({+ currPage: 1,+ totalPages: 1,+ subjects: [],+ hasMore: false,+ })++ renderHook(+ () => useSearchForWhiteListCandidates({+ keyword: 'team one',+ groupId: 'group-1',+ resultsPerPage: 20,+ }, true),+ { wrapper: createWrapper() },+ )++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/enterprise/webapp/app/subject/search?keyword=team+one&groupId=group-1&resultsPerPage=20&pageNumber=1')+ })+ })++ it('should return public access when webapp auth is disabled', async () => {+ const { result } = renderHook(() => useGetUserCanAccessApp({ appId: 'app-1' }), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(result.current.data).toEqual({ result: true })+ })+ expect(getUserCanAccess).not.toHaveBeenCalled()+ })++ it('should call share access check when webapp auth is enabled', async () => {+ mockSystemFeatures.webappAuthEnabled = true++ renderHook(() => useGetUserCanAccessApp({ appId: 'app-1', isInstalledApp: false }), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(getUserCanAccess).toHaveBeenCalledWith('app-1', false)+ })+ })+ })+})diff --git a/web/service/access-control/__tests__/use-dataset-access-config.spec.tsx b/web/service/access-control/__tests__/use-dataset-access-config.spec.tsxnew file mode 100644index 00000000000..da9ab1b7b4e--- /dev/null+++ b/web/service/access-control/__tests__/use-dataset-access-config.spec.tsx@@ -0,0 +1,167 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook } from '@testing-library/react'+import {+ useDatasetAccessRules,+ useDatasetUserAccessSettings,+ useRemoveDatasetAccessPolicyMemberBindings,+ useUpdateDatasetOpenScope,+ useUpdateDatasetUserAccessSettings,+} from '../use-dataset-access-config'++const mocks = vi.hoisted(() => ({+ accessRulesQueryOptions: vi.fn(() => ({+ queryKey: ['rbac-access-config', 'datasets', 'access-rules'],+ queryFn: vi.fn().mockResolvedValue({ dataset_id: 'dataset-1', items: [] }),+ })),+ accessRulesKey: vi.fn(() => ['rbac-access-config', 'datasets', 'access-rules']),+ userAccessSettingsQueryOptions: vi.fn(() => ({+ queryKey: ['rbac-access-config', 'datasets', 'user-access-settings'],+ queryFn: vi.fn().mockResolvedValue({ data: [], scope: 'specific' }),+ })),+ userAccessSettingsKey: vi.fn(() => ['rbac-access-config', 'datasets', 'user-access-settings']),+ userAccessSettingsQueryKey: vi.fn(() => ['rbac-access-config', 'datasets', 'user-access-settings', 'dataset-1']),+ updateOpenScope: vi.fn().mockResolvedValue({}),+ updateUserAccessSettings: vi.fn().mockResolvedValue({}),+ removeMemberBindings: vi.fn().mockResolvedValue({}),+}))++vi.mock('@/service/client', () => ({+ consoleClient: {+ rbacAccessConfig: {+ datasets: {+ updateOpenScope: mocks.updateOpenScope,+ updateUserAccessSettings: mocks.updateUserAccessSettings,+ removeMemberBindings: mocks.removeMemberBindings,+ },+ },+ },+ consoleQuery: {+ rbacAccessConfig: {+ datasets: {+ accessRules: {+ key: mocks.accessRulesKey,+ queryOptions: mocks.accessRulesQueryOptions,+ },+ userAccessSettings: {+ key: mocks.userAccessSettingsKey,+ queryKey: mocks.userAccessSettingsQueryKey,+ queryOptions: mocks.userAccessSettingsQueryOptions,+ },+ },+ },+ },+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('use-dataset-access-config', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ // Queries load dataset-specific access policies from the RBAC dataset route.+ describe('Queries', () => {+ it('should fetch access rules for a dataset id', () => {+ renderHook(() => useDatasetAccessRules('dataset-1', 'ja'), { wrapper: createWrapper() })++ expect(mocks.accessRulesQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ datasetId: 'dataset-1',+ },+ query: {+ language: 'ja',+ },+ },+ })+ })+ })++ // User access settings mirror the app access-config API shape for datasets.+ describe('User Access Settings', () => {+ it('should fetch user access settings for a dataset id', () => {+ renderHook(() => useDatasetUserAccessSettings('dataset-1', 'zh'), { wrapper: createWrapper() })++ expect(mocks.userAccessSettingsQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ datasetId: 'dataset-1',+ },+ query: {+ language: 'zh',+ },+ },+ })+ })++ it('should update user access settings for a dataset id', async () => {+ const { result } = renderHook(() => useUpdateDatasetUserAccessSettings('dataset-1'), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync({ accountId: 'account-1', accessPolicyIds: ['policy-1', 'policy-2'] })+ })++ expect(mocks.updateUserAccessSettings).toHaveBeenCalledWith({+ params: {+ datasetId: 'dataset-1',+ accountId: 'account-1',+ },+ body: {+ access_policy_ids: ['policy-1', 'policy-2'],+ },+ })+ expect(mocks.userAccessSettingsKey).toHaveBeenCalled()+ expect(mocks.accessRulesKey).toHaveBeenCalled()+ })++ it('should remove dataset access policy member bindings for account ids', async () => {+ const { result } = renderHook(() => useRemoveDatasetAccessPolicyMemberBindings('dataset-1'), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync({ accessPolicyId: 'policy-1', accountIds: ['account-1'] })+ })++ expect(mocks.removeMemberBindings).toHaveBeenCalledWith({+ params: {+ datasetId: 'dataset-1',+ policyId: 'policy-1',+ },+ body: {+ account_ids: ['account-1'],+ },+ })+ expect(mocks.userAccessSettingsKey).toHaveBeenCalled()+ expect(mocks.accessRulesKey).toHaveBeenCalled()+ })++ it('should update open scope for a dataset id', async () => {+ const { result } = renderHook(() => useUpdateDatasetOpenScope('dataset-1'), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync('specific')+ })++ expect(mocks.updateOpenScope).toHaveBeenCalledWith({+ params: {+ datasetId: 'dataset-1',+ },+ body: {+ scope: 'specific',+ },+ })+ expect(mocks.userAccessSettingsKey).toHaveBeenCalled()+ })+ })+})diff --git a/web/service/access-control/__tests__/use-member-roles.spec.tsx b/web/service/access-control/__tests__/use-member-roles.spec.tsxnew file mode 100644index 00000000000..57919ce919f--- /dev/null+++ b/web/service/access-control/__tests__/use-member-roles.spec.tsx@@ -0,0 +1,79 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook, waitFor } from '@testing-library/react'+import { get, put } from '@/service/base'+import { commonQueryKeys } from '@/service/use-common'+import { useRolesOfMember, useUpdateRolesOfMember } from '../use-member-roles'++vi.mock('@/service/base', () => ({+ get: vi.fn(),+ put: vi.fn(),+}))++const createQueryClient = () => new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+})++const createWrapper = (queryClient = createQueryClient()) => {+ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('use-member-roles', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(get).mockResolvedValue({ account_id: 'member-1', roles: [] })+ vi.mocked(put).mockResolvedValue({})+ })++ // Queries load roles for one workspace member.+ describe('Queries', () => {+ it('should fetch roles for a member id', async () => {+ renderHook(() => useRolesOfMember('member-1', 'en'), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/workspaces/current/rbac/members/member-1/rbac-roles', {+ params: { language: 'en' },+ })+ })+ })+ })++ // Mutations update role ids using the API contract body shape.+ describe('Mutations', () => {+ it('should update roles for a member id', async () => {+ const { result } = renderHook(() => useUpdateRolesOfMember(), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync({+ memberId: 'member-1',+ roleIds: ['role-1'],+ })+ })++ expect(put).toHaveBeenCalledWith('/workspaces/current/rbac/members/member-1/rbac-roles', {+ body: { role_ids: ['role-1'] },+ })+ })++ it('should invalidate members after updating roles', async () => {+ const queryClient = createQueryClient()+ const membersQueryKey = [...commonQueryKeys.members, 'en-US']+ queryClient.setQueryData(membersQueryKey, { accounts: [] })+ const { result } = renderHook(() => useUpdateRolesOfMember(), { wrapper: createWrapper(queryClient) })++ await act(async () => {+ await result.current.mutateAsync({+ memberId: 'member-1',+ roleIds: ['role-1'],+ })+ })++ expect(queryClient.getQueryState(membersQueryKey)?.isInvalidated).toBe(true)+ })+ })+})diff --git a/web/service/access-control/__tests__/use-permission-catalog.spec.tsx b/web/service/access-control/__tests__/use-permission-catalog.spec.tsxnew file mode 100644index 00000000000..5b32cfab300--- /dev/null+++ b/web/service/access-control/__tests__/use-permission-catalog.spec.tsx@@ -0,0 +1,66 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderHook, waitFor } from '@testing-library/react'+import { get } from '@/service/base'+import {+ useAppPermissionCatalog,+ useDatasetPermissionCatalog,+ useWorkspacePermissionCatalog,+} from '../use-permission-catalog'++vi.mock('@/service/base', () => ({+ get: vi.fn(),+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('use-permission-catalog', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(get).mockResolvedValue({ groups: [] })+ })++ // Permission catalogs use separate workspace/app/dataset endpoints.+ describe('Queries', () => {+ it('should fetch workspace permission catalog', async () => {+ renderHook(() => useWorkspacePermissionCatalog(), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/workspaces/current/rbac/role-permissions/catalog')+ })+ })++ it('should fetch app permission catalog when enabled', async () => {+ renderHook(() => useAppPermissionCatalog(true), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/workspaces/current/rbac/role-permissions/catalog/app')+ })+ })++ it('should fetch dataset permission catalog when enabled', async () => {+ renderHook(() => useDatasetPermissionCatalog(true), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/workspaces/current/rbac/role-permissions/catalog/dataset')+ })+ })++ it('should not fetch resource catalogs when disabled', () => {+ renderHook(() => useAppPermissionCatalog(false), { wrapper: createWrapper() })+ renderHook(() => useDatasetPermissionCatalog(false), { wrapper: createWrapper() })++ expect(get).not.toHaveBeenCalled()+ })+ })+})diff --git a/web/service/access-control/__tests__/use-permission-keys.spec.tsx b/web/service/access-control/__tests__/use-permission-keys.spec.tsxnew file mode 100644index 00000000000..1849a48a5ed--- /dev/null+++ b/web/service/access-control/__tests__/use-permission-keys.spec.tsx@@ -0,0 +1,43 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderHook, waitFor } from '@testing-library/react'+import { get } from '@/service/base'+import { useWorkspacePermissionKeys } from '../use-permission-keys'++vi.mock('@/service/base', () => ({+ get: vi.fn(),+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('useWorkspacePermissionKeys', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(get).mockResolvedValue({+ workspace: { permission_keys: [] },+ app: { default_permission_keys: [], overrides: [] },+ dataset: { default_permission_keys: [], overrides: [] },+ })+ })++ // Current-user permissions come from the my-permissions RBAC endpoint.+ describe('Queries', () => {+ it('should fetch workspace permission keys', async () => {+ renderHook(() => useWorkspacePermissionKeys(), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/workspaces/current/rbac/my-permissions')+ })+ })+ })+})diff --git a/web/service/access-control/__tests__/use-workspace-access-rules.spec.tsx b/web/service/access-control/__tests__/use-workspace-access-rules.spec.tsxnew file mode 100644index 00000000000..e7b2ecdce33--- /dev/null+++ b/web/service/access-control/__tests__/use-workspace-access-rules.spec.tsx@@ -0,0 +1,119 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook, waitFor } from '@testing-library/react'+import { del, get, post, put } from '@/service/base'+import {+ useCopyAccessRule,+ useCreateAccessRule,+ useDeleteAccessRule,+ useInfiniteWorkspaceAppAccessRules,+ useInfiniteWorkspaceDatasetAccessRules,+ useUpdateAccessRule,+} from '../use-workspace-access-rules'++vi.mock('@/service/base', () => ({+ del: vi.fn(),+ get: vi.fn(),+ post: vi.fn(),+ put: vi.fn(),+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('use-workspace-access-rules', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(get).mockResolvedValue({ items: [], pagination: {} })+ vi.mocked(post).mockResolvedValue({})+ vi.mocked(put).mockResolvedValue({})+ vi.mocked(del).mockResolvedValue({})+ })++ // Queries load workspace-level app and dataset access policies from separate endpoints.+ describe('Queries', () => {+ it('should fetch workspace app access rules', async () => {+ renderHook(() => useInfiniteWorkspaceAppAccessRules({ page: 1, limit: 20, language: 'zh' }), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/workspaces/current/rbac/workspace/apps/access-policy', {+ params: { page: 1, limit: 20, language: 'zh' },+ })+ })+ })++ it('should fetch workspace dataset access rules', async () => {+ renderHook(() => useInfiniteWorkspaceDatasetAccessRules({ page: 1, limit: 20, language: 'ja' }), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(get).toHaveBeenCalledWith('/workspaces/current/rbac/workspace/datasets/access-policy', {+ params: { page: 1, limit: 20, language: 'ja' },+ })+ })+ })+ })++ // Rule mutations normalize form data to the API body expected by RBAC access policies.+ describe('Rule Mutations', () => {+ it('should create and update access rules', async () => {+ const createHook = renderHook(() => useCreateAccessRule(), { wrapper: createWrapper() })+ const updateHook = renderHook(() => useUpdateAccessRule(), { wrapper: createWrapper() })++ await act(async () => {+ await createHook.result.current.mutateAsync({+ resourceType: 'app',+ name: 'App rule',+ description: 'App access',+ permission_keys: ['app.acl.edit'],+ })+ await updateHook.result.current.mutateAsync({+ id: 'policy-1',+ resourceType: 'dataset',+ name: 'Dataset rule',+ description: 'Dataset access',+ permission_keys: ['dataset.acl.edit'],+ })+ })++ expect(post).toHaveBeenCalledWith('/workspaces/current/rbac/access-policies', {+ body: {+ resource_type: 'app',+ name: 'App rule',+ description: 'App access',+ permission_keys: ['app.acl.edit'],+ },+ })+ expect(put).toHaveBeenCalledWith('/workspaces/current/rbac/access-policies/policy-1', {+ body: {+ id: 'policy-1',+ name: 'Dataset rule',+ description: 'Dataset access',+ permission_keys: ['dataset.acl.edit'],+ },+ })+ })++ it('should copy and delete access rules by id', async () => {+ const copyHook = renderHook(() => useCopyAccessRule('app'), { wrapper: createWrapper() })+ const deleteHook = renderHook(() => useDeleteAccessRule('dataset'), { wrapper: createWrapper() })++ await act(async () => {+ await copyHook.result.current.mutateAsync('policy-1')+ await deleteHook.result.current.mutateAsync('policy-2')+ })++ expect(post).toHaveBeenCalledWith('/workspaces/current/rbac/access-policies/policy-1/copy', {})+ expect(del).toHaveBeenCalledWith('/workspaces/current/rbac/access-policies/policy-2', {})+ })+ })+})diff --git a/web/service/access-control/__tests__/use-workspace-roles.spec.tsx b/web/service/access-control/__tests__/use-workspace-roles.spec.tsxnew file mode 100644index 00000000000..866501da7c2--- /dev/null+++ b/web/service/access-control/__tests__/use-workspace-roles.spec.tsx@@ -0,0 +1,192 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook, waitFor } from '@testing-library/react'+import { commonQueryKeys } from '../../use-common'+import {+ useCopyWorkspaceRole,+ useCreateWorkspaceRole,+ useDeleteWorkspaceRole,+ useGetMembersOfRole,+ useUpdateWorkspaceRole,+ useWorkspaceRoleList,+} from '../use-workspace-roles'++const mockServiceBase = vi.hoisted(() => ({+ del: vi.fn(),+ get: vi.fn(),+ post: vi.fn(),+ put: vi.fn(),+}))++vi.mock('../../base', () => mockServiceBase)++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++const createWrapperWithClient = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })++ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )++ return {+ queryClient,+ wrapper,+ }+}++const roleListResponse = {+ data: [],+ pagination: {+ total_count: 0,+ per_page: 20,+ current_page: 1,+ total_pages: 1,+ },+}++describe('use-workspace-roles', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockServiceBase.get.mockResolvedValue(roleListResponse)+ mockServiceBase.post.mockResolvedValue({})+ mockServiceBase.put.mockResolvedValue({})+ mockServiceBase.del.mockResolvedValue({})+ })++ // Role list pagination starts from the provided page and passes query params through.+ describe('Queries', () => {+ it('should fetch workspace roles with pagination params', async () => {+ renderHook(() => useWorkspaceRoleList({ page: 2, limit: 20, language: 'zh' }), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(mockServiceBase.get).toHaveBeenCalledWith('/workspaces/current/rbac/roles', {+ params: {+ limit: 20,+ language: 'zh',+ page: 2,+ },+ })+ })+ })++ it('should fetch members assigned to a workspace role with pagination params', async () => {+ renderHook(() => useGetMembersOfRole({ roleId: 'role-1', page: 2, limit: 1 }), { wrapper: createWrapper() })++ await waitFor(() => {+ expect(mockServiceBase.get).toHaveBeenCalledWith('/workspaces/current/rbac/roles/role-1/members', {+ params: {+ page: 2,+ limit: 1,+ },+ })+ })+ })+ })++ // Role mutations call the expected RBAC role management endpoints.+ describe('Mutations', () => {+ it('should create a workspace role', async () => {+ const { result } = renderHook(() => useCreateWorkspaceRole(), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync({+ name: 'Support',+ description: 'Support role',+ permission_keys: ['workspace.member.manage'],+ })+ })++ expect(mockServiceBase.post).toHaveBeenCalledWith('/workspaces/current/rbac/roles', {+ body: {+ name: 'Support',+ description: 'Support role',+ permission_keys: ['workspace.member.manage'],+ },+ })+ })++ it('should update a workspace role', async () => {+ const { result } = renderHook(() => useUpdateWorkspaceRole(), { wrapper: createWrapper() })++ await act(async () => {+ await result.current.mutateAsync({+ id: 'role-1',+ name: 'Support',+ description: 'Support role',+ permission_keys: [],+ })+ })++ expect(mockServiceBase.put).toHaveBeenCalledWith('/workspaces/current/rbac/roles/role-1', {+ body: {+ id: 'role-1',+ name: 'Support',+ description: 'Support role',+ permission_keys: [],+ },+ })+ })++ it('should delete and copy workspace roles by id', async () => {+ const deleteHook = renderHook(() => useDeleteWorkspaceRole(), { wrapper: createWrapper() })+ const copyHook = renderHook(() => useCopyWorkspaceRole(), { wrapper: createWrapper() })++ await act(async () => {+ await deleteHook.result.current.mutateAsync('role-1')+ await copyHook.result.current.mutateAsync({+ roleId: 'role-2',+ copy_member: false,+ })+ })++ expect(mockServiceBase.del).toHaveBeenCalledWith('/workspaces/current/rbac/roles/role-1')+ expect(mockServiceBase.post).toHaveBeenCalledWith('/workspaces/current/rbac/roles/role-2/copy', {+ body: { copy_member: false },+ })+ })++ it('should invalidate members after deleting a workspace role', async () => {+ const { queryClient, wrapper } = createWrapperWithClient()+ queryClient.setQueryData(commonQueryKeys.members, { accounts: [] })+ const { result } = renderHook(() => useDeleteWorkspaceRole(), { wrapper })++ await act(async () => {+ await result.current.mutateAsync('role-1')+ })++ expect(queryClient.getQueryState(commonQueryKeys.members)?.isInvalidated).toBe(true)+ })++ it('should invalidate members after copying a workspace role with member assignments', async () => {+ const { queryClient, wrapper } = createWrapperWithClient()+ queryClient.setQueryData(commonQueryKeys.members, { accounts: [] })+ const { result } = renderHook(() => useCopyWorkspaceRole(), { wrapper })++ await act(async () => {+ await result.current.mutateAsync({+ roleId: 'role-1',+ copy_member: true,+ })+ })++ expect(queryClient.getQueryState(commonQueryKeys.members)?.isInvalidated).toBe(true)+ })+ })+})diff --git a/web/service/access-control/use-app-access-config.ts b/web/service/access-control/use-app-access-config.tsnew file mode 100644index 00000000000..79f9426f279--- /dev/null+++ b/web/service/access-control/use-app-access-config.ts@@ -0,0 +1,113 @@+import type { AccessControlTemplateLanguage } from '@/i18n-config/language'+import type {+ RemoveAppAccessPolicyMemberBindingsRequest,+ ResourceOpenScope,+ UpdateAppUserAccessSettingsRequest,+} from '@/models/access-control'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { consoleClient, consoleQuery } from '@/service/client'++const NAME_SPACE = 'app-access-config'++export const useAppAccessRules = (appId: string, language: AccessControlTemplateLanguage) => {+ return useQuery(consoleQuery.rbacAccessConfig.apps.accessRules.queryOptions({+ input: {+ params: {+ appId,+ },+ query: {+ language,+ },+ },+ }))+}++export const useAppUserAccessSettings = (appId: string, language: AccessControlTemplateLanguage) => {+ return useQuery(consoleQuery.rbacAccessConfig.apps.userAccessSettings.queryOptions({+ input: {+ params: {+ appId,+ },+ query: {+ language,+ },+ },+ }))+}++export const useUpdateAppUserAccessSettings = (appId: string) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'update-app-user-access-settings', appId],+ mutationFn: (payload: UpdateAppUserAccessSettingsRequest) => consoleClient.rbacAccessConfig.apps.updateUserAccessSettings({+ params: {+ appId,+ accountId: payload.accountId,+ },+ body: {+ access_policy_ids: payload.accessPolicyIds,+ },+ }),+ onSuccess: async () => {+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.apps.userAccessSettings.key(),+ }),+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.apps.accessRules.key(),+ }),+ ])+ },+ })+}++export const useRemoveAppAccessPolicyMemberBindings = (appId: string) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'remove-app-access-policy-member-bindings', appId],+ mutationFn: (payload: RemoveAppAccessPolicyMemberBindingsRequest) => consoleClient.rbacAccessConfig.apps.removeMemberBindings({+ params: {+ appId,+ policyId: payload.accessPolicyId,+ },+ body: {+ account_ids: payload.accountIds,+ },+ }),+ onSuccess: async () => {+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.apps.userAccessSettings.key(),+ }),+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.apps.accessRules.key(),+ }),+ ])+ },+ })+}++export const useUpdateAppOpenScope = (appId: string) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'update-app-open-scope', appId],+ mutationFn: (openScope: ResourceOpenScope) => consoleClient.rbacAccessConfig.apps.updateOpenScope({+ params: {+ appId,+ },+ body: {+ scope: openScope,+ },+ }),+ onSuccess: async () => {+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.apps.userAccessSettings.key(),+ }),+ ])+ },+ })+}diff --git a/web/service/access-control.ts b/web/service/access-control/use-app-access-control.tssimilarity index 76%rename from web/service/access-control.tsrename to web/service/access-control/use-app-access-control.tsindex d6eabf05ef0..aafe53ec0f8 100644--- a/web/service/access-control.ts+++ b/web/service/access-control/use-app-access-control.ts@@ -1,8 +1,8 @@import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'import { useInfiniteQuery, useQuery } from '@tanstack/react-query'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { get } from './base'-import { getUserCanAccess } from './share'+import { get } from '../base'+import { getUserCanAccess } from '../share'const NAME_SPACE = 'access-control'@@ -23,16 +23,25 @@ type SearchResults = {hasMore: boolean}-export const useSearchForWhiteListCandidates = (query: { keyword?: string, groupId?: AccessControlGroup['id'], resultsPerPage?: number }, enabled: boolean) => {+type SearchForWhiteListCandidatesQuery = {+ keyword?: string+ groupId?: AccessControlGroup['id']+ resultsPerPage?: number+}++export const useSearchForWhiteListCandidates = (query: SearchForWhiteListCandidatesQuery, enabled: boolean) => {+ const { keyword, groupId, resultsPerPage } = query+return useInfiniteQuery({- queryKey: [NAME_SPACE, 'app-whitelist-candidates', query],+ queryKey: [NAME_SPACE, 'app-whitelist-candidates', keyword, groupId, resultsPerPage],queryFn: ({ pageParam }) => {const params = new URLSearchParams()- Object.keys(query).forEach((key) => {- const typedKey = key as keyof typeof query- if (query[typedKey])- params.append(key, `${query[typedKey]}`)- })+ if (keyword)+ params.append('keyword', keyword)+ if (groupId)+ params.append('groupId', groupId)+ if (resultsPerPage)+ params.append('resultsPerPage', `${resultsPerPage}`)params.append('pageNumber', `${pageParam}`)return get<SearchResults>(`/enterprise/webapp/app/subject/search?${new URLSearchParams(params).toString()}`)},diff --git a/web/service/access-control/use-dataset-access-config.ts b/web/service/access-control/use-dataset-access-config.tsnew file mode 100644index 00000000000..36f3727daf9--- /dev/null+++ b/web/service/access-control/use-dataset-access-config.ts@@ -0,0 +1,123 @@+import type { AccessControlTemplateLanguage } from '@/i18n-config/language'+import type {+ RemoveDatasetAccessPolicyMemberBindingsRequest,+ ResourceOpenScope,+ UpdateDatasetUserAccessSettingsRequest,+} from '@/models/access-control'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { consoleClient, consoleQuery } from '@/service/client'++const NAME_SPACE = 'dataset-access-config'++type DatasetAccessConfigQueryOptions = {+ enabled?: boolean+}++export const useDatasetAccessRules = (datasetId: string, language: AccessControlTemplateLanguage, options?: DatasetAccessConfigQueryOptions) => {+ return useQuery({+ ...consoleQuery.rbacAccessConfig.datasets.accessRules.queryOptions({+ input: {+ params: {+ datasetId,+ },+ query: {+ language,+ },+ },+ }),+ enabled: options?.enabled ?? true,+ })+}++export const useDatasetUserAccessSettings = (datasetId: string, language: AccessControlTemplateLanguage, options?: DatasetAccessConfigQueryOptions) => {+ return useQuery({+ ...consoleQuery.rbacAccessConfig.datasets.userAccessSettings.queryOptions({+ input: {+ params: {+ datasetId,+ },+ query: {+ language,+ },+ },+ }),+ enabled: options?.enabled ?? true,+ })+}++export const useUpdateDatasetUserAccessSettings = (datasetId: string) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'update-dataset-user-access-settings', datasetId],+ mutationFn: (payload: UpdateDatasetUserAccessSettingsRequest) => consoleClient.rbacAccessConfig.datasets.updateUserAccessSettings({+ params: {+ datasetId,+ accountId: payload.accountId,+ },+ body: {+ access_policy_ids: payload.accessPolicyIds,+ },+ }),+ onSuccess: async () => {+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.datasets.userAccessSettings.key(),+ }),+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.datasets.accessRules.key(),+ }),+ ])+ },+ })+}++export const useRemoveDatasetAccessPolicyMemberBindings = (datasetId: string) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'remove-dataset-access-policy-member-bindings', datasetId],+ mutationFn: (payload: RemoveDatasetAccessPolicyMemberBindingsRequest) => consoleClient.rbacAccessConfig.datasets.removeMemberBindings({+ params: {+ datasetId,+ policyId: payload.accessPolicyId,+ },+ body: {+ account_ids: payload.accountIds,+ },+ }),+ onSuccess: async () => {+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.datasets.userAccessSettings.key(),+ }),+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.datasets.accessRules.key(),+ }),+ ])+ },+ })+}++export const useUpdateDatasetOpenScope = (datasetId: string) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'update-dataset-open-scope', datasetId],+ mutationFn: (openScope: ResourceOpenScope) => consoleClient.rbacAccessConfig.datasets.updateOpenScope({+ params: {+ datasetId,+ },+ body: {+ scope: openScope,+ },+ }),+ onSuccess: async () => {+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: consoleQuery.rbacAccessConfig.datasets.userAccessSettings.key(),+ }),+ ])+ },+ })+}diff --git a/web/service/access-control/use-member-roles.ts b/web/service/access-control/use-member-roles.tsnew file mode 100644index 00000000000..265db742b0e--- /dev/null+++ b/web/service/access-control/use-member-roles.ts@@ -0,0 +1,36 @@+import type { AccessControlTemplateLanguage } from '@/i18n-config/language'+import type { RolesOfMemberResponse, UpdateRolesOfMemberRequest } from '@/models/access-control'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { get, put } from '../base'+import { commonQueryKeys } from '../use-common'++const NAME_SPACE = 'rbac-member-roles'++export const useRolesOfMember = (memberId: string, language: AccessControlTemplateLanguage) => {+ return useQuery({+ queryKey: [NAME_SPACE, 'member-roles', memberId, language],+ queryFn: () => get<RolesOfMemberResponse>(`/workspaces/current/rbac/members/${memberId}/rbac-roles`, {+ params: {+ language,+ },+ }),+ })+}++export const useUpdateRolesOfMember = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'update-member-roles'],+ mutationFn: (request: UpdateRolesOfMemberRequest) => {+ const { memberId, roleIds } = request+ return put<RolesOfMemberResponse>(`/workspaces/current/rbac/members/${memberId}/rbac-roles`, {+ body: { role_ids: roleIds },+ })+ },+ onSuccess: (_, { memberId }) => Promise.all([+ queryClient.invalidateQueries({ queryKey: [NAME_SPACE, 'member-roles', memberId] }),+ queryClient.invalidateQueries({ queryKey: commonQueryKeys.members }),+ ]),+ })+}diff --git a/web/service/access-control/use-permission-catalog.ts b/web/service/access-control/use-permission-catalog.tsnew file mode 100644index 00000000000..f6b6602d0ee--- /dev/null+++ b/web/service/access-control/use-permission-catalog.ts@@ -0,0 +1,30 @@+import type {+ PermissionGroups,+} from '@/models/access-control'+import { useQuery } from '@tanstack/react-query'+import { get } from '../base'++const NAME_SPACE = 'rbac-permission-catalog'++export const useWorkspacePermissionCatalog = () => {+ return useQuery({+ queryKey: [NAME_SPACE, 'workspace'],+ queryFn: () => get<PermissionGroups>('/workspaces/current/rbac/role-permissions/catalog'),+ })+}++export const useAppPermissionCatalog = (enabled?: boolean) => {+ return useQuery({+ queryKey: [NAME_SPACE, 'app'],+ queryFn: () => get<PermissionGroups>('/workspaces/current/rbac/role-permissions/catalog/app'),+ enabled: enabled ?? true,+ })+}++export const useDatasetPermissionCatalog = (enabled?: boolean) => {+ return useQuery({+ queryKey: [NAME_SPACE, 'dataset'],+ queryFn: () => get<PermissionGroups>('/workspaces/current/rbac/role-permissions/catalog/dataset'),+ enabled: enabled ?? true,+ })+}diff --git a/web/service/access-control/use-permission-keys.ts b/web/service/access-control/use-permission-keys.tsnew file mode 100644index 00000000000..af19cf3e840--- /dev/null+++ b/web/service/access-control/use-permission-keys.ts@@ -0,0 +1,12 @@+import type { PermissionKeysResponse } from '@/models/access-control'+import { useQuery } from '@tanstack/react-query'+import { get } from '../base'++const NAME_SPACE = 'workspace-permission-keys'++export const useWorkspacePermissionKeys = () => {+ return useQuery({+ queryKey: [NAME_SPACE],+ queryFn: () => get<PermissionKeysResponse>('/workspaces/current/rbac/my-permissions'),+ })+}diff --git a/web/service/access-control/use-workspace-access-rules.ts b/web/service/access-control/use-workspace-access-rules.tsnew file mode 100644index 00000000000..8d07cd824f5--- /dev/null+++ b/web/service/access-control/use-workspace-access-rules.ts@@ -0,0 +1,139 @@+import type {+ AccessPolicy,+ AccessPolicyResourceType,+ CreateAccessPolicyRequest,+ GetAppAccessPoliciesResponse,+ GetDatasetAccessPoliciesResponse,+ UpdateAccessPolicyRequest,+ WorkspaceAccessRulesRequest,+} from '@/models/access-control'+import type { CommonResponse } from '@/models/common'+import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'+import { del, get, post, put } from '../base'++const NAME_SPACE = 'workspace-access-rules'++type WorkspaceAccessRulesQueryParams = Omit<WorkspaceAccessRulesRequest, 'page'>++const workspaceAccessRulesQueryKeys = {+ app: (params?: WorkspaceAccessRulesQueryParams) => params ? [NAME_SPACE, 'app', params] as const : [NAME_SPACE, 'app'] as const,+ dataset: (params?: WorkspaceAccessRulesQueryParams) => params ? [NAME_SPACE, 'dataset', params] as const : [NAME_SPACE, 'dataset'] as const,+}++export const useInfiniteWorkspaceAppAccessRules = (params: WorkspaceAccessRulesRequest = {}) => {+ const { page = 1, ...queryParams } = params++ return useInfiniteQuery({+ queryKey: workspaceAccessRulesQueryKeys.app(queryParams),+ queryFn: ({ pageParam }) => get<GetAppAccessPoliciesResponse>('/workspaces/current/rbac/workspace/apps/access-policy', {+ params: {+ ...queryParams,+ page: pageParam,+ },+ }),+ initialPageParam: page,+ getNextPageParam: (lastPage) => {+ const { current_page, total_pages } = lastPage.pagination++ if (current_page < total_pages)+ return current_page + 1++ return undefined+ },+ })+}++export const useInfiniteWorkspaceDatasetAccessRules = (params: WorkspaceAccessRulesRequest = {}) => {+ const { page = 1, ...queryParams } = params++ return useInfiniteQuery({+ queryKey: workspaceAccessRulesQueryKeys.dataset(queryParams),+ queryFn: ({ pageParam }) => get<GetDatasetAccessPoliciesResponse>('/workspaces/current/rbac/workspace/datasets/access-policy', {+ params: {+ ...queryParams,+ page: pageParam,+ },+ }),+ initialPageParam: page,+ getNextPageParam: (lastPage) => {+ const { current_page, total_pages } = lastPage.pagination++ if (current_page < total_pages)+ return current_page + 1++ return undefined+ },+ })+}++export const useCreateAccessRule = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'create'],+ mutationFn: (data: CreateAccessPolicyRequest & { resourceType: AccessPolicyResourceType }) => {+ const { name, description, permission_keys, resourceType } = data+ return post<AccessPolicy>('/workspaces/current/rbac/access-policies', {+ body: {+ resource_type: resourceType,+ name,+ description,+ permission_keys,+ },+ })+ },+ onSuccess: (_, { resourceType }) => {+ queryClient.invalidateQueries({ queryKey: resourceType === 'app' ? workspaceAccessRulesQueryKeys.app() : workspaceAccessRulesQueryKeys.dataset() })+ },+ })+}++export const useUpdateAccessRule = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'update'],+ mutationFn: (data: UpdateAccessPolicyRequest & { resourceType: AccessPolicyResourceType }) => {+ const { id, name, description, permission_keys } = data+ return put<AccessPolicy>(`/workspaces/current/rbac/access-policies/${id}`, {+ body: {+ id,+ name,+ description,+ permission_keys,+ },+ })+ },+ onSuccess: (_, { resourceType }) => {+ queryClient.invalidateQueries({ queryKey: resourceType === 'app' ? workspaceAccessRulesQueryKeys.app() : workspaceAccessRulesQueryKeys.dataset() })+ },+ })+}++export const useCopyAccessRule = (resourceType: AccessPolicyResourceType) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'copy', resourceType],+ mutationFn: (id: string) => {+ return post<AccessPolicy>(`/workspaces/current/rbac/access-policies/${id}/copy`, {})+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: resourceType === 'app' ? workspaceAccessRulesQueryKeys.app() : workspaceAccessRulesQueryKeys.dataset() })+ },+ })+}++export const useDeleteAccessRule = (resourceType: AccessPolicyResourceType) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'delete', resourceType],+ mutationFn: (id: string) => {+ return del<CommonResponse>(`/workspaces/current/rbac/access-policies/${id}`, {})+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: resourceType === 'app' ? workspaceAccessRulesQueryKeys.app() : workspaceAccessRulesQueryKeys.dataset() })+ },+ })+}diff --git a/web/service/access-control/use-workspace-roles.ts b/web/service/access-control/use-workspace-roles.tsnew file mode 100644index 00000000000..bff4a0d3101--- /dev/null+++ b/web/service/access-control/use-workspace-roles.ts@@ -0,0 +1,118 @@+import type {+ CopyWorkspaceRoleRequest,+ CreateRoleRequest,+ GetMembersOfRoleRequest,+ GetMembersOfRoleResponse,+ Role,+ RoleListRequest,+ RoleListResponse,+ UpdateRolesRequest,+} from '@/models/access-control'+import type { CommonResponse } from '@/models/common'+import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { del, get, post, put } from '../base'+import { commonQueryKeys } from '../use-common'++const NAME_SPACE = 'rbac-role-management'++export const useWorkspaceRoleList = (params: RoleListRequest) => {+ const { page = 1, ...queryParams } = params++ return useInfiniteQuery({+ queryKey: [NAME_SPACE, 'workspace-role-list', queryParams],+ queryFn: ({ pageParam }) => get<RoleListResponse>('/workspaces/current/rbac/roles', {+ params: {+ ...queryParams,+ page: pageParam,+ },+ }),+ initialPageParam: page,+ getNextPageParam: (lastPage) => {+ const { current_page, total_pages } = lastPage.pagination++ if (current_page < total_pages)+ return current_page + 1++ return undefined+ },+ })+}++export const useCreateWorkspaceRole = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'create-workspace-role'],+ mutationFn: (data: CreateRoleRequest) =>+ post<Role>('/workspaces/current/rbac/roles', {+ body: { ...data },+ }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [NAME_SPACE, 'workspace-role-list'] })+ },+ })+}++export const useUpdateWorkspaceRole = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'update-workspace-role'],+ mutationFn: (data: UpdateRolesRequest) =>+ put<Role>(`/workspaces/current/rbac/roles/${data.id}`, {+ body: { ...data },+ }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [NAME_SPACE, 'workspace-role-list'] })+ },+ })+}++export const useDeleteWorkspaceRole = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'delete-workspace-role'],+ mutationFn: (id: string) =>+ del<CommonResponse>(`/workspaces/current/rbac/roles/${id}`),+ onSuccess: () => Promise.all([+ queryClient.invalidateQueries({ queryKey: [NAME_SPACE, 'workspace-role-list'] }),+ queryClient.invalidateQueries({ queryKey: commonQueryKeys.members }),+ ]),+ })+}++export const useCopyWorkspaceRole = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationKey: [NAME_SPACE, 'copy-workspace-role'],+ mutationFn: ({ roleId, copy_member }: CopyWorkspaceRoleRequest) =>+ post<Role>(`/workspaces/current/rbac/roles/${roleId}/copy`, {+ body: { copy_member },+ }),+ onSuccess: (_role, variables) => {+ const invalidations = [+ queryClient.invalidateQueries({ queryKey: [NAME_SPACE, 'workspace-role-list'] }),+ ]++ if (variables.copy_member)+ invalidations.push(queryClient.invalidateQueries({ queryKey: commonQueryKeys.members }))++ return Promise.all(invalidations)+ },+ })+}++export const useGetMembersOfRole = (params: GetMembersOfRoleRequest) => {+ const { roleId, ...paginationParams } = params+ return useQuery({+ queryKey: [NAME_SPACE, 'members-of-role', roleId, paginationParams],+ queryFn: () => get<GetMembersOfRoleResponse>(`/workspaces/current/rbac/roles/${roleId}/members`, {+ params: {+ ...paginationParams,+ },+ }),+ enabled: !!roleId,+ })+}diff --git a/web/service/apps.ts b/web/service/apps.tsindex d8e5e2136bb..8b6ca176486 100644--- a/web/service/apps.ts+++ b/web/service/apps.ts@@ -96,8 +96,8 @@ export const importDSLConfirm = ({ import_id }: { import_id: string }): Promise<return post<DSLImportResponse>(`apps/imports/${import_id}/confirm`, { body: {} })}-export const switchApp = ({ appID, name, icon_type, icon, icon_background }: { appID: string, name: string, icon_type: AppIconType, icon: string, icon_background?: string | null }): Promise<{ new_app_id: string }> => {- return post<{ new_app_id: string }>(`apps/${appID}/convert-to-workflow`, { body: { name, icon_type, icon, icon_background } })+export const switchApp = ({ appID, name, icon_type, icon, icon_background }: { appID: string, name: string, icon_type: AppIconType, icon: string, icon_background?: string | null }): Promise<{ new_app_id: string, permission_keys: string[] }> => {+ return post<{ new_app_id: string, permission_keys: string[] }>(`apps/${appID}/convert-to-workflow`, { body: { name, icon_type, icon, icon_background } })}export const deleteApp = (appID: string): Promise<CommonResponse> => {diff --git a/web/service/base.ts b/web/service/base.tsindex 9bd7be87042..9dd15d66ea4 100644--- a/web/service/base.ts+++ b/web/service/base.ts@@ -509,6 +509,7 @@ export const ssePost = async ([PASSPORT_HEADER_NAME]: getWebAppPassport(shareCode!),}),} as RequestInit, fetchOptions)+ options.headers = new Headers(options.headers)const contentType = (options.headers as Headers).get('Content-Type')if (!contentType)@@ -660,6 +661,7 @@ export const sseGet = async ([PASSPORT_HEADER_NAME]: getWebAppPassport(shareCode!),}),} as RequestInit, fetchOptions)+ options.headers = new Headers(options.headers)const contentType = (options.headers as Headers).get('Content-Type')if (!contentType)diff --git a/web/service/fetch.ts b/web/service/fetch.tsindex 5fa9c25e325..597e0be1bab 100644--- a/web/service/fetch.ts+++ b/web/service/fetch.ts@@ -156,7 +156,6 @@ async function base<T>(url: string, options: FetchOptionType = {}, otherOptions:redirect: 'follow',} as constconst { params, body, headers: headersFromProps, ...init } = { ...baseOptions, ...options }- const headers = new Headers(headersFromProps || {})const {isPublicAPI = false,@@ -169,6 +168,8 @@ async function base<T>(url: string, options: FetchOptionType = {}, otherOptions:request,} = otherOptions+ const headers = new Headers(headersFromProps || {})+let base: stringif (isMarketplaceAPI)base = MARKETPLACE_API_PREFIX@@ -259,15 +260,15 @@ async function base<T>(url: string, options: FetchOptionType = {}, otherOptions:* standard `base()` fetch wrapper.*/export function postWithKeepalive(url: string, body: Record<string, unknown>): void {- const headers: Record<string, string> = {+ const headers = new Headers({'Content-Type': ContentType.json,[CSRF_HEADER_NAME]: Cookies.get(CSRF_COOKIE_NAME()) || '',- }+ })// Add Authorization header if an access token is availableconst accessToken = getWebAppAccessToken()if (accessToken)- headers.Authorization = `Bearer ${accessToken}`+ headers.set('Authorization', `Bearer ${accessToken}`)globalThis.fetch(url, {method: 'POST',diff --git a/web/service/knowledge/use-dataset.ts b/web/service/knowledge/use-dataset.tsindex 152aea73e04..b606a4bfb95 100644--- a/web/service/knowledge/use-dataset.ts+++ b/web/service/knowledge/use-dataset.ts@@ -198,11 +198,12 @@ export const useExternalKnowledgeApiList = (options?: { enabled?: boolean }) =>export const useDatasetTestingRecords = (datasetId?: string,params?: { page: number, limit: number },+ options?: { enabled?: boolean },) => {return useQuery<HitTestingRecordsResponse>({queryKey: [NAME_SPACE, 'testing-records', datasetId, params],queryFn: () => get<HitTestingRecordsResponse>(`/datasets/${datasetId}/queries`, { params }),- enabled: !!datasetId && !!params,+ enabled: !!datasetId && !!params && (options?.enabled ?? true),placeholderData: keepPreviousData,})}diff --git a/web/service/use-apps.ts b/web/service/use-apps.tsindex fcff50b9677..6a742d2a1fc 100644--- a/web/service/use-apps.ts+++ b/web/service/use-apps.ts@@ -25,6 +25,7 @@ type DateRangeParams = {end?: string}+export const appDetailQueryKeyPrefix = [NAME_SPACE, 'detail']const useAppFullListKey = [NAME_SPACE, 'full-list']export const useGenerateRuleTemplate = (type: GeneratorType, disabled?: boolean) => {@@ -42,9 +43,10 @@ export const useGenerateRuleTemplate = (type: GeneratorType, disabled?: boolean)export const useAppDetail = (appID: string) => {return useQuery<App>({- queryKey: [NAME_SPACE, 'detail', appID],+ queryKey: [...appDetailQueryKeyPrefix, appID],queryFn: () => get<App>(`/apps/${appID}`),enabled: !!appID,+ gcTime: 0,})}diff --git a/web/service/use-common.ts b/web/service/use-common.tsindex 4a39c5c8dd4..1ee2451ffad 100644--- a/web/service/use-common.ts+++ b/web/service/use-common.ts@@ -5,6 +5,7 @@ import type {ModelProvider,ModelTypeEnum,} from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { AccessControlTemplateLanguage } from '@/i18n-config/language'import type {AccountIntegrate,CodeBasedExtension,@@ -12,7 +13,6 @@ import type {FileUploadConfigResponse,LangGeniusVersionResponse,Member,- PluginProvider,StructuredOutputRulesRequestBody,StructuredOutputRulesResponse,} from '@/models/common'@@ -32,7 +32,6 @@ export const commonQueryKeys = {defaultModel: (type: ModelTypeEnum) => [NAME_SPACE, 'default-model', type] as const,retrievalMethods: [NAME_SPACE, 'support-retrieval-methods'] as const,accountIntegrates: [NAME_SPACE, 'account-integrates'] as const,- pluginProviders: [NAME_SPACE, 'plugin-providers'] as const,notionConnection: [NAME_SPACE, 'notion-connection'] as const,codeBasedExtensions: (module?: string) => [NAME_SPACE, 'code-based-extensions', module] as const,invitationCheck: (params?: { workspace_id?: string, email?: string, token?: string }) => [@@ -125,10 +124,14 @@ type MemberResponse = {accounts: Member[] | null}-export const useMembers = () => {+export const useMembers = (language?: AccessControlTemplateLanguage) => {return useQuery<MemberResponse>({- queryKey: commonQueryKeys.members,- queryFn: () => get<MemberResponse>('/workspaces/current/members', { params: {} }),+ queryKey: [...commonQueryKeys.members, language],+ queryFn: () => get<MemberResponse>('/workspaces/current/members', {+ params: {+ language,+ },+ }),})}@@ -229,13 +232,6 @@ export const useAccountIntegrates = () => {})}-export const usePluginProviders = () => {- return useQuery<PluginProvider[] | null>({- queryKey: commonQueryKeys.pluginProviders,- queryFn: () => get<PluginProvider[] | null>('/workspaces/current/tool-providers'),- })-}-export const useCodeBasedExtensions = (module: string) => {return useQuery<CodeBasedExtension>({queryKey: commonQueryKeys.codeBasedExtensions(module),diff --git a/web/service/use-explore.ts b/web/service/use-explore.tsindex 9683376b2ff..9c568263c89 100644--- a/web/service/use-explore.ts+++ b/web/service/use-explore.ts@@ -20,7 +20,7 @@ type ExploreAppListData = {allList: App[]}-export const useExploreAppList = () => {+export const useExploreAppList = (options: { enabled?: boolean } = {}) => {const locale = useLocale()const exploreAppsInput = locale? { query: { language: locale } }@@ -36,6 +36,7 @@ export const useExploreAppList = () => {allList: [...recommended_apps].sort((a, b) => a.position - b.position),}},+ enabled: options.enabled,})}diff --git a/web/service/use-plugins.ts b/web/service/use-plugins.tsindex d2ccc2b681a..38b36c89c11 100644--- a/web/service/use-plugins.ts+++ b/web/service/use-plugins.ts@@ -38,10 +38,11 @@ import { cloneDeep } from 'es-toolkit/object'import { useCallback, useEffect, useRef } from 'react'import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'import { getFormattedPlugin } from '@/app/components/plugins/marketplace/utils'-import { PermissionType, PluginCategoryEnum, TaskStatus } from '@/app/components/plugins/types'+import { PluginCategoryEnum, TaskStatus } from '@/app/components/plugins/types'import { useAppContext } from '@/context/app-context'import { fetchModelProviderModelList } from '@/service/common'import { fetchPluginInfoFromMarketPlace, uninstallPlugin } from '@/service/plugins'+import { hasPermission } from '@/utils/permission'// eslint-disable-next-line no-restricted-importsimport { get, getMarketplace, post, postMarketplace } from './base'import { consoleQuery } from './client'@@ -565,18 +566,19 @@ const areAutoUpgradeSettingsEqual = (left: AutoUpdateConfig | undefined, right:&& areStringArraysEqual(left?.include_plugins ?? [], right?.include_plugins ?? [])}-export const hasPluginPermission = (permission: PermissionType | undefined, isAdmin: boolean) => {- if (!permission)- return false+// legacy plugin permission+// export const hasPluginPermission = (permission: PermissionType | undefined, isAdmin: boolean) => {+// if (!permission)+// return false- if (permission === PermissionType.noOne)- return false+// if (permission === PermissionType.noOne)+// return false- if (permission === PermissionType.everyone)- return true+// if (permission === PermissionType.everyone)+// return true- return isAdmin-}+// return isAdmin+// }export const usePluginPermissionSettings = () => {return useQuery({@@ -811,12 +813,8 @@ export const useFetchPluginsInMarketPlaceByInfo = (infos: MarketplacePluginInfoRexport const usePluginTaskList = (category?: PluginCategoryEnum | string) => {const initializedRef = useRef(false)const queryClient = useQueryClient()- const { isCurrentWorkspaceManager, isCurrentWorkspaceOwner } = useAppContext()- const { data: permissions } = usePluginPermissionSettings()- const canManagement = hasPluginPermission(- permissions?.install_permission,- isCurrentWorkspaceManager || isCurrentWorkspaceOwner,- )+ const { workspacePermissionKeys } = useAppContext()+ const canManagement = hasPermission(workspacePermissionKeys, 'plugin.install')const { refreshPluginList } = useRefreshPluginList()const query = useQuery<PluginTaskListResponse>({enabled: canManagement,diff --git a/web/service/use-tools.ts b/web/service/use-tools.tsindex f05e2241e2c..b9eb7a8cabf 100644--- a/web/service/use-tools.ts+++ b/web/service/use-tools.ts@@ -1,4 +1,4 @@-import type { QueryKey } from '@tanstack/react-query'+import type { QueryKey, UseQueryOptions } from '@tanstack/react-query'import type {Collection,MCPServerDetail,@@ -199,10 +199,11 @@ export const useUpdateMCPTools = () => {})}-export const useMCPServerDetail = (appID: string) => {+export const useMCPServerDetail = (appID: string, enabled = true) => {return useQuery<MCPServerDetail>({queryKey: [NAME_SPACE, 'MCPServerDetail', appID],queryFn: () => get<MCPServerDetail>(`/apps/${appID}/server`),+ enabled,})}@@ -307,7 +308,10 @@ export type AppTrigger = {updated_at: string}-export const useAppTriggers = (appId: string | undefined, options?: any) => {+export const useAppTriggers = (+ appId: string | undefined,+ options?: Omit<UseQueryOptions<{ data: AppTrigger[] }>, 'queryKey' | 'queryFn'>,+) => {return useQuery<{ data: AppTrigger[] }>({queryKey: [NAME_SPACE, 'app-triggers', appId],queryFn: () => get<{ data: AppTrigger[] }>(`/apps/${appId}/triggers`),diff --git a/web/types/app.ts b/web/types/app.tsindex b051fc7f4fc..85d7f7824bc 100644--- a/web/types/app.ts+++ b/web/types/app.ts@@ -360,6 +360,10 @@ export type App = {app_model_config: ModelConfig/** Timestamp of creation */created_at: number+ /** Creator account ID */+ created_by?: string+ /** Resource maintainer account ID */+ maintainer?: string/** Timestamp of update */updated_at: number/** Web Application Configuration */@@ -382,6 +386,8 @@ export type App = {has_draft_trigger?: boolean/** Type */workflow_kind?: WorkflowKind | null+ /** ACL permission keys */+ permission_keys?: string[]}export type AppSSO = {diff --git a/web/utils/app-redirection.spec.ts b/web/utils/app-redirection.spec.tsindex ab790b1acc3..d3d9cb02b9f 100644--- a/web/utils/app-redirection.spec.ts+++ b/web/utils/app-redirection.spec.ts@@ -3,57 +3,81 @@* Tests navigation path generation based on user permissions and app modes*/import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import { getRedirection, getRedirectionPath } from './app-redirection'describe('app-redirection', () => {/*** Tests getRedirectionPath which determines the correct path based on:- * - User's editor permissions+ * - App ACL layout access permissions+ * - App ACL monitor and access config permissions* - App mode (workflow, advanced-chat, chat, completion, agent-chat)*/describe('getRedirectionPath', () => {- it('returns overview path when user is not editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.CHAT }- const result = getRedirectionPath(false, app)- expect(result).toBe('/app/app-123/overview')+ it('returns develop path when app ACL cannot access guarded pages', () => {+ const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [] }+ const result = getRedirectionPath(app)+ expect(result).toBe('/app/app-123/develop')})- it('returns workflow path for workflow mode when user is editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.WORKFLOW }- const result = getRedirectionPath(true, app)+ it('returns workflow path for workflow mode when app ACL can access layout', () => {+ const app = { id: 'app-123', mode: AppModeEnum.WORKFLOW, permission_keys: [AppACLPermission.ViewLayout] }+ const result = getRedirectionPath(app)expect(result).toBe('/app/app-123/workflow')})- it('returns workflow path for advanced-chat mode when user is editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.ADVANCED_CHAT }- const result = getRedirectionPath(true, app)+ it('returns workflow path for advanced-chat mode when app ACL can access layout', () => {+ const app = { id: 'app-123', mode: AppModeEnum.ADVANCED_CHAT, permission_keys: [AppACLPermission.TestAndRun] }+ const result = getRedirectionPath(app)expect(result).toBe('/app/app-123/workflow')})- it('returns configuration path for chat mode when user is editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.CHAT }- const result = getRedirectionPath(true, app)+ it('returns configuration path for chat mode when app ACL can access layout', () => {+ const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [AppACLPermission.Edit] }+ const result = getRedirectionPath(app)expect(result).toBe('/app/app-123/configuration')})- it('returns configuration path for completion mode when user is editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.COMPLETION }- const result = getRedirectionPath(true, app)+ it('returns configuration path for completion mode when app ACL can access layout', () => {+ const app = { id: 'app-123', mode: AppModeEnum.COMPLETION, permission_keys: [AppACLPermission.ViewLayout] }+ const result = getRedirectionPath(app)expect(result).toBe('/app/app-123/configuration')})- it('returns configuration path for agent-chat mode when user is editor', () => {- const app = { id: 'app-456', mode: AppModeEnum.AGENT_CHAT }- const result = getRedirectionPath(true, app)+ it('returns configuration path for agent-chat mode when app ACL can access layout', () => {+ const app = { id: 'app-456', mode: AppModeEnum.AGENT_CHAT, permission_keys: [AppACLPermission.ViewLayout] }+ const result = getRedirectionPath(app)expect(result).toBe('/app/app-456/configuration')})it('handles different app IDs', () => {- const app1 = { id: 'abc-123', mode: AppModeEnum.CHAT }- const app2 = { id: 'xyz-789', mode: AppModeEnum.WORKFLOW }+ const app1 = { id: 'abc-123', mode: AppModeEnum.CHAT, permission_keys: [] }+ const app2 = { id: 'xyz-789', mode: AppModeEnum.WORKFLOW, permission_keys: [AppACLPermission.ViewLayout] }- expect(getRedirectionPath(false, app1)).toBe('/app/abc-123/overview')- expect(getRedirectionPath(true, app2)).toBe('/app/xyz-789/workflow')+ expect(getRedirectionPath(app1)).toBe('/app/abc-123/develop')+ expect(getRedirectionPath(app2)).toBe('/app/xyz-789/workflow')+ })++ it('returns layout path when the app maintainer has app.create_and_management permission without app ACL keys', () => {+ const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [] }++ expect(getRedirectionPath(app, {+ currentUserId: 'user-1',+ resourceMaintainer: 'user-1',+ workspacePermissionKeys: ['app.create_and_management'],+ })).toBe('/app/app-123/configuration')+ })++ it('returns access config path when app ACL can only configure access', () => {+ const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [AppACLPermission.AccessConfig] }++ expect(getRedirectionPath(app)).toBe('/app/app-123/access-config')+ })++ it('returns overview path when app ACL can only monitor the app', () => {+ const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [AppACLPermission.Monitor] }++ expect(getRedirectionPath(app)).toBe('/app/app-123/overview')})})@@ -64,42 +88,42 @@ describe('app-redirection', () => {/*** Tests that the redirection function is called with the correct path*/- it('calls redirection function with correct path for non-editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.CHAT }+ it('calls redirection function with develop path when app ACL cannot access guarded pages', () => {+ const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [] }const mockRedirect = vi.fn()- getRedirection(false, app, mockRedirect)+ getRedirection(app, mockRedirect)- expect(mockRedirect).toHaveBeenCalledWith('/app/app-123/overview')+ expect(mockRedirect).toHaveBeenCalledWith('/app/app-123/develop')expect(mockRedirect).toHaveBeenCalledTimes(1)})- it('calls redirection function with workflow path for editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.WORKFLOW }+ it('calls redirection function with workflow path when app ACL can access layout', () => {+ const app = { id: 'app-123', mode: AppModeEnum.WORKFLOW, permission_keys: [AppACLPermission.ViewLayout] }const mockRedirect = vi.fn()- getRedirection(true, app, mockRedirect)+ getRedirection(app, mockRedirect)expect(mockRedirect).toHaveBeenCalledWith('/app/app-123/workflow')expect(mockRedirect).toHaveBeenCalledTimes(1)})- it('calls redirection function with configuration path for chat mode editor', () => {- const app = { id: 'app-123', mode: AppModeEnum.CHAT }+ it('calls redirection function with configuration path for chat mode with layout access', () => {+ const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [AppACLPermission.ViewLayout] }const mockRedirect = vi.fn()- getRedirection(true, app, mockRedirect)+ getRedirection(app, mockRedirect)expect(mockRedirect).toHaveBeenCalledWith('/app/app-123/configuration')expect(mockRedirect).toHaveBeenCalledTimes(1)})it('works with different redirection functions', () => {- const app = { id: 'app-123', mode: AppModeEnum.WORKFLOW }+ const app = { id: 'app-123', mode: AppModeEnum.WORKFLOW, permission_keys: [AppACLPermission.ViewLayout] }const paths: string[] = []const customRedirect = (path: string) => paths.push(path)- getRedirection(true, app, customRedirect)+ getRedirection(app, customRedirect)expect(paths).toEqual(['/app/app-123/workflow'])})diff --git a/web/utils/app-redirection.ts b/web/utils/app-redirection.tsindex 5ed8419e059..b7e02f936e3 100644--- a/web/utils/app-redirection.ts+++ b/web/utils/app-redirection.ts@@ -1,25 +1,40 @@+import type { ResourceMaintainerPermissionOptions } from '@/utils/permission'import { AppModeEnum } from '@/types/app'+import { getAppACLCapabilities } from '@/utils/permission'++type AppRedirectionTarget = {+ id: string+ mode: AppModeEnum+ permission_keys?: string[]+}export const getRedirectionPath = (- isCurrentWorkspaceEditor: boolean,- app: { id: string, mode: AppModeEnum },+ app: AppRedirectionTarget,+ maintainerPermissionOptions?: ResourceMaintainerPermissionOptions,) => {- if (!isCurrentWorkspaceEditor) {- return `/app/${app.id}/overview`- }- else {+ const appACLCapabilities = getAppACLCapabilities(app.permission_keys, maintainerPermissionOptions)++ if (appACLCapabilities.canAccessLayout) {if (app.mode === AppModeEnum.WORKFLOW || app.mode === AppModeEnum.ADVANCED_CHAT)return `/app/${app.id}/workflow`elsereturn `/app/${app.id}/configuration`}++ if (appACLCapabilities.canMonitor)+ return `/app/${app.id}/overview`++ if (appACLCapabilities.canAccessConfig)+ return `/app/${app.id}/access-config`++ return `/app/${app.id}/develop`}export const getRedirection = (- isCurrentWorkspaceEditor: boolean,- app: { id: string, mode: AppModeEnum },+ app: AppRedirectionTarget,redirectionFunc: (href: string) => void,+ maintainerPermissionOptions?: ResourceMaintainerPermissionOptions,) => {- const redirectionPath = getRedirectionPath(isCurrentWorkspaceEditor, app)+ const redirectionPath = getRedirectionPath(app, maintainerPermissionOptions)redirectionFunc(redirectionPath)}diff --git a/web/utils/permission.spec.ts b/web/utils/permission.spec.tsindex 42c6e9636e3..311796cc14c 100644--- a/web/utils/permission.spec.ts+++ b/web/utils/permission.spec.ts@@ -3,7 +3,14 @@ import { DatasetPermission } from '@/models/datasets'* Test suite for permission utility functions* Tests dataset edit permission logic based on user roles and dataset settings*/-import { hasEditPermissionForDataset } from './permission'+import {+ AppACLPermission,+ DatasetACLPermission,+ getAppACLCapabilities,+ getDatasetACLCapabilities,+ hasEditPermissionForDataset,+ hasPermission,+} from './permission'describe('permission', () => {/**@@ -92,4 +99,105 @@ describe('permission', () => {expect(hasEditPermissionForDataset(creatorId, config)).toBe(true)})})++ describe('hasPermissionKey', () => {+ const permissionKey = 'workspace.member.manage'++ it('returns true when the permission key exists', () => {+ expect(hasPermission(['workspace.role.manage', permissionKey], permissionKey)).toBe(true)+ })++ it('returns false when the permission key does not exist', () => {+ expect(hasPermission(['workspace.role.manage'], permissionKey)).toBe(false)+ })+ })++ describe('getAppACLCapabilities', () => {+ it('allows test-and-run users to access layout without edit or comment', () => {+ const capabilities = getAppACLCapabilities([AppACLPermission.TestAndRun])++ expect(capabilities.canTestAndRun).toBe(true)+ expect(capabilities.canAccessLayout).toBe(true)+ expect(capabilities.canComment).toBe(false)+ expect(capabilities.canEdit).toBe(false)+ })++ it('allows view-layout users to preview the app and comment but not run/debug', () => {+ const capabilities = getAppACLCapabilities([AppACLPermission.ViewLayout])++ expect(capabilities.canPreviewApp).toBe(true)+ expect(capabilities.canAccessLayout).toBe(true)+ expect(capabilities.canComment).toBe(true)+ expect(capabilities.canTestAndRun).toBe(false)+ })+ })++ describe('app maintainer capabilities', () => {+ it('grants all app ACL capabilities without injecting app ACL permission keys', () => {+ const permissionKeys: string[] = []+ const capabilities = getAppACLCapabilities(permissionKeys, {+ currentUserId: 'user-1',+ resourceMaintainer: 'user-1',+ workspacePermissionKeys: ['app.create_and_management'],+ })++ expect(capabilities.canViewLayout).toBe(true)+ expect(capabilities.canTestAndRun).toBe(true)+ expect(capabilities.canEdit).toBe(true)+ expect(capabilities.canImportExportDSL).toBe(true)+ expect(capabilities.canDelete).toBe(true)+ expect(capabilities.canReleaseAndVersion).toBe(true)+ expect(capabilities.canMonitor).toBe(true)+ expect(capabilities.canAccessConfig).toBe(true)+ expect(permissionKeys).toEqual([])+ })++ it('keeps app ACL capabilities unchanged when the maintainer lacks app.create_and_management permission', () => {+ const capabilities = getAppACLCapabilities([AppACLPermission.ViewLayout], {+ currentUserId: 'user-1',+ resourceMaintainer: 'user-1',+ workspacePermissionKeys: [],+ })++ expect(capabilities.canViewLayout).toBe(true)+ expect(capabilities.canEdit).toBe(false)+ expect(capabilities.canDelete).toBe(false)+ })+ })++ describe('dataset maintainer capabilities', () => {+ it('grants all dataset ACL capabilities without injecting dataset ACL permission keys', () => {+ const permissionKeys: string[] = []+ const capabilities = getDatasetACLCapabilities(permissionKeys, {+ currentUserId: 'user-1',+ resourceMaintainer: 'user-1',+ workspacePermissionKeys: ['dataset.create_and_management'],+ })++ expect(capabilities.canReadonly).toBe(true)+ expect(capabilities.canEdit).toBe(true)+ expect(capabilities.canImportExportDSL).toBe(true)+ expect(capabilities.canPipelineTest).toBe(true)+ expect(capabilities.canDocumentDownload).toBe(true)+ expect(capabilities.canRetrievalRecall).toBe(true)+ expect(capabilities.canUse).toBe(true)+ expect(capabilities.canDeleteFile).toBe(true)+ expect(capabilities.canPipelineRelease).toBe(true)+ expect(capabilities.canDelete).toBe(true)+ expect(capabilities.canAccessConfig).toBe(true)+ expect(permissionKeys).toEqual([])+ })++ it('keeps dataset ACL capabilities unchanged when the current user is not the maintainer', () => {+ const capabilities = getDatasetACLCapabilities([DatasetACLPermission.Readonly], {+ currentUserId: 'user-1',+ resourceMaintainer: 'user-2',+ workspacePermissionKeys: ['dataset.create_and_management'],+ })++ expect(capabilities.canReadonly).toBe(true)+ expect(capabilities.canEdit).toBe(false)+ expect(capabilities.canDelete).toBe(false)+ })+ })})diff --git a/web/utils/permission.ts b/web/utils/permission.tsindex 8a7b9f5fa1a..733e58611ce 100644--- a/web/utils/permission.ts+++ b/web/utils/permission.ts@@ -1,5 +1,71 @@+import type { PermissionKey } from '@/models/access-control'import { DatasetPermission } from '@/models/datasets'+export const AppACLPermission = {+ ViewLayout: 'app.acl.view_layout',+ TestAndRun: 'app.acl.test_and_run',+ Edit: 'app.acl.edit',+ ImportExportDSL: 'app.acl.import_export_dsl',+ Delete: 'app.acl.delete',+ ReleaseAndVersion: 'app.acl.release_and_version',+ Monitor: 'app.acl.monitor',+ AccessConfig: 'app.acl.access_config',+} as const++export const DatasetACLPermission = {+ Readonly: 'dataset.acl.readonly',+ Edit: 'dataset.acl.edit',+ ImportExportDSL: 'dataset.acl.import_export_dsl',+ PipelineTest: 'dataset.acl.pipeline_test',+ DocumentDownload: 'dataset.acl.document_download',+ RetrievalRecall: 'dataset.acl.retrieval_recall',+ Use: 'dataset.acl.use',+ DeleteFile: 'dataset.acl.delete_file',+ PipelineRelease: 'dataset.acl.pipeline_release',+ Delete: 'dataset.acl.delete',+ AccessConfig: 'dataset.acl.access_config',+} as const++export const BillingPermission = {+ View: 'billing.view',+ Manage: 'billing.manage',+ SubscriptionManage: 'billing.subscription.manage',+} as const++export type ResourceMaintainerPermissionOptions = {+ currentUserId?: string | null+ resourceMaintainer?: string | null+ workspacePermissionKeys?: readonly PermissionKey[] | null+}++type AppACLCapabilities = {+ canViewLayout: boolean+ canTestAndRun: boolean+ canEdit: boolean+ canAccessLayout: boolean+ canComment: boolean+ canPreviewApp: boolean+ canImportExportDSL: boolean+ canDelete: boolean+ canReleaseAndVersion: boolean+ canMonitor: boolean+ canAccessConfig: boolean+}++type DatasetACLCapabilities = {+ canReadonly: boolean+ canEdit: boolean+ canImportExportDSL: boolean+ canPipelineTest: boolean+ canDocumentDownload: boolean+ canRetrievalRecall: boolean+ canUse: boolean+ canDeleteFile: boolean+ canPipelineRelease: boolean+ canDelete: boolean+ canAccessConfig: boolean+}+type DatasetConfig = {createdBy: stringpartialMemberList: string[]@@ -16,3 +82,76 @@ export const hasEditPermissionForDataset = (userId: string, datasetConfig: Datasreturn partialMemberList.includes(userId)return false}++export const hasPermission = (permissionKeys: readonly PermissionKey[] | null | undefined, permissionKeySet: PermissionKey | PermissionKey[]) => {+ if (!permissionKeys)+ return false++ if (Array.isArray(permissionKeySet)) {+ return permissionKeySet.some(key => permissionKeys.includes(key))+ }+ const singlePermissionKey = permissionKeySet+ return permissionKeys.includes(singlePermissionKey)+}++const shouldGrantMaintainerPermissions = (+ options: ResourceMaintainerPermissionOptions | undefined,+ createPermissionKey: PermissionKey,+) => {+ if (!options?.currentUserId || !options?.resourceMaintainer)+ return false++ return options.currentUserId === options.resourceMaintainer+ && hasPermission(options.workspacePermissionKeys, createPermissionKey)+}++const hasResourcePermission = (+ permissionKeys: readonly PermissionKey[] | null | undefined,+ permissionKey: PermissionKey,+ hasMaintainerPermissions: boolean,+) => hasMaintainerPermissions || hasPermission(permissionKeys, permissionKey)++export const getAppACLCapabilities = (+ permissionKeys: readonly PermissionKey[] | null | undefined,+ options?: ResourceMaintainerPermissionOptions,+): AppACLCapabilities => {+ const hasMaintainerPermissions = shouldGrantMaintainerPermissions(options, 'app.create_and_management')+ const canViewLayout = hasResourcePermission(permissionKeys, AppACLPermission.ViewLayout, hasMaintainerPermissions)+ const canTestAndRun = hasResourcePermission(permissionKeys, AppACLPermission.TestAndRun, hasMaintainerPermissions)+ const canEdit = hasResourcePermission(permissionKeys, AppACLPermission.Edit, hasMaintainerPermissions)++ return {+ canViewLayout,+ canTestAndRun,+ canEdit,+ canAccessLayout: canViewLayout || canTestAndRun || canEdit,+ canComment: canViewLayout || canEdit,+ canPreviewApp: canViewLayout || canTestAndRun,+ canImportExportDSL: hasResourcePermission(permissionKeys, AppACLPermission.ImportExportDSL, hasMaintainerPermissions),+ canDelete: hasResourcePermission(permissionKeys, AppACLPermission.Delete, hasMaintainerPermissions),+ canReleaseAndVersion: hasResourcePermission(permissionKeys, AppACLPermission.ReleaseAndVersion, hasMaintainerPermissions),+ canMonitor: hasResourcePermission(permissionKeys, AppACLPermission.Monitor, hasMaintainerPermissions),+ canAccessConfig: hasResourcePermission(permissionKeys, AppACLPermission.AccessConfig, hasMaintainerPermissions),+ }+}++export const getDatasetACLCapabilities = (+ permissionKeys: readonly PermissionKey[] | null | undefined,+ options?: ResourceMaintainerPermissionOptions,+): DatasetACLCapabilities => {+ const hasMaintainerPermissions = shouldGrantMaintainerPermissions(options, 'dataset.create_and_management')++ return {+ canReadonly: hasResourcePermission(permissionKeys, DatasetACLPermission.Readonly, hasMaintainerPermissions),+ canEdit: hasResourcePermission(permissionKeys, DatasetACLPermission.Edit, hasMaintainerPermissions),+ canImportExportDSL: hasResourcePermission(permissionKeys, DatasetACLPermission.ImportExportDSL, hasMaintainerPermissions),+ canPipelineTest: hasResourcePermission(permissionKeys, DatasetACLPermission.PipelineTest, hasMaintainerPermissions),+ canDocumentDownload: hasResourcePermission(permissionKeys, DatasetACLPermission.DocumentDownload, hasMaintainerPermissions),+ canRetrievalRecall: hasResourcePermission(permissionKeys, DatasetACLPermission.RetrievalRecall, hasMaintainerPermissions),+ canUse: hasResourcePermission(permissionKeys, DatasetACLPermission.Use, hasMaintainerPermissions),+ canDeleteFile: hasResourcePermission(permissionKeys, DatasetACLPermission.DeleteFile, hasMaintainerPermissions),+ canPipelineRelease: hasResourcePermission(permissionKeys, DatasetACLPermission.PipelineRelease, hasMaintainerPermissions),+ canDelete: hasResourcePermission(permissionKeys, DatasetACLPermission.Delete, hasMaintainerPermissions),+ canAccessConfig: hasResourcePermission(permissionKeys, DatasetACLPermission.AccessConfig, hasMaintainerPermissions),+ }+}