Skip to content

armgit / dify

Public Imported from GitHub
0

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

feat: add agent resource permissions (#41940)

Wu Tianweif89c3e6ec746
diff --git a/api/controllers/common/agent_access.py b/api/controllers/common/agent_access.py
new file mode 100644
index 00000000000..1f2df6dfb47
--- /dev/null
+++ b/api/controllers/common/agent_access.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from sqlalchemy.orm import Session
+
+from services.agent.roster_service import AgentRosterService
+from services.enterprise import rbac_service as enterprise_rbac_service
+
+if TYPE_CHECKING:
+ from services.app_service import AppListBaseParams
+ from services.enterprise.rbac_service import MyPermissionsResponse
+
+
+AGENT_LIST_PERMISSION_KEYS: frozenset[str] = frozenset({"agent.acl.preview"})
+
+
+def has_agent_list_permission(permission_keys: Sequence[str]) -> bool:
+ """Return whether the permission set makes an Agent visible in resource lists."""
+ return any(permission_key in AGENT_LIST_PERMISSION_KEYS for permission_key in permission_keys)
+
+
+@dataclass(frozen=True)
+class AgentAccessFilter:
+ """Resolved resource-level visibility for Agent list endpoints.
+
+ ``accessible_agent_ids`` of ``None`` means every Agent is visible. An
+ explicit set limits list queries to exactly those Agent resources.
+ """
+
+ accessible_agent_ids: set[str] | None
+
+ @classmethod
+ def unrestricted(cls) -> AgentAccessFilter:
+ return cls(accessible_agent_ids=None)
+
+ def apply_to_app_params(self, params: AppListBaseParams, *, tenant_id: str, session: Session) -> None:
+ """Translate visible Agent ids to their Agent App ids before pagination."""
+ if self.accessible_agent_ids is None:
+ return
+ if not self.accessible_agent_ids:
+ params.accessible_app_ids = []
+ return
+
+ params.accessible_app_ids = AgentRosterService(session).load_app_ids_for_agents(
+ tenant_id=tenant_id,
+ agent_ids=sorted(self.accessible_agent_ids),
+ )
+
+
+def resolve_agent_access_filter(
+ tenant_id: str,
+ account_id: str,
+ *,
+ session: Session,
+ permissions: MyPermissionsResponse | None = None,
+) -> AgentAccessFilter:
+ """Compute Agent resources visible to an account in a workspace."""
+ if permissions is None:
+ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(
+ tenant_id,
+ account_id,
+ session=session,
+ )
+ whitelist_scope = enterprise_rbac_service.RBACService.AgentAccess.whitelist_resources(tenant_id, account_id)
+ has_default_preview = has_agent_list_permission(
+ permissions.agent.default_permission_keys
+ ) or has_agent_list_permission(permissions.workspace.permission_keys)
+
+ permission_agent_ids: set[str] | None = None
+ if not has_default_preview:
+ permission_agent_ids = {
+ override.resource_id
+ for override in permissions.agent.overrides
+ if has_agent_list_permission(override.permission_keys)
+ }
+
+ if whitelist_scope.unrestricted:
+ accessible_agent_ids = permission_agent_ids
+ else:
+ accessible_agent_ids = set(whitelist_scope.resource_ids)
+
+ return AgentAccessFilter(accessible_agent_ids=accessible_agent_ids)
diff --git a/api/controllers/console/agent/roster.py b/api/controllers/console/agent/roster.py
index a8ba32477af..5811d0c54fb 100644
--- a/api/controllers/console/agent/roster.py
+++ b/api/controllers/console/agent/roster.py
@@ -7,6 +7,8 @@ from pydantic import AliasChoices, BaseModel, Field, field_validator
from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session
+from configs import dify_config
+from controllers.common.agent_access import resolve_agent_access_filter
from controllers.common.rbac import AgentId, RBACCheck, Workspace
from controllers.common.schema import (
query_params_from_model,
@@ -78,6 +80,7 @@ from services.agent.observability_service import (
)
from services.agent.roster_service import AgentRosterService
from services.app_service import AgentAppPublicationCounts, AppListParams, AppService, CreateAppParams
+from services.enterprise import rbac_service as enterprise_rbac_service
from services.enterprise.enterprise_service import EnterpriseService
from services.entities.agent_entities import ComposerSavePayload, RosterListQuery
from services.system_feature_service import SystemFeatureService
@@ -251,6 +254,7 @@ class AgentStatisticsQuery(BaseModel):
class AgentAppPartial(GenericAppPartial):
+ permission_keys: list[str]
app_id: str | None = None
backing_app_id: str | None = None
hidden_app_backed: bool = False
@@ -263,6 +267,7 @@ class AgentAppPartial(GenericAppPartial):
class AgentAppDetailWithSite(GenericAppDetailWithSite):
+ permission_keys: list[str]
app_id: str | None = None
backing_app_id: str | None = None
hidden_app_backed: bool = False
@@ -392,7 +397,7 @@ def _serialize_agent_app_detail(
app_model.access_mode = app_setting.access_mode # type: ignore[attr-defined]
roster_service = _agent_roster_service(session)
- payload = AgentAppDetailWithSite.model_validate(
+ payload = GenericAppDetailWithSite.model_validate(
app_model,
from_attributes=True,
context={"session": session},
@@ -429,7 +434,14 @@ def _serialize_agent_app_detail(
payload["debug_conversation_message_count"] = message_count
payload["role"] = agent.role or ""
payload["access_ready"] = agent_has_workflow_callable_active_snapshot(session=session, agent=agent)
- return payload
+ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(
+ app_model.tenant_id,
+ current_user.id,
+ agent_id=agent.id,
+ session=session,
+ )
+ payload["permission_keys"] = permissions.agent.permission_keys_by_resource_ids([agent.id]).get(agent.id, [])
+ return AgentAppDetailWithSite.model_validate(payload).model_dump(mode="json", exclude={"bound_agent_id"})
def _serialize_agent_app_pagination(
@@ -439,6 +451,7 @@ def _serialize_agent_app_pagination(
tenant_id: str,
current_user: Account,
publication_counts: AgentAppPublicationCounts,
+ agent_permissions: enterprise_rbac_service.ResourcePermissionSnapshot,
) -> dict:
"""Serialize Agent App lists with roster-shaped items.
@@ -471,20 +484,23 @@ def _serialize_agent_app_pagination(
agents=list(agents_by_app_id.values()),
account_id=current_user.id,
)
- payload = AgentAppPagination.model_validate(
+ permission_keys_by_agent_id = agent_permissions.permission_keys_by_resource_ids(
+ [agent.id for agent in agents_by_app_id.values()]
+ )
+ payload = GenericAppPagination.model_validate(
{
"page": app_pagination.page,
"limit": app_pagination.per_page,
"total": app_pagination.total,
"has_more": app_pagination.has_next,
"data": app_pagination.items,
- "publication_counts": {
- "published": publication_counts.published,
- "drafts": publication_counts.drafts,
- },
},
context={"session": session},
).model_dump(mode="json")
+ payload["publication_counts"] = {
+ "published": publication_counts.published,
+ "drafts": publication_counts.drafts,
+ }
for item in payload["data"]:
app_id = item["id"]
item.pop("bound_agent_id", None)
@@ -495,6 +511,7 @@ def _serialize_agent_app_pagination(
item["hidden_app_backed"] = False
item["id"] = agent.id
item["debug_conversation_id"] = debug_conversation_ids_by_agent_id.get(agent.id)
+ item["permission_keys"] = permission_keys_by_agent_id.get(agent.id, [])
item["role"] = agent.role or ""
item["active_config_is_published"] = active_config_is_published_by_agent_id.get(agent.id, False)
item["reference_count"] = reference_counts_by_agent_id.get(agent.id, 0)
@@ -607,7 +624,6 @@ class AgentAppListApi(Resource):
@setup_required
@login_required
@account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, Workspace()))
@with_current_user
@with_current_tenant_id
@with_session
@@ -628,6 +644,20 @@ class AgentAppListApi(Resource):
agent_is_published=agent_is_published,
)
+ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(
+ current_tenant_id,
+ current_user.id,
+ session=session,
+ )
+ if dify_config.RBAC_ENABLED:
+ access_filter = resolve_agent_access_filter(
+ current_tenant_id,
+ current_user.id,
+ session=session,
+ permissions=permissions,
+ )
+ access_filter.apply_to_app_params(params, tenant_id=current_tenant_id, session=session)
+
app_service = AppService()
publication_counts = app_service.get_agent_publication_counts(
current_user.id,
@@ -656,6 +686,7 @@ class AgentAppListApi(Resource):
tenant_id=current_tenant_id,
current_user=current_user,
publication_counts=publication_counts,
+ agent_permissions=permissions.agent,
)
@console_ns.expect(console_ns.models[AgentAppCreatePayload.__name__])
@@ -1059,11 +1090,33 @@ class AgentInviteOptionsApi(Resource):
@setup_required
@login_required
@account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, Workspace()))
+ @with_current_user
@with_current_tenant_id
@with_session(write=False)
@model_validate(AgentInviteOptionsQuery)
- def get(self, req_data: AgentInviteOptionsQuery, session: Session, tenant_id: str):
+ def get(
+ self,
+ req_data: AgentInviteOptionsQuery,
+ session: Session,
+ tenant_id: str,
+ current_user: Account,
+ ):
+ accessible_agent_ids = None
+ if dify_config.RBAC_ENABLED:
+ permissions = enterprise_rbac_service.RBACService.MyPermissions.get(
+ tenant_id,
+ current_user.id,
+ session=session,
+ )
+ access_filter = resolve_agent_access_filter(
+ tenant_id,
+ current_user.id,
+ session=session,
+ permissions=permissions,
+ )
+ if access_filter.accessible_agent_ids is not None:
+ accessible_agent_ids = sorted(access_filter.accessible_agent_ids)
+
return dump_response(
AgentInviteOptionsResponse,
_agent_roster_service(session).list_invite_options(
@@ -1072,6 +1125,7 @@ class AgentInviteOptionsApi(Resource):
limit=req_data.limit,
keyword=req_data.keyword,
app_id=req_data.app_id,
+ accessible_agent_ids=accessible_agent_ids,
),
)
diff --git a/api/controllers/console/workspace/rbac.py b/api/controllers/console/workspace/rbac.py
index 9a036af6122..1ef222fbe81 100644
--- a/api/controllers/console/workspace/rbac.py
+++ b/api/controllers/console/workspace/rbac.py
@@ -401,6 +401,9 @@ class _AccessPolicyUpdateRequest(BaseModel):
permission_keys: list[str] = []
+register_schema_models(console_ns, _AccessPolicyCreateRequest, _AccessPolicyUpdateRequest)
+
+
@console_ns.route("/workspaces/current/rbac/access-policies")
class RBACAccessPoliciesApi(Resource):
@login_required
@@ -420,9 +423,10 @@ class RBACAccessPoliciesApi(Resource):
)
)
+ @console_ns.expect(console_ns.models[_AccessPolicyCreateRequest.__name__])
+ @console_ns.response(201, "Policy created", console_ns.models[svc.AccessPolicy.__name__])
@login_required
@rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace()))
- @console_ns.response(201, "Policy created", console_ns.models[svc.AccessPolicy.__name__])
def post(self):
tenant_id, account_id = _current_ids()
request = _payload(_AccessPolicyCreateRequest)
@@ -448,9 +452,10 @@ class RBACAccessPolicyItemApi(Resource):
tenant_id, account_id = _current_ids()
return _dump(svc.RBACService.AccessPolicies.get(tenant_id, account_id, str(policy_id)))
+ @console_ns.expect(console_ns.models[_AccessPolicyUpdateRequest.__name__])
+ @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicy.__name__])
@login_required
@rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace()))
- @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)
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index c60f5a5d8a6..216419ee6f2 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -11148,11 +11148,17 @@ Returns permission flags that control workspace features like member invitations
| 200 | Success |
### [POST] /workspaces/current/rbac/access-policies
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [_AccessPolicyCreateRequest](#_accesspolicycreaterequest)<br> |
+
#### Responses
-| Code | Description |
-| ---- | ----------- |
-| 200 | Success |
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | Policy created | **application/json**: [AccessPolicy](#accesspolicy)<br> |
### [DELETE] /workspaces/current/rbac/access-policies/{policy_id}
#### Parameters
@@ -11187,11 +11193,17 @@ Returns permission flags that control workspace features like member invitations
| ---- | ---------- | ----------- | -------- | ------ |
| policy_id | path | | Yes | string (uuid) |
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [_AccessPolicyUpdateRequest](#_accesspolicyupdaterequest)<br> |
+
#### Responses
-| Code | Description |
-| ---- | ----------- |
-| 200 | Success |
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Success | **application/json**: [AccessPolicy](#accesspolicy)<br> |
### [POST] /workspaces/current/rbac/access-policies/{policy_id}/copy
#### Parameters
@@ -13690,7 +13702,7 @@ Model class for AI model.
| mode | string | | Yes |
| model_config | [AppModelConfigResponse](#appmodelconfigresponse) | | No |
| name | string | | Yes |
-| permission_keys | [ string ] | | No |
+| permission_keys | [ string ] | | Yes |
| role | string | | No |
| site | [AppDetailSiteResponse](#appdetailsiteresponse) | | No |
| tags | [ [Tag](#tag) ] | | No |
@@ -13770,7 +13782,7 @@ default (the config form sends the full desired feature state on save).
| mode | string | | Yes |
| model_config | [ModelConfigPartial](#modelconfigpartial) | | No |
| name | string | | Yes |
-| permission_keys | [ string ] | | No |
+| permission_keys | [ string ] | | Yes |
| published_reference_count | integer | | No |
| published_references | [ [AgentAppPublishedReferenceResponse](#agentapppublishedreferenceresponse) ] | | No |
| reference_count | integer | | No |
@@ -21365,6 +21377,14 @@ Model class for provider quota configuration.
| ---- | ---- | ----------- | -------- |
| QuotaUnit | string | | |
+#### RBACResourceType
+
+Resource types understood by access policies.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| RBACResourceType | string | Resource types understood by access policies. | |
+
#### RBACRole
| Name | Type | Description | Required |
@@ -25143,6 +25163,15 @@ Workflow tool configuration
| ---- | ---- | ----------- | -------- |
| language | string, <br>**Available values:** "en", "ja", "zh" | Localized policy label language | No |
+#### _AccessPolicyCreateRequest
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| description | string | | No |
+| name | string | | Yes |
+| permission_keys | [ string ], <br>**Default:** | | No |
+| resource_type | [RBACResourceType](#rbacresourcetype) | | Yes |
+
#### _AccessPolicyList
| Name | Type | Description | Required |
@@ -25150,6 +25179,14 @@ Workflow tool configuration
| data | [ [AccessPolicy](#accesspolicy) ] | | No |
| pagination | [Pagination](#pagination) | | No |
+#### _AccessPolicyUpdateRequest
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| description | string | | No |
+| name | string | | Yes |
+| permission_keys | [ string ], <br>**Default:** | | No |
+
#### _DeleteMemberBindingsRequest
| Name | Type | Description | Required |
diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.py
index e781feb169e..cb090cd7d7a 100644
--- a/api/services/agent/roster_service.py
+++ b/api/services/agent/roster_service.py
@@ -1,4 +1,5 @@
import logging
+from collections.abc import Sequence
from typing import Any, TypedDict
from sqlalchemy import and_, func, or_, select
@@ -226,7 +227,14 @@ class AgentRosterService:
}
def list_invite_options(
- self, *, tenant_id: str, page: int = 1, limit: int = 20, keyword: str | None = None, app_id: str | None = None
+ self,
+ *,
+ tenant_id: str,
+ page: int = 1,
+ limit: int = 20,
+ keyword: str | None = None,
+ app_id: str | None = None,
+ accessible_agent_ids: Sequence[str] | None = None,
) -> dict[str, Any]:
"""List active roster Agents whose published snapshot can be called by Workflow."""
@@ -234,6 +242,8 @@ class AgentRosterService:
Agent.active_config_has_model.is_(True),
workflow_callable_active_snapshot_filter(),
)
+ if accessible_agent_ids is not None:
+ stmt = stmt.where(Agent.id.in_(accessible_agent_ids))
total = self._session.scalar(select(func.count()).select_from(stmt.subquery())) or 0
agents = list(self._session.scalars(stmt.offset((page - 1) * limit).limit(limit)).all())
versions_by_id = self._load_versions_by_id(
@@ -912,6 +922,22 @@ class AgentRosterService:
).all()
return {agent.app_id: agent for agent in agents if agent.app_id and agent.id}
+ def load_app_ids_for_agents(self, *, tenant_id: str, agent_ids: Sequence[str]) -> list[str]:
+ """Return active Agent App ids for the requested roster Agents."""
+ if not agent_ids:
+ return []
+ app_ids = self._session.scalars(
+ select(Agent.app_id).where(
+ Agent.tenant_id == tenant_id,
+ Agent.id.in_(agent_ids),
+ Agent.app_id.is_not(None),
+ Agent.scope == AgentScope.ROSTER,
+ Agent.source.in_(APP_BACKED_AGENT_SOURCES),
+ Agent.status == AgentStatus.ACTIVE,
+ )
+ ).all()
+ return sorted({str(app_id) for app_id in app_ids if app_id})
+
def get_app_backing_agent(self, *, tenant_id: str, app_id: str) -> Agent | None:
"""Return the roster Agent that backs the given Agent App, if any."""
return self._session.scalar(
diff --git a/api/tests/unit_tests/controllers/common/test_agent_access.py b/api/tests/unit_tests/controllers/common/test_agent_access.py
new file mode 100644
index 00000000000..33857fe03af
--- /dev/null
+++ b/api/tests/unit_tests/controllers/common/test_agent_access.py
@@ -0,0 +1,180 @@
+"""Unit tests for Agent resource-list RBAC filtering."""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.orm import Session
+
+from controllers.common.agent_access import (
+ AGENT_LIST_PERMISSION_KEYS,
+ AgentAccessFilter,
+ has_agent_list_permission,
+ resolve_agent_access_filter,
+)
+from models.agent import Agent, AgentKind, AgentScope, AgentSource, AgentStatus
+from services.app_service import AppListParams
+from services.enterprise.rbac_service import (
+ MyPermissionsResponse,
+ ResourcePermissionKeys,
+ ResourcePermissionSnapshot,
+ ResourceWhitelistResources,
+ WorkspacePermissionSnapshot,
+)
+
+_RBAC_MODULE = "controllers.common.agent_access.enterprise_rbac_service"
+
+
+def _permissions(
+ *,
+ workspace_keys: list[str] | None = None,
+ agent_default_keys: list[str] | None = None,
+ agent_overrides: list[ResourcePermissionKeys] | None = None,
+) -> MyPermissionsResponse:
+ return MyPermissionsResponse(
+ workspace=WorkspacePermissionSnapshot(permission_keys=workspace_keys or []),
+ agent=ResourcePermissionSnapshot(
+ default_permission_keys=agent_default_keys or [],
+ overrides=agent_overrides or [],
+ ),
+ )
+
+
+def _agent(
+ *,
+ agent_id: str,
+ app_id: str | None,
+ source: AgentSource = AgentSource.AGENT_APP,
+ status: AgentStatus = AgentStatus.ACTIVE,
+) -> Agent:
+ return Agent(
+ id=agent_id,
+ tenant_id="tenant-1",
+ name=agent_id,
+ description="",
+ role="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=source,
+ app_id=app_id,
+ status=status,
+ created_by="account-1",
+ updated_by="account-1",
+ )
+
+
+class TestHasAgentListPermission:
+ def test_matches_preview_permission(self) -> None:
+ for key in AGENT_LIST_PERMISSION_KEYS:
+ assert has_agent_list_permission([key])
+
+ def test_rejects_non_preview_permissions(self) -> None:
+ assert not has_agent_list_permission(["agent.acl.edit", "agent.acl.delete"])
+ assert not has_agent_list_permission([])
+
+
+class TestAgentAccessFilter:
+ def test_unrestricted_leaves_app_params_untouched(self, unbound_session: Session) -> None:
+ params = AppListParams(mode="agent")
+
+ AgentAccessFilter.unrestricted().apply_to_app_params(
+ params,
+ tenant_id="tenant-1",
+ session=unbound_session,
+ )
+
+ assert params.accessible_app_ids is None
+
+ def test_maps_visible_agent_ids_to_active_agent_apps(self, sqlite_session: Session) -> None:
+ sqlite_session.add_all(
+ [
+ _agent(agent_id="agent-1", app_id="app-2"),
+ _agent(agent_id="agent-2", app_id="app-1"),
+ _agent(agent_id="agent-3", app_id="workflow-app", source=AgentSource.ROSTER),
+ _agent(agent_id="agent-4", app_id="archived-app", status=AgentStatus.ARCHIVED),
+ ]
+ )
+ sqlite_session.flush()
+ params = AppListParams(mode="agent")
+
+ AgentAccessFilter(accessible_agent_ids={"agent-1", "agent-2", "agent-3", "agent-4"}).apply_to_app_params(
+ params, tenant_id="tenant-1", session=sqlite_session
+ )
+
+ assert params.accessible_app_ids == ["app-1", "app-2"]
+
+ def test_empty_visible_set_filters_every_agent_app(self, unbound_session: Session) -> None:
+ params = AppListParams(mode="agent")
+
+ AgentAccessFilter(accessible_agent_ids=set()).apply_to_app_params(
+ params,
+ tenant_id="tenant-1",
+ session=unbound_session,
+ )
+
+ assert params.accessible_app_ids == []
+
+
+class TestResolveAgentAccessFilter:
+ def _patch_whitelist(self, monkeypatch: pytest.MonkeyPatch, whitelist: ResourceWhitelistResources) -> None:
+ monkeypatch.setattr(
+ f"{_RBAC_MODULE}.RBACService.AgentAccess.whitelist_resources",
+ lambda _tenant_id, _account_id: whitelist,
+ )
+
+ def test_default_preview_is_unrestricted(self, monkeypatch: pytest.MonkeyPatch, unbound_session: Session) -> None:
+ self._patch_whitelist(monkeypatch, ResourceWhitelistResources(unrestricted=True))
+
+ access_filter = resolve_agent_access_filter(
+ "tenant-1",
+ "account-1",
+ session=unbound_session,
+ permissions=_permissions(agent_default_keys=["agent.acl.preview"]),
+ )
+
+ assert access_filter.accessible_agent_ids is None
+
+ def test_collects_preview_overrides_without_default_preview(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ unbound_session: Session,
+ ) -> None:
+ self._patch_whitelist(monkeypatch, ResourceWhitelistResources(unrestricted=True))
+
+ access_filter = resolve_agent_access_filter(
+ "tenant-1",
+ "account-1",
+ session=unbound_session,
+ permissions=_permissions(
+ agent_overrides=[
+ ResourcePermissionKeys(
+ resource_id="agent-1",
+ permission_keys=["agent.acl.preview"],
+ ),
+ ResourcePermissionKeys(
+ resource_id="agent-2",
+ permission_keys=["agent.acl.edit"],
+ ),
+ ]
+ ),
+ )
+
+ assert access_filter.accessible_agent_ids == {"agent-1"}
+
+ def test_restricted_whitelist_is_the_visibility_boundary(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ unbound_session: Session,
+ ) -> None:
+ self._patch_whitelist(
+ monkeypatch,
+ ResourceWhitelistResources(unrestricted=False, resource_ids=["agent-9"]),
+ )
+
+ access_filter = resolve_agent_access_filter(
+ "tenant-1",
+ "account-1",
+ session=unbound_session,
+ permissions=_permissions(workspace_keys=["agent.acl.preview"]),
+ )
+
+ assert access_filter.accessible_agent_ids == {"agent-9"}
diff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
index 17397b0076b..f6c832957fb 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
@@ -302,6 +302,16 @@ def test_agent_app_write_routes_do_not_reuse_app_billing_quota() -> None:
assert '@cloud_edition_billing_resource_check("apps")' not in getsource(route_class)
+def test_agent_list_reads_do_not_require_workspace_preview() -> None:
+ for route_class in (AgentAppListApi, AgentInviteOptionsApi):
+ assert "RBACPermission.AGENT_PREVIEW, Workspace()" not in getsource(route_class.get)
+
+
+def test_agent_app_permission_keys_are_required_response_fields() -> None:
+ assert roster_controller.AgentAppPartial.model_fields["permission_keys"].is_required()
+ assert roster_controller.AgentAppDetailWithSite.model_fields["permission_keys"].is_required()
+
+
@pytest.fixture
def account_id() -> str:
return "account-1"
@@ -311,6 +321,33 @@ def test_agent_app_list_and_create_use_agent_route(
app: Flask, monkeypatch: pytest.MonkeyPatch, account_id: str, sqlite_session: Session
) -> None:
captured: dict[str, object] = {}
+ permissions = roster_controller.enterprise_rbac_service.MyPermissionsResponse(
+ agent=roster_controller.enterprise_rbac_service.ResourcePermissionSnapshot(
+ overrides=[
+ roster_controller.enterprise_rbac_service.ResourcePermissionKeys(
+ resource_id="agent-list",
+ permission_keys=["agent.acl.preview"],
+ )
+ ]
+ )
+ )
+
+ class FakeAgentAccessFilter:
+ def apply_to_app_params(self, params, *, tenant_id: str, session: object) -> None:
+ captured["access_filter"] = {"tenant_id": tenant_id, "session": session}
+ params.accessible_app_ids = ["app-list"]
+
+ monkeypatch.setattr(
+ roster_controller.enterprise_rbac_service.RBACService.MyPermissions,
+ "get",
+ lambda *_args, **_kwargs: permissions,
+ )
+ monkeypatch.setattr(
+ roster_controller,
+ "resolve_agent_access_filter",
+ lambda *_args, **_kwargs: FakeAgentAccessFilter(),
+ )
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
class FakeAppService:
def get_app(self, app_obj: object, *, session: object) -> object:
@@ -427,6 +464,7 @@ def test_agent_app_list_and_create_use_agent_route(
assert listed["data"][0]["id"] == "agent-list"
assert listed["data"][0]["app_id"] == "app-list"
assert listed["data"][0]["debug_conversation_id"] == "debug-conversation-list"
+ assert listed["data"][0]["permission_keys"] == ["agent.acl.preview"]
assert listed["data"][0]["role"] == "List role"
assert listed["data"][0]["active_config_is_published"] is False
assert listed["data"][0]["reference_count"] == 2
@@ -448,6 +486,8 @@ def test_agent_app_list_and_create_use_agent_route(
assert list_params.is_created_by_me is True
assert list_params.agent_is_published is True
assert list_params.status == "normal"
+ assert list_params.accessible_app_ids == ["app-list"]
+ assert captured["access_filter"] == {"tenant_id": "tenant-1", "session": sqlite_session}
count_call = cast(dict[str, object], captured["counts"])
count_params = cast(Any, count_call["params"])
assert count_params.agent_is_published is True
@@ -574,6 +614,15 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(
"agent_has_workflow_callable_active_snapshot",
lambda **_kwargs: False,
)
+ monkeypatch.setattr(
+ roster_controller.enterprise_rbac_service.RBACService.MyPermissions,
+ "get",
+ lambda *_args, **_kwargs: roster_controller.enterprise_rbac_service.MyPermissionsResponse(
+ agent=roster_controller.enterprise_rbac_service.ResourcePermissionSnapshot(
+ default_permission_keys=["agent.acl.preview"]
+ )
+ ),
+ )
class FakeAppService:
def get_app(self, app_obj: object, *, session: object) -> object:
@@ -597,6 +646,7 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(
assert detail["debug_conversation_has_messages"] is True
assert detail["debug_conversation_message_count"] == 2
assert detail["role"] == "Resolved role"
+ assert detail["permission_keys"] == ["agent.acl.preview"]
assert detail["access_ready"] is False
assert "active_config_is_published" not in detail
assert "bound_agent_id" not in detail
@@ -1066,10 +1116,59 @@ def test_invite_options_get_parses_app_id(app: Flask, monkeypatch: pytest.Monkey
monkeypatch.setattr(roster_controller.AgentRosterService, "list_invite_options", list_invite_options)
with app.test_request_context("/console/api/agent/invite-options?page=1&limit=10&app_id=app-1"):
result = unwrap(AgentInviteOptionsApi.get)(
- AgentInviteOptionsApi(), AgentInviteOptionsQuery(page=1, limit=10, app_id="app-1"), MagicMock(), "tenant-1"
+ AgentInviteOptionsApi(),
+ AgentInviteOptionsQuery(page=1, limit=10, app_id="app-1"),
+ MagicMock(),
+ "tenant-1",
+ _account(),
)
assert result == {"data": [], "page": 1, "limit": 10, "total": 0, "has_more": False}
- assert captured == {"tenant_id": "tenant-1", "page": 1, "limit": 10, "keyword": None, "app_id": "app-1"}
+ assert captured == {
+ "tenant_id": "tenant-1",
+ "page": 1,
+ "limit": 10,
+ "keyword": None,
+ "app_id": "app-1",
+ "accessible_agent_ids": None,
+ }
+
+
+def test_invite_options_get_applies_resource_visibility(
+ app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+ permissions = roster_controller.enterprise_rbac_service.MyPermissionsResponse()
+
+ monkeypatch.setattr(
+ roster_controller.enterprise_rbac_service.RBACService.MyPermissions,
+ "get",
+ lambda *_args, **_kwargs: permissions,
+ )
+ monkeypatch.setattr(
+ roster_controller,
+ "resolve_agent_access_filter",
+ lambda *_args, **_kwargs: SimpleNamespace(accessible_agent_ids={"agent-2", "agent-1"}),
+ )
+ monkeypatch.setattr(
+ roster_controller.AgentRosterService,
+ "list_invite_options",
+ lambda _self, **kwargs: (
+ captured.update(kwargs) or {"data": [], "page": 1, "limit": 10, "total": 0, "has_more": False}
+ ),
+ )
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
+
+ with app.test_request_context("/console/api/agent/invite-options?page=1&limit=10"):
+ unwrap(AgentInviteOptionsApi.get)(
+ AgentInviteOptionsApi(),
+ AgentInviteOptionsQuery(page=1, limit=10),
+ MagicMock(),
+ "tenant-1",
+ _account(),
+ )
+
+ assert captured["accessible_agent_ids"] == ["agent-1", "agent-2"]
def test_agent_versions_call_services(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/api/tests/unit_tests/controllers/test_rbac_access_policy_schema.py b/api/tests/unit_tests/controllers/test_rbac_access_policy_schema.py
new file mode 100644
index 00000000000..5bde17c71e7
--- /dev/null
+++ b/api/tests/unit_tests/controllers/test_rbac_access_policy_schema.py
@@ -0,0 +1,47 @@
+"""Access-policy writes must expose typed bodies through the RBAC decorators."""
+
+import json
+from typing import cast
+
+import pytest
+
+
+def _object_at(root: dict[str, object], *keys: str) -> dict[str, object]:
+ current: object = root
+ for key in keys:
+ assert isinstance(current, dict)
+ current = current[key]
+ assert isinstance(current, dict)
+ return cast(dict[str, object], current)
+
+
[email protected](scope="module")
+def console_schema(tmp_path_factory: pytest.TempPathFactory) -> dict[str, object]:
+ from dev.generate_swagger_specs import generate_specs
+
+ output_dir = tmp_path_factory.mktemp("rbac-openapi")
+ generate_specs(output_dir)
+ schema: object = json.loads((output_dir / "console-openapi.json").read_text())
+ assert isinstance(schema, dict)
+ return cast(dict[str, object], schema)
+
+
+ ("method", "path", "model", "status"),
+ [
+ ("post", "/workspaces/current/rbac/access-policies", "_AccessPolicyCreateRequest", "201"),
+ ("put", "/workspaces/current/rbac/access-policies/{policy_id}", "_AccessPolicyUpdateRequest", "200"),
+ ],
+)
+def test_access_policy_write_contracts(
+ console_schema: dict[str, object], method: str, path: str, model: str, status: str
+) -> None:
+ operation = _object_at(console_schema, "paths", path, method)
+ request_body = _object_at(operation, "requestBody", "content", "application/json", "schema")
+ assert request_body["$ref"] == f"#/components/schemas/{model}"
+
+ properties = _object_at(console_schema, "components", "schemas", model, "properties")
+ assert {"name", "description", "permission_keys"} <= properties.keys()
+ assert _object_at(properties, "permission_keys", "items")["type"] == "string"
+ response = _object_at(operation, "responses", status, "content", "application/json", "schema")
+ assert response["$ref"] == "#/components/schemas/AccessPolicy"
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 7916faa27cd..32b771f1555 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -2721,14 +2721,6 @@
"count": 2
}
},
- "web/app/components/header/account-setting/permission-group-list.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/header/github-star/index.tsx": {
"@tanstack/query/prefer-query-options": {
"count": 1
@@ -5457,14 +5449,6 @@
"count": 1
}
},
- "web/service/access-control/use-workspace-access-rules.ts": {
- "@tanstack/query/prefer-query-options": {
- "count": 2
- },
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/service/access-control/use-workspace-roles.ts": {
"@tanstack/query/prefer-query-options": {
"count": 6
diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.ts
index 7b9014a58e5..83680198b6b 100644
--- a/packages/contracts/generated/api/console/agent/types.gen.ts
+++ b/packages/contracts/generated/api/console/agent/types.gen.ts
@@ -49,7 +49,7 @@ export type AgentAppDetailWithSite = {
mode: string
model_config?: AppModelConfigResponse | null
name: string
- permission_keys?: Array<string>
+ permission_keys: Array<string>
role?: string | null
site?: AppDetailSiteResponse | null
tags?: Array<Tag>
@@ -457,7 +457,7 @@ export type AgentAppPartial = {
mode: string
model_config?: ModelConfigPartial | null
name: string
- permission_keys?: Array<string>
+ permission_keys: Array<string>
published_reference_count?: number
published_references?: Array<AgentAppPublishedReferenceResponse>
reference_count?: number | null
@@ -1770,7 +1770,7 @@ export type AgentAppDetailWithSiteWritable = {
mode: string
model_config?: AppModelConfigResponse | null
name: string
- permission_keys?: Array<string>
+ permission_keys: Array<string>
role?: string | null
site?: AppDetailSiteResponseWritable | null
tags?: Array<Tag>
@@ -1805,7 +1805,7 @@ export type AgentAppPartialWritable = {
mode: string
model_config?: ModelConfigPartial | null
name: string
- permission_keys?: Array<string>
+ permission_keys: Array<string>
published_reference_count?: number
published_references?: Array<AgentAppPublishedReferenceResponse>
reference_count?: number | null
diff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.ts
index 77c929cd007..87f89cb82ac 100644
--- a/packages/contracts/generated/api/console/agent/zod.gen.ts
+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts
@@ -376,7 +376,7 @@ export const zAgentAppDetailWithSite = z.object({
mode: z.string(),
model_config: zAppModelConfigResponse.nullish(),
name: z.string(),
- permission_keys: z.array(z.string()).optional(),
+ permission_keys: z.array(z.string()),
role: z.string().nullish(),
site: zAppDetailSiteResponse.nullish(),
tags: z.array(zTag).optional(),
@@ -860,7 +860,7 @@ export const zAgentAppPartial = z.object({
mode: z.string(),
model_config: zModelConfigPartial.nullish(),
name: z.string(),
- permission_keys: z.array(z.string()).optional(),
+ permission_keys: z.array(z.string()),
published_reference_count: z.int().optional().default(0),
published_references: z.array(zAgentAppPublishedReferenceResponse).optional(),
reference_count: z.int().nullish(),
@@ -2483,7 +2483,7 @@ export const zAgentAppPartialWritable = z.object({
mode: z.string(),
model_config: zModelConfigPartial.nullish(),
name: z.string(),
- permission_keys: z.array(z.string()).optional(),
+ permission_keys: z.array(z.string()),
published_reference_count: z.int().optional().default(0),
published_references: z.array(zAgentAppPublishedReferenceResponse).optional(),
reference_count: z.int().nullish(),
@@ -2566,7 +2566,7 @@ export const zAgentAppDetailWithSiteWritable = z.object({
mode: z.string(),
model_config: zAppModelConfigResponse.nullish(),
name: z.string(),
- permission_keys: z.array(z.string()).optional(),
+ permission_keys: z.array(z.string()),
role: z.string().nullish(),
site: zAppDetailSiteResponseWritable.nullish(),
tags: z.array(zTag).optional(),
diff --git a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
index 0ff9cd3c520..eeadc47516e 100644
--- a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
@@ -377,6 +377,7 @@ import {
zPostWorkspacesCurrentPluginUploadGithubResponse,
zPostWorkspacesCurrentPluginUploadPkgBody,
zPostWorkspacesCurrentPluginUploadPkgResponse,
+ zPostWorkspacesCurrentRbacAccessPoliciesBody,
zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyPath,
zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse,
zPostWorkspacesCurrentRbacAccessPoliciesResponse,
@@ -480,6 +481,7 @@ import {
zPutWorkspacesCurrentModelProvidersByProviderModelsCredentialsBody,
zPutWorkspacesCurrentModelProvidersByProviderModelsCredentialsPath,
zPutWorkspacesCurrentModelProvidersByProviderModelsCredentialsResponse,
+ zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdBody,
zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath,
zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse,
zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockPath,
@@ -2348,7 +2350,12 @@ export const put5 = oc
path: '/workspaces/current/rbac/access-policies/{policy_id}',
tags: ['console'],
})
- .input(z.object({ params: zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath }))
+ .input(
+ z.object({
+ body: zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdBody,
+ params: zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath,
+ }),
+ )
.output(zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse)
export const byPolicyId = {
@@ -2374,8 +2381,10 @@ export const post45 = oc
method: 'POST',
operationId: 'postWorkspacesCurrentRbacAccessPolicies',
path: '/workspaces/current/rbac/access-policies',
+ successStatus: 201,
tags: ['console'],
})
+ .input(z.object({ body: zPostWorkspacesCurrentRbacAccessPoliciesBody }))
.output(zPostWorkspacesCurrentRbacAccessPoliciesResponse)
export const accessPolicies = {
diff --git a/packages/contracts/generated/api/console/workspaces/types.gen.ts b/packages/contracts/generated/api/console/workspaces/types.gen.ts
index 4b3373e7bf1..dabaaf28a73 100644
--- a/packages/contracts/generated/api/console/workspaces/types.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/types.gen.ts
@@ -527,6 +527,33 @@ export type PluginCategoryListResponse = {
plugins: Array<PluginCategoryInstalledPluginResponse>
}
+export type AccessPolicyCreateRequest = {
+ description?: string
+ name: string
+ permission_keys?: Array<string>
+ resource_type: RbacResourceType
+}
+
+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 AccessPolicyUpdateRequest = {
+ description?: string
+ name: string
+ permission_keys?: Array<string>
+}
+
export type DeleteMemberBindingsRequest = {
account_ids?: Array<string>
}
@@ -1655,6 +1682,8 @@ export type PluginCategoryInstalledPluginResponse = {
version: string
}
+export type RbacResourceType = 'agent' | 'app' | 'dataset'
+
export type AccessPolicyMemberBinding = {
access_policy_id: string
account_id: string
@@ -1690,20 +1719,6 @@ export type Pagination = {
total_pages?: number
}
-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 RbacRole = {
category?: string
description?: string
@@ -4372,16 +4387,14 @@ export type GetWorkspacesCurrentRbacAccessPoliciesResponse =
GetWorkspacesCurrentRbacAccessPoliciesResponses[keyof GetWorkspacesCurrentRbacAccessPoliciesResponses]
export type PostWorkspacesCurrentRbacAccessPoliciesData = {
- body?: never
+ body: AccessPolicyCreateRequest
path?: never
query?: never
url: '/workspaces/current/rbac/access-policies'
}
export type PostWorkspacesCurrentRbacAccessPoliciesResponses = {
- 200: {
- [key: string]: unknown
- }
+ 201: AccessPolicy
}
export type PostWorkspacesCurrentRbacAccessPoliciesResponse =
@@ -4424,7 +4437,7 @@ export type GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse =
GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses[keyof GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses]
export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = {
- body?: never
+ body: AccessPolicyUpdateRequest
path: {
policy_id: string
}
@@ -4433,9 +4446,7 @@ export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = {
}
export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses = {
- 200: {
- [key: string]: unknown
- }
+ 200: AccessPolicy
}
export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse =
diff --git a/packages/contracts/generated/api/console/workspaces/zod.gen.ts b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
index efec8abd342..2b3115878af 100644
--- a/packages/contracts/generated/api/console/workspaces/zod.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
@@ -373,6 +373,32 @@ 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),
+})
+
+/**
+ * _AccessPolicyUpdateRequest
+ */
+export const zAccessPolicyUpdateRequest = z.object({
+ description: z.string().optional().default(''),
+ name: z.string(),
+ permission_keys: z.array(z.string()).optional().default([]),
+})
+
/**
* _DeleteMemberBindingsRequest
*/
@@ -388,6 +414,13 @@ export const zReplaceUserAccessPolicies = z.object({
account_ids: z.array(z.string()).optional(),
})
+/**
+ * ReplaceUserAccessPoliciesResponse
+ */
+export const zReplaceUserAccessPoliciesResponse = z.object({
+ access_policies: z.array(zAccessPolicy).optional(),
+})
+
/**
* ResourceWhitelist
*/
@@ -1201,6 +1234,23 @@ export const zPluginPermissionResponse = z.object({
install_permission: zTenantPluginInstallPermission,
})
+/**
+ * RBACResourceType
+ *
+ * Resource types understood by access policies.
+ */
+export const zRbacResourceType = z.enum(['agent', 'app', 'dataset'])
+
+/**
+ * _AccessPolicyCreateRequest
+ */
+export const zAccessPolicyCreateRequest = z.object({
+ description: z.string().optional().default(''),
+ name: z.string(),
+ permission_keys: z.array(z.string()).optional().default([]),
+ resource_type: zRbacResourceType,
+})
+
/**
* AccessPolicyMemberBinding
*/
@@ -1253,30 +1303,6 @@ export const zPagination = z.object({
total_pages: z.int().optional().default(0),
})
-/**
- * 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),
-})
-
-/**
- * ReplaceUserAccessPoliciesResponse
- */
-export const zReplaceUserAccessPoliciesResponse = z.object({
- access_policies: z.array(zAccessPolicy).optional(),
-})
-
/**
* RBACRole
*/
@@ -4830,10 +4856,12 @@ export const zGetWorkspacesCurrentPluginByCategoryListResponse = zPluginCategory
*/
export const zGetWorkspacesCurrentRbacAccessPoliciesResponse = z.record(z.string(), z.unknown())
+export const zPostWorkspacesCurrentRbacAccessPoliciesBody = zAccessPolicyCreateRequest
+
/**
- * Success
+ * Policy created
*/
-export const zPostWorkspacesCurrentRbacAccessPoliciesResponse = z.record(z.string(), z.unknown())
+export const zPostWorkspacesCurrentRbacAccessPoliciesResponse = zAccessPolicy
export const zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({
policy_id: z.uuid(),
@@ -4859,6 +4887,8 @@ export const zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = z.recor
z.unknown(),
)
+export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdBody = zAccessPolicyUpdateRequest
+
export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({
policy_id: z.uuid(),
})
@@ -4866,10 +4896,7 @@ export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({
/**
* Success
*/
-export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = z.record(
- z.string(),
- z.unknown(),
-)
+export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = zAccessPolicy
export const zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyPath = z.object({
policy_id: z.uuid(),
diff --git a/web/app/(commonLayout)/agents/[agentId]/access-config/page.tsx b/web/app/(commonLayout)/agents/[agentId]/access-config/page.tsx
new file mode 100644
index 00000000000..0660a85d852
--- /dev/null
+++ b/web/app/(commonLayout)/agents/[agentId]/access-config/page.tsx
@@ -0,0 +1,6 @@
+import { AgentDetailPage } from '@/features/agent-v2/agent-detail/page'
+
+export default async function Page({ params }: { params: Promise<{ agentId: string }> }) {
+ const { agentId } = await params
+ return <AgentDetailPage agentId={agentId} section="access-config" />
+}
diff --git a/web/app/(commonLayout)/agents/__tests__/agents-access-guard.spec.tsx b/web/app/(commonLayout)/agents/__tests__/agents-access-guard.spec.tsx
deleted file mode 100644
index b7c4d8507d5..00000000000
--- a/web/app/(commonLayout)/agents/__tests__/agents-access-guard.spec.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { screen, waitFor } from '@testing-library/react'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { render } from '@/test/console/render'
-import { AgentsAccessGuard } from '../agents-access-guard'
-
-const mockReplace = vi.fn()
-const mockConsoleStateReader = vi.fn()
-
-vi.mock('@/next/navigation', () => ({
- useRouter: () => ({
- replace: mockReplace,
- }),
-}))
-
-vi.mock('@/context/workspace-state', async () => {
- const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
-
- return createWorkspaceStateModuleMock(() => mockConsoleStateReader())
-})
-vi.mock('@/context/permission-state', async () => {
- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
-
- return createPermissionStateModuleMock(() => mockConsoleStateReader())
-})
-vi.mock('@/features/agent-v2/permissions', () => {
- return {
- useCanManageAgents: () =>
- mockConsoleStateReader().workspacePermissionKeys.includes('agent.acl.preview'),
- }
-})
-
-type ConsoleStateFixture = {
- isLoadingCurrentWorkspace: boolean
- isLoadingWorkspacePermissionKeys: boolean
- workspacePermissionKeys: string[]
- currentWorkspace: {
- id: string
- }
-}
-
-const baseContext: ConsoleStateFixture = {
- isLoadingCurrentWorkspace: false,
- isLoadingWorkspacePermissionKeys: false,
- workspacePermissionKeys: ['agent.acl.preview'],
- currentWorkspace: {
- id: 'workspace-1',
- },
-}
-
-const setConsoleState = (overrides: Partial<ConsoleStateFixture> = {}) => {
- mockConsoleStateReader.mockReturnValue({
- ...baseContext,
- ...overrides,
- })
-}
-
-describe('AgentsAccessGuard', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- setConsoleState()
- })
-
- it('renders loading while the workspace is loading', () => {
- setConsoleState({ isLoadingCurrentWorkspace: true, currentWorkspace: { id: '' } })
-
- render(
- <AgentsAccessGuard>
- <div>agents</div>
- </AgentsAccessGuard>,
- )
-
- expect(screen.getByRole('status')).toBeInTheDocument()
- expect(screen.queryByText('agents')).not.toBeInTheDocument()
- expect(mockReplace).not.toHaveBeenCalled()
- })
-
- it('renders loading while workspace permissions are loading', () => {
- setConsoleState({ isLoadingWorkspacePermissionKeys: true })
-
- render(
- <AgentsAccessGuard>
- <div>agents</div>
- </AgentsAccessGuard>,
- )
-
- expect(screen.getByRole('status')).toBeInTheDocument()
- expect(screen.queryByText('agents')).not.toBeInTheDocument()
- expect(mockReplace).not.toHaveBeenCalled()
- })
-
- it('redirects to /apps without agent.acl.preview', async () => {
- setConsoleState({ workspacePermissionKeys: ['dataset.create_and_management'] })
-
- render(
- <AgentsAccessGuard>
- <div>agents</div>
- </AgentsAccessGuard>,
- )
-
- expect(screen.queryByText('agents')).not.toBeInTheDocument()
- await waitFor(() => {
- expect(mockReplace).toHaveBeenCalledWith('/')
- })
- })
-
- it('renders children with agent.acl.preview', () => {
- render(
- <AgentsAccessGuard>
- <div>agents</div>
- </AgentsAccessGuard>,
- )
-
- expect(screen.getByText('agents')).toBeInTheDocument()
- expect(mockReplace).not.toHaveBeenCalled()
- })
-})
diff --git a/web/app/(commonLayout)/agents/__tests__/layout.spec.tsx b/web/app/(commonLayout)/agents/__tests__/layout.spec.tsx
index edb7035db74..6746cc82f70 100644
--- a/web/app/(commonLayout)/agents/__tests__/layout.spec.tsx
+++ b/web/app/(commonLayout)/agents/__tests__/layout.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import type { Dependency } from '@/app/components/plugins/types'
import { render, screen } from '@testing-library/react'
import { useStore as usePluginDependencyStore } from '@/app/components/workflow/plugin-dependency/store'
@@ -19,12 +18,6 @@ vi.mock('../feature-guard', () => ({
guardAgentV2Route: () => mocks.guardAgentV2Route(),
}))
-// Access control is covered by agents-access-guard.spec.tsx; this suite is
-// about the feature-flag guard only.
-vi.mock('../agents-access-guard', () => ({
- AgentsAccessGuard: ({ children }: { children: ReactNode }) => <>{children}</>,
-}))
-
describe('RosterLayout', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/web/app/(commonLayout)/agents/agents-access-guard.tsx b/web/app/(commonLayout)/agents/agents-access-guard.tsx
deleted file mode 100644
index 2b0002df750..00000000000
--- a/web/app/(commonLayout)/agents/agents-access-guard.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-'use client'
-
-import type { ReactNode } from 'react'
-import { useAtomValue } from 'jotai'
-import { useEffect } from 'react'
-import Loading from '@/app/components/base/loading'
-import { workspacePermissionKeysLoadingAtom } from '@/context/permission-state'
-import { currentWorkspaceIdAtom, currentWorkspaceLoadingAtom } from '@/context/workspace-state'
-import { useCanManageAgents } from '@/features/agent-v2/permissions'
-import { useRouter } from '@/next/navigation'
-
-export function AgentsAccessGuard({ children }: { children: ReactNode }) {
- const currentWorkspaceId = useAtomValue(currentWorkspaceIdAtom)
- const isLoadingCurrentWorkspace = useAtomValue(currentWorkspaceLoadingAtom)
- const isLoadingWorkspacePermissionKeys = useAtomValue(workspacePermissionKeysLoadingAtom)
- const canManageAgents = useCanManageAgents()
- const router = useRouter()
- const isLoadingAccess = isLoadingCurrentWorkspace || isLoadingWorkspacePermissionKeys
- const shouldRedirect = !isLoadingAccess && !!currentWorkspaceId && !canManageAgents
-
- useEffect(() => {
- if (shouldRedirect) router.replace('/')
- }, [shouldRedirect, router])
-
- if (isLoadingAccess || !currentWorkspaceId) return <Loading type="app" />
-
- if (shouldRedirect) return null
-
- return children
-}
diff --git a/web/app/(commonLayout)/agents/layout.tsx b/web/app/(commonLayout)/agents/layout.tsx
index ec47488a564..b65ce3ffa0c 100644
--- a/web/app/(commonLayout)/agents/layout.tsx
+++ b/web/app/(commonLayout)/agents/layout.tsx
@@ -1,15 +1,14 @@
import type { ReactNode } from 'react'
import PluginDependency from '@/app/components/workflow/plugin-dependency'
-import { AgentsAccessGuard } from './agents-access-guard'
import { guardAgentV2Route } from './feature-guard'
export default function Layout({ children }: { children: ReactNode }) {
guardAgentV2Route()
return (
- <AgentsAccessGuard>
+ <>
<PluginDependency />
{children}
- </AgentsAccessGuard>
+ </>
)
}
diff --git a/web/app/components/access-rules-editor/__tests__/index.spec.tsx b/web/app/components/access-rules-editor/__tests__/index.spec.tsx
index d13d09a3332..4a6b498ece5 100644
--- a/web/app/components/access-rules-editor/__tests__/index.spec.tsx
+++ b/web/app/components/access-rules-editor/__tests__/index.spec.tsx
@@ -8,10 +8,11 @@ const mockMembers = vi.hoisted(() => ({
accounts: [] as Member[] | null,
isLoading: false,
}))
-const mockUseMembers = vi.hoisted(() => vi.fn())
+const mockMembersQuery = vi.hoisted(() => vi.fn())
-vi.mock('@/service/use-common', () => ({
- useMembers: mockUseMembers,
+vi.mock('@tanstack/react-query', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@tanstack/react-query')>()),
+ useQuery: mockMembersQuery,
}))
const createRule = (resourceType: 'app' | 'dataset'): AccessPolicyWithBindings => ({
@@ -89,9 +90,9 @@ describe('AccessRulesEditor', () => {
vi.clearAllMocks()
mockMembers.accounts = []
mockMembers.isLoading = false
- mockUseMembers.mockImplementation(() => ({
+ mockMembersQuery.mockImplementation(() => ({
data: { accounts: mockMembers.accounts },
- isLoading: mockMembers.isLoading,
+ isPending: mockMembers.isLoading,
}))
})
@@ -433,9 +434,9 @@ describe('AccessRulesEditor', () => {
/>,
)
- expect(mockUseMembers).not.toHaveBeenCalled()
+ expect(mockMembersQuery).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
- expect(mockUseMembers).toHaveBeenCalledTimes(1)
+ expect(mockMembersQuery).toHaveBeenCalledTimes(1)
const dialog = await screen.findByRole('dialog', {
name: 'permission.accessRule.addMembersTitle',
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.tsx
index b024cf7eb1e..3175f1fd500 100644
--- a/web/app/components/access-rules-editor/add-access-subject-popover.tsx
+++ b/web/app/components/access-rules-editor/add-access-subject-popover.tsx
@@ -1,15 +1,15 @@
'use client'
-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 { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'
+import { useQuery } from '@tanstack/react-query'
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 { consoleQuery } from '@/service/console'
import { DEFAULT_ACCESS_POLICY_ID } from './constants'
type AddAccessSubjectPopoverProps = {
@@ -32,7 +32,12 @@ function AddAccessSubjectPopoverContent({
}: AddAccessSubjectPopoverContentProps) {
const { t } = useTranslation()
const [searchValue, setSearchValue] = useState('')
- const { data: membersData, isLoading } = useMembers()
+ const {
+ data: membersData,
+ isPending: isLoading,
+ error,
+ refetch,
+ } = useQuery(consoleQuery.workspaces.current.members.get.queryOptions())
const existingAccountIdSet = useMemo(() => new Set(existingAccountIds), [existingAccountIds])
const availableMembers = useMemo(() => {
const normalizedSearchValue = searchValue.trim().toLowerCase()
@@ -49,13 +54,6 @@ function AddAccessSubjectPopoverContent({
})
}, [membersData?.accounts, searchValue])
- const handleAddMember = useCallback(
- (member: Member) => {
- onAddAccessSubject(member.id, [DEFAULT_ACCESS_POLICY_ID])
- },
- [onAddAccessSubject],
- )
-
const addLabel = t(($) => $['operation.add'], { ns: 'common' })
const addMembersTitle = t(($) => $['accessRule.addMembersTitle'], { ns: 'permission' })
const addedLabel = t(($) => $['operation.added'], { ns: 'common' })
@@ -87,7 +85,14 @@ function AddAccessSubjectPopoverContent({
</InputGroupAddon>
</InputGroup>
</div>
- {isLoading ? (
+ {error ? (
+ <div role="alert" className="flex items-center justify-center gap-2 p-3">
+ <span>{t(($) => $['api.actionFailed'], { ns: 'common' })}</span>
+ <Button onClick={() => void refetch()}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ </div>
+ ) : isLoading ? (
<div className="flex h-20 items-center justify-center p-1">
<Loading type="app" />
</div>
@@ -143,7 +148,7 @@ function AddAccessSubjectPopoverContent({
'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)}
+ onClick={() => onAddAccessSubject(member.id, [DEFAULT_ACCESS_POLICY_ID])}
>
{isUpdating ? (
<span className="i-ri-loader-2-line size-3.5 animate-spin" aria-hidden />
diff --git a/web/app/components/access-rules-editor/index.tsx b/web/app/components/access-rules-editor/index.tsx
index 39a72eb2d15..1810c04da43 100644
--- a/web/app/components/access-rules-editor/index.tsx
+++ b/web/app/components/access-rules-editor/index.tsx
@@ -1,6 +1,9 @@
'use client'
-import type { AccessPolicyWithBindings, ResourceUserAccessSetting } from '@/models/access-control'
+import type {
+ AccessPolicy,
+ ResourceUserAccessPolicies,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { cn } from '@langgenius/dify-ui/cn'
@@ -21,8 +24,8 @@ export type AccessPolicyMemberBindingRemoval = {
}
export type AccessRulesEditorProps = {
- rules: AccessPolicyWithBindings[]
- userAccessSettings: ResourceUserAccessSetting[]
+ rules: { policy?: Pick<AccessPolicy, 'id' | 'name'> | null }[]
+ userAccessSettings: ResourceUserAccessPolicies[]
isLoadingRules: boolean
isLoadingUserAccessSettings: boolean
automaticIncludeWorkspaceMembers?: boolean
@@ -77,17 +80,23 @@ function AccessRulesEditor({
const shouldCenterTableBody = isLoading || userAccessSettings.length === 0
const areMembershipChangesDisabled = automaticIncludeWorkspaceMembers === true
const policyOptions = useMemo(() => {
- return rules.map((rule) => ({
- id: rule.policy.id,
- name: rule.policy.name,
- }))
+ return rules.flatMap((rule) =>
+ rule.policy
+ ? [
+ {
+ id: rule.policy.id,
+ name: rule.policy.name,
+ },
+ ]
+ : [],
+ )
}, [rules])
const protectedAccountIds = useMemo(() => {
const accountIds = new Set<string>()
for (const setting of userAccessSettings) {
const accountId = setting.account.account_id
- const isWorkspaceOwner = setting.roles.some((role) => role.role_tag === 'owner')
+ const isWorkspaceOwner = setting.roles?.some((role) => role.role_tag === 'owner')
if (accountId === maintainerId || isWorkspaceOwner) accountIds.add(accountId)
}
@@ -119,7 +128,7 @@ function AccessRulesEditor({
const accountId = setting.account.account_id
if (!selectedAccountIds.has(accountId) || protectedAccountIds.has(accountId)) continue
- const accessPolicyId = setting.access_policies[0]?.id ?? DEFAULT_ACCESS_POLICY_ID
+ const accessPolicyId = setting.access_policies?.[0]?.id ?? DEFAULT_ACCESS_POLICY_ID
const accountIds = accountIdsByAccessPolicyId.get(accessPolicyId)
if (accountIds) accountIds.push(accountId)
else accountIdsByAccessPolicyId.set(accessPolicyId, [accountId])
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.tsx
index 75b2ee7c70b..8db26ca5603 100644
--- a/web/app/components/access-rules-editor/user-access-policy-row.tsx
+++ b/web/app/components/access-rules-editor/user-access-policy-row.tsx
@@ -1,6 +1,6 @@
'use client'
-import type { ResourceUserAccessSetting } from '@/models/access-control'
+import type { ResourceUserAccessPolicies } from '@dify/contracts/api/console/workspaces/types.gen'
import { Avatar } from '@langgenius/dify-ui/avatar'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { cn } from '@langgenius/dify-ui/cn'
@@ -23,7 +23,7 @@ type PolicyOption = {
}
type UserAccessPolicyRowProps = {
- setting: ResourceUserAccessSetting
+ setting: ResourceUserAccessPolicies
policyOptions: PolicyOption[]
disabled: boolean
membershipChangesDisabled?: boolean
@@ -53,15 +53,16 @@ function UserAccessPolicyRow({
}: UserAccessPolicyRowProps) {
const { t } = useTranslation()
const accountId = setting.account.account_id
- const selectedPolicy = setting.access_policies[0]
+ const accountName = setting.account.account_name || setting.account.email || accountId
+ const selectedPolicy = setting.access_policies?.[0]
const selectedPolicyId = selectedPolicy?.id ?? DEFAULT_ACCESS_POLICY_ID
const isPolicySelectDisabled = disabled || isProtected || !onChange
const isRemoveDisabled = disabled || membershipChangesDisabled || isProtected || !onRemove
const isSelectionDisabled =
disabled || membershipChangesDisabled || selectionDisabled || isProtected || !onSelectedChange
const defaultAccessPolicyName = t(($) => $['accessRule.defaultPermission'], { ns: 'permission' })
- const accountEmail = setting.account.email || setting.account.account_name
- const isWorkspaceOwner = setting.roles.some((role) => role.role_tag === 'owner')
+ const accountEmail = setting.account.email || accountName
+ const isWorkspaceOwner = setting.roles?.some((role) => role.role_tag === 'owner')
const handlePolicyChange = useCallback(
(nextPolicyId: string | null) => {
@@ -82,22 +83,20 @@ function UserAccessPolicyRow({
<tr className={cn('grid min-h-19 items-center gap-4 py-4', ACCESS_RULE_TABLE_GRID, className)}>
<td className="flex min-w-0 items-center gap-3">
<Checkbox
- aria-label={setting.account.account_name}
+ aria-label={accountName}
checked={selected}
disabled={isSelectionDisabled}
onCheckedChange={(checked) => onSelectedChange?.(accountId, checked)}
/>
<Avatar
avatar={setting.account.avatar ?? null}
- name={setting.account.account_name}
+ name={accountName}
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>
+ <span className="truncate system-md-medium text-text-secondary">{accountName}</span>
{isMaintainer && (
<span className="max-w-32 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' })}
@@ -117,7 +116,7 @@ function UserAccessPolicyRow({
<SelectTrigger
aria-label={t(($) => $['accessRule.exceptionPermissionFor'], {
ns: 'permission',
- name: setting.account.account_name,
+ name: accountName,
})}
size="small"
disabled={isPolicySelectDisabled}
@@ -126,7 +125,7 @@ function UserAccessPolicyRow({
<SelectValue>
{selectedPolicyId === DEFAULT_ACCESS_POLICY_ID
? defaultAccessPolicyName
- : setting.access_policies[0]?.name}
+ : selectedPolicy?.name}
</SelectValue>
</SelectTrigger>
<SelectContent>
diff --git a/web/app/components/app/create-app-dropdown.tsx b/web/app/components/app/create-app-dropdown.tsx
index 9d7290674bc..ee8d6301e30 100644
--- a/web/app/components/app/create-app-dropdown.tsx
+++ b/web/app/components/app/create-app-dropdown.tsx
@@ -15,9 +15,9 @@ import {
} from '@/app/components/step-by-step-tour/dropdown-menu'
type CreateAppDropdownProps = {
- onCreateBlank: () => void
+ onCreateBlank?: () => void
onCreateTemplate?: () => void
- onImportDSL: () => void
+ onImportDSL?: () => void
stepByStepTourControlledOpen?: boolean
stepByStepTourTarget?: string
stepByStepTourHighlightPart?: string
@@ -62,56 +62,64 @@ export function CreateAppDropdown({
className: 'w-70 p-0',
})}
>
- <div className="py-1">
- <DropdownMenuItem
- className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"
- onClick={onCreateBlank}
- >
- <span
- aria-hidden
- className="i-ri-sticky-note-add-line size-4 shrink-0 text-text-secondary"
- />
- <span className="min-w-0 flex-1 truncate px-1">
- {t(($) => $['newApp.startFromBlank'], { ns: 'app' })}
- </span>
- </DropdownMenuItem>
- {onCreateTemplate && (
+ {(onCreateBlank || onCreateTemplate) && (
+ <div className="py-1">
+ {onCreateBlank && (
+ <DropdownMenuItem
+ className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"
+ onClick={onCreateBlank}
+ >
+ <span
+ aria-hidden
+ className="i-ri-sticky-note-add-line size-4 shrink-0 text-text-secondary"
+ />
+ <span className="min-w-0 flex-1 truncate px-1">
+ {t(($) => $['newApp.startFromBlank'], { ns: 'app' })}
+ </span>
+ </DropdownMenuItem>
+ )}
+ {onCreateTemplate && (
+ <DropdownMenuItem
+ className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"
+ onClick={onCreateTemplate}
+ >
+ <span
+ aria-hidden
+ className="i-ri-apps-2-add-line size-4 shrink-0 text-text-secondary"
+ />
+ <span className="min-w-0 flex-1 truncate px-1">
+ {t(($) => $['newApp.startFromTemplate'], { ns: 'app' })}
+ </span>
+ </DropdownMenuItem>
+ )}
+ </div>
+ )}
+ {onImportDSL && (onCreateBlank || onCreateTemplate) && (
+ <div className="h-px bg-divider-subtle" />
+ )}
+ {onImportDSL && (
+ <div className="py-1">
<DropdownMenuItem
- className="h-8 gap-1 rounded-lg px-2 py-1 system-md-regular text-text-secondary"
- onClick={onCreateTemplate}
+ className={cn(
+ 'h-auto items-start gap-1 rounded-lg px-2 py-1.5',
+ 'hover:bg-state-base-hover focus:bg-state-base-hover',
+ )}
+ onClick={onImportDSL}
>
- <span
- aria-hidden
- className="i-ri-apps-2-add-line size-4 shrink-0 text-text-secondary"
- />
- <span className="min-w-0 flex-1 truncate px-1">
- {t(($) => $['newApp.startFromTemplate'], { ns: 'app' })}
- </span>
- </DropdownMenuItem>
- )}
- </div>
- <div className="h-px bg-divider-subtle" />
- <div className="py-1">
- <DropdownMenuItem
- className={cn(
- 'h-auto items-start gap-1 rounded-lg px-2 py-1.5',
- 'hover:bg-state-base-hover focus:bg-state-base-hover',
- )}
- onClick={onImportDSL}
- >
- <span className="flex h-5 shrink-0 items-center py-0.5">
- <span aria-hidden className="i-ri-file-upload-line size-4 text-text-secondary" />
- </span>
- <span className="flex min-w-0 flex-1 flex-col justify-center gap-0.5 px-1">
- <span className="system-md-regular text-text-secondary">
- {t(($) => $.importDSL, { ns: 'app' })}
+ <span className="flex h-5 shrink-0 items-center py-0.5">
+ <span aria-hidden className="i-ri-file-upload-line size-4 text-text-secondary" />
</span>
- <span className="system-xs-regular text-text-tertiary">
- {t(($) => $['newApp.dropDSLToCreateApp'], { ns: 'app' })}
+ <span className="flex min-w-0 flex-1 flex-col justify-center gap-0.5 px-1">
+ <span className="system-md-regular text-text-secondary">
+ {t(($) => $.importDSL, { ns: 'app' })}
+ </span>
+ <span className="system-xs-regular text-text-tertiary">
+ {t(($) => $['newApp.dropDSLToCreateApp'], { ns: 'app' })}
+ </span>
</span>
- </span>
- </DropdownMenuItem>
- </div>
+ </DropdownMenuItem>
+ </div>
+ )}
</DropdownMenuContent>
</DropdownMenu>
)
diff --git a/web/app/components/goto-anything/__tests__/index.spec.tsx b/web/app/components/goto-anything/__tests__/index.spec.tsx
index 4cc4b3a0751..1cc2c2582e9 100644
--- a/web/app/components/goto-anything/__tests__/index.spec.tsx
+++ b/web/app/components/goto-anything/__tests__/index.spec.tsx
@@ -130,7 +130,6 @@ vi.mock('../actions/agent', () => ({
const visibilityState = vi.hoisted(() => ({
agentEnabled: true,
- canManageAgents: true,
datasetOperator: false,
enableSkill: true,
}))
@@ -147,10 +146,6 @@ vi.mock('@/features/agent-v2/feature-flag', () => ({
isAgentV2Enabled: () => visibilityState.agentEnabled,
}))
-vi.mock('@/features/agent-v2/permissions', () => ({
- useCanManageAgents: () => visibilityState.canManageAgents,
-}))
-
vi.mock(
'@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission',
() => ({
@@ -273,7 +268,6 @@ describe('GotoAnything', () => {
previousRemoteData = {}
matchActionMock.mockReset()
visibilityState.agentEnabled = true
- visibilityState.canManageAgents = true
visibilityState.datasetOperator = false
visibilityState.enableSkill = true
mockFindCommand = null
@@ -419,26 +413,10 @@ describe('GotoAnything', () => {
describe('search functionality', () => {
it.each([
- [
- { agentEnabled: true, canManageAgents: true, datasetOperator: false, enableSkill: true },
- true,
- true,
- ],
- [
- { agentEnabled: false, canManageAgents: true, datasetOperator: false, enableSkill: true },
- false,
- true,
- ],
- [
- { agentEnabled: true, canManageAgents: false, datasetOperator: true, enableSkill: true },
- false,
- false,
- ],
- [
- { agentEnabled: true, canManageAgents: true, datasetOperator: false, enableSkill: false },
- true,
- false,
- ],
+ [{ agentEnabled: true, datasetOperator: false, enableSkill: true }, true, true],
+ [{ agentEnabled: false, datasetOperator: false, enableSkill: true }, false, true],
+ [{ agentEnabled: true, datasetOperator: true, enableSkill: true }, true, false],
+ [{ agentEnabled: true, datasetOperator: false, enableSkill: false }, true, false],
] as const)(
'matches scope visibility to workspace capabilities',
(visibility, agents, skills) => {
diff --git a/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx b/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx
index 5a11cce8ae1..6949e886050 100644
--- a/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx
+++ b/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx
@@ -24,6 +24,7 @@ function agent(overrides: Partial<AgentAppPartial> = {}): AgentAppPartial {
description: 'Investigates a topic',
mode: 'agent-chat',
icon_url: null,
+ permission_keys: [],
...overrides,
}
}
diff --git a/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsx b/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsx
index 09467e3ef40..79eba4cbde2 100644
--- a/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsx
+++ b/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsx
@@ -49,9 +49,6 @@ vi.mock('@/i18n-config', () => ({
vi.mock('@/features/agent-v2/feature-flag', () => ({
isAgentV2Enabled: () => true,
}))
-vi.mock('@/features/agent-v2/permissions', () => ({
- useCanManageAgents: () => true,
-}))
vi.mock('../command-bus', () => ({
executeCommand: (...args: unknown[]) => mockExecuteCommand(...args),
diff --git a/web/app/components/goto-anything/actions/commands/slash-provider.tsx b/web/app/components/goto-anything/actions/commands/slash-provider.tsx
index 0c1ce0c3c32..60f74003288 100644
--- a/web/app/components/goto-anything/actions/commands/slash-provider.tsx
+++ b/web/app/components/goto-anything/actions/commands/slash-provider.tsx
@@ -6,7 +6,6 @@ import { ENABLE_FEATURE_PREVIEW } from '@/config'
import { useDocLink } from '@/context/i18n'
import { isCurrentWorkspaceDatasetOperatorAtom } from '@/context/workspace-state'
import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'
-import { useCanManageAgents } from '@/features/agent-v2/permissions'
import { setLocaleOnClient } from '@/i18n-config'
import { accountCommand } from './account'
import { createCommand } from './create'
@@ -61,9 +60,8 @@ const unregisterSlashCommands = () => {
export const SlashCommandProvider = () => {
const theme = useTheme()
const getDocsHomeUrl = useDocLink()
- const canManageAgents = useCanManageAgents()
const isCurrentWorkspaceDatasetOperator = useAtomValue(isCurrentWorkspaceDatasetOperatorAtom)
- const agentsAvailable = isAgentV2Enabled() && canManageAgents
+ const agentsAvailable = isAgentV2Enabled()
const skillsAvailable = !isCurrentWorkspaceDatasetOperator
useEffect(() => {
registerSlashCommands({
diff --git a/web/app/components/goto-anything/index.tsx b/web/app/components/goto-anything/index.tsx
index b0a23c860e2..052eaaefd2b 100644
--- a/web/app/components/goto-anything/index.tsx
+++ b/web/app/components/goto-anything/index.tsx
@@ -42,7 +42,6 @@ import { selectWorkflowNode } from '@/app/components/workflow/utils/node-navigat
import { useGetLanguage } from '@/context/i18n'
import { isCurrentWorkspaceDatasetOperatorAtom } from '@/context/workspace-state'
import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'
-import { useCanManageAgents } from '@/features/agent-v2/permissions'
import { usePathname, useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { PluginInstallPermissionProvider } from '../plugins/install-plugin/components/plugin-install-permission-provider'
@@ -231,14 +230,13 @@ export function GotoAnything() {
const pathname = usePathname()
const router = useRouter()
const defaultLocale = useGetLanguage()
- const canManageAgents = useCanManageAgents()
const isCurrentWorkspaceDatasetOperator = useAtomValue(isCurrentWorkspaceDatasetOperatorAtom)
const { data: enableSkill } = useQuery(
consoleQuery.features.get.queryOptions({
select: (features) => features.enable_skill,
}),
)
- const agentsAvailable = isAgentV2Enabled() && canManageAgents
+ const agentsAvailable = isAgentV2Enabled()
const skillsAvailable = enableSkill === true && !isCurrentWorkspaceDatasetOperator
const isWorkflowPage =
appWorkflowPathPattern.test(pathname) || sharedWorkflowPathPattern.test(pathname)
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.tsx
index 062fa3cc61a..6e84c8e014b 100644
--- 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.tsx
@@ -37,11 +37,8 @@ const permissionGroups = [
}),
]
-const getPermissionRow = (permissionName: string) =>
- screen.getByText(permissionName).closest('div')!
-
const getPermissionCheckbox = (permissionName: string) =>
- within(getPermissionRow(permissionName)).getByRole('checkbox')
+ screen.getByRole('checkbox', { name: permissionName })
describe('PermissionGroupList', () => {
beforeEach(() => {
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.tsx
index 5eed388f2fa..40d97383f55 100644
--- 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.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'
-import type { AccessPolicyWithBindings } from '@/models/access-control'
+import type { AccessRule } from '../types'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -17,7 +17,7 @@ vi.mock('@/context/permission-state', async () => {
}))
})
-const rule: AccessPolicyWithBindings = {
+const rule: AccessRule = {
policy: {
id: 'app-rule-1',
tenant_id: 'tenant-1',
@@ -28,8 +28,8 @@ const rule: AccessPolicyWithBindings = {
permission_keys: ['app.edit'],
is_builtin: true,
category: 'global_system_default',
- created_at: '2026-01-01',
- updated_at: '2026-01-01',
+ created_at: 1767225600,
+ updated_at: 1767225600,
},
roles: [
{
@@ -44,6 +44,8 @@ const rule: AccessPolicyWithBindings = {
{
account_id: 'account-1',
account_name: 'Levi',
+ avatar: '',
+ email: '[email protected]',
binding_id: 'account-binding-1',
is_locked: false,
},
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.tsx
index 6d498d4fe85..e4799d12ea1 100644
--- 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.tsx
@@ -1,274 +1,204 @@
-import type { AccessPolicyWithBindings } from '@/models/access-control'
-import { toast } from '@langgenius/dify-ui/toast'
-import { render, screen } from '@testing-library/react'
+import { act, render, screen, waitFor, within } 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 { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { seedWorkspacePermissionsQuery } from '@/test/console/workspace-permissions'
+import { createAccessPolicyFixture } from '@/test/fixtures/access-policy'
import AccessRulesPage from '../index'
-const mocks = vi.hoisted(() => ({
- createAccessRule: vi.fn(),
- updateAccessRule: vi.fn(),
+const request = vi.hoisted(() => vi.fn())
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request,
}))
-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 pagination = { total_count: 1, per_page: 20, current_page: 1, total_pages: 1 }
+const providers = {
+ app: consoleQuery.workspaces.current.rbac.workspace.apps.accessPolicy.get,
+ dataset: consoleQuery.workspaces.current.rbac.workspace.datasets.accessPolicy.get,
+ agent: consoleQuery.workspaces.current.rbac.workspace.agents.accessPolicy.get,
}
+const resourceTypes = ['app', 'dataset', 'agent'] as const
+const sent: Request[] = []
-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()
+function setup({ canManage = true, builtin = false } = {}) {
+ const { wrapper, queryClient } = createConsoleQueryWrapper({
+ workspacePermissionKeys: canManage ? ['workspace.role.manage'] : [],
})
-
- return {
- mutate: mock,
- mutateAsync: mock,
+ for (const resourceType of resourceTypes) {
+ const rule = createAccessPolicyFixture({
+ id: `${resourceType}-rule`,
+ resource_type: resourceType,
+ name: `${resourceType} rule`,
+ permission_keys: [`${resourceType}.acl.edit`],
+ is_builtin: builtin,
+ })
+ queryClient.setQueryData(
+ providers[resourceType].infiniteOptions({
+ input: (page) => ({ query: { language: 'en', page, limit: 20 } }),
+ initialPageParam: 1,
+ getNextPageParam: () => undefined,
+ }).queryKey,
+ {
+ pages: [{ items: [{ policy: rule, accounts: [], roles: [] }], pagination }],
+ pageParams: [1],
+ },
+ )
+ queryClient.setQueryData(
+ consoleQuery.workspaces.current.rbac.rolePermissions.catalog[resourceType].get.queryKey({
+ input: {},
+ }),
+ {
+ groups: [
+ {
+ group_key: `${resourceType}_acl`,
+ group_name: resourceType,
+ description: '',
+ permissions: [
+ { key: `${resourceType}.acl.edit`, name: 'Edit configuration', description: '' },
+ ],
+ },
+ ],
+ },
+ )
}
+ request.mockImplementation(
+ async (_url: string, _init: RequestInit, options: { request: Request }) => {
+ const req = options.request
+ sent.push(req.clone())
+ if (req.method === 'GET') {
+ const resourceType = new URL(req.url).pathname.includes('/datasets/')
+ ? 'dataset'
+ : new URL(req.url).pathname.includes('/apps/')
+ ? 'app'
+ : 'agent'
+ return Response.json({
+ items: [
+ {
+ policy: createAccessPolicyFixture({ resource_type: resourceType }),
+ accounts: [],
+ roles: [],
+ },
+ ],
+ pagination,
+ })
+ }
+ return Response.json(createAccessPolicyFixture())
+ },
+ )
+ return { ...render(<AccessRulesPage />, { wrapper }), queryClient }
}
-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>,
- )
+async function openSection(resourceType: (typeof resourceTypes)[number]) {
+ const trigger = screen.getByRole('button', {
+ name: new RegExp(`^permission.accessRule.${resourceType}Title`),
+ })
+ if (trigger.getAttribute('aria-expanded') !== 'true') await userEvent.click(trigger)
+ return trigger.closest('section')!
}
describe('AccessRulesPage', () => {
beforeEach(() => {
vi.clearAllMocks()
- setupHooks()
+ sent.length = 0
})
- 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('renders App, Dataset, and Agent permission sets', () => {
+ setup()
+ for (const type of resourceTypes)
+ expect(
+ screen.getByRole('button', { name: new RegExp(`^permission.accessRule.${type}Title`) }),
+ ).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.each(resourceTypes)(
+ 'creates a %s permission set through the generated endpoint',
+ async (type) => {
+ setup()
+ const section = await openSection(type)
+ await userEvent.click(
+ within(section).getByRole('button', { name: 'permission.accessRule.newPermissionSet' }),
+ )
+ const dialog = screen.getByRole('dialog')
+ await userEvent.type(
+ within(dialog).getByRole('textbox', { name: /permissionSet.nameLabel/ }),
+ 'Custom policy',
+ )
+ await userEvent.click(
+ within(dialog).getByRole('checkbox', { name: new RegExp(`${type}.acl.edit`) }),
+ )
+ await userEvent.click(
+ within(dialog).getByRole('button', { name: 'common.operation.confirm' }),
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ const mutation = sent.find((req) => req.method === 'POST')!
+ expect(new URL(mutation.url).pathname).toMatch(/\/rbac\/access-policies$/)
+ expect(await mutation.json()).toEqual({
+ name: 'Custom policy',
+ description: '',
+ permission_keys: [`${type}.acl.edit`],
+ resource_type: type,
+ })
+ },
+ )
- it('creates dataset permission sets with dataset resource type', async () => {
- render(<AccessRulesPage />)
+ it.each(resourceTypes)(
+ 'updates a %s permission set with the generated request body',
+ async (type) => {
+ setup()
+ const section = await openSection(type)
+ await userEvent.click(
+ within(section).getByRole('button', { name: 'common.operation.moreActions' }),
+ )
+ await userEvent.click(screen.getByRole('menuitem', { name: 'common.operation.edit' }))
+ await userEvent.type(
+ screen.getByRole('textbox', { name: 'permission.permissionSet.descriptionLabel' }),
+ ' updated',
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ const mutation = sent.find((req) => req.method === 'PUT')!
+ expect(new URL(mutation.url).pathname).toMatch(new RegExp(`/access-policies/${type}-rule$`))
+ expect(await mutation.json()).toMatchObject({
+ name: `${type} rule`,
+ description: 'Edit Agent configuration updated',
+ permission_keys: [`${type}.acl.edit`],
+ })
+ },
+ )
+ it('keeps built-in Agent policies read-only and offers duplication', async () => {
+ setup({ builtin: true })
+ const section = await openSection('agent')
await userEvent.click(
- screen.getByRole('button', { name: 'create permission.accessRule.datasetTitle' }),
+ within(section).getByRole('button', { name: 'common.operation.moreActions' }),
)
- 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')
+ expect(
+ screen.queryByRole('menuitem', { name: 'common.operation.delete' }),
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByRole('menuitem', { name: 'permission.common.duplicateAction' }),
+ ).toBeInTheDocument()
+ await userEvent.click(screen.getByRole('menuitem', { name: 'common.operation.view' }))
+ expect(screen.getByRole('textbox', { name: /permissionSet.nameLabel/ })).toBeDisabled()
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.confirm' }),
+ ).not.toBeInTheDocument()
})
- it('updates dataset permission sets with dataset resource type', async () => {
- render(<AccessRulesPage />)
-
+ it('closes a mutation dialog when role management is revoked', async () => {
+ const { queryClient } = setup()
+ const section = await openSection('agent')
await userEvent.click(
- screen.getByRole('button', { name: 'edit permission.accessRule.datasetTitle' }),
+ within(section).getByRole('button', { name: 'permission.accessRule.newPermissionSet' }),
)
- 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')
+ act(() => {
+ seedWorkspacePermissionsQuery(queryClient, [])
+ })
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(
+ screen.queryByRole('button', { name: 'permission.accessRule.newPermissionSet' }),
+ ).not.toBeInTheDocument()
+ expect(sent.filter((req) => req.method !== 'GET')).toHaveLength(0)
})
})
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.tsx
index 0c3b879227b..6e2a4bbae28 100644
--- 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.tsx
@@ -1,6 +1,6 @@
'use client'
-import type { AccessPolicy } from '@/models/access-control'
+import type { AccessPolicy } from '@dify/contracts/api/console/workspaces/types.gen'
import {
AlertDialog,
AlertDialogActions,
@@ -19,12 +19,10 @@ import {
} from '@langgenius/dify-ui/dropdown-menu'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { toast } from '@langgenius/dify-ui/toast'
+import { useMutation } from '@tanstack/react-query'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import {
- useCopyAccessRule,
- useDeleteAccessRule,
-} from '@/service/access-control/use-workspace-access-rules'
+import { consoleQuery } from '@/service/console'
type AccessRuleRowMenuProps = {
rule: AccessPolicy
@@ -37,9 +35,11 @@ const AccessRuleRowMenu = ({ rule, onView, onEdit }: AccessRuleRowMenuProps) =>
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 { mutate: copyAccessRule } = useMutation(
+ consoleQuery.workspaces.current.rbac.accessPolicies.byPolicyId.copy.post.mutationOptions(),
+ )
+ const { mutate: deleteAccessRule, isPending: isDeletingAccessRule } = useMutation(
+ consoleQuery.workspaces.current.rbac.accessPolicies.byPolicyId.delete.mutationOptions(),
)
const handleView = useCallback(() => {
@@ -47,12 +47,15 @@ const AccessRuleRowMenu = ({ rule, onView, onEdit }: AccessRuleRowMenuProps) =>
}, [onView])
const handleCopyRules = useCallback(() => {
- copyAccessRule(rule.id, {
- onSuccess: () => {
- toast.success(t(($) => $['accessRule.copied'], { ns: 'permission' }))
- setOpen(false)
+ copyAccessRule(
+ { params: { policy_id: rule.id } },
+ {
+ onSuccess: () => {
+ toast.success(t(($) => $['accessRule.copied'], { ns: 'permission' }))
+ setOpen(false)
+ },
},
- })
+ )
}, [copyAccessRule, rule.id, t])
const openDeleteConfirm = useCallback(() => {
@@ -61,12 +64,15 @@ const AccessRuleRowMenu = ({ rule, onView, onEdit }: AccessRuleRowMenuProps) =>
}, [])
const handleDelete = useCallback(() => {
- deleteAccessRule(rule.id, {
- onSuccess: () => {
- toast.success(t(($) => $['accessRule.deleted'], { ns: 'permission' }))
- setShowDeleteConfirm(false)
+ deleteAccessRule(
+ { params: { policy_id: rule.id } },
+ {
+ onSuccess: () => {
+ toast.success(t(($) => $['accessRule.deleted'], { ns: 'permission' }))
+ setShowDeleteConfirm(false)
+ },
},
- })
+ )
}, [deleteAccessRule, rule.id, t])
const isBuiltIn = rule.is_builtin
diff --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.tsx
index b5a8e7df5a5..cc206d860d5 100644
--- 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.tsx
@@ -1,18 +1,18 @@
'use client'
-import type { AccessPolicyWithBindings } from '@/models/access-control'
+import type { AccessRule } from './types'
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
+ rule: AccessRule
canManage: boolean
className?: string
showMenu?: boolean
- onView?: (rule: AccessPolicyWithBindings) => void
- onEdit?: (rule: AccessPolicyWithBindings) => void
+ onView?: (rule: AccessRule) => void
+ onEdit?: (rule: AccessRule) => void
}
const AccessRuleRow = ({
@@ -26,7 +26,7 @@ const AccessRuleRow = ({
const { t } = useTranslation()
const { policy } = rule
const description =
- policy.description.trim() || t(($) => $['accessRule.noDescription'], { ns: 'permission' })
+ policy.description?.trim() || t(($) => $['accessRule.noDescription'], { ns: 'permission' })
const handleView = useCallback(() => onView?.(rule), [onView, rule])
const handleEdit = useCallback(() => onEdit?.(rule), [onEdit, rule])
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.tsx
index 67cd0a4cb11..bb9250f9a4b 100644
--- 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.tsx
@@ -1,6 +1,6 @@
'use client'
-import type { AccessPolicyWithBindings } from '@/models/access-control'
+import type { AccessRule } from './types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'
@@ -15,7 +15,7 @@ import AccessRuleRow from './access-rule-row'
type AccessRuleSectionProps = {
title: string
- rules: AccessPolicyWithBindings[]
+ rules: AccessRule[]
totalCount?: number
isLoadingRules: boolean
isFetchingNextPage?: boolean
@@ -24,8 +24,9 @@ type AccessRuleSectionProps = {
error?: unknown
defaultExpanded?: boolean
onCreate?: () => void
- onViewRule?: (rule: AccessPolicyWithBindings) => void
- onEditRule?: (rule: AccessPolicyWithBindings) => void
+ onViewRule?: (rule: AccessRule) => void
+ onEditRule?: (rule: AccessRule) => void
+ onRetry?: () => void
className?: string
}
@@ -42,6 +43,7 @@ const AccessRuleSection = ({
onCreate,
onViewRule,
onEditRule,
+ onRetry,
className,
}: AccessRuleSectionProps) => {
const { t } = useTranslation()
@@ -144,7 +146,12 @@ const AccessRuleSection = ({
/>
}
>
- {isLoadingRules ? (
+ {error ? (
+ <div role="alert" className="flex items-center justify-center gap-3 py-8">
+ <span>{t(($) => $['api.actionFailed'], { ns: 'common' })}</span>
+ <Button onClick={onRetry}>{t(($) => $['operation.retry'], { ns: 'common' })}</Button>
+ </div>
+ ) : isLoadingRules ? (
<div className="px-1 py-8 text-center">
<Loading type="app" />
</div>
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.tsx
deleted file mode 100644
index 93620bbc74a..00000000000
--- a/web/app/components/header/account-setting/access-rules-page/app-access-rule-section.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-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 AppAccessRuleSection
diff --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.tsx
deleted file mode 100644
index a0f825f1a95..00000000000
--- a/web/app/components/header/account-setting/access-rules-page/dataset-access-rule-section.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-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 DatasetAccessRuleSection
diff --git a/web/app/components/header/account-setting/access-rules-page/index.tsx b/web/app/components/header/account-setting/access-rules-page/index.tsx
index bd8569adc20..ff8e0c5badb 100644
--- a/web/app/components/header/account-setting/access-rules-page/index.tsx
+++ b/web/app/components/header/account-setting/access-rules-page/index.tsx
@@ -1,13 +1,13 @@
'use client'
-import AppAccessRuleSection from './app-access-rule-section'
-import DatasetAccessRuleSection from './dataset-access-rule-section'
+import { ResourceAccessRuleSection } from './resource-access-rule-section'
const AccessRulesPage = () => {
return (
<div className="flex flex-col gap-4">
- <AppAccessRuleSection />
- <DatasetAccessRuleSection />
+ <ResourceAccessRuleSection resourceType="app" />
+ <ResourceAccessRuleSection resourceType="dataset" />
+ <ResourceAccessRuleSection resourceType="agent" />
</div>
)
}
diff --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.tsx
index 8ecc52563de..7ac31c1e9ce 100644
--- 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.tsx
@@ -1,8 +1,9 @@
import type { PermissionCatalogResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ReactNode } from 'react'
import { QueryClientProvider } from '@tanstack/react-query'
-import { render, screen } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { AgentPermission } from '@/features/agent-v2/acl'
import { consoleQuery } from '@/service/console'
import { createTestQueryClient } from '@/test/query-client'
import PermissionSetModal from '../index'
@@ -77,6 +78,22 @@ const renderModal = (modal: ReactNode) => {
datasetPermissionCatalog,
)
+ queryClient.setQueryData(
+ consoleQuery.workspaces.current.rbac.rolePermissions.catalog.agent.get.queryKey({ input: {} }),
+ {
+ groups: [
+ {
+ group_key: 'agent_acl',
+ group_name: 'Agent',
+ description: '',
+ permissions: Object.values(AgentPermission)
+ .filter((key) => key !== AgentPermission.Create)
+ .map((key) => ({ key, name: key, description: '' })),
+ },
+ ],
+ },
+ )
+
return render(<QueryClientProvider client={queryClient}>{modal}</QueryClientProvider>)
}
@@ -244,4 +261,49 @@ describe('PermissionSetModal', () => {
).not.toBeInTheDocument()
})
})
+ it('renders all eleven Agent ACL permissions without the workspace create permission', () => {
+ renderModal(
+ <PermissionSetModal
+ open
+ mode="create"
+ resourceType="agent"
+ onClose={vi.fn()}
+ onSubmit={vi.fn()}
+ />,
+ )
+ for (const permission of Object.values(AgentPermission).filter(
+ (key) => key !== AgentPermission.Create,
+ )) {
+ expect(
+ screen.getByRole('checkbox', { name: getPermissionKeyMatcher(permission) }),
+ ).toBeInTheDocument()
+ }
+ expect(screen.queryByRole('checkbox', { name: /agent.create/ })).not.toBeInTheDocument()
+ })
+
+ it('keeps the form open and preserves input after a failed save', async () => {
+ const close = vi.fn()
+ const submit = vi.fn().mockRejectedValue(new Error('Unavailable'))
+ renderModal(
+ <PermissionSetModal
+ open
+ mode="create"
+ resourceType="agent"
+ onClose={close}
+ onSubmit={submit}
+ />,
+ )
+ await userEvent.type(
+ screen.getByRole('textbox', { name: /permissionSet.nameLabel/ }),
+ 'Agent reviewers',
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent('common.api.actionFailed'),
+ )
+ expect(screen.getByRole('textbox', { name: /permissionSet.nameLabel/ })).toHaveValue(
+ 'Agent reviewers',
+ )
+ expect(close).not.toHaveBeenCalled()
+ })
})
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.ts
index 70d4de11fab..37385f954dd 100644
--- 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.ts
@@ -8,13 +8,9 @@ import { consoleQuery } from '@/service/console'
export const usePermissionsGroups = (resourceType: AccessPolicyResourceType) => {
const { t } = useTranslation()
const permissionCatalogQueryOptions =
- resourceType === 'app'
- ? consoleQuery.workspaces.current.rbac.rolePermissions.catalog.app.get.queryOptions({
- input: {},
- })
- : consoleQuery.workspaces.current.rbac.rolePermissions.catalog.dataset.get.queryOptions({
- input: {},
- })
+ consoleQuery.workspaces.current.rbac.rolePermissions.catalog[resourceType].get.queryOptions({
+ input: {},
+ })
const { data: permissionCatalog } = useQuery(permissionCatalogQueryOptions)
const groups = useMemo(() => {
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.tsx
index 049c8eb131a..958b6b71493 100644
--- 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.tsx
@@ -31,7 +31,7 @@ type PermissionSetModalProps = {
resourceType: AccessPolicyResourceType
initialValues?: Partial<PermissionSetFormValues>
onClose: () => void
- onSubmit: (values: PermissionSetFormValues) => void
+ onSubmit: (values: PermissionSetFormValues) => void | Promise<void>
}
type PermissionSetModalBodyProps = Omit<PermissionSetModalProps, 'open'>
@@ -51,19 +51,29 @@ const PermissionSetModalBody = ({
const [permissionKeys, setPermissionKeys] = useState<string[]>(
initialValues?.permissionKeys ?? [],
)
+ const [isSubmitting, setIsSubmitting] = useState(false)
+ const [submitFailed, setSubmitFailed] = useState(false)
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()
+ const handleConfirm = async () => {
+ if (readonly || !canSubmit || isSubmitting) return
+ setIsSubmitting(true)
+ setSubmitFailed(false)
+ try {
+ await onSubmit({
+ name: trimmedName,
+ description: description.trim(),
+ permissionKeys,
+ })
+ onClose()
+ } catch {
+ setSubmitFailed(true)
+ } finally {
+ setIsSubmitting(false)
+ }
}
return (
@@ -71,102 +81,120 @@ const PermissionSetModalBody = ({
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">
- <DialogClose
- render={
- <IconButton
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- size="lg"
- className="absolute inset-e-6 top-6"
- >
- <span aria-hidden className="i-ri-close-line size-4" />
- </IconButton>
- }
- />
- <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>
+ <form
+ className="contents"
+ onSubmit={(event) => {
+ event.preventDefault()
+ void handleConfirm()
+ }}
+ >
+ <div className="relative shrink-0 px-6 pt-6 pb-4">
+ <DialogClose
+ render={
+ <IconButton
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ size="lg"
+ className="absolute inset-e-6 top-6"
+ >
+ <span aria-hidden className="i-ri-close-line size-4" />
+ </IconButton>
+ }
+ />
+ <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>
- <div className="border-t border-divider-subtle" />
+ <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 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}
+ required
+ />
+ </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 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 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>
- <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={getEnterpriseDocUrl('/use/workspace/permission-reference', docLanguage)}
- 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 className="flex shrink-0 items-center justify-between gap-3 border-t border-divider-subtle px-6 py-4">
+ {submitFailed && (
+ <p role="alert" className="system-xs-regular text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
)}
+ <a
+ href={getEnterpriseDocUrl('/use/workspace/permission-reference', docLanguage)}
+ 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 type="button" variant="secondary" onClick={onClose}>
+ {readonly
+ ? t(($) => $['operation.close'], { ns: 'common' })
+ : t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
+ {!readonly && (
+ <Button type="submit" variant="primary" disabled={!canSubmit} loading={isSubmitting}>
+ {t(($) => $['operation.confirm'], { ns: 'common' })}
+ </Button>
+ )}
+ </div>
</div>
- </div>
+ </form>
</DialogContent>
)
}
diff --git a/web/app/components/header/account-setting/access-rules-page/resource-access-rule-section.tsx b/web/app/components/header/account-setting/access-rules-page/resource-access-rule-section.tsx
new file mode 100644
index 00000000000..496384a325c
--- /dev/null
+++ b/web/app/components/header/account-setting/access-rules-page/resource-access-rule-section.tsx
@@ -0,0 +1,108 @@
+'use client'
+
+import type { PermissionSetFormValues, PermissionSetModalMode } from './permission-set-modal'
+import type { AccessRule } from './types'
+import type { AccessPolicyResourceType } from '@/models/access-control'
+import { toast } from '@langgenius/dify-ui/toast'
+import { useInfiniteQuery, useMutation } from '@tanstack/react-query'
+import { useAtomValue } from 'jotai'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useLocale } from '@/context/i18n'
+import { workspacePermissionKeysAtom } from '@/context/permission-state'
+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'
+import { consoleQuery } from '@/service/console'
+import { hasPermission } from '@/utils/permission'
+import AccessRuleSection from './access-rule-section'
+import PermissionSetModal from './permission-set-modal'
+
+const resourceQueries = {
+ app: consoleQuery.workspaces.current.rbac.workspace.apps.accessPolicy.get,
+ dataset: consoleQuery.workspaces.current.rbac.workspace.datasets.accessPolicy.get,
+ agent: consoleQuery.workspaces.current.rbac.workspace.agents.accessPolicy.get,
+}
+
+export function ResourceAccessRuleSection({
+ resourceType,
+}: {
+ resourceType: AccessPolicyResourceType
+}) {
+ const { t } = useTranslation('permission')
+ const language = getAccessControlTemplateLanguage(useLocale())
+ const canManage = hasPermission(
+ useAtomValue(workspacePermissionKeysAtom),
+ 'workspace.role.manage',
+ )
+ const [modal, setModal] = useState<{ mode: PermissionSetModalMode; rule?: AccessRule } | null>(
+ null,
+ )
+ const rulesQuery = useInfiniteQuery(
+ resourceQueries[resourceType].infiniteOptions({
+ input: (page) => ({ query: { language, page, limit: 20 } }),
+ initialPageParam: 1,
+ getNextPageParam: (lastPage) => {
+ const page = lastPage.pagination?.current_page ?? 1
+ return page < (lastPage.pagination?.total_pages ?? 0) ? page + 1 : undefined
+ },
+ }),
+ )
+ const createRule = useMutation(
+ consoleQuery.workspaces.current.rbac.accessPolicies.post.mutationOptions(),
+ )
+ const updateRule = useMutation(
+ consoleQuery.workspaces.current.rbac.accessPolicies.byPolicyId.put.mutationOptions(),
+ )
+ const rules = (rulesQuery.data?.pages.flatMap((page) => page.items ?? []) ?? []).flatMap(
+ (rule) => (rule.policy ? [{ ...rule, policy: rule.policy }] : []),
+ )
+
+ const submit = async ({ name, description, permissionKeys }: PermissionSetFormValues) => {
+ if (!canManage || !modal || modal.mode === 'view') return
+ const body = { name, description, permission_keys: permissionKeys }
+ if (modal.mode === 'create') {
+ await createRule.mutateAsync({ body: { ...body, resource_type: resourceType } })
+ toast.success(t(($) => $['accessRule.created']))
+ } else if (modal.rule) {
+ await updateRule.mutateAsync({ params: { policy_id: modal.rule.policy.id }, body })
+ toast.success(t(($) => $['accessRule.updated']))
+ }
+ }
+
+ return (
+ <>
+ <AccessRuleSection
+ title={t(($) => $[`accessRule.${resourceType}Title`])}
+ rules={rules}
+ totalCount={rulesQuery.data?.pages[0]?.pagination?.total_count}
+ isLoadingRules={rulesQuery.isPending}
+ isFetchingNextPage={rulesQuery.isFetchingNextPage}
+ hasNextPage={rulesQuery.hasNextPage}
+ fetchNextPage={() => void rulesQuery.fetchNextPage()}
+ error={rulesQuery.error}
+ onRetry={() => void rulesQuery.refetch()}
+ defaultExpanded={resourceType === 'app'}
+ onCreate={() => setModal({ mode: 'create' })}
+ onViewRule={(rule) => setModal({ mode: 'view', rule })}
+ onEditRule={(rule) => setModal({ mode: 'edit', rule })}
+ />
+ {modal && (modal.mode === 'view' || canManage) && (
+ <PermissionSetModal
+ open
+ mode={modal.mode}
+ resourceType={resourceType}
+ initialValues={
+ modal.rule
+ ? {
+ name: modal.rule.policy.name,
+ description: modal.rule.policy.description ?? '',
+ permissionKeys: modal.rule.policy.permission_keys ?? [],
+ }
+ : undefined
+ }
+ onClose={() => setModal(null)}
+ onSubmit={submit}
+ />
+ )}
+ </>
+ )
+}
diff --git a/web/app/components/header/account-setting/access-rules-page/types.ts b/web/app/components/header/account-setting/access-rules-page/types.ts
new file mode 100644
index 00000000000..f4d77407c07
--- /dev/null
+++ b/web/app/components/header/account-setting/access-rules-page/types.ts
@@ -0,0 +1,6 @@
+import type {
+ AccessMatrixItem,
+ AccessPolicy,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+
+export type AccessRule = AccessMatrixItem & { policy: AccessPolicy }
diff --git a/web/app/components/header/account-setting/permission-group-list.tsx b/web/app/components/header/account-setting/permission-group-list.tsx
index c64fecc8a83..e5c8502ffe3 100644
--- a/web/app/components/header/account-setting/permission-group-list.tsx
+++ b/web/app/components/header/account-setting/permission-group-list.tsx
@@ -151,7 +151,7 @@ const PermissionGroupList = ({
const checked = selectedSet.has(permission.key)
return (
- <div
+ <label
key={permission.key}
className={cn(
'flex min-h-9 items-center gap-3 px-3 py-1.5',
@@ -161,7 +161,6 @@ const PermissionGroupList = ({
checked && 'bg-state-accent-hover',
checked && !readonly && 'hover:bg-state-accent-hover',
)}
- onClick={() => togglePermission(permission.key)}
>
<Checkbox
checked={checked}
@@ -174,7 +173,7 @@ const PermissionGroupList = ({
<span className="min-w-0 flex-1 truncate system-md-regular text-text-secondary">
{permission.name}
</span>
- </div>
+ </label>
)
})}
</div>
diff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsx
index 3c56b76e197..e48fe95d894 100644
--- a/web/app/components/main-nav/__tests__/index.spec.tsx
+++ b/web/app/components/main-nav/__tests__/index.spec.tsx
@@ -747,7 +747,7 @@ describe('MainNav', () => {
)
})
- it('hides the roster entry when the user lacks agent.acl.preview', () => {
+ it('shows the roster entry when the user lacks agent.acl.preview', () => {
mockConsoleState.current = {
...consoleState,
workspacePermissionKeys: ownerWorkspacePermissionKeys.filter(
@@ -757,12 +757,6 @@ describe('MainNav', () => {
renderMainNav()
- expect(screen.queryByRole('link', { name: /Agents/ })).not.toBeInTheDocument()
- })
-
- it('shows the roster entry when the user has agent.acl.preview', () => {
- renderMainNav()
-
expect(screen.getByRole('link', { name: /Agents/ })).toBeInTheDocument()
})
@@ -842,7 +836,7 @@ describe('MainNav', () => {
expect(screen.getAllByText('team')).toHaveLength(1)
})
- it('keeps unrestricted main routes visible for dataset operators while hiding roster', () => {
+ it('keeps unrestricted main routes and roster visible for dataset operators', () => {
mockConsoleState.current = {
...consoleState,
currentWorkspace: {
@@ -859,7 +853,7 @@ describe('MainNav', () => {
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: /Agents/ })).not.toBeInTheDocument()
+ expect(screen.getByRole('link', { name: /Agents/ })).toHaveAttribute('href', '/agents')
expect(screen.queryByRole('link', { name: /common.mainNav.skills/ })).not.toBeInTheDocument()
expect(screen.getByRole('link', { name: /common.menus.datasets/ })).toHaveAttribute(
'href',
@@ -888,7 +882,7 @@ describe('MainNav', () => {
isCurrentWorkspaceDatasetOperator: false,
isCurrentWorkspaceManager: false,
isCurrentWorkspaceOwner: false,
- workspacePermissionKeys: ['app_library.access', 'tool.manage', 'agent.acl.preview'],
+ workspacePermissionKeys: ['app_library.access', 'tool.manage'],
}
renderMainNav({ branding: { enabled: false } })
diff --git a/web/app/components/main-nav/index.tsx b/web/app/components/main-nav/index.tsx
index 5aa79c5f73a..f191188c5f0 100644
--- a/web/app/components/main-nav/index.tsx
+++ b/web/app/components/main-nav/index.tsx
@@ -13,7 +13,6 @@ import StepByStepTourMount from '@/app/components/step-by-step-tour/mount'
import { isCurrentWorkspaceDatasetOperatorAtom } from '@/context/workspace-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'
-import { useCanManageAgents } from '@/features/agent-v2/permissions'
import { useCanViewSkills } from '@/features/skills/permissions'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import dynamic from '@/next/dynamic'
@@ -39,7 +38,6 @@ export function MainNav({ className }: MainNavProps) {
select: (data) => data.meta.currentEnv,
})
const agentV2Enabled = isAgentV2Enabled()
- const canManageAgents = useCanManageAgents()
const canViewSkills = useCanViewSkills()
const { data: enableSkill } = useQuery(
consoleQuery.features.get.queryOptions({
@@ -54,7 +52,6 @@ export function MainNav({ className }: MainNavProps) {
MAIN_NAV_ROUTES.filter((route) =>
isMainNavRouteVisible(route, {
agentV2Enabled,
- canManageAgents,
canViewSkills,
isCurrentWorkspaceDatasetOperator,
marketplaceEnabled: systemFeatures.enable_marketplace,
@@ -69,7 +66,6 @@ export function MainNav({ className }: MainNavProps) {
})),
[
agentV2Enabled,
- canManageAgents,
canViewSkills,
enableSkill,
isCurrentWorkspaceDatasetOperator,
diff --git a/web/app/components/main-nav/routes.ts b/web/app/components/main-nav/routes.ts
index c54c9af346d..721768fff37 100644
--- a/web/app/components/main-nav/routes.ts
+++ b/web/app/components/main-nav/routes.ts
@@ -17,7 +17,6 @@ export type MainNavRouteConfig = {
export type MainNavRouteVisibilityOptions = {
agentV2Enabled: boolean
- canManageAgents: boolean
canViewSkills: boolean
isCurrentWorkspaceDatasetOperator: boolean
marketplaceEnabled: boolean
@@ -30,7 +29,6 @@ export type DetailSidebarVisibilityOptions = Pick<
>
const VISIBLE_TO_ALL: MainNavRouteVisibility = () => true
-const CAN_MANAGE_AGENTS: MainNavRouteVisibility = (options) => options.canManageAgents
const SKILL_ENABLED_FOR_WORKSPACE: MainNavRouteVisibility = (options) =>
options.skillEnabled && options.canViewSkills && !options.isCurrentWorkspaceDatasetOperator
@@ -67,7 +65,7 @@ export const MAIN_NAV_ROUTES = [
active: (path: string) => isPathUnderRoute(path, '/agents'),
icon: 'i-custom-vender-main-nav-agent',
activeIcon: 'i-custom-vender-main-nav-agent-active',
- visibility: CAN_MANAGE_AGENTS,
+ visibility: VISIBLE_TO_ALL,
feature: 'agentV2',
},
{
diff --git a/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx b/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx
index e24112c1d9a..db91d7e67e1 100644
--- a/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx
@@ -4,14 +4,9 @@ import userEvent from '@testing-library/user-event'
import { AgentSelectorContent } from '../agent-selector'
const mocks = vi.hoisted(() => ({
- canManageAgents: true,
agents: [] as Array<{ id: string; name: string }>,
}))
-vi.mock('@/features/agent-v2/permissions', () => ({
- useCanManageAgents: () => mocks.canManageAgents,
-}))
-
vi.mock('@/app/components/workflow/hooks-store', () => ({
useHooksStore: () => undefined,
}))
@@ -59,11 +54,10 @@ const renderSelector = async ({
describe('AgentSelectorContent', () => {
beforeEach(() => {
- mocks.canManageAgents = true
mocks.agents = []
})
- it('offers the Agent Console link with agent.acl.preview', async () => {
+ it('offers the Agent Console link without a workspace preview gate', async () => {
await renderSelector({ onStartFromScratch: vi.fn() })
const listbox = screen.getByRole('listbox')
@@ -99,26 +93,6 @@ describe('AgentSelectorContent', () => {
expect(listbox.querySelector('.overflow-y-auto')).not.toBeInTheDocument()
})
- it('hides the Agent Console link without agent.acl.preview', async () => {
- mocks.canManageAgents = false
-
- await renderSelector()
-
- expect(screen.queryByText(manageInConsoleLabel)).not.toBeInTheDocument()
- })
-
- it('keeps start from scratch without agent.acl.preview', async () => {
- mocks.canManageAgents = false
-
- await renderSelector({ onStartFromScratch: vi.fn() })
-
- const listbox = screen.getByRole('listbox')
- const startButton = screen.getByRole('button', { name: startFromScratchLabel })
-
- expect(listbox).not.toContainElement(startButton)
- expect(screen.queryByText(manageInConsoleLabel)).not.toBeInTheDocument()
- })
-
it('should move focus from the combobox to actions outside the listbox', async () => {
const user = userEvent.setup()
await renderSelector({ onStartFromScratch: vi.fn() })
@@ -150,13 +124,4 @@ describe('AgentSelectorContent', () => {
expect(onStartFromScratch).toHaveBeenCalledOnce()
})
-
- it('renders no action row when neither action is available', async () => {
- mocks.canManageAgents = false
-
- await renderSelector()
-
- expect(screen.queryByText(startFromScratchLabel)).not.toBeInTheDocument()
- expect(screen.queryByText(manageInConsoleLabel)).not.toBeInTheDocument()
- })
})
diff --git a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
index d2ab3e75d9a..4141d717904 100644
--- a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
@@ -50,12 +50,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
},
}))
-// Permission-dependent selector actions are covered by agent-selector.spec.tsx;
-// this suite is about block insertion.
-vi.mock('@/features/agent-v2/permissions', () => ({
- useCanManageAgents: () => true,
-}))
-
const createBlock = (
type: BlockEnum,
title: string,
diff --git a/web/app/components/workflow/block-selector/agent-selector.tsx b/web/app/components/workflow/block-selector/agent-selector.tsx
index b140e910517..fa1b05ee184 100644
--- a/web/app/components/workflow/block-selector/agent-selector.tsx
+++ b/web/app/components/workflow/block-selector/agent-selector.tsx
@@ -22,7 +22,6 @@ import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import Badge from '@/app/components/base/badge'
import { useHooksStore } from '@/app/components/workflow/hooks-store'
-import { useCanManageAgents } from '@/features/agent-v2/permissions'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
import BlockIcon from '../block-icon'
@@ -58,7 +57,6 @@ export function AgentSelectorContent({
staleTime: 0,
})
const agents = agentsQuery.data?.data ?? []
- const canManageAgents = useCanManageAgents()
const handleInputValueChange = (nextSearchText: string, details: ComboboxChangeEventDetails) => {
if (details.reason !== 'item-press') setSearchText(nextSearchText)
}
@@ -84,8 +82,6 @@ export function AgentSelectorContent({
? t(($) => $['roster.emptySearch'], { ns: 'agentV2' })
: t(($) => $['roster.empty'], { ns: 'agentV2' })
: null
- const hasActions = !!onStartFromScratch || canManageAgents
-
return (
<div className="w-60 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
<Combobox<AgentInviteOptionResponse>
@@ -125,43 +121,39 @@ export function AgentSelectorContent({
agents.map((agent) => <AgentSelectorItem key={agent.id} agent={agent} />)}
</ComboboxList>
)}
- {hasActions && (
- <div className="border-t border-divider-subtle p-1">
- {onStartFromScratch && (
- <Button
- variant="ghost"
- size="medium"
- className="h-7 w-full justify-start gap-2 rounded-md px-2 py-1.5 text-left system-sm-regular text-text-secondary"
- onClick={onStartFromScratch}
- >
- <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-tertiary" />
- <span className="min-w-0 flex-1 truncate">
- {t(($) => $['roster.nodeSelector.startFromScratch'], { ns: 'agentV2' })}
- </span>
- </Button>
- )}
- {canManageAgents && (
- <Link
- href="/agents"
- target="_blank"
- rel="noopener noreferrer"
- className={cn(
- buttonVariants({ variant: 'ghost', size: 'medium' }),
- 'h-7 w-full justify-start gap-2 rounded-md px-2 py-1.5 text-left system-sm-regular text-text-secondary',
- )}
- onClick={() => onOpenChange(false)}
- >
- <span
- aria-hidden
- className="i-ri-arrow-right-up-line size-4 shrink-0 text-text-tertiary"
- />
- <span className="min-w-0 flex-1 truncate">
- {t(($) => $['roster.nodeSelector.manageInAgentConsole'], { ns: 'agentV2' })}
- </span>
- </Link>
+ <div className="border-t border-divider-subtle p-1">
+ {onStartFromScratch && (
+ <Button
+ variant="ghost"
+ size="medium"
+ className="h-7 w-full justify-start gap-2 rounded-md px-2 py-1.5 text-left system-sm-regular text-text-secondary"
+ onClick={onStartFromScratch}
+ >
+ <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-tertiary" />
+ <span className="min-w-0 flex-1 truncate">
+ {t(($) => $['roster.nodeSelector.startFromScratch'], { ns: 'agentV2' })}
+ </span>
+ </Button>
+ )}
+ <Link
+ href="/agents"
+ target="_blank"
+ rel="noopener noreferrer"
+ className={cn(
+ buttonVariants({ variant: 'ghost', size: 'medium' }),
+ 'h-7 w-full justify-start gap-2 rounded-md px-2 py-1.5 text-left system-sm-regular text-text-secondary',
)}
- </div>
- )}
+ onClick={() => onOpenChange(false)}
+ >
+ <span
+ aria-hidden
+ className="i-ri-arrow-right-up-line size-4 shrink-0 text-text-tertiary"
+ />
+ <span className="min-w-0 flex-1 truncate">
+ {t(($) => $['roster.nodeSelector.manageInAgentConsole'], { ns: 'agentV2' })}
+ </span>
+ </Link>
+ </div>
</Combobox>
</div>
)
diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx
index d53e1150749..3614cd3edbe 100644
--- a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx
@@ -154,7 +154,7 @@ vi.mock('../../_base/hooks/use-node-crud', () => ({
}))
vi.mock('@/features/agent-v2/permissions', () => ({
- useCanManageAgents: () => true,
+ useCanCreateAgents: () => true,
}))
vi.mock('@/app/components/workflow/block-selector/agent-selector', () => ({
@@ -394,6 +394,7 @@ describe('agent/panel', () => {
icon: 'N',
icon_background: '#E9D7FE',
icon_type: 'emoji',
+ permission_keys: ['agent.acl.edit'],
role: 'Researcher',
}
: undefined,
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
index 26192f89f55..c6556ef549e 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
@@ -32,10 +32,10 @@ const mocks = vi.hoisted(() => ({
uploadWorkflowSandboxFile: vi.fn(),
}))
-const permission = vi.hoisted(() => ({ canManageAgents: true }))
+const permission = vi.hoisted(() => ({ canCreateAgents: true }))
vi.mock('@/features/agent-v2/permissions', () => ({
- useCanManageAgents: () => permission.canManageAgents,
+ useCanCreateAgents: () => permission.canCreateAgents,
}))
vi.mock('@/app/components/base/amplitude', () => ({
@@ -496,7 +496,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {
vi.clearAllMocks()
useAppStore.getState().setAppDetail({ mode: AppModeEnum.WORKFLOW } as never)
mocks.completeBuildConversation = undefined
- permission.canManageAgents = true
+ permission.canCreateAgents = true
mocks.loadBuildDraft.mockRejectedValue(new Response(null, { status: 404 }))
mocks.checkoutBuildDraft.mockResolvedValue({
agent_soul: {},
@@ -904,8 +904,8 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {
).not.toBeInTheDocument()
})
- it('should hide the save-to-roster menu when the user cannot manage agents', async () => {
- permission.canManageAgents = false
+ it('should hide the save-to-roster menu when the user cannot create agents', async () => {
+ permission.canCreateAgents = false
renderWorkspace({
onSaveInlineToRoster: vi.fn(),
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx
index 865be24b4ed..f434a6475c7 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx
@@ -4,17 +4,15 @@ import { useRef } from 'react'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { AgentRosterField } from '../agent-roster-field'
-const permission = vi.hoisted(() => ({ canManageAgents: true }))
-
vi.mock('@/features/agent-v2/permissions', () => ({
- useCanManageAgents: () => permission.canManageAgents,
+ useCanCreateAgents: () => true,
}))
vi.mock('@/app/components/workflow/block-selector/agent-selector', () => ({
AgentSelectorContent: () => null,
}))
-function renderDetailRosterField() {
+function renderDetailRosterField(permissionKeys = ['agent.acl.edit']) {
function Harness() {
const portalContainerRef = useRef<HTMLDivElement>(null)
@@ -24,6 +22,7 @@ function renderDetailRosterField() {
agent={{
id: 'roster-agent-1',
name: 'Roster Agent',
+ permission_keys: permissionKeys,
role: 'Shared roster agent',
}}
portalContainerRef={portalContainerRef}
@@ -62,10 +61,6 @@ function renderInlineRosterField() {
}
describe('AgentRosterField', () => {
- beforeEach(() => {
- permission.canManageAgents = true
- })
-
it('shows Make Copy in the roster detail panel', async () => {
const user = userEvent.setup()
renderDetailRosterField()
@@ -79,18 +74,17 @@ describe('AgentRosterField', () => {
).toBeInTheDocument()
})
- it('keeps Make Copy available when the user cannot manage agents', async () => {
- permission.canManageAgents = false
+ it('does not offer editing for a preview-only Agent', async () => {
const user = userEvent.setup()
- renderDetailRosterField()
+ renderDetailRosterField(['agent.acl.preview'])
await user.click(
screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ }),
)
expect(
- await screen.findByRole('button', { name: 'workflow.nodes.agent.roster.makeCopy' }),
- ).toBeInTheDocument()
+ screen.queryByRole('link', { name: 'workflow.nodes.agent.roster.editInConsole' }),
+ ).not.toBeInTheDocument()
})
it('returns focus to the inline setup trigger when the dialog closes with Escape', async () => {
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/edit-in-console-link.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/edit-in-console-link.spec.tsx
index a50d2abc3a6..f9a6d180df0 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/edit-in-console-link.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/edit-in-console-link.spec.tsx
@@ -1,57 +1,17 @@
import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
import { EditInConsoleLink } from '../edit-in-console-link'
-const systemFeatures = vi.hoisted(() => ({ rbacEnabled: false }))
-
-vi.mock('@tanstack/react-query', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-query')>()
-
- return {
- ...actual,
- useSuspenseQuery: () => ({ data: { rbac_enabled: systemFeatures.rbacEnabled } }),
- }
-})
-
describe('EditInConsoleLink', () => {
- beforeEach(() => {
- systemFeatures.rbacEnabled = false
- })
-
- it('renders a link to the agent console when permitted', () => {
- render(<EditInConsoleLink agentId="agent-1" canManageAgents />)
+ it('renders a link to the agent console without a workspace preview gate', () => {
+ render(<EditInConsoleLink agentId="agent-1" />)
const link = screen.getByRole('link', { name: /editInConsole/ })
- expect(link).toHaveAttribute('href', expect.stringContaining('/agents/agent-1'))
- })
-
- it('explains the role requirement when editing is not permitted', async () => {
- const user = userEvent.setup()
- render(<EditInConsoleLink agentId="agent-1" canManageAgents={false} />)
-
- expect(screen.queryByRole('link')).not.toBeInTheDocument()
- const button = screen.getByRole('button', { name: /editInConsole/ })
- expect(button).toHaveAttribute('aria-disabled', 'true')
-
- await user.hover(button)
- expect(
- await screen.findByText('workflow.nodes.agent.roster.editInConsoleDisabled', {
- selector: '[data-open]',
- }),
- ).toBeVisible()
- })
-
- it('includes the Manage Agents permission in the RBAC explanation', async () => {
- const user = userEvent.setup()
- systemFeatures.rbacEnabled = true
- render(<EditInConsoleLink agentId="agent-1" canManageAgents={false} />)
-
- await user.hover(screen.getByRole('button', { name: /editInConsole/ }))
-
- expect(
- await screen.findByText('workflow.nodes.agent.roster.editInConsoleDisabledRbac', {
- selector: '[data-open]',
- }),
- ).toBeVisible()
+ expect(link).toHaveAttribute('href', '/agents/agent-1/configure')
+ expect(screen.getByText('workflow.nodes.agent.roster.editInConsole')).toHaveAttribute(
+ 'title',
+ 'workflow.nodes.agent.roster.editInConsole',
+ )
+ expect(link).toHaveAttribute('target', '_blank')
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer')
})
})
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
index 6f068bc216d..dbf79e57b25 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
@@ -70,7 +70,7 @@ import {
trackAgentPreviewModeRun,
useInlineAgentScope,
} from '@/features/agent-v2/analytics'
-import { useCanManageAgents } from '@/features/agent-v2/permissions'
+import { useCanCreateAgents } from '@/features/agent-v2/permissions'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { consoleQuery } from '@/service/console'
import { FlowType } from '@/types/common'
@@ -827,9 +827,9 @@ function WorkflowInlineAgentConfigureMoreAction({
onSaveInlineToRoster: () => void
}) {
const { t } = useTranslation('common')
- const canManageAgents = useCanManageAgents()
+ const canCreateAgents = useCanCreateAgents()
- if (!canManageAgents) return null
+ if (!canCreateAgents) return null
return (
<DropdownMenu modal={false}>
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx
index f64c093fc49..5e8a20d0814 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx
@@ -31,7 +31,8 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import { AgentSelectorContent } from '@/app/components/workflow/block-selector/agent-selector'
-import { useCanManageAgents } from '@/features/agent-v2/permissions'
+import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
+import { useCanCreateAgents } from '@/features/agent-v2/permissions'
import { EditInConsoleLink } from './edit-in-console-link'
const i18nPrefix = 'nodes.agent'
@@ -44,6 +45,7 @@ type AgentRosterDisplayData = {
icon_type?: string | null
id: string
name: string
+ permission_keys?: string[]
role?: string | null
}
@@ -122,7 +124,7 @@ function AgentRosterDrawer({
onClose: () => void
}) {
const { t } = useTranslation()
- const canManageAgents = useCanManageAgents()
+ const canCreateAgents = useCanCreateAgents()
const isSetup = mode === 'setup'
const title = isInlineSetup
? t(($) => $[`${i18nPrefix}.roster.inlineSetup.name`], { ns: 'workflow' })
@@ -130,7 +132,8 @@ function AgentRosterDrawer({
const description = isSetup
? t(($) => $[`${i18nPrefix}.roster.inlineSetup.description`], { ns: 'workflow' })
: agent.role
- const showInlineActions = isInlineSetup && !!onSaveInlineToRoster && canManageAgents
+ const canConfigureAgent = getAgentACLCapabilities(agent.permission_keys).canConfigure
+ const showInlineActions = isInlineSetup && !!onSaveInlineToRoster && canCreateAgents
return (
<Drawer
@@ -251,8 +254,8 @@ function AgentRosterDrawer({
</div>
{!isSetup && showDetailActions && (
<div className="flex h-8 gap-2 pl-1">
- {showConsoleLink && (
- <EditInConsoleLink agentId={agent.id} canManageAgents={canManageAgents} />
+ {showConsoleLink && canConfigureAgent && (
+ <EditInConsoleLink agentId={agent.id} />
)}
<Button
variant="secondary"
diff --git a/web/app/components/workflow/nodes/agent-v2/components/edit-in-console-link.tsx b/web/app/components/workflow/nodes/agent-v2/components/edit-in-console-link.tsx
index 560b674a467..f7a1b07b719 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/edit-in-console-link.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/edit-in-console-link.tsx
@@ -1,66 +1,26 @@
-'use client'
-
-import { Button, buttonVariants } from '@langgenius/dify-ui/button'
+import { buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { getAgentDetailPath } from '@/features/agent-v2/agent-detail/routes'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import Link from '@/next/link'
const layoutClassName = 'min-w-0 flex-1 px-3'
-export function EditInConsoleLink({
- agentId,
- canManageAgents,
-}: {
- agentId: string
- canManageAgents: boolean
-}) {
+export function EditInConsoleLink({ agentId }: { agentId: string }) {
const { t } = useTranslation()
- const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const label = t(($) => $['nodes.agent.roster.editInConsole'], { ns: 'workflow' })
- const disabledMessage = t(
- ($) =>
- $[
- systemFeatures.rbac_enabled
- ? 'nodes.agent.roster.editInConsoleDisabledRbac'
- : 'nodes.agent.roster.editInConsoleDisabled'
- ],
- { ns: 'workflow' },
- )
-
- const content = (
- <>
- <span aria-hidden className="i-ri-external-link-line size-4 shrink-0" />
- <span className="truncate">{label}</span>
- </>
- )
-
- if (canManageAgents) {
- return (
- <Link
- className={cn(buttonVariants(), layoutClassName)}
- href={getAgentDetailPath(agentId, 'configure')}
- target="_blank"
- rel="noopener noreferrer"
- >
- {content}
- </Link>
- )
- }
return (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button className={layoutClassName} disabled focusableWhenDisabled>
- {content}
- </Button>
- }
- />
- <TooltipContent>{disabledMessage}</TooltipContent>
- </Tooltip>
+ <Link
+ className={cn(buttonVariants(), layoutClassName)}
+ href={getAgentDetailPath(agentId, 'configure')}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <span aria-hidden className="i-ri-external-link-line size-4 shrink-0" />
+ <span className="truncate" title={label}>
+ {label}
+ </span>
+ </Link>
)
}
diff --git a/web/context/permission-state.ts b/web/context/permission-state.ts
index 5fd54aabc4e..c96eb49056b 100644
--- a/web/context/permission-state.ts
+++ b/web/context/permission-state.ts
@@ -20,6 +20,10 @@ export const datasetDefaultPermissionKeysAtom = atom((get) => {
return get(workspacePermissionKeysQueryAtom).data?.dataset?.default_permission_keys ?? []
})
+export const agentDefaultPermissionKeysAtom = atom((get) => {
+ return get(workspacePermissionKeysQueryAtom).data?.agent?.default_permission_keys ?? []
+})
+
export const workspacePermissionKeysLoadingAtom = atom((get) => {
return get(workspacePermissionKeysQueryAtom).isPending
})
diff --git a/web/features/agent-v2/__tests__/permissions.spec.tsx b/web/features/agent-v2/__tests__/permissions.spec.tsx
index e9d57067d5e..d872e06efbe 100644
--- a/web/features/agent-v2/__tests__/permissions.spec.tsx
+++ b/web/features/agent-v2/__tests__/permissions.spec.tsx
@@ -1,23 +1,45 @@
-import { render, screen } from '@testing-library/react'
+import { renderHook } from '@testing-library/react'
+import { consoleQuery } from '@/service/console'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
-import { useCanManageAgents } from '../permissions'
+import { AgentPermission, getAgentACLCapabilities } from '../acl'
+import { useCanCreateAgents, useCanImportAgents } from '../permissions'
-function PermissionProbe() {
- return <span>{String(useCanManageAgents())}</span>
-}
+describe('Agent creation and DSL import permissions', () => {
+ it('does not let legacy manage or preview grant creation', () => {
+ const { wrapper } = createConsoleQueryWrapper({
+ workspacePermissionKeys: ['agent.manage', AgentPermission.Preview],
+ })
+ const { result } = renderHook(() => useCanCreateAgents(), { wrapper })
+ expect(result.current).toBe(false)
+ })
-describe('useCanManageAgents', () => {
- it.each([
- [['agent.acl.preview'], 'true'],
- [['dataset.create_and_management'], 'false'],
- ])(
- 'resolves agent.acl.preview from the current permission snapshot',
- (permissionKeys, expected) => {
- const { wrapper } = createConsoleQueryWrapper({ workspacePermissionKeys: permissionKeys })
-
- render(<PermissionProbe />, { wrapper })
-
- expect(screen.getByText(expected)).toBeInTheDocument()
+ it.each([true, false])(
+ 'uses default Agent ACL for import independently of create: %s',
+ (canImport) => {
+ const { wrapper, queryClient } = createConsoleQueryWrapper({
+ workspacePermissionKeys: [AgentPermission.Create],
+ })
+ const key = consoleQuery.workspaces.current.rbac.myPermissions.get.queryKey()
+ queryClient.setQueryData(key, {
+ ...queryClient.getQueryData(key),
+ agent: {
+ default_permission_keys: canImport ? [AgentPermission.ImportExportDSL] : [],
+ overrides: [],
+ },
+ })
+ const { result } = renderHook(
+ () => ({ canCreate: useCanCreateAgents(), canImport: useCanImportAgents() }),
+ { wrapper },
+ )
+ expect(result.current).toEqual({ canCreate: true, canImport })
},
)
+
+ it('requires both edit and run for Build mode', () => {
+ expect(getAgentACLCapabilities([AgentPermission.Edit]).canBuild).toBe(false)
+ expect(getAgentACLCapabilities([AgentPermission.TestAndRun]).canBuild).toBe(false)
+ expect(
+ getAgentACLCapabilities([AgentPermission.Edit, AgentPermission.TestAndRun]).canBuild,
+ ).toBe(true)
+ })
})
diff --git a/web/features/agent-v2/acl.ts b/web/features/agent-v2/acl.ts
new file mode 100644
index 00000000000..4a762c2164b
--- /dev/null
+++ b/web/features/agent-v2/acl.ts
@@ -0,0 +1,57 @@
+import { hasPermission } from '@/utils/permission'
+
+export const AgentPermission = {
+ Create: 'agent.create',
+ Preview: 'agent.acl.preview',
+ Edit: 'agent.acl.edit',
+ TestAndRun: 'agent.acl.test_and_run',
+ ReleaseAndVersion: 'agent.acl.release_and_version',
+ AccessPointView: 'agent.acl.access_point_view',
+ AccessPointManage: 'agent.acl.access_point_manage',
+ LogManage: 'agent.acl.log_manage',
+ Monitor: 'agent.acl.monitor',
+ AccessConfig: 'agent.acl.access_config',
+ ImportExportDSL: 'agent.acl.import_export_dsl',
+ Delete: 'agent.acl.delete',
+} as const
+
+export function getAgentACLCapabilities(permissionKeys: readonly string[] | undefined) {
+ const canEdit = hasPermission(permissionKeys, AgentPermission.Edit)
+ const canTestAndRun = hasPermission(permissionKeys, AgentPermission.TestAndRun)
+ const canReleaseAndVersion = hasPermission(permissionKeys, AgentPermission.ReleaseAndVersion)
+
+ return {
+ canPreview: hasPermission(permissionKeys, AgentPermission.Preview),
+ canEdit,
+ canTestAndRun,
+ canBuild: canEdit && canTestAndRun,
+ canReleaseAndVersion,
+ canConfigure: canEdit || canTestAndRun || canReleaseAndVersion,
+ canViewAccessPoint: hasPermission(permissionKeys, AgentPermission.AccessPointView),
+ canManageAccessPoint: hasPermission(permissionKeys, AgentPermission.AccessPointManage),
+ canManageLogs: hasPermission(permissionKeys, AgentPermission.LogManage),
+ canMonitor: hasPermission(permissionKeys, AgentPermission.Monitor),
+ canAccessConfig: hasPermission(permissionKeys, AgentPermission.AccessConfig),
+ canImportExportDSL: hasPermission(permissionKeys, AgentPermission.ImportExportDSL),
+ canDelete: hasPermission(permissionKeys, AgentPermission.Delete),
+ }
+}
+
+export function getAgentDefaultSection(capabilities: ReturnType<typeof getAgentACLCapabilities>) {
+ if (capabilities.canConfigure) return 'configure'
+ if (capabilities.canViewAccessPoint) return 'access'
+ if (capabilities.canManageLogs) return 'logs'
+ if (capabilities.canMonitor) return 'monitoring'
+ if (capabilities.canAccessConfig) return 'access-config'
+ return undefined
+}
+
+export function getAgentSectionAccess(capabilities: ReturnType<typeof getAgentACLCapabilities>) {
+ return {
+ configure: capabilities.canConfigure,
+ access: capabilities.canViewAccessPoint,
+ logs: capabilities.canManageLogs,
+ monitoring: capabilities.canMonitor,
+ 'access-config': capabilities.canAccessConfig,
+ }
+}
diff --git a/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx b/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx
index 63fd96c2c78..6215125739a 100644
--- a/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx
+++ b/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx
@@ -1,106 +1,100 @@
-import { render, screen, waitFor } from '@testing-library/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
+import { AgentPermission } from '@/features/agent-v2/acl'
import useDocumentTitle from '@/hooks/use-document-title'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createAgentFixture } from '@/test/fixtures/agent'
import { AgentDetailLayout } from '../layout'
-const mockReplace = vi.hoisted(() => vi.fn())
-const mockPathname = vi.hoisted(() => ({ value: '/agents/agent-1/configure' }))
-const mockAgentQuery = vi.hoisted(() => ({
- data: {
- name: 'Agent',
- } as { name: string } | undefined,
- error: null as unknown,
-}))
-
-vi.mock('@tanstack/react-query', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-query')>()
- return {
- ...actual,
- useQuery: vi.fn(() => mockAgentQuery),
- }
-})
-
+const router = vi.hoisted(() => ({ replace: vi.fn() }))
+const location = vi.hoisted(() => ({ pathname: '/agents/agent-1/configure' }))
vi.mock('@/next/navigation', () => ({
- usePathname: () => mockPathname.value,
- useRouter: () => ({
- back: vi.fn(),
- forward: vi.fn(),
- refresh: vi.fn(),
- push: vi.fn(),
- replace: mockReplace,
- prefetch: vi.fn(),
- }),
+ usePathname: () => location.pathname,
+ useRouter: () => router,
}))
+vi.mock('@/hooks/use-document-title', () => ({ default: vi.fn() }))
-vi.mock('@/hooks/use-document-title', () => ({
- default: vi.fn(),
-}))
+const detailKey = consoleQuery.agent.byAgentId.get.queryKey({
+ input: { params: { agent_id: 'agent-1' } },
+})
-const mockUseDocumentTitle = vi.mocked(useDocumentTitle)
+function setup(permissionKeys = createAgentFixture().permission_keys, rbacEnabled = true) {
+ const { wrapper, queryClient } = createConsoleQueryWrapper({
+ systemFeatures: { rbac_enabled: rbacEnabled },
+ })
+ queryClient.setQueryData(detailKey, createAgentFixture({ permission_keys: permissionKeys }))
+ return { wrapper, queryClient }
+}
-vi.mock('@/service/console', () => ({
- consoleQuery: {
- agent: {
- byAgentId: {
- get: {
- queryOptions: vi.fn((input) => input),
- },
- },
- },
- },
-}))
+const content = (
+ <AgentDetailLayout agentId="agent-1">
+ <div>Agent detail content</div>
+ </AgentDetailLayout>
+)
describe('AgentDetailLayout', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockAgentQuery.data = {
- name: 'Agent',
- }
- mockAgentQuery.error = null
- mockPathname.value = '/agents/agent-1/configure'
+ location.pathname = '/agents/agent-1/configure'
})
- it.each([
- ['configure', 'agentV2.agentDetail.sections.configure'],
- ['access', 'agentV2.agentDetail.sections.access'],
- ['logs', 'agentV2.agentDetail.sections.logs'],
- ['monitoring', 'agentV2.agentDetail.sections.monitoring'],
- ])('identifies the %s section in the document title', (section, sectionTitle) => {
- mockPathname.value = `/agents/agent-1/${section}`
+ it.each(['configure', 'access', 'logs', 'monitoring', 'access-config'])(
+ 'renders the authorized %s page and its document title',
+ (section) => {
+ location.pathname = `/agents/agent-1/${section}`
+ render(content, setup())
+ expect(screen.getByText('Agent detail content')).toBeInTheDocument()
+ expect(useDocumentTitle).toHaveBeenLastCalledWith(
+ `agentV2.agentDetail.sections.${section} · Agent`,
+ )
+ expect(screen.queryByRole('complementary')).not.toBeInTheDocument()
+ },
+ )
- render(
- <AgentDetailLayout agentId="agent-1">
- <div>Agent detail content</div>
- </AgentDetailLayout>,
- )
+ it.each(['configure', 'logs', 'monitoring', 'access-config'])(
+ 'blocks direct navigation to %s for a viewer',
+ async (section) => {
+ location.pathname = `/agents/agent-1/${section}`
+ render(content, setup([AgentPermission.Preview, AgentPermission.AccessPointView]))
+ expect(screen.queryByText('Agent detail content')).not.toBeInTheDocument()
+ await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/agents/agent-1/access'))
+ },
+ )
- expect(mockUseDocumentTitle).toHaveBeenLastCalledWith(`${sectionTitle} · Agent`)
+ it('unmounts protected content when resource permissions are revoked', async () => {
+ const { wrapper, queryClient } = setup()
+ render(content, { wrapper })
+ act(() => {
+ queryClient.setQueryData(detailKey, createAgentFixture({ permission_keys: [] }))
+ })
+ await waitFor(() => expect(screen.queryByText('Agent detail content')).not.toBeInTheDocument())
+ expect(router.replace).toHaveBeenCalledWith('/agents')
})
- it('should render detail content without owning navigation landmarks', () => {
- render(
- <AgentDetailLayout agentId="agent-1">
- <div>Agent detail content</div>
- </AgentDetailLayout>,
- )
-
- expect(screen.getByText('Agent detail content')).toBeInTheDocument()
- expect(screen.queryByRole('main')).not.toBeInTheDocument()
- expect(screen.queryByRole('complementary', { name: 'Detail sidebar' })).not.toBeInTheDocument()
+ it('hides ACL management when RBAC is disabled', async () => {
+ location.pathname = '/agents/agent-1/access-config'
+ render(content, setup(undefined, false))
+ expect(screen.queryByText('Agent detail content')).not.toBeInTheDocument()
+ await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/agents/agent-1/configure'))
})
- it('should redirect to roster when agent detail returns 404', async () => {
- mockAgentQuery.data = undefined
- mockAgentQuery.error = new Response(null, { status: 404 })
-
- render(
- <AgentDetailLayout agentId="missing-agent">
- <div>Agent detail content</div>
- </AgentDetailLayout>,
- )
-
- await waitFor(() => {
- expect(mockReplace).toHaveBeenCalledWith('/agents')
- })
+ it('redirects to the roster when the agent no longer exists', async () => {
+ const { wrapper, queryClient } = setup()
+ queryClient.setDefaultOptions({ queries: { retry: false, retryOnMount: false } })
+ queryClient
+ .getQueryCache()
+ .find({ queryKey: detailKey })!
+ .setState({
+ data: undefined,
+ error: Object.assign(new Response(null, { status: 404 }), {
+ name: 'NotFound',
+ message: 'Not found',
+ }),
+ status: 'error',
+ fetchStatus: 'idle',
+ })
+ render(content, { wrapper })
+ await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/agents'))
expect(screen.queryByText('Agent detail content')).not.toBeInTheDocument()
})
})
diff --git a/web/features/agent-v2/agent-detail/__tests__/navigation.spec.tsx b/web/features/agent-v2/agent-detail/__tests__/navigation.spec.tsx
index 8751a2ccf45..78ed7e211ed 100644
--- a/web/features/agent-v2/agent-detail/__tests__/navigation.spec.tsx
+++ b/web/features/agent-v2/agent-detail/__tests__/navigation.spec.tsx
@@ -2,6 +2,7 @@ import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/t
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { AgentPermission } from '@/features/agent-v2/acl'
import { AgentDetailSection, AgentDetailTop } from '../navigation'
const mocks = vi.hoisted(() => ({
@@ -12,6 +13,14 @@ const mocks = vi.hoisted(() => ({
replace: vi.fn(),
}))
+vi.mock('@/features/agent-v2/permissions', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/features/agent-v2/permissions')>()),
+ useCanCreateAgents: () => true,
+}))
+vi.mock('@/features/system-features/client', () => ({
+ systemFeaturesQueryOptions: () => ({ queryKey: ['system-features'] }),
+}))
+
vi.mock('@/app/components/app/use-export-app-dsl', () => ({
useExportAppDsl: () => ({
exportAppDsl: mocks.exportAppDsl,
@@ -24,6 +33,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {
return {
...actual,
+ useSuspenseQuery: () => ({ data: { rbac_enabled: true } }),
useQuery: () => ({
data: mocks.queryData,
isPending: !mocks.queryData,
@@ -81,6 +91,7 @@ vi.mock('@/service/console', () => ({
}))
const createAgent = (overrides: Partial<AgentAppDetailWithSite> = {}): AgentAppDetailWithSite => ({
+ permission_keys: Object.values(AgentPermission),
app_id: 'app-1',
description: 'Find and summarize market materials.',
enable_api: true,
diff --git a/web/features/agent-v2/agent-detail/access-config/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/access-config/__tests__/page.spec.tsx
new file mode 100644
index 00000000000..aa596bdafaf
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access-config/__tests__/page.spec.tsx
@@ -0,0 +1,250 @@
+import { zResourceUserAccessPolicies } from '@dify/contracts/api/console/workspaces/zod.gen'
+import { act, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { AgentPermission } from '@/features/agent-v2/acl'
+import { RESOURCE_ACCESS_SETTINGS_PAGE_SIZE } from '@/service/access-control/constants'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createAccessPolicyFixture } from '@/test/fixtures/access-policy'
+import { createAgentFixture } from '@/test/fixtures/agent'
+import { AgentAccessConfigPage } from '../page'
+
+const request = vi.hoisted(() => vi.fn())
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request,
+}))
+
+const resource = consoleQuery.workspaces.current.rbac.agents.byAgentId
+const params = { agent_id: 'agent-1' }
+const policy = createAccessPolicyFixture()
+const sent: Request[] = []
+const createUser = (id: string, name: string, policies = [policy]) =>
+ zResourceUserAccessPolicies.parse({
+ account: { account_id: id, account_name: name, email: `${id}@example.com` },
+ access_policies: policies,
+ roles: [],
+ })
+
+function setup({
+ automatic = false,
+ users = [createUser('evan', 'Evan')],
+ permissions = [AgentPermission.AccessConfig] as string[],
+} = {}) {
+ const { wrapper, queryClient } = createConsoleQueryWrapper({
+ systemFeatures: { rbac_enabled: true },
+ })
+ const detailKey = consoleQuery.agent.byAgentId.get.queryKey({ input: { params } })
+ queryClient.setQueryData(detailKey, createAgentFixture({ permission_keys: permissions }))
+ const state = { automatic, users, failUsers: false }
+ const userPage = (page = 1, size: number = RESOURCE_ACCESS_SETTINGS_PAGE_SIZE) => ({
+ data: state.users.slice((page - 1) * size, page * size),
+ pagination: {
+ current_page: page,
+ per_page: size,
+ total_count: state.users.length,
+ total_pages: Math.ceil(state.users.length / size),
+ },
+ })
+ queryClient.setQueryData(
+ resource.accessPolicy.get.queryKey({ input: { params, query: { language: 'en' } } }),
+ { agent_id: 'agent-1', items: [{ policy, roles: [], accounts: [] }] },
+ )
+ queryClient.setQueryData(
+ resource.userAccessPolicies.get.queryKey({
+ input: {
+ params,
+ query: { language: 'en', page: 1, limit: RESOURCE_ACCESS_SETTINGS_PAGE_SIZE },
+ },
+ }),
+ userPage(),
+ )
+ queryClient.setQueryData(resource.whitelist.get.queryKey({ input: { params } }), {
+ account_ids: users.map((user) => user.account.account_id),
+ })
+ queryClient.setQueryData(resource.whitelistConfig.get.queryKey({ input: { params } }), {
+ automatic_include_workspace_members: automatic,
+ })
+ request.mockImplementation(
+ async (_url: string, _init: RequestInit, options: { request: Request }) => {
+ const req = options.request
+ sent.push(req.clone())
+ const url = new URL(req.url)
+ if (req.method === 'GET') {
+ if (url.pathname.endsWith('/user-access-policies')) {
+ if (state.failUsers) return Response.json({ message: 'Unavailable' }, { status: 500 })
+ return Response.json(
+ userPage(Number(url.searchParams.get('page')), Number(url.searchParams.get('limit'))),
+ )
+ }
+ if (url.pathname.endsWith('/whitelist_config'))
+ return Response.json({ automatic_include_workspace_members: state.automatic })
+ if (url.pathname.endsWith('/whitelist'))
+ return Response.json({ account_ids: state.users.map((user) => user.account.account_id) })
+ if (url.pathname.endsWith('/access-policy')) return Response.json({ items: [{ policy }] })
+ if (url.pathname.endsWith('/members'))
+ return Response.json({
+ accounts: [
+ {
+ id: 'mia',
+ name: 'Mia',
+ email: '[email protected]',
+ role: 'normal',
+ status: 'active',
+ },
+ ],
+ })
+ if (url.pathname.endsWith('/agent/agent-1'))
+ return Response.json(createAgentFixture({ permission_keys: permissions }))
+ }
+ if (req.method === 'PUT' && url.pathname.endsWith('/whitelist')) {
+ const body = await req.json()
+ state.automatic = body.automatic_include_workspace_members
+ return Response.json({ account_ids: state.users.map((user) => user.account.account_id) })
+ }
+ if (req.method === 'PUT' && url.pathname.endsWith('/access-policies')) {
+ const body = await req.json()
+ const id = url.pathname.split('/users/')[1]!.split('/')[0]!
+ const policies = body.access_policy_ids.includes(policy.id) ? [policy] : []
+ state.users = [
+ ...state.users.filter((user) => user.account.account_id !== id),
+ createUser(id, id === 'mia' ? 'Mia' : 'Evan', policies),
+ ]
+ return Response.json({ access_policies: policies })
+ }
+ if (req.method === 'DELETE') {
+ const body = await req.json()
+ state.users = state.users.filter(
+ (user) => !body.account_ids.includes(user.account.account_id),
+ )
+ return Response.json({ result: 'success' })
+ }
+ throw new Error(`Unexpected request ${req.method} ${url.pathname}`)
+ },
+ )
+ return {
+ ...render(<AgentAccessConfigPage agentId="agent-1" />, { wrapper }),
+ queryClient,
+ detailKey,
+ state,
+ }
+}
+
+const inclusionSwitch = () =>
+ screen.getByRole('switch', { name: 'permission.accessRule.automaticallyIncludeWorkspaceMembers' })
+
+describe('AgentAccessConfigPage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ sent.length = 0
+ })
+
+ it('uses the server inclusion setting and disables adding or removing automatic members', () => {
+ setup({ automatic: true })
+ expect(inclusionSwitch()).toHaveAttribute('aria-checked', 'true')
+ expect(screen.getByRole('button', { name: 'common.operation.add' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'common.operation.remove' })).toBeDisabled()
+ expect(screen.getByRole('combobox')).toBeEnabled()
+ expect(request).not.toHaveBeenCalled()
+ })
+
+ it('updates automatic inclusion and refreshes resource permissions', async () => {
+ const { queryClient, detailKey } = setup()
+ const invalidate = vi.spyOn(queryClient, 'invalidateQueries')
+ await userEvent.click(inclusionSwitch())
+ await waitFor(() => expect(inclusionSwitch()).toHaveAttribute('aria-checked', 'true'))
+ await waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: detailKey }))
+ const mutation = sent.find((req) => req.method === 'PUT')!
+ expect(new URL(mutation.url).pathname).toMatch(/\/agents\/agent-1\/whitelist$/)
+ expect(await mutation.json()).toEqual({ automatic_include_workspace_members: true })
+ })
+
+ it('adds a workspace member with the default permission set', async () => {
+ setup()
+ await userEvent.click(screen.getByRole('button', { name: 'common.operation.add' }))
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: 'permission.accessRule.addMemberAria:{"name":"Mia"}',
+ }),
+ )
+ await waitFor(() => expect(screen.getByRole('row', { name: /Mia/ })).toBeInTheDocument())
+ const mutation = sent.find((req) => req.method === 'PUT')!
+ expect(new URL(mutation.url).pathname).toMatch(/\/users\/mia\/access-policies$/)
+ expect(await mutation.json()).toEqual({ access_policy_ids: ['default'] })
+ })
+
+ it('updates a member policy using the selected policy id', async () => {
+ setup({ users: [createUser('evan', 'Evan', [])] })
+ await userEvent.click(screen.getByRole('combobox'))
+ await userEvent.click(screen.getByRole('option', { name: policy.name }))
+ await waitFor(() => expect(sent.some((req) => req.method === 'PUT')).toBe(true))
+ expect(await sent.find((req) => req.method === 'PUT')!.json()).toEqual({
+ access_policy_ids: [policy.id],
+ })
+ })
+
+ it('batch removes members by their policy bindings', async () => {
+ setup({ users: [createUser('evan', 'Evan'), createUser('mia', 'Mia', [])] })
+ await userEvent.click(screen.getByRole('checkbox', { name: 'common.operation.selectAll' }))
+ await userEvent.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ await userEvent.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: 'common.operation.sure',
+ }),
+ )
+ await waitFor(() =>
+ expect(screen.getByText('permission.accessRule.noUserAccessSettings')).toBeInTheDocument(),
+ )
+ const removals = sent.filter((req) => req.method === 'DELETE')
+ expect(removals.map((req) => new URL(req.url).pathname)).toEqual([
+ `/console/api/workspaces/current/rbac/agents/agent-1/access-policies/${policy.id}/member-bindings`,
+ '/console/api/workspaces/current/rbac/agents/agent-1/access-policies/default/member-bindings',
+ ])
+ expect(await Promise.all(removals.map((req) => req.json()))).toEqual([
+ { account_ids: ['evan'] },
+ { account_ids: ['mia'] },
+ ])
+ })
+
+ it('returns to the previous page after removing its last member', async () => {
+ const users = Array.from({ length: RESOURCE_ACCESS_SETTINGS_PAGE_SIZE + 1 }, (_, i) =>
+ createUser(`user-${i}`, `Member ${i}`),
+ )
+ setup({ users })
+ await userEvent.click(screen.getByRole('button', { name: 'common.pagination.next' }))
+ const lastRow = await screen.findByRole('row', {
+ name: new RegExp(`Member ${RESOURCE_ACCESS_SETTINGS_PAGE_SIZE}`),
+ })
+ await userEvent.click(within(lastRow).getByRole('button', { name: 'common.operation.remove' }))
+ await screen.findByRole('row', { name: /Member 0/ })
+ expect(screen.getByRole('button', { name: 'common.pagination.previous' })).toBeDisabled()
+ })
+
+ it('shows a retry action when member pagination fails', async () => {
+ const { state } = setup({
+ users: Array.from({ length: RESOURCE_ACCESS_SETTINGS_PAGE_SIZE + 1 }, (_, i) =>
+ createUser(`user-${i}`, `Member ${i}`),
+ ),
+ })
+ state.failUsers = true
+ await userEvent.click(screen.getByRole('button', { name: 'common.pagination.next' }))
+ await screen.findByRole('alert')
+ state.failUsers = false
+ await userEvent.click(screen.getByRole('button', { name: 'common.operation.retry' }))
+ await screen.findByRole('row', {
+ name: new RegExp(`Member ${RESOURCE_ACCESS_SETTINGS_PAGE_SIZE}`),
+ })
+ })
+
+ it('removes management UI when access_config is revoked', async () => {
+ const { queryClient, detailKey } = setup()
+ act(() => {
+ queryClient.setQueryData(
+ detailKey,
+ createAgentFixture({ permission_keys: [AgentPermission.Preview] }),
+ )
+ })
+ await waitFor(() => expect(screen.queryByRole('table')).not.toBeInTheDocument())
+ expect(request).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/access-config/page.tsx b/web/features/agent-v2/agent-detail/access-config/page.tsx
new file mode 100644
index 00000000000..1b5449bd3d6
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access-config/page.tsx
@@ -0,0 +1,174 @@
+'use client'
+
+import type { AccessPolicyMemberBindingRemoval } from '@/app/components/access-rules-editor'
+import { Button } from '@langgenius/dify-ui/button'
+import { keepPreviousData, useMutation, useQuery } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import AccessRulesEditor from '@/app/components/access-rules-editor'
+import { useLocale } from '@/context/i18n'
+import { useAgentPermissions } from '@/features/agent-v2/permissions'
+import { getAccessControlTemplateLanguage } from '@/i18n-config/language'
+import { RESOURCE_ACCESS_SETTINGS_PAGE_SIZE } from '@/service/access-control/constants'
+import { consoleQuery } from '@/service/console'
+
+export function AgentAccessConfigPage({ agentId }: { agentId: string }) {
+ const { t } = useTranslation()
+ const language = getAccessControlTemplateLanguage(useLocale())
+ const { agentQuery, canAccessConfig } = useAgentPermissions(agentId)
+ const [page, setPage] = useState(1)
+ const [pageSize, setPageSize] = useState<number>(RESOURCE_ACCESS_SETTINGS_PAGE_SIZE)
+ const [updatingAccountId, setUpdatingAccountId] = useState<string | null>(null)
+ const [isRemoving, setIsRemoving] = useState(false)
+ const resource = consoleQuery.workspaces.current.rbac.agents.byAgentId
+ const params = { agent_id: agentId }
+ const rules = useQuery(
+ resource.accessPolicy.get.queryOptions({
+ input: { params, query: { language } },
+ enabled: canAccessConfig,
+ }),
+ )
+ const users = useQuery(
+ resource.userAccessPolicies.get.queryOptions({
+ input: { params, query: { language, page, limit: pageSize } },
+ enabled: canAccessConfig,
+ placeholderData: keepPreviousData,
+ }),
+ )
+ const whitelist = useQuery(
+ resource.whitelist.get.queryOptions({ input: { params }, enabled: canAccessConfig }),
+ )
+ const config = useQuery(
+ resource.whitelistConfig.get.queryOptions({ input: { params }, enabled: canAccessConfig }),
+ )
+ const updateScope = useMutation(resource.whitelist.put.mutationOptions())
+ const updateUser = useMutation(
+ resource.users.byTargetAccountId.accessPolicies.put.mutationOptions(),
+ )
+ const removeMembers = useMutation(
+ resource.accessPolicies.byPolicyId.memberBindings.delete.mutationOptions(),
+ )
+ const automaticIncludeWorkspaceMembers = updateScope.isPending
+ ? updateScope.variables.body.automatic_include_workspace_members
+ : config.data?.automatic_include_workspace_members
+ const pagination = users.data?.pagination
+ const totalPages = pagination?.total_pages ?? 0
+ const error = rules.error || users.error || whitelist.error || config.error
+ const isBusy = isRemoving || updateScope.isPending || updateUser.isPending
+ const canChangeMembership = canAccessConfig && automaticIncludeWorkspaceMembers === false
+
+ const changeUserPolicies = (accountId: string, accessPolicyIds: string[], isAdding = false) => {
+ if (!canAccessConfig || isBusy) return
+ setUpdatingAccountId(accountId)
+ updateUser.mutate(
+ {
+ params: { ...params, target_account_id: accountId },
+ body: { access_policy_ids: accessPolicyIds },
+ },
+ {
+ onSuccess: () => {
+ if (isAdding)
+ setPage(Math.max(1, Math.ceil(((pagination?.total_count ?? 0) + 1) / pageSize)))
+ },
+ onSettled: () => setUpdatingAccountId(null),
+ },
+ )
+ }
+
+ const removeBindings = async (removals: AccessPolicyMemberBindingRemoval[]) => {
+ if (!canChangeMembership || isBusy) return
+ setIsRemoving(true)
+ let removedCount = 0
+ try {
+ // Keep each successful removal visible even if a later policy group fails.
+ for (const { accessPolicyId, accountIds } of removals) {
+ await removeMembers.mutateAsync({
+ params: { ...params, policy_id: accessPolicyId },
+ body: { account_ids: accountIds },
+ })
+ removedCount += accountIds.length
+ }
+ } finally {
+ if (page > 1 && removedCount > 0 && removedCount >= (users.data?.data?.length ?? 0)) {
+ setPage((current) => (current === page ? page - 1 : current))
+ }
+ setIsRemoving(false)
+ }
+ }
+
+ if (!canAccessConfig) return null
+
+ return (
+ <div className="flex h-full min-h-0 flex-col overflow-hidden bg-background-default-subtle">
+ <header className="flex min-h-15.5 shrink-0 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.agentDescription'], { ns: 'permission' })}
+ </p>
+ </header>
+ <main className="flex min-h-0 w-full max-w-240 flex-1 flex-col px-6 pt-8 pb-10 sm:pr-20 sm:pl-12.5">
+ {error ? (
+ <div role="alert" className="flex items-center justify-center gap-3 py-8">
+ <span>{t(($) => $['api.actionFailed'], { ns: 'common' })}</span>
+ <Button
+ onClick={() => {
+ void Promise.all([
+ rules.refetch(),
+ users.refetch(),
+ whitelist.refetch(),
+ config.refetch(),
+ ])
+ }}
+ >
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ </div>
+ ) : (
+ <AccessRulesEditor
+ className="min-h-0 w-full flex-1"
+ rules={rules.data?.items ?? []}
+ userAccessSettings={users.data?.data ?? []}
+ isLoadingRules={rules.isPending || whitelist.isPending || config.isPending}
+ isLoadingUserAccessSettings={users.isPending}
+ automaticIncludeWorkspaceMembers={automaticIncludeWorkspaceMembers}
+ isUpdatingAutomaticIncludeWorkspaceMembers={updateScope.isPending}
+ existingAccountIds={whitelist.data?.account_ids ?? []}
+ currentPage={page}
+ pageSize={pageSize}
+ totalCount={pagination?.total_count}
+ totalPages={totalPages}
+ isChangingPage={users.isPlaceholderData || isBusy}
+ updatingAccountId={updatingAccountId}
+ maintainerId={agentQuery.data?.maintainer}
+ onAutomaticIncludeWorkspaceMembersChange={(checked) => {
+ if (!canAccessConfig || isBusy || config.isPending) return
+ setPage(1)
+ updateScope.mutate({ params, body: { automatic_include_workspace_members: checked } })
+ }}
+ onPageChange={setPage}
+ onPageSizeChange={(size) => {
+ setPage(1)
+ setPageSize(size)
+ }}
+ onUserAccessPoliciesChange={changeUserPolicies}
+ onAddAccessSubject={
+ canChangeMembership
+ ? (accountId, policies) => {
+ changeUserPolicies(accountId, policies, true)
+ }
+ : undefined
+ }
+ onRemoveAccessPolicyMemberBinding={(accountId, accessPolicyId) => {
+ void removeBindings([{ accessPolicyId, accountIds: [accountId] }]).catch(
+ () => undefined,
+ )
+ }}
+ onBatchRemoveAccessPolicyMemberBindings={removeBindings}
+ />
+ )}
+ </main>
+ </div>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
index 268e2fe87e9..c7ff7124249 100644
--- a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
@@ -9,6 +9,8 @@ import { QueryClient } from '@tanstack/react-query'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { AgentPermission } from '@/features/agent-v2/acl'
+import { consoleQuery } from '@/service/console'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { createQueryClientWrapper } from '@/test/console/query-client'
import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data'
@@ -151,6 +153,11 @@ vi.mock('@/service/console', () => ({
agent: {
byAgentId: {
get: {
+ queryOptions: ({ input }: { input: { params: { agent_id: string } } }) => ({
+ queryKey: ['agent-detail', input.params.agent_id],
+ queryFn: async () => createAgent(),
+ staleTime: Infinity,
+ }),
queryKey: ({ input }: { input: { params: { agent_id: string } } }) => [
'agent-detail',
input.params.agent_id,
@@ -205,6 +212,7 @@ vi.mock('@/service/console', () => ({
function createAgent(overrides: Partial<AgentAppDetailWithSite> = {}): AgentAppDetailWithSite {
return {
+ permission_keys: Object.values(AgentPermission),
access_ready: true,
enable_api: true,
enable_site: true,
@@ -308,6 +316,11 @@ function createConsoleQueryClient(webAppAuthEnabled = true) {
},
})
seedAccountProfileQuery(queryClient, { id: 'user-1' })
+ queryClient.setQueryData<AgentAppDetailWithSite>(
+ consoleQuery.agent.byAgentId.get.queryOptions({ input: { params: { agent_id: 'agent-1' } } })
+ .queryKey,
+ createAgent(),
+ )
seedFeatures(queryClient)
return queryClient
}
@@ -1027,7 +1040,7 @@ describe('Agent access surface cards', () => {
createAgent({
access_mode: 'private_all',
maintainer: 'user-2',
- permission_keys: ['app.acl.release_and_version'],
+ permission_keys: [AgentPermission.ReleaseAndVersion],
})
const organizationAccessLabel = 'app.accessControlDialog.accessItems.organization'
@@ -1087,7 +1100,7 @@ describe('Agent access surface cards', () => {
agent={createAgent({
access_mode: 'private_all',
maintainer: 'user-2',
- permission_keys: [],
+ permission_keys: [AgentPermission.AccessPointManage],
})}
agentId="agent-1"
isLoading={false}
@@ -1124,7 +1137,7 @@ describe('Agent access surface cards', () => {
app_id: 'source-app-1',
backing_app_id: 'backing-app-1',
maintainer: 'user-2',
- permission_keys: ['app.acl.release_and_version'],
+ permission_keys: [AgentPermission.ReleaseAndVersion],
})}
agentId="agent-1"
isLoading={false}
@@ -1140,4 +1153,86 @@ describe('Agent access surface cards', () => {
})
})
})
+ it('allows viewers to copy and open WebApp addresses while disabling management actions', async () => {
+ const user = userEvent.setup()
+ renderWithQueryClient(
+ <WebAppAccessCard
+ agent={createAgent({
+ permission_keys: [AgentPermission.Preview, AgentPermission.AccessPointView],
+ })}
+ agentId="agent-1"
+ isLoading={false}
+ />,
+ )
+ expect(
+ screen.getByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),
+ ).toHaveAttribute('href', 'https://chat.example.test/agent/site-token')
+ expect(
+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.copyAccessUrl' }),
+ ).toBeEnabled()
+ expect(
+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.showQrCode' }),
+ ).toBeEnabled()
+ for (const action of ['embedIntoSite', 'customFrontend', 'settings']) {
+ expect(
+ screen.getByRole('button', { name: `agentV2.agentDetail.access.webApp.actions.${action}` }),
+ ).toBeDisabled()
+ }
+ expect(
+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.refreshUrl' }),
+ ).toBeDisabled()
+ const toggle = screen.getByRole('switch')
+ await user.click(toggle)
+ expect(mocks.siteEnableMutation).not.toHaveBeenCalled()
+ expect(mocks.accessSubjectsQueryFn).not.toHaveBeenCalled()
+ })
+
+ it('allows API viewers to copy the endpoint and read documentation without fetching API keys', async () => {
+ const user = userEvent.setup()
+ mocks.apiAccessQueryFn.mockResolvedValue(createAgentApiAccessResponse())
+ const client = createConsoleQueryClient()
+ client.setQueryData(
+ ['agent-detail', 'agent-1'],
+ createAgent({ permission_keys: [AgentPermission.AccessPointView] }),
+ )
+ render(<ServiceApiAccessCard agentId="agent-1" />, {
+ wrapper: createAccessCardWrapper(client),
+ })
+ expect(
+ await screen.findByRole('button', { name: 'agentV2.agentDetail.access.copyServiceEndpoint' }),
+ ).toBeEnabled()
+ expect(
+ screen.getByRole('link', {
+ name: 'agentV2.agentDetail.access.serviceApi.actions.apiReference',
+ }),
+ ).toHaveAttribute('href', 'https://docs.example.test/api-reference/guides/agent')
+ const apiKeys = screen.getByRole('button', { name: /serviceApi.actions.apiKey/ })
+ expect(apiKeys).toBeDisabled()
+ await user.click(apiKeys)
+ await user.click(screen.getByRole('switch'))
+ expect(mocks.apiKeysQueryFn).not.toHaveBeenCalled()
+ expect(mocks.apiEnableMutation).not.toHaveBeenCalled()
+ })
+
+ it('closes the settings dialog when Agent access point management is revoked', async () => {
+ const user = userEvent.setup()
+ const queryClient = createConsoleQueryClient()
+ const { rerender } = render(
+ <WebAppAccessCard agent={createAgent()} agentId="agent-1" isLoading={false} />,
+ { wrapper: createAccessCardWrapper(queryClient) },
+ )
+ await user.click(
+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' }),
+ )
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ rerender(
+ <WebAppAccessCard
+ agent={createAgent({ permission_keys: [AgentPermission.AccessPointView] })}
+ agentId="agent-1"
+ isLoading={false}
+ />,
+ )
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(mocks.siteMutation).not.toHaveBeenCalled()
+ })
})
diff --git a/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
index e2ff559d5f0..21bff295487 100644
--- a/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next'
import { AccessPointCard } from '@/app/components/base/access-point/card'
import { AccessPointUrl } from '@/app/components/base/access-point/url'
import { useDocLink } from '@/context/i18n'
+import { useAgentPermissions } from '@/features/agent-v2/permissions'
import { consoleQuery } from '@/service/console'
import { AgentApiKeyModal } from './agent-api-key-modal'
@@ -19,6 +20,7 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {
const docLink = useDocLink()
const queryClient = useQueryClient()
const [apiKeyModalOpen, setApiKeyModalOpen] = useState(false)
+ const { canManageAccessPoint } = useAgentPermissions(agentId)
const apiAccessQueryOptions = consoleQuery.agent.byAgentId.apiAccess.get.queryOptions({
input: {
params: {
@@ -78,11 +80,13 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {
],
)
const notAvailableLabel = t(($) => $['agentDetail.access.workflow.notAvailable'])
- const apiKeyActionDisabled = apiAccessQuery.isPending || apiAccessQuery.isError || !accessReady
+ const apiKeyActionDisabled =
+ !canManageAccessPoint || apiAccessQuery.isPending || apiAccessQuery.isError || !accessReady
const showPublishRequiredMessage =
!apiAccessQuery.isPending && !apiAccessQuery.isError && !accessReady
function handleEnabledChange(enabled: boolean) {
+ if (!canManageAccessPoint) return
toggleServiceApiMutation.mutate({
params: {
agent_id: agentId,
@@ -96,14 +100,14 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {
return (
<>
<AccessPointCard
- className="min-h-[222px]"
+ className="min-h-55.5"
headingLevel={3}
title={t(($) => $['agentDetail.access.serviceApi.title'])}
description={t(($) => $['agentDetail.access.serviceApi.description'])}
icon="i-custom-vender-knowledge-api-aggregate"
status={status}
statusLabel={statusLabel}
- switchDisabled={apiAccessQuery.isPending || apiAccessQuery.isError || !accessReady}
+ switchDisabled={apiKeyActionDisabled}
switchDisabledReason={
showPublishRequiredMessage ? t(($) => $['agentDetail.access.publishRequired']) : undefined
}
@@ -175,11 +179,13 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {
/>
</AccessPointCard>
- <AgentApiKeyModal
- agentId={agentId}
- open={apiKeyModalOpen}
- onOpenChange={setApiKeyModalOpen}
- />
+ {canManageAccessPoint && (
+ <AgentApiKeyModal
+ agentId={agentId}
+ open={apiKeyModalOpen}
+ onOpenChange={setApiKeyModalOpen}
+ />
+ )}
</>
)
}
diff --git a/web/features/agent-v2/agent-detail/access/components/use-web-app-access-control.ts b/web/features/agent-v2/agent-detail/access/components/use-web-app-access-control.ts
index 76f4fa8603a..350b766b44b 100644
--- a/web/features/agent-v2/agent-detail/access/components/use-web-app-access-control.ts
+++ b/web/features/agent-v2/agent-detail/access/components/use-web-app-access-control.ts
@@ -3,14 +3,11 @@
import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'
import type { SelectorParam } from 'i18next'
import { useSuspenseQuery } from '@tanstack/react-query'
-import { useAtomValue } from 'jotai'
import { useTranslation } from 'react-i18next'
-import { workspacePermissionKeysAtom } from '@/context/permission-state'
-import { userProfileQueryOptions } from '@/features/account-profile/client'
+import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { AccessMode, isAccessMode } from '@/models/access-control'
import { useAppWhiteListSubjects } from '@/service/access-control/use-app-access-control'
-import { getAppACLCapabilities } from '@/utils/permission'
const ACCESS_MODE_ICON_MAP: Record<AccessMode, string> = {
[AccessMode.ORGANIZATION]: 'i-ri-building-line',
@@ -37,16 +34,7 @@ export function useWebAppAccessControl(
...systemFeaturesQueryOptions(),
select: (systemFeatures) => systemFeatures.webapp_auth.enabled,
})
- const { data: currentUserId } = useSuspenseQuery({
- ...userProfileQueryOptions(),
- select: (data) => data.profile.id,
- })
- const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
- const { canReleaseAndVersion: canManage } = getAppACLCapabilities(agent?.permission_keys, {
- currentUserId,
- resourceMaintainer: agent?.maintainer,
- workspacePermissionKeys,
- })
+ const { canReleaseAndVersion: canManage } = getAgentACLCapabilities(agent?.permission_keys)
const hasAccessControl = Boolean(webAppAuthEnabled && appId && accessMode)
const { data: accessSubjects } = useAppWhiteListSubjects(
appId,
diff --git a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
index 30836795bc0..a1e91110141 100644
--- a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
@@ -19,6 +19,7 @@ import SettingsModal from '@/app/components/app/overview/settings'
import { AccessPointCard } from '@/app/components/base/access-point/card'
import { AccessPointUrl } from '@/app/components/base/access-point/url'
import AppIcon from '@/app/components/base/app-icon'
+import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
import dynamic from '@/next/dynamic'
import { consoleQuery } from '@/service/console'
import { AppModeEnum } from '@/types/app'
@@ -48,7 +49,10 @@ export function WebAppAccessCard({
site?.app_base_url || (typeof window === 'undefined' ? '' : window.location.origin)
const webAppUrl = getAgentWebAppUrl(agent)
const accessReady = Boolean(agent?.access_ready)
- const canManageWebApp = Boolean(appId && accessReady)
+ const { canManageAccessPoint, canReleaseAndVersion } = getAgentACLCapabilities(
+ agent?.permission_keys,
+ )
+ const canManageWebApp = canManageAccessPoint && Boolean(appId && accessReady)
const embeddedConfig =
appId && accessToken
? {
@@ -131,6 +135,8 @@ export function WebAppAccessCard({
toggleSiteMutation.isPending && pendingEnabled !== undefined
? pendingEnabled
: Boolean(agent?.enable_site)
+ const canUseIntegrationActions =
+ canManageWebApp && optimisticEnabled && !toggleSiteMutation.isPending
const status = isLoading ? 'loading' : optimisticEnabled ? 'inService' : 'disabled'
const statusLabel = isLoading
? tCommon(($) => $.loading)
@@ -145,12 +151,14 @@ export function WebAppAccessCard({
const icon = agent ? getSettingsIcon(agent) : null
const notAvailableLabel = t(($) => $['agentDetail.access.workflow.notAvailable'])
const openUrl =
- webAppUrl && agent?.enable_site && !toggleSiteMutation.isPending ? webAppUrl : undefined
+ accessReady && webAppUrl && agent?.enable_site && !toggleSiteMutation.isPending
+ ? webAppUrl
+ : undefined
const publishRequiredMessage = t(($) => $['agentDetail.access.publishRequired'])
const showPublishRequiredMessage = !isLoading && !accessReady
function handleEnabledChange(enabled: boolean) {
- if (!appId) return
+ if (!appId || !canManageWebApp) return
toggleSiteMutation.mutate({
params: {
@@ -163,7 +171,7 @@ export function WebAppAccessCard({
}
function handleRefreshUrl() {
- if (!appId) return
+ if (!appId || !canManageWebApp) return
resetAccessTokenMutation.mutate({
params: {
@@ -173,7 +181,7 @@ export function WebAppAccessCard({
}
async function handleSaveSettings(params: ConfigParams) {
- if (!appId) return
+ if (!appId || !canManageWebApp) return
const { enable_sso: _enableSso, ...body } = params
const sitePayload = body satisfies AppSiteUpdatePayload
@@ -251,7 +259,7 @@ export function WebAppAccessCard({
<>
<Button
variant="secondary"
- disabled={!embeddedConfig}
+ disabled={!canUseIntegrationActions || !embeddedConfig}
onClick={() => setShowEmbeddedModal(true)}
className="flex items-center gap-1 px-3"
>
@@ -260,7 +268,7 @@ export function WebAppAccessCard({
</Button>
<Button
variant="secondary"
- disabled={!customizeConfig}
+ disabled={!canUseIntegrationActions || !customizeConfig}
onClick={() => setShowCustomizeModal(true)}
className="flex items-center gap-1 px-3"
>
@@ -269,7 +277,7 @@ export function WebAppAccessCard({
</Button>
<Button
variant="secondary"
- disabled={!settingsAppInfo || updateSiteMutation.isPending}
+ disabled={!canManageWebApp || !settingsAppInfo || updateSiteMutation.isPending}
onClick={() => setShowSettingsModal(true)}
className="flex items-center gap-1 px-3"
>
@@ -314,7 +322,7 @@ export function WebAppAccessCard({
)}
</AccessPointCard>
- {settingsAppInfo && (
+ {canManageWebApp && settingsAppInfo && (
<SettingsModal
isChat
appInfo={settingsAppInfo}
@@ -323,7 +331,7 @@ export function WebAppAccessCard({
onSave={handleSaveSettings}
/>
)}
- {customizeConfig && (
+ {canManageWebApp && customizeConfig && (
<CustomizeModal
isShow={showCustomizeModal}
onClose={() => setShowCustomizeModal(false)}
@@ -332,7 +340,7 @@ export function WebAppAccessCard({
sourceCodeRepository="webapp-conversation"
/>
)}
- {embeddedConfig && (
+ {canManageWebApp && embeddedConfig && (
<EmbeddedModal
isShow={showEmbeddedModal}
onClose={() => setShowEmbeddedModal(false)}
@@ -342,7 +350,7 @@ export function WebAppAccessCard({
webAppRoute="agent"
/>
)}
- {showAccessControl && accessControl.state === 'ready' && (
+ {canReleaseAndVersion && showAccessControl && accessControl.state === 'ready' && (
<AccessControl
app={accessControl.app}
onClose={() => setShowAccessControl(false)}
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
index 90fb44f58d6..d6f259ab62f 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
@@ -4,7 +4,9 @@ import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ScopeProvider } from 'jotai-scope'
import { useState } from 'react'
+import { AgentPermission } from '@/features/agent-v2/acl'
import { AgentScope } from '@/features/agent-v2/analytics'
+import { consoleQuery } from '@/service/console'
import { renderWithNuqs as render } from '@/test/nuqs-testing'
import { AgentConfigureComposerScope } from '../components/composer-session'
import { useAgentConfigureData } from '../hooks'
@@ -23,6 +25,7 @@ const mocks = vi.hoisted(() => ({
queryState: {
agent: {
data: {
+ permission_keys: [] as string[],
debug_conversation_has_messages: true,
debug_conversation_id: 'debug-conversation-old' as string | null,
debug_conversation_message_count: 1,
@@ -489,6 +492,8 @@ vi.mock('../components/preview/header', () => ({
AgentPreviewHeader: (props: {
mode: 'build' | 'preview'
previewEnabled: boolean
+ buildEnabled?: boolean
+ showChatFeaturesAction?: boolean
onModeChange: (mode: 'build' | 'preview') => void
onToggleChatFeatures: () => void
onOpenWorkingDirectory: () => void
@@ -505,12 +510,18 @@ vi.mock('../components/preview/header', () => ({
>
preview mode
</button>
- <button type="button" onClick={() => props.onModeChange('build')}>
+ <button
+ type="button"
+ disabled={props.buildEnabled === false}
+ onClick={() => props.onModeChange('build')}
+ >
build mode
</button>
- <button type="button" onClick={props.onToggleChatFeatures}>
- chat features
- </button>
+ {props.showChatFeaturesAction !== false && (
+ <button type="button" onClick={props.onToggleChatFeatures}>
+ chat features
+ </button>
+ )}
{props.showWorkingDirectoryAction && (
<button type="button" onClick={props.onOpenWorkingDirectory}>
open working directory
@@ -531,6 +542,16 @@ vi.mock('../components/preview/versions-panel', () => ({
),
}))
+function createQueryClient() {
+ const client = new QueryClient()
+ client.setQueryData<Partial<typeof mocks.queryState.agent.data>>(
+ consoleQuery.agent.byAgentId.get.queryOptions({ input: { params: { agent_id: 'agent-1' } } })
+ .queryKey,
+ mocks.queryState.agent.data,
+ )
+ return client
+}
+
describe('AgentConfigurePage', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -559,6 +580,7 @@ describe('AgentConfigurePage', () => {
mocks.discardBuildDraft.mockResolvedValue({ result: 'success' })
mocks.queryState.agent = {
data: {
+ permission_keys: Object.values(AgentPermission),
debug_conversation_has_messages: true,
debug_conversation_id: 'debug-conversation-old',
debug_conversation_message_count: 1,
@@ -605,7 +627,7 @@ describe('AgentConfigurePage', () => {
describe('Loading state', () => {
it('should load the build draft while keeping the page pending with composer data', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
render(
<QueryClientProvider client={queryClient}>
@@ -630,7 +652,7 @@ describe('AgentConfigurePage', () => {
})
it('should initialize the composer from the active build draft after its pending check', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -696,7 +718,7 @@ describe('AgentConfigurePage', () => {
})
it('should leave the configure landmark to the orchestrate panel after loading', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {},
isFetching: false,
@@ -719,7 +741,7 @@ describe('AgentConfigurePage', () => {
})
it('should initialize the composer from recovered query data after the initial request fails', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: undefined as unknown,
isFetching: false,
@@ -780,7 +802,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
{ searchParams: '?mode=preview' },
@@ -809,7 +831,7 @@ describe('AgentConfigurePage', () => {
}
const { onUrlUpdate } = render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
{ searchParams: '?source=shared-link' },
@@ -853,7 +875,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigureComposerScopeHarness />
</QueryClientProvider>,
)
@@ -917,7 +939,7 @@ describe('AgentConfigurePage', () => {
}
const { onUrlUpdate } = render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
)
@@ -979,7 +1001,7 @@ describe('AgentConfigurePage', () => {
}
const { onUrlUpdate } = render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
)
@@ -1094,7 +1116,7 @@ describe('AgentConfigurePage', () => {
}
const { onUrlUpdate } = render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
)
@@ -1131,7 +1153,7 @@ describe('AgentConfigurePage', () => {
it('should reset Build on mode switch, then save and force checkout when starting chat', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const draftSave = createDeferredPromise<{ agent_soul: object }>()
const forcedBuildDraft = {
agent_soul: {
@@ -1255,7 +1277,7 @@ describe('AgentConfigurePage', () => {
it('should stay in Build without checkout or send when saving before chat fails', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.saveComposerDraft.mockRejectedValue(new Error('save failed'))
mocks.queryState.composer = {
data: {
@@ -1339,7 +1361,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigureComposerScopeHarness />
</QueryClientProvider>,
)
@@ -1369,7 +1391,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigureComposerScopeHarness />
</QueryClientProvider>,
)
@@ -1410,7 +1432,7 @@ describe('AgentConfigurePage', () => {
it('should run preview with the shared chat API without entering build draft mode outside community edition', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
clearBuildConversation()
mocks.queryState.composer = {
data: {},
@@ -1460,7 +1482,7 @@ describe('AgentConfigurePage', () => {
it('should refresh only the preview conversation when restarting preview mode', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {},
isFetching: false,
@@ -1527,7 +1549,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
)
@@ -1542,7 +1564,7 @@ describe('AgentConfigurePage', () => {
it('should not keep a stale clear command after the composer content remounts', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {},
isFetching: false,
@@ -1625,7 +1647,7 @@ describe('AgentConfigurePage', () => {
}
const view = render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
)
@@ -1638,7 +1660,7 @@ describe('AgentConfigurePage', () => {
view.unmount()
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
{ searchParams: '?mode=preview' },
@@ -1659,7 +1681,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
{ searchParams: '?mode=preview' },
@@ -1684,7 +1706,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
{ searchParams: '?mode=preview' },
@@ -1730,7 +1752,7 @@ describe('AgentConfigurePage', () => {
refetch: vi.fn(),
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
{ searchParams: '?mode=preview' },
@@ -1773,7 +1795,7 @@ describe('AgentConfigurePage', () => {
it('should disable restart when the debug conversation has no messages', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.agent = {
...mocks.queryState.agent,
data: {
@@ -1822,7 +1844,7 @@ describe('AgentConfigurePage', () => {
}
const { onUrlUpdate } = render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
)
@@ -1843,7 +1865,7 @@ describe('AgentConfigurePage', () => {
})
it('should stay in normal draft mode when build draft returns 404 even if a debug conversation exists', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -1888,7 +1910,7 @@ describe('AgentConfigurePage', () => {
})
it('should keep build draft query refresh owned by explicit workflow actions', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -1925,7 +1947,7 @@ describe('AgentConfigurePage', () => {
})
it('should enter build draft mode when build draft data exists', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -1978,7 +2000,7 @@ describe('AgentConfigurePage', () => {
})
it('should track the run without checking out again in active build draft mode', async () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -2034,7 +2056,7 @@ describe('AgentConfigurePage', () => {
})
it('should show the working directory action after the first build reply completes', async () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -2099,7 +2121,7 @@ describe('AgentConfigurePage', () => {
})
it('should hide the working directory action when the build chat has no conversation', () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.agent = {
...mocks.queryState.agent,
data: {
@@ -2155,7 +2177,7 @@ describe('AgentConfigurePage', () => {
it('should show chat features from the active build draft source as read-only', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -2212,7 +2234,7 @@ describe('AgentConfigurePage', () => {
})
it('should switch to build draft mode without resetting the sending chat when sending from normal draft mode', async () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -2284,7 +2306,7 @@ describe('AgentConfigurePage', () => {
})
it('should block build chat checkout when no model is configured', async () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
modelHooksState.defaultTextGenerationModel = undefined
mocks.queryState.composer = {
data: {
@@ -2331,7 +2353,7 @@ describe('AgentConfigurePage', () => {
it('should keep the build draft bar disabled while a build conversation is responding', async () => {
vi.useFakeTimers()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const refetchBuildDraft = vi.fn().mockResolvedValue({})
mocks.queryState.composer = {
data: {
@@ -2399,7 +2421,7 @@ describe('AgentConfigurePage', () => {
})
it('should not keep a stale build draft action lock after the composer content remounts', async () => {
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -2489,7 +2511,7 @@ describe('AgentConfigurePage', () => {
it('should settle build draft actions when the build completion refresh fails', async () => {
vi.useFakeTimers()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const refetchBuildDraft = vi.fn().mockRejectedValue(new Error('refresh failed'))
mocks.queryState.composer = {
data: {
@@ -2547,7 +2569,7 @@ describe('AgentConfigurePage', () => {
it('should not let a previous build completion refresh unlock a new build run', async () => {
vi.useFakeTimers()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const refetchBuildDraft = vi.fn().mockResolvedValue({})
mocks.queryState.composer = {
data: {
@@ -2609,7 +2631,7 @@ describe('AgentConfigurePage', () => {
it('should ignore a previous build completion refresh that is already in flight', async () => {
vi.useFakeTimers()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const refetchBuildDraft = vi.fn()
const staleRefresh = createDeferredPromise<unknown>()
refetchBuildDraft.mockReturnValueOnce(staleRefresh.promise)
@@ -2697,7 +2719,7 @@ describe('AgentConfigurePage', () => {
it('should discard the build draft when restarting build mode with a build draft', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {},
isFetching: false,
@@ -2752,7 +2774,7 @@ describe('AgentConfigurePage', () => {
it('should switch soul source to view version when selecting a version from build draft mode', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {
agent_soul: {
@@ -2808,7 +2830,7 @@ describe('AgentConfigurePage', () => {
it('should rebase the composer from the restored version', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const refetchComposer = vi.fn(async () => {
mocks.queryState.composer = {
...mocks.queryState.composer,
@@ -2878,7 +2900,7 @@ describe('AgentConfigurePage', () => {
it('should apply the build draft and rebase the composer store from the refetched normal draft', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
const refetchComposer = vi.fn(async () => {
mocks.queryState.composer = {
@@ -3016,7 +3038,7 @@ describe('AgentConfigurePage', () => {
}
render(
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider client={createQueryClient()}>
<AgentConfigurePage agentId="agent-1" />
</QueryClientProvider>,
)
@@ -3036,7 +3058,7 @@ describe('AgentConfigurePage', () => {
it('should keep the build draft UI while the applied normal draft is still refreshing', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const refetchComposerDeferred = createDeferredPromise<unknown>()
const refetchComposer = vi.fn(async () => {
const result = await refetchComposerDeferred.promise
@@ -3123,7 +3145,7 @@ describe('AgentConfigurePage', () => {
it('should keep exiting build draft when debug conversation refresh fails after applying build draft', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
const refetchComposer = vi.fn(async () => {
mocks.queryState.composer = {
...mocks.queryState.composer,
@@ -3223,7 +3245,7 @@ describe('AgentConfigurePage', () => {
it('should discard the build draft and start a new build session', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.queryState.composer = {
data: {},
isFetching: false,
@@ -3278,7 +3300,7 @@ describe('AgentConfigurePage', () => {
it('should keep exiting build draft when debug conversation refresh fails after discarding build draft', async () => {
const user = userEvent.setup()
- const queryClient = new QueryClient()
+ const queryClient = createQueryClient()
mocks.refreshDebugConversation.mockRejectedValueOnce(new Error('refresh failed'))
mocks.queryState.composer = {
data: {},
@@ -3337,4 +3359,33 @@ describe('AgentConfigurePage', () => {
})
})
})
+ it.each([
+ [AgentPermission.Edit, 'readonly:no', 'publish:no', false],
+ [AgentPermission.TestAndRun, 'readonly:yes', 'publish:no', true],
+ [AgentPermission.ReleaseAndVersion, 'readonly:yes', 'publish:yes', false],
+ ])('keeps edit, run, and publish independent for %s', (permission, readonly, publish, canRun) => {
+ mocks.queryState.agent.data.permission_keys = [AgentPermission.Preview, permission]
+ mocks.queryState.composer = {
+ data: { agent_soul: {} },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ render(
+ <QueryClientProvider client={createQueryClient()}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ { searchParams: '?mode=build' },
+ )
+ const panel = screen.getByRole('region', { name: 'orchestrate-panel' })
+ expect(panel).toHaveTextContent(readonly)
+ expect(panel).toHaveTextContent(publish)
+ expect(screen.getByRole('button', { name: 'build mode' })).toBeDisabled()
+ expect(screen.queryByRole('region', { name: 'build-chat' })).not.toBeInTheDocument()
+ if (canRun) expect(screen.getByRole('region', { name: 'preview-chat' })).toBeInTheDocument()
+ else expect(screen.queryByRole('region', { name: 'preview-chat' })).not.toBeInTheDocument()
+ expect(mocks.saveComposerDraft).not.toHaveBeenCalled()
+ })
})
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
index a5be3c16c57..5e27852b31a 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
@@ -7,6 +7,7 @@ import { createStore, Provider as JotaiProvider } from 'jotai'
import { Suspense } from 'react'
import { CollectionType } from '@/app/components/tools/types'
import { MetadataFilteringModeEnum } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
+import { AgentPermission } from '@/features/agent-v2/acl'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import {
agentComposerDraftAtom,
@@ -15,6 +16,8 @@ import {
import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'
import { agentComposerSkillsAtom } from '@/features/agent-v2/agent-composer/store-modules/skills'
+import { consoleQuery } from '@/service/console'
+import { createAgentFixture } from '@/test/fixtures/agent'
import { useAgentConfigureSync } from '../use-agent-configure-sync'
const toastMock = vi.hoisted(() => ({
@@ -235,12 +238,14 @@ function renderUseAgentConfigureSync({
baseConfig,
currentModel,
enabled = true,
+ publishEnabled,
suspend = false,
}: {
agentName?: Parameters<typeof useAgentConfigureSync>[0]['agentName']
baseConfig?: Parameters<typeof useAgentConfigureSync>[0]['baseConfig']
currentModel?: Parameters<typeof useAgentConfigureSync>[0]['currentModel']
enabled?: boolean
+ publishEnabled?: boolean
suspend?: boolean
} = {}) {
const queryClient = new QueryClient({
@@ -249,6 +254,10 @@ function renderUseAgentConfigureSync({
mutations: { retry: false },
},
})
+ queryClient.setQueryData(
+ consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
+ createAgentFixture(),
+ )
const store = createStore()
const pendingRender = new Promise<void>(() => {})
const wrapper = ({ children }: PropsWithChildren) => (
@@ -268,6 +277,7 @@ function renderUseAgentConfigureSync({
baseConfig: props.baseConfig,
currentModel: props.currentModel,
enabled: props.enabled,
+ publishEnabled: publishEnabled ?? props.enabled,
})
if (props.suspend) throw pendingRender
@@ -350,6 +360,7 @@ describe('useAgentConfigureSync', () => {
queryClient.setQueryData(['agent-detail', 'agent-1'], {
active_config_is_published: true,
name: 'Agent',
+ permission_keys: Object.values(AgentPermission),
})
act(() => {
@@ -362,6 +373,7 @@ describe('useAgentConfigureSync', () => {
expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
active_config_is_published: true,
name: 'Agent',
+ permission_keys: Object.values(AgentPermission),
})
expect(composerPutMutationFn).not.toHaveBeenCalled()
@@ -388,6 +400,7 @@ describe('useAgentConfigureSync', () => {
expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
active_config_is_published: true,
name: 'Agent',
+ permission_keys: Object.values(AgentPermission),
})
})
@@ -483,6 +496,7 @@ describe('useAgentConfigureSync', () => {
queryClient.setQueryData(['agent-detail', 'agent-1'], {
active_config_is_published: true,
name: 'Agent',
+ permission_keys: Object.values(AgentPermission),
})
act(() => {
@@ -503,6 +517,7 @@ describe('useAgentConfigureSync', () => {
expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
active_config_is_published: true,
name: 'Agent',
+ permission_keys: Object.values(AgentPermission),
})
})
@@ -1001,6 +1016,7 @@ describe('useAgentConfigureSync', () => {
queryClient.setQueryData(['agent-detail', 'agent-1'], {
active_config_is_published: true,
name: 'Agent',
+ permission_keys: Object.values(AgentPermission),
})
await act(async () => {
@@ -1011,6 +1027,7 @@ describe('useAgentConfigureSync', () => {
expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
active_config_is_published: true,
name: 'Agent',
+ permission_keys: Object.values(AgentPermission),
})
})
@@ -1628,4 +1645,76 @@ describe('useAgentConfigureSync', () => {
}),
)
})
+ it('runs with no draft writes when edit permission is absent', async () => {
+ const { queryClient, result, store, unmount } = renderUseAgentConfigureSync({
+ enabled: false,
+ currentModel: configuredModel,
+ })
+ queryClient.setQueryData(['agent-detail', 'agent-1'], {
+ permission_keys: [AgentPermission.TestAndRun],
+ })
+ act(() => {
+ store.set(agentComposerPromptAtom, 'Unsaved local changes')
+ })
+ await act(async () => {
+ await result.current.saveDraft()
+ await vi.advanceTimersByTimeAsync(5000)
+ window.dispatchEvent(new Event('beforeunload'))
+ unmount()
+ })
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ expect(publishAgentMutationFn).not.toHaveBeenCalled()
+ })
+
+ it('publishes the server draft without writing configuration when only release is granted', async () => {
+ const { queryClient, result } = renderUseAgentConfigureSync({
+ enabled: false,
+ publishEnabled: true,
+ currentModel: configuredModel,
+ })
+ queryClient.setQueryData(['agent-detail', 'agent-1'], {
+ permission_keys: [AgentPermission.ReleaseAndVersion],
+ })
+ await act(async () => {
+ await result.current.publishDraft()
+ })
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ expect(publishAgentMutationFn).toHaveBeenCalledOnce()
+ expect(toastMock.success).toHaveBeenCalledOnce()
+ })
+
+ it('does not flush dirty configuration after edit permission is revoked before unmount', async () => {
+ const { queryClient, store, unmount } = renderUseAgentConfigureSync()
+ act(() => {
+ store.set(agentComposerPromptAtom, 'Dirty before revocation')
+ queryClient.setQueryData(['agent-detail', 'agent-1'], { permission_keys: [] })
+ unmount()
+ })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ })
+
+ it('cancels publishing without a success toast if release permission is revoked during save', async () => {
+ const saving = createDeferredPromise<{ agent_soul: Record<string, unknown> }>()
+ composerPutMutationFn.mockReturnValueOnce(saving.promise)
+ const { queryClient, result } = renderUseAgentConfigureSync({ currentModel: configuredModel })
+ let publishing!: Promise<void>
+ act(() => {
+ publishing = result.current.publishDraft()
+ })
+ await act(async () => {
+ await Promise.resolve()
+ })
+ queryClient.setQueryData(['agent-detail', 'agent-1'], {
+ permission_keys: [AgentPermission.Edit],
+ })
+ await act(async () => {
+ saving.resolve({ agent_soul: {} })
+ await publishing
+ })
+ expect(publishAgentMutationFn).not.toHaveBeenCalled()
+ expect(toastMock.success).not.toHaveBeenCalled()
+ })
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
index 8d4c92a1ddd..2bbf7fc7bae 100644
--- a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
@@ -83,7 +83,7 @@ export function AgentConfigureComposerScope({
agentId,
activeVersionId,
composerAgentSoulConfig: composerQuery.data?.agent_soul,
- isBuildMode: rightPanelMode === 'build',
+ isBuildMode: configureData.capabilities.canBuild && rightPanelMode === 'build',
isViewingVersion,
normalAgentSoulConfig: agentSoulConfig,
setSoulSourceOverride,
@@ -284,6 +284,7 @@ function AgentConfigurePageComposerContent({
onSelectVersion: (versionId: string | null) => void
}) {
const {
+ capabilities,
agentQuery,
composerQuery,
versionQuery,
@@ -333,7 +334,7 @@ function AgentConfigurePageComposerContent({
const setShowPreviewVersions = useSetAtom(agentConfigureShowPreviewVersionsAtom)
const rebaseComposerDraft = useSetAtom(rebaseAgentComposerDraftAtom)
const queryClient = useQueryClient()
- const showBuildDraftBar = buildDraft.isActive
+ const showBuildDraftBar = capabilities.canBuild && buildDraft.isActive
const resetBuildChatState = useCallback(async () => {
setCompletedBuildConversationId(null)
setConversationId({ mode: 'build', conversationId: null })
@@ -355,7 +356,13 @@ function AgentConfigurePageComposerContent({
agentName: agentQuery.data?.name,
baseConfig: agentSoulConfig,
currentModel,
- enabled: composerQuery.isSuccess && !selectedVersionId && !buildDraft.isActive,
+ enabled:
+ capabilities.canEdit && composerQuery.isSuccess && !selectedVersionId && !buildDraft.isActive,
+ publishEnabled:
+ capabilities.canReleaseAndVersion &&
+ composerQuery.isSuccess &&
+ !selectedVersionId &&
+ !buildDraft.isActive,
})
const {
buildCallbackGeneration,
@@ -429,6 +436,7 @@ function AgentConfigurePageComposerContent({
? (agentQuery.data?.debug_conversation_has_messages ?? false) || buildDraft.isActive
: !!conversationIds[rightPanelChatMode]
const isRestartCurrentChatDisabled =
+ !capabilities.canTestAndRun ||
!hasRestartCurrentChatTarget ||
buildDraftActionsDisabled ||
isEnteringBuildMode ||
@@ -436,6 +444,7 @@ function AgentConfigurePageComposerContent({
buildDraftActions.isApplyingBuildDraft ||
buildDraftActions.isDiscardingBuildDraft
const isChatFeaturesReadOnly =
+ !capabilities.canEdit ||
isEnteringBuildMode ||
buildDraftActionsDisabled ||
(isViewingVersion && versionQuery.isPending) ||
@@ -478,6 +487,7 @@ function AgentConfigurePageComposerContent({
textGenerationModelList={textGenerationModelList}
isPublishing={isPublishing}
readOnly={
+ !capabilities.canEdit ||
!composerQuery.isSuccess ||
isViewingVersion ||
buildDraft.isActive ||
@@ -486,7 +496,7 @@ function AgentConfigurePageComposerContent({
selectedVersionSnapshot={isViewingVersion ? activeConfigSnapshot : undefined}
isBuildDraftActive={buildDraft.isActive}
buildDraftChangedKeys={buildDraft.changedKeys}
- showPublishBar={!buildDraft.isActive}
+ showPublishBar={capabilities.canReleaseAndVersion && !buildDraft.isActive}
bottomAction={
showBuildDraftBar ? (
<AgentBuildDraftBar
@@ -524,6 +534,8 @@ function AgentConfigurePageComposerContent({
<AgentPreviewHeader
mode={rightPanelChatMode}
previewEnabled={previewEnabled}
+ buildEnabled={capabilities.canBuild}
+ showChatFeaturesAction={capabilities.canEdit}
isChatFeaturesOpen={showChatFeatures}
onModeChange={changeRightPanelMode}
onToggleChatFeatures={() => setShowChatFeatures((open) => !open)}
@@ -533,11 +545,13 @@ function AgentConfigurePageComposerContent({
}}
onRefresh={restartCurrentChat}
refreshDisabled={isRestartCurrentChatDisabled}
- showWorkingDirectoryAction={showWorkingDirectoryAction}
+ showWorkingDirectoryAction={capabilities.canBuild && showWorkingDirectoryAction}
/>
}
chat={
- buildDraft.isPending ? (
+ !(rightPanelMode === 'build'
+ ? capabilities.canBuild
+ : previewEnabled) ? null : buildDraft.isPending ? (
<Loading type="app" />
) : (
<AgentConfigureRightPanelChat
@@ -612,7 +626,7 @@ function AgentConfigurePageComposerContent({
}
sidePanels={
<>
- {showPreviewVersions && (
+ {capabilities.canReleaseAndVersion && showPreviewVersions && (
<AgentPreviewVersionsPanel
agentId={agentId}
activeVersionId={activeVersionId}
@@ -620,15 +634,15 @@ function AgentConfigurePageComposerContent({
onClose={() => setShowPreviewVersions(false)}
/>
)}
- {workingDirectoryPanel.panel}
+ {capabilities.canBuild && workingDirectoryPanel.panel}
<AgentChatFeaturesPanel
- show={showChatFeatures}
+ show={capabilities.canEdit && showChatFeatures}
appFeatures={buildDraft.agentSoulConfig?.app_features}
disabled={isChatFeaturesReadOnly}
onClose={() => setShowChatFeatures(false)}
/>
<AgentConfigureClearSessionConfirmDialog
- open={showSwitchToPreviewConfirm}
+ open={capabilities.canBuild && showSwitchToPreviewConfirm}
title={t(($) => $['agentDetail.configure.switchToPreviewConfirm.title'])}
onOpenChange={setShowSwitchToPreviewConfirm}
onConfirm={confirmSwitchToPreview}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx
index d0380318b35..51ac341a26c 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx
@@ -112,6 +112,7 @@ export function AgentPreviewHeader({
mode,
previewEnabled,
isChatFeaturesOpen,
+ buildEnabled = true,
onModeChange,
onToggleChatFeatures,
onOpenWorkingDirectory,
@@ -124,6 +125,7 @@ export function AgentPreviewHeader({
mode: AgentConfigureRightPanelMode
previewEnabled: boolean
isChatFeaturesOpen: boolean
+ buildEnabled?: boolean
onModeChange: (mode: AgentConfigureRightPanelMode) => void
onToggleChatFeatures: () => void
onOpenWorkingDirectory: () => void
@@ -163,7 +165,11 @@ export function AgentPreviewHeader({
onValueChange={(value) => onModeChange(value)}
aria-label={t(($) => $['agentDetail.configure.rightPanel.modeLabel'])}
>
- <SegmentedControlItem<AgentConfigureRightPanelMode> value="build" className="uppercase">
+ <SegmentedControlItem<AgentConfigureRightPanelMode>
+ value="build"
+ disabled={!buildEnabled}
+ className="uppercase"
+ >
<span aria-hidden className="i-custom-vender-agent-v2-configure-build size-4" />
{t(($) => $['agentDetail.configure.rightPanel.build'])}
</SegmentedControlItem>
diff --git a/web/features/agent-v2/agent-detail/configure/hooks.ts b/web/features/agent-v2/agent-detail/configure/hooks.ts
index 05ac8a53247..881e728de2e 100644
--- a/web/features/agent-v2/agent-detail/configure/hooks.ts
+++ b/web/features/agent-v2/agent-detail/configure/hooks.ts
@@ -1,9 +1,6 @@
'use client'
-import type {
- AgentConfigSnapshotDetailResponse,
- AgentSoulConfig,
-} from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import { skipToken, useQuery } from '@tanstack/react-query'
import { useAtom, useAtomValue } from 'jotai'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
@@ -11,11 +8,12 @@ import {
useDefaultModel,
useTextGenerationCurrentProviderAndModelAndModelList,
} from '@/app/components/header/account-setting/model-provider-page/hooks'
+import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
import { agentComposerAppFeaturesAtom } from '@/features/agent-v2/agent-composer/store-modules/app-features'
import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
import { consoleQuery } from '@/service/console'
-export function useAgentConfigureData(agentId: string, selectedVersionId: string | null) {
+export function useAgentConfigureData(agentId: string, requestedVersionId: string | null) {
const agentQuery = useQuery(
consoleQuery.agent.byAgentId.get.queryOptions({
input: {
@@ -34,8 +32,11 @@ export function useAgentConfigureData(agentId: string, selectedVersionId: string
},
}),
)
+ const capabilities = getAgentACLCapabilities(agentQuery.data?.permission_keys)
+ const selectedVersionId = capabilities.canReleaseAndVersion ? requestedVersionId : null
const publishedVersionId = composerQuery.data?.active_config_snapshot?.id
- const shouldLoadPublishedVersion = !selectedVersionId && !composerQuery.data?.agent_soul
+ const shouldLoadPublishedVersion =
+ capabilities.canReleaseAndVersion && !selectedVersionId && !composerQuery.data?.agent_soul
const versionIdToLoad =
selectedVersionId ?? (shouldLoadPublishedVersion ? publishedVersionId : undefined)
const shouldLoadVersion = !!versionIdToLoad
@@ -51,7 +52,7 @@ export function useAgentConfigureData(agentId: string, selectedVersionId: string
: skipToken,
}),
)
- const versionDetail = versionQuery.data as AgentConfigSnapshotDetailResponse | undefined
+ const versionDetail = versionQuery.data
const activeVersionId =
selectedVersionId ?? (shouldLoadPublishedVersion ? publishedVersionId : null)
const activeConfigSnapshot = selectedVersionId
@@ -64,6 +65,7 @@ export function useAgentConfigureData(agentId: string, selectedVersionId: string
agentQuery.isPending || composerQuery.isPending || (shouldLoadVersion && versionQuery.isPending)
return {
+ capabilities,
agentQuery,
composerQuery,
versionQuery,
diff --git a/web/features/agent-v2/agent-detail/configure/page.tsx b/web/features/agent-v2/agent-detail/configure/page.tsx
index dfad7370c55..2945954e18a 100644
--- a/web/features/agent-v2/agent-detail/configure/page.tsx
+++ b/web/features/agent-v2/agent-detail/configure/page.tsx
@@ -45,15 +45,18 @@ function AgentConfigurePageContent({ agentId }: AgentConfigurePageProps) {
...systemFeaturesQueryOptions(),
select: (systemFeatures) => systemFeatures.deployment_edition,
})
- const previewEnabled = deploymentEdition !== 'COMMUNITY'
- const rightPanelMode = requestedMode === 'preview' && previewEnabled ? 'preview' : 'build'
+ const { canBuild, canTestAndRun } = configureData.capabilities
+ const previewEnabled = canTestAndRun && deploymentEdition !== 'COMMUNITY'
+ const rightPanelMode =
+ !canBuild || (requestedMode === 'preview' && previewEnabled) ? 'preview' : 'build'
const changeRightPanelMode = useCallback(
(nextMode: AgentConfigureRightPanelMode) => {
if (nextMode === 'preview' && !previewEnabled) return
+ if (nextMode === 'build' && !canBuild) return
return setRequestedMode(nextMode)
},
- [previewEnabled, setRequestedMode],
+ [canBuild, previewEnabled, setRequestedMode],
)
return (
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
index 76f34a4fe2b..f2098c18718 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
@@ -12,6 +12,7 @@ import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { trackEvent } from '@/app/components/base/amplitude'
import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'
+import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
import {
useKnowledgeValidationMessage,
@@ -38,12 +39,14 @@ export function useAgentConfigureSync({
baseConfig,
currentModel,
enabled,
+ publishEnabled,
}: {
agentId: string
agentName?: string | null
baseConfig?: AgentSoulConfig
currentModel?: DefaultModel
enabled: boolean
+ publishEnabled: boolean
}) {
const { t: tCommon } = useTranslation('common')
const { t: tWorkflow } = useTranslation('workflow')
@@ -57,6 +60,7 @@ export function useAgentConfigureSync({
const baseConfigRef = useRef(baseConfig)
const currentModelRef = useRef(currentModel)
const enabledRef = useRef(enabled)
+ const publishEnabledRef = useRef(publishEnabled)
const lastAutosavedDraftKeyRef = useRef<string | undefined>(undefined)
const latestAppliedSaveSequenceRef = useRef(0)
const nextSaveSequenceRef = useRef(0)
@@ -64,11 +68,25 @@ export function useAgentConfigureSync({
const explicitlySavingDraftKeysRef = useRef(new Set<string>())
const publishInFlightRef = useRef(false)
+ // The layout can unmount this hook before a revoked permission reaches its props.
+ const getCurrentPermissions = useCallback(
+ () =>
+ getAgentACLCapabilities(
+ queryClient.getQueryData(
+ consoleQuery.agent.byAgentId.get.queryKey({
+ input: { params: { agent_id: agentId } },
+ }),
+ )?.permission_keys,
+ ),
+ [agentId, queryClient],
+ )
+
useEffect(() => {
baseConfigRef.current = baseConfig
currentModelRef.current = currentModel
enabledRef.current = enabled
- }, [baseConfig, currentModel, enabled])
+ publishEnabledRef.current = publishEnabled
+ }, [baseConfig, currentModel, enabled, publishEnabled])
const getAgentSoulDraft = useCallback(
() =>
@@ -134,36 +152,47 @@ export function useAgentConfigureSync({
publish?: boolean
silent?: boolean
}) => {
+ const permissions = getCurrentPermissions()
+ if (
+ publish
+ ? !publishEnabledRef.current || !permissions.canReleaseAndVersion
+ : !enabledRef.current || !permissions.canEdit
+ )
+ return false
const savedDraftKey = JSON.stringify(configSnapshot)
const saveSequence = ++nextSaveSequenceRef.current
- try {
- await saveComposerDraft({
- params: {
- agent_id: agentId,
- },
- body: {
- variant: 'agent_app',
- save_strategy: 'save_to_current_version',
- agent_soul: configSnapshot,
- },
- })
- } catch (error) {
- // Autosave is silent and keeps the local draft intact; explicit commands must stop at this boundary.
- if (!silent) {
- if (publish) throw error
- throw new Error('Failed to save agent composer draft.')
+ if (enabledRef.current && permissions.canEdit) {
+ try {
+ await saveComposerDraft({
+ params: {
+ agent_id: agentId,
+ },
+ body: {
+ variant: 'agent_app',
+ save_strategy: 'save_to_current_version',
+ agent_soul: configSnapshot,
+ },
+ })
+ } catch (error) {
+ // Autosave is silent and keeps the local draft intact; explicit commands must stop at this boundary.
+ if (!silent) {
+ if (publish) throw error
+ throw new Error('Failed to save agent composer draft.')
+ }
+
+ return false
}
- return false
+ applySavedDraft({
+ draftBaseline,
+ draftKey: savedDraftKey,
+ saveSequence,
+ })
}
- applySavedDraft({
- draftBaseline,
- draftKey: savedDraftKey,
- saveSequence,
- })
-
if (publish) {
+ if (!publishEnabledRef.current || !getCurrentPermissions().canReleaseAndVersion)
+ return false
await publishAgent({
params: {
agent_id: agentId,
@@ -201,6 +230,7 @@ export function useAgentConfigureSync({
draftBaseline: AgentSoulConfigFormState
draftKey: string
}) => {
+ if (!enabledRef.current || !getCurrentPermissions().canEdit) return false
const saveSequence = ++nextSaveSequenceRef.current
try {
await saveComposerDraftOnPageClose({
@@ -224,7 +254,7 @@ export function useAgentConfigureSync({
})
return true
},
- [agentId, applySavedDraft, saveComposerDraftOnPageClose],
+ [agentId, applySavedDraft, getCurrentPermissions, saveComposerDraftOnPageClose],
)
const { isPending: isPublishing, mutateAsync: runPublishTransaction } = useMutation(
@@ -237,7 +267,7 @@ export function useAgentConfigureSync({
configSnapshot: AgentSoulConfig
draftBaseline: AgentSoulConfigFormState
}) => {
- await saveComposer({
+ return saveComposer({
configSnapshot,
draftBaseline,
publish: true,
@@ -262,7 +292,7 @@ export function useAgentConfigureSync({
const debouncedSaveDraft = useMemo(
() =>
debounce(() => {
- latestDraftSaveRef.current()
+ if (enabledRef.current) latestDraftSaveRef.current()
}, DRAFT_AUTOSAVE_WAIT),
[],
)
@@ -368,7 +398,12 @@ export function useAgentConfigureSync({
}, [saveDirtyDraftOnPageClose])
const publishDraft = useCallback(async () => {
- if (!enabledRef.current || publishInFlightRef.current) return
+ if (
+ !publishEnabledRef.current ||
+ !getCurrentPermissions().canReleaseAndVersion ||
+ publishInFlightRef.current
+ )
+ return
const draft = store.get(agentComposerDraftAtom)
const configSnapshot = formStateToAgentSoulConfig({
@@ -406,10 +441,11 @@ export function useAgentConfigureSync({
publishInFlightRef.current = true
try {
debouncedSaveDraft.cancel?.()
- await runPublishTransaction({
+ const published = await runPublishTransaction({
configSnapshot,
draftBaseline: draft,
})
+ if (!published) return
trackEvent('app_published_time', {
action_mode: 'app',
app_id: agentId,
@@ -442,6 +478,7 @@ export function useAgentConfigureSync({
agentName,
debouncedSaveDraft,
getKnowledgeValidationMessage,
+ getCurrentPermissions,
runPublishTransaction,
store,
tCommon,
diff --git a/web/features/agent-v2/agent-detail/layout.tsx b/web/features/agent-v2/agent-detail/layout.tsx
index e1710fb1f0a..857c5ceea5b 100644
--- a/web/features/agent-v2/agent-detail/layout.tsx
+++ b/web/features/agent-v2/agent-detail/layout.tsx
@@ -1,12 +1,14 @@
'use client'
import type { ReactNode } from 'react'
-import { useQuery } from '@tanstack/react-query'
+import { Button } from '@langgenius/dify-ui/button'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
+import Loading from '@/app/components/base/loading'
+import { getAgentDefaultSection, getAgentSectionAccess } from '@/features/agent-v2/acl'
+import { useAgentPermissions } from '@/features/agent-v2/permissions'
import useDocumentTitle from '@/hooks/use-document-title'
import { usePathname, useRouter } from '@/next/navigation'
-import { consoleQuery } from '@/service/console'
type AgentDetailLayoutProps = {
agentId: string
@@ -19,33 +21,49 @@ export function AgentDetailLayout({ agentId, children }: AgentDetailLayoutProps)
const { t } = useTranslation('agentV2')
const pathname = usePathname()
const router = useRouter()
- const agentQuery = useQuery(
- consoleQuery.agent.byAgentId.get.queryOptions({
- input: {
- params: {
- agent_id: agentId,
- },
- },
- }),
- )
+ const { t: tCommon } = useTranslation('common')
+ const { agentQuery, ...capabilities } = useAgentPermissions(agentId)
const shouldRedirectToRoster = isNotFoundResponse(agentQuery.error)
- const section = pathname.endsWith('/access')
- ? 'access'
- : pathname.endsWith('/logs')
- ? 'logs'
- : pathname.endsWith('/monitoring')
- ? 'monitoring'
- : 'configure'
+ const section = pathname.endsWith('/access-config')
+ ? 'access-config'
+ : pathname.endsWith('/access')
+ ? 'access'
+ : pathname.endsWith('/logs')
+ ? 'logs'
+ : pathname.endsWith('/monitoring')
+ ? 'monitoring'
+ : 'configure'
const sectionTitle = t(($) => $[`agentDetail.sections.${section}`])
const agentTitle = agentQuery.data?.name ?? t(($) => $['agentDetail.documentTitle'])
+ const canAccessSection = getAgentSectionAccess(capabilities)[section]
+ const defaultSection = getAgentDefaultSection(capabilities)
+ const redirectPath = shouldRedirectToRoster
+ ? '/agents'
+ : agentQuery.isSuccess && !canAccessSection
+ ? defaultSection
+ ? `/agents/${agentId}/${defaultSection}`
+ : '/agents'
+ : undefined
useDocumentTitle(`${sectionTitle} · ${agentTitle}`)
useEffect(() => {
- if (shouldRedirectToRoster) router.replace('/agents')
- }, [router, shouldRedirectToRoster])
+ if (redirectPath) router.replace(redirectPath)
+ }, [router, redirectPath])
- if (shouldRedirectToRoster) return null
+ if (agentQuery.isPending) return <Loading />
+ if (redirectPath) return null
+ if (agentQuery.isError) {
+ return (
+ <div role="alert" className="flex h-full items-center justify-center gap-3">
+ <span>{t(($) => $['roster.loadingError'])}</span>
+ <Button onClick={() => void agentQuery.refetch()}>
+ {tCommon(($) => $['operation.retry'])}
+ </Button>
+ </div>
+ )
+ }
+ if (!canAccessSection) return null
return (
<div className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
diff --git a/web/features/agent-v2/agent-detail/navigation.tsx b/web/features/agent-v2/agent-detail/navigation.tsx
index 1c7439aa682..492808e7659 100644
--- a/web/features/agent-v2/agent-detail/navigation.tsx
+++ b/web/features/agent-v2/agent-detail/navigation.tsx
@@ -9,7 +9,6 @@ import { DialogTrigger } from '@langgenius/dify-ui/dialog'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { formatForDisplay } from '@tanstack/react-hotkeys'
-import { skipToken, useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import NavLink from '@/app/components/app-sidebar/nav-link'
import AppIcon from '@/app/components/base/app-icon'
@@ -18,9 +17,10 @@ import SidebarLeftArrowIcon from '@/app/components/base/icons/src/vender/Sidebar
import { DetailSidebarToggleButton } from '@/app/components/detail-sidebar/toggle-button'
import { gotoAnythingDialogHandle } from '@/app/components/goto-anything/dialog-handle'
import { GOTO_ANYTHING_HOTKEY } from '@/app/components/goto-anything/hotkeys'
+import { getAgentSectionAccess } from '@/features/agent-v2/acl'
+import { useAgentPermissions } from '@/features/agent-v2/permissions'
import Link from '@/next/link'
import { usePathname } from '@/next/navigation'
-import { consoleQuery } from '@/service/console'
import { getAgentDetailPath, getAgentIdFromPathname } from './routes'
import { AgentDetailSidebarActions } from './sidebar-actions'
@@ -55,6 +55,7 @@ const fileListLineIcon = createAgentNavIcon('i-ri-file-list-3-line')
const fileListFillIcon = createAgentNavIcon('i-ri-file-list-3-fill')
const dashboardLineIcon = createAgentNavIcon('i-ri-dashboard-2-line')
const dashboardFillIcon = createAgentNavIcon('i-ri-dashboard-2-fill')
+const accessConfigIcon = createAgentNavIcon('i-ri-shield-user-line')
const getAgentDetailNavigation = (agentId: string): AgentDetailNavItem[] => [
{
@@ -81,6 +82,12 @@ const getAgentDetailNavigation = (agentId: string): AgentDetailNavItem[] => [
icon: dashboardLineIcon,
activeIcon: dashboardFillIcon,
},
+ {
+ labelKey: 'agentDetail.sections.access-config',
+ href: getAgentDetailPath(agentId, 'access-config'),
+ icon: accessConfigIcon,
+ activeIcon: accessConfigIcon,
+ },
]
export function AgentDetailTop({ expand = true, onToggle }: AgentDetailTopProps) {
@@ -166,22 +173,16 @@ export function AgentDetailSection({ expand = true }: AgentDetailSectionProps) {
const { t } = useTranslation('agentV2')
const pathname = usePathname()
const agentId = getAgentIdFromPathname(pathname)
- const agentQuery = useQuery(
- consoleQuery.agent.byAgentId.get.queryOptions({
- input: agentId
- ? {
- params: {
- agent_id: agentId,
- },
- }
- : skipToken,
- }),
- )
+ const { agentQuery, ...capabilities } = useAgentPermissions(agentId)
if (!agentId) return null
- const navigation = getAgentDetailNavigation(agentId)
const agent = agentQuery.data
+ const sectionAccess = getAgentSectionAccess(capabilities)
+ const navigation = getAgentDetailNavigation(agentId).filter(
+ (item) =>
+ sectionAccess[item.labelKey.slice('agentDetail.sections.'.length) as AgentDetailSectionKey],
+ )
const imageUrl =
agent?.icon_type === 'image' || agent?.icon_type === 'link' ? agent.icon : undefined
const iconType = (imageUrl ? 'image' : agent?.icon_type) as AgentIconType | null | undefined
diff --git a/web/features/agent-v2/agent-detail/page.tsx b/web/features/agent-v2/agent-detail/page.tsx
index 049e6330881..58cfd2624b0 100644
--- a/web/features/agent-v2/agent-detail/page.tsx
+++ b/web/features/agent-v2/agent-detail/page.tsx
@@ -1,6 +1,7 @@
'use client'
import type { AgentDetailSectionKey } from './section'
+import { AgentAccessConfigPage } from './access-config/page'
import { AgentAccessPage } from './access/page'
import { AgentConfigurePage } from './configure/page'
import { AgentLogsPage } from './logs/page'
@@ -12,6 +13,8 @@ type AgentDetailPageProps = {
}
export function AgentDetailPage({ agentId, section }: AgentDetailPageProps) {
+ if (section === 'access-config') return <AgentAccessConfigPage agentId={agentId} />
+
if (section === 'monitoring') return <AgentMonitoringPage agentId={agentId} />
if (section === 'logs') return <AgentLogsPage agentId={agentId} />
diff --git a/web/features/agent-v2/agent-detail/section.ts b/web/features/agent-v2/agent-detail/section.ts
index 9e242c01372..640ff84058f 100644
--- a/web/features/agent-v2/agent-detail/section.ts
+++ b/web/features/agent-v2/agent-detail/section.ts
@@ -1 +1 @@
-export type AgentDetailSectionKey = 'configure' | 'access' | 'logs' | 'monitoring'
+export type AgentDetailSectionKey = 'configure' | 'access' | 'logs' | 'monitoring' | 'access-config'
diff --git a/web/features/agent-v2/agent-detail/sidebar-actions.tsx b/web/features/agent-v2/agent-detail/sidebar-actions.tsx
index 4e04ed08d54..0a26f0be27d 100644
--- a/web/features/agent-v2/agent-detail/sidebar-actions.tsx
+++ b/web/features/agent-v2/agent-detail/sidebar-actions.tsx
@@ -13,12 +13,15 @@ import { toast } from '@langgenius/dify-ui/toast'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useExportAppDsl } from '@/app/components/app/use-export-app-dsl'
+import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
+import { useCanCreateAgents } from '@/features/agent-v2/permissions'
import { DeleteAgentDialog } from '@/features/agent-v2/roster/components/delete-agent-dialog'
import { DuplicateAgentDialog } from '@/features/agent-v2/roster/components/duplicate-agent-dialog'
import { EditAgentDialog } from '@/features/agent-v2/roster/components/edit-agent-dialog'
import { useRouter } from '@/next/navigation'
-type AgentDetailSidebarActionAgent = AgentFormSource & Pick<AgentAppPartial, 'app_id'>
+type AgentDetailSidebarActionAgent = AgentFormSource &
+ Pick<AgentAppPartial, 'app_id' | 'permission_keys'>
export function AgentDetailSidebarActions({ agent }: { agent: AgentDetailSidebarActionAgent }) {
const { t } = useTranslation('agentV2')
@@ -29,6 +32,8 @@ export function AgentDetailSidebarActions({ agent }: { agent: AgentDetailSidebar
const [isDeleteOpen, setIsDeleteOpen] = useState(false)
const { exportAppDsl, isExporting } = useExportAppDsl()
const router = useRouter()
+ const capabilities = getAgentACLCapabilities(agent.permission_keys)
+ const canDuplicate = useCanCreateAgents() && capabilities.canPreview
const handleEditOpen = () => {
setIsEditOpen(true)
}
@@ -38,6 +43,7 @@ export function AgentDetailSidebarActions({ agent }: { agent: AgentDetailSidebar
}
const handleExport = () => {
+ if (!capabilities.canImportExportDSL) return
if (!agent.app_id) {
toast.error(tApp(($) => $.exportFailed))
return
@@ -49,6 +55,14 @@ export function AgentDetailSidebarActions({ agent }: { agent: AgentDetailSidebar
})
}
+ if (
+ !capabilities.canEdit &&
+ !canDuplicate &&
+ !capabilities.canImportExportDSL &&
+ !capabilities.canDelete
+ )
+ return null
+
return (
<>
<DropdownMenu>
@@ -59,45 +73,65 @@ export function AgentDetailSidebarActions({ agent }: { agent: AgentDetailSidebar
<span aria-hidden className="i-ri-more-fill size-4" />
</DropdownMenuTrigger>
<DropdownMenuContent placement="bottom-end" sideOffset={4} className="w-40">
- <DropdownMenuItem className="gap-2" onClick={handleEditOpen}>
- <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />
- <span>{t(($) => $['roster.editInfo'])}</span>
- </DropdownMenuItem>
- <DropdownMenuItem className="gap-2" onClick={handleDuplicateOpen}>
- <span aria-hidden className="i-ri-file-copy-line size-4 shrink-0 text-text-tertiary" />
- <span>{tCommon(($) => $['operation.duplicate'])}</span>
- </DropdownMenuItem>
- <DropdownMenuItem className="gap-2" disabled={isExporting} onClick={handleExport}>
- <span
- aria-hidden
- className="i-ri-file-download-line size-4 shrink-0 text-text-tertiary"
- />
- <span>{tApp(($) => $.export)}</span>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- className="gap-2"
- onClick={() => setIsDeleteOpen(true)}
- >
- <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />
- <span>{tCommon(($) => $['operation.delete'])}</span>
- </DropdownMenuItem>
+ {capabilities.canEdit && (
+ <DropdownMenuItem className="gap-2" onClick={handleEditOpen}>
+ <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />
+ <span>{t(($) => $['roster.editInfo'])}</span>
+ </DropdownMenuItem>
+ )}
+ {canDuplicate && (
+ <DropdownMenuItem className="gap-2" onClick={handleDuplicateOpen}>
+ <span
+ aria-hidden
+ className="i-ri-file-copy-line size-4 shrink-0 text-text-tertiary"
+ />
+ <span>{tCommon(($) => $['operation.duplicate'])}</span>
+ </DropdownMenuItem>
+ )}
+ {capabilities.canImportExportDSL && (
+ <DropdownMenuItem className="gap-2" disabled={isExporting} onClick={handleExport}>
+ <span
+ aria-hidden
+ className="i-ri-file-download-line size-4 shrink-0 text-text-tertiary"
+ />
+ <span>{tApp(($) => $.export)}</span>
+ </DropdownMenuItem>
+ )}
+ {capabilities.canDelete &&
+ (capabilities.canEdit || canDuplicate || capabilities.canImportExportDSL) && (
+ <DropdownMenuSeparator />
+ )}
+ {capabilities.canDelete && (
+ <DropdownMenuItem
+ variant="destructive"
+ className="gap-2"
+ onClick={() => setIsDeleteOpen(true)}
+ >
+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />
+ <span>{tCommon(($) => $['operation.delete'])}</span>
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
- <EditAgentDialog agent={agent} open={isEditOpen} onOpenChange={setIsEditOpen} />
- <DuplicateAgentDialog
- agent={agent}
- open={isDuplicateOpen}
- onOpenChange={setIsDuplicateOpen}
- />
- <DeleteAgentDialog
- agentId={agent.id}
- agentName={agent.name}
- open={isDeleteOpen}
- onOpenChange={setIsDeleteOpen}
- onDeleted={() => router.replace('/agents')}
- />
+ {capabilities.canEdit && (
+ <EditAgentDialog agent={agent} open={isEditOpen} onOpenChange={setIsEditOpen} />
+ )}
+ {canDuplicate && (
+ <DuplicateAgentDialog
+ agent={agent}
+ open={isDuplicateOpen}
+ onOpenChange={setIsDuplicateOpen}
+ />
+ )}
+ {capabilities.canDelete && (
+ <DeleteAgentDialog
+ agentId={agent.id}
+ agentName={agent.name}
+ open={isDeleteOpen}
+ onOpenChange={setIsDeleteOpen}
+ onDeleted={() => router.replace('/agents')}
+ />
+ )}
</>
)
}
diff --git a/web/features/agent-v2/permissions.ts b/web/features/agent-v2/permissions.ts
index 322fd259f54..74d66ee0992 100644
--- a/web/features/agent-v2/permissions.ts
+++ b/web/features/agent-v2/permissions.ts
@@ -1,13 +1,39 @@
'use client'
+import { skipToken, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { workspacePermissionKeysAtom } from '@/context/permission-state'
+import {
+ agentDefaultPermissionKeysAtom,
+ workspacePermissionKeysAtom,
+} from '@/context/permission-state'
+import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { consoleQuery } from '@/service/console'
import { hasPermission } from '@/utils/permission'
+import { AgentPermission, getAgentACLCapabilities } from './acl'
-const AGENT_PREVIEW_PERMISSION_KEY = 'agent.acl.preview'
+export function useCanCreateAgents() {
+ return hasPermission(useAtomValue(workspacePermissionKeysAtom), AgentPermission.Create)
+}
+
+export function useCanImportAgents() {
+ return hasPermission(
+ useAtomValue(agentDefaultPermissionKeysAtom),
+ AgentPermission.ImportExportDSL,
+ )
+}
-export const useCanManageAgents = () => {
- const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
+export function useAgentPermissions(agentId: string | undefined) {
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
+ const agentQuery = useQuery(
+ consoleQuery.agent.byAgentId.get.queryOptions({
+ input: agentId ? { params: { agent_id: agentId } } : skipToken,
+ }),
+ )
- return hasPermission(workspacePermissionKeys, AGENT_PREVIEW_PERMISSION_KEY)
+ const capabilities = getAgentACLCapabilities(agentQuery.data?.permission_keys)
+ return {
+ agentQuery,
+ ...capabilities,
+ canAccessConfig: capabilities.canAccessConfig && systemFeatures.rbac_enabled,
+ }
}
diff --git a/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
index 93d279c6928..568929e7f29 100644
--- a/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
@@ -4,11 +4,17 @@ import { toast } from '@langgenius/dify-ui/toast'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { AgentPermission } from '@/features/agent-v2/acl'
import { AgentRosterList } from '../agent-roster-list'
const { duplicateAgentMutationFn } = vi.hoisted(() => ({
duplicateAgentMutationFn: vi.fn(),
}))
+const workspacePermissions = vi.hoisted(() => ({ canCreate: true }))
+vi.mock('@/features/agent-v2/permissions', () => ({
+ useCanCreateAgents: () => workspacePermissions.canCreate,
+}))
+
const exportAppDslMock = vi.hoisted(() => vi.fn())
const exportAppDslState = vi.hoisted(() => ({ isExporting: false }))
@@ -58,6 +64,7 @@ vi.mock('@/service/console', () => ({
}))
const createAgent = (overrides: Partial<AgentAppPartial> = {}): AgentAppPartial => ({
+ permission_keys: Object.values(AgentPermission),
active_config_is_published: false,
app_id: 'app-1',
description: 'Find and summarize market materials.',
@@ -104,6 +111,7 @@ const renderList = (agents: AgentAppPartial[], overrides: Partial<ReadyState> =
describe('AgentRosterList', () => {
beforeEach(() => {
vi.clearAllMocks()
+ workspacePermissions.canCreate = true
vi.spyOn(toast, 'error').mockReturnValue('toast-id')
vi.spyOn(toast, 'success').mockReturnValue('toast-id')
duplicateAgentMutationFn.mockResolvedValue(
@@ -595,4 +603,37 @@ describe('AgentRosterList', () => {
within(reopenedDialog).getByRole('button', { name: 'common.operation.save' }),
).toBeDisabled()
})
+
+ it('renders preview-only agent cards without navigation', () => {
+ workspacePermissions.canCreate = false
+ renderList([createAgent({ permission_keys: [AgentPermission.Preview] })])
+
+ const card = screen.getByRole('listitem', { name: 'Research Agent' })
+ expect(within(card).queryByRole('link', { name: 'Research Agent' })).not.toBeInTheDocument()
+ expect(card).toHaveAccessibleDescription(
+ 'agentV2.roster.usageStatus.draft Find and summarize market materials.',
+ )
+ })
+
+ it('links viewers to access points and hides mutation menus including the context menu', async () => {
+ workspacePermissions.canCreate = false
+ renderList([
+ createAgent({ permission_keys: [AgentPermission.Preview, AgentPermission.AccessPointView] }),
+ ])
+ const link = screen.getByRole('link', { name: 'Research Agent' })
+ expect(link).toHaveAttribute('href', '/agents/agent-1/access')
+ expect(screen.queryByRole('button', { name: /roster.moreActions/ })).not.toBeInTheDocument()
+ await userEvent.pointer({ target: link, keys: '[MouseRight]' })
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
+ it('allows duplication with workspace create permission without granting resource edits', async () => {
+ renderList([
+ createAgent({ permission_keys: [AgentPermission.Preview, AgentPermission.AccessPointView] }),
+ ])
+ await userEvent.click(screen.getByRole('button', { name: /roster.moreActions/ }))
+ expect(screen.getAllByRole('menuitem').map((item) => item.textContent)).toEqual([
+ 'common.operation.duplicate',
+ ])
+ })
})
diff --git a/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx b/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx
index 5993db4ab83..2ad973879da 100644
--- a/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx
@@ -53,6 +53,7 @@ const createAgent = (overrides: Partial<AgentAppPartial> = {}): AgentAppPartial
id: 'agent-1',
mode: 'agent',
name: 'Research Agent',
+ permission_keys: [],
role: 'Research Assistant',
...overrides,
})
diff --git a/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx b/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx
index 74f8145ca44..c6995c1e539 100644
--- a/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx
@@ -69,6 +69,7 @@ const createAgent = (overrides: Partial<AgentAppPartial> = {}): AgentAppPartial
icon_url: null,
mode: 'agent',
name: 'Research Agent',
+ permission_keys: [],
role: 'Research Assistant',
...overrides,
})
diff --git a/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx b/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx
index ee8258b08dd..1e3f4415fc9 100644
--- a/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx
@@ -4,6 +4,13 @@ import userEvent from '@testing-library/user-event'
import { renderWithNuqs } from '@/test/nuqs-testing'
import { RosterToolbar } from '../roster-toolbar'
+const permissions = vi.hoisted(() => ({ canCreate: true, canImport: true }))
+
+vi.mock('@/features/agent-v2/permissions', () => ({
+ useCanCreateAgents: () => permissions.canCreate,
+ useCanImportAgents: () => permissions.canImport,
+}))
+
vi.mock('@/app/components/app/create-from-dsl-modal', () => ({
default: ({ show, onSuccess }: { show: boolean; onSuccess?: () => void }) =>
show ? (
@@ -39,6 +46,38 @@ const renderToolbar = ({
}
describe('RosterToolbar', () => {
+ beforeEach(() => {
+ permissions.canCreate = true
+ permissions.canImport = true
+ })
+
+ it.each([
+ { canCreate: true, canImport: false },
+ { canCreate: false, canImport: true },
+ ])('separates create and import permissions: %o', async (grants) => {
+ Object.assign(permissions, grants)
+ renderToolbar()
+
+ await userEvent.click(screen.getByRole('button', { name: 'common.operation.create' }))
+
+ expect(Boolean(screen.queryByRole('menuitem', { name: 'app.newApp.startFromBlank' }))).toBe(
+ grants.canCreate,
+ )
+ expect(Boolean(screen.queryByRole('menuitem', { name: /app\.importDSL/ }))).toBe(
+ grants.canImport,
+ )
+ })
+
+ it('hides the create menu when neither action is permitted', () => {
+ permissions.canCreate = false
+ permissions.canImport = false
+ renderToolbar()
+
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.create' }),
+ ).not.toBeInTheDocument()
+ })
+
it('opens the shared create menu for blank Agent creation and DSL import', async () => {
const user = userEvent.setup()
const { queryClient } = renderToolbar()
diff --git a/web/features/agent-v2/roster/components/agent-roster-list.tsx b/web/features/agent-v2/roster/components/agent-roster-list.tsx
index 44625a88fd8..77ff2d6371b 100644
--- a/web/features/agent-v2/roster/components/agent-roster-list.tsx
+++ b/web/features/agent-v2/roster/components/agent-roster-list.tsx
@@ -26,6 +26,8 @@ import { useExportAppDsl } from '@/app/components/app/use-export-app-dsl'
import AppIcon from '@/app/components/base/app-icon'
import { SkeletonRectangle } from '@/app/components/base/skeleton'
import { MAIN_NAV_APP_CARD_GRID_CLASS_NAME } from '@/app/components/main-nav/app-card-grid'
+import { getAgentACLCapabilities, getAgentDefaultSection } from '@/features/agent-v2/acl'
+import { useCanCreateAgents } from '@/features/agent-v2/permissions'
import useTimestamp from '@/hooks/use-timestamp'
import Link from '@/next/link'
import { AgentWorkflowReferencesDropdown } from './agent-workflow-references-dropdown'
@@ -155,10 +157,10 @@ function AgentRosterPlaceholderState({
type AgentCardActionMenuItemsProps = {
kind: 'context' | 'dropdown'
isExporting: boolean
- onDelete: () => void
- onDuplicate: () => void
- onEdit: () => void
- onExport: () => void
+ onDelete?: () => void
+ onDuplicate?: () => void
+ onEdit?: () => void
+ onExport?: () => void
}
function AgentCardActionMenuItems({
@@ -177,23 +179,31 @@ function AgentCardActionMenuItems({
return (
<>
- <MenuItem className="gap-2" onClick={onEdit}>
- <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />
- <span>{t(($) => $['roster.editInfo'])}</span>
- </MenuItem>
- <MenuItem className="gap-2" onClick={onDuplicate}>
- <span aria-hidden className="i-ri-file-copy-line size-4 shrink-0 text-text-tertiary" />
- <span>{tCommon(($) => $['operation.duplicate'])}</span>
- </MenuItem>
- <MenuItem className="gap-2" disabled={isExporting} onClick={onExport}>
- <span aria-hidden className="i-ri-download-line size-4 shrink-0 text-text-tertiary" />
- <span>{tApp(($) => $.export)}</span>
- </MenuItem>
- <MenuSeparator />
- <MenuItem variant="destructive" className="gap-2" onClick={onDelete}>
- <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />
- <span>{tCommon(($) => $['operation.delete'])}</span>
- </MenuItem>
+ {onEdit && (
+ <MenuItem className="gap-2" onClick={onEdit}>
+ <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />
+ <span>{t(($) => $['roster.editInfo'])}</span>
+ </MenuItem>
+ )}
+ {onDuplicate && (
+ <MenuItem className="gap-2" onClick={onDuplicate}>
+ <span aria-hidden className="i-ri-file-copy-line size-4 shrink-0 text-text-tertiary" />
+ <span>{tCommon(($) => $['operation.duplicate'])}</span>
+ </MenuItem>
+ )}
+ {onExport && (
+ <MenuItem className="gap-2" disabled={isExporting} onClick={onExport}>
+ <span aria-hidden className="i-ri-download-line size-4 shrink-0 text-text-tertiary" />
+ <span>{tApp(($) => $.export)}</span>
+ </MenuItem>
+ )}
+ {onDelete && (onEdit || onDuplicate || onExport) && <MenuSeparator />}
+ {onDelete && (
+ <MenuItem variant="destructive" className="gap-2" onClick={onDelete}>
+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />
+ <span>{tCommon(($) => $['operation.delete'])}</span>
+ </MenuItem>
+ )}
</>
)
}
@@ -207,6 +217,14 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
const draftStatusId = useId()
const [activeDialog, setActiveDialog] = useState<'delete' | 'duplicate' | 'edit' | null>(null)
const { exportAppDsl, isExporting } = useExportAppDsl()
+ const capabilities = getAgentACLCapabilities(agent.permission_keys)
+ const canDuplicate = useCanCreateAgents() && capabilities.canPreview
+ const hasActions =
+ capabilities.canEdit ||
+ canDuplicate ||
+ capabilities.canImportExportDSL ||
+ capabilities.canDelete
+ const defaultSection = getAgentDefaultSection(capabilities)
const updatedAt =
agent.updated_at != null
? formatTime(
@@ -250,6 +268,7 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
}
const handleExport = () => {
+ if (!capabilities.canImportExportDSL) return
if (!agent.app_id) {
toast.error(tApp(($) => $.exportFailed))
return
@@ -261,95 +280,111 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
})
}
+ const cardContent = (
+ <>
+ <div className="flex items-center gap-3 pt-3.5 pr-4 pb-2 pl-3.5">
+ <span aria-hidden className="shrink-0">
+ <AppIcon
+ size="xl"
+ rounded
+ iconType={iconType}
+ icon={agent.icon ?? undefined}
+ background={agent.icon_background}
+ imageUrl={imageUrl}
+ />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5 py-px">
+ <h2 id={nameId} className="truncate system-md-semibold text-text-secondary">
+ {agent.name}
+ </h2>
+ <p className="truncate system-xs-regular text-text-tertiary">{agent.role}</p>
+ </div>
+ </div>
+ <div className="px-4 py-1 system-xs-regular text-text-tertiary">
+ <div id={descriptionId} className="line-clamp-2 min-h-8">
+ {agent.description}
+ </div>
+ </div>
+ {isDraft && (
+ <div className="pointer-events-none absolute top-[-0.5px] right-0 flex h-5 items-start overflow-hidden">
+ <div className="h-5 w-3 bg-background-section-burn [clip-path:polygon(0_0,100%_0,100%_100%)]" />
+ <div
+ id={draftStatusId}
+ className="flex h-5 items-center bg-background-section-burn pr-2 pl-0.5 system-2xs-medium-uppercase text-text-tertiary"
+ >
+ {t(($) => $['roster.usageStatus.draft'])}
+ </div>
+ </div>
+ )}
+ </>
+ )
+ const cardClassName = 'flex h-full min-w-0 flex-col rounded-xl pb-9 outline-hidden'
+
return (
<li
aria-labelledby={nameId}
+ aria-describedby={defaultSection ? undefined : accessibleDescriptionIds || undefined}
className="group relative isolate col-span-1 h-36.5 min-w-0 overflow-hidden rounded-xl border-[0.5px] border-solid border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3 transition-shadow duration-200 ease-in-out after:pointer-events-none after:absolute after:inset-0 after:z-1 after:rounded-xl after:content-[''] focus-within:bg-components-card-bg-alt hover:bg-components-card-bg-alt hover:shadow-md hover:shadow-shadow-shadow-5 has-data-popup-open:bg-components-card-bg-alt has-data-popup-open:shadow-md has-data-popup-open:shadow-shadow-shadow-5 has-[>a:focus-visible]:after:inset-ring-2 has-[>a:focus-visible]:after:inset-ring-state-accent-solid motion-reduce:transition-none [@media(hover:none)]:bg-components-card-bg-alt"
>
<ContextMenu>
<ContextMenuTrigger
render={
- <Link
- href={`/agents/${agent.id}/configure`}
- aria-labelledby={nameId}
- aria-describedby={accessibleDescriptionIds || undefined}
- className="flex h-full min-w-0 cursor-pointer touch-manipulation flex-col rounded-xl pb-9 outline-hidden"
- >
- <div className="flex items-center gap-3 pt-3.5 pr-4 pb-2 pl-3.5">
- <span aria-hidden className="shrink-0">
- <AppIcon
- size="xl"
- rounded
- iconType={iconType}
- icon={agent.icon ?? undefined}
- background={agent.icon_background}
- imageUrl={imageUrl}
- />
- </span>
- <div className="flex min-w-0 flex-1 flex-col gap-0.5 py-px">
- <h2 id={nameId} className="truncate system-md-semibold text-text-secondary">
- {agent.name}
- </h2>
- <p className="truncate system-xs-regular text-text-tertiary">{agent.role}</p>
- </div>
- </div>
- <div className="px-4 py-1 system-xs-regular text-text-tertiary">
- <div id={descriptionId} className="line-clamp-2 min-h-8">
- {agent.description}
- </div>
- </div>
- {isDraft && (
- <div className="pointer-events-none absolute top-[-0.5px] right-0 flex h-5 items-start overflow-hidden">
- <div className="h-5 w-3 bg-background-section-burn [clip-path:polygon(0_0,100%_0,100%_100%)]" />
- <div
- id={draftStatusId}
- className="flex h-5 items-center bg-background-section-burn pr-2 pl-0.5 system-2xs-medium-uppercase text-text-tertiary"
- >
- {t(($) => $['roster.usageStatus.draft'])}
- </div>
- </div>
- )}
- </Link>
+ defaultSection ? (
+ <Link
+ href={`/agents/${agent.id}/${defaultSection}`}
+ aria-labelledby={nameId}
+ aria-describedby={accessibleDescriptionIds || undefined}
+ className={cn(cardClassName, 'cursor-pointer touch-manipulation')}
+ >
+ {cardContent}
+ </Link>
+ ) : (
+ <div className={cardClassName}>{cardContent}</div>
+ )
}
/>
- <ContextMenuContent className="w-40">
- <AgentCardActionMenuItems
- kind="context"
- isExporting={isExporting}
- onEdit={handleEditOpen}
- onDuplicate={handleDuplicateOpen}
- onExport={handleExport}
- onDelete={handleDeleteOpen}
- />
- </ContextMenuContent>
- </ContextMenu>
- <div className="pointer-events-none absolute top-[-0.5px] right-[-0.5px] flex h-16 w-30 items-start justify-end bg-[linear-gradient(67deg,var(--color-components-card-bg-alt-transparent)_0%,var(--color-components-card-bg-alt)_75%)] p-2 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 has-data-popup-open:opacity-100 [@media(hover:none)]:opacity-100">
- <div className="pointer-events-none flex items-center overflow-hidden rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-lg backdrop-blur-xs group-focus-within:pointer-events-auto group-hover:pointer-events-auto has-data-popup-open:pointer-events-auto [@media(hover:none)]:pointer-events-auto">
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger
- render={
- <IconButton
- aria-label={t(($) => $['roster.moreActions'], { name: agent.name })}
- size="lg"
- className="data-popup-open:bg-state-base-hover"
- >
- <span aria-hidden className="i-ri-more-fill size-4.5" />
- </IconButton>
- }
+ {hasActions && (
+ <ContextMenuContent className="w-40">
+ <AgentCardActionMenuItems
+ kind="context"
+ isExporting={isExporting}
+ onEdit={capabilities.canEdit ? handleEditOpen : undefined}
+ onDuplicate={canDuplicate ? handleDuplicateOpen : undefined}
+ onExport={capabilities.canImportExportDSL ? handleExport : undefined}
+ onDelete={capabilities.canDelete ? handleDeleteOpen : undefined}
/>
- <DropdownMenuContent placement="bottom-end" sideOffset={4} className="w-40">
- <AgentCardActionMenuItems
- kind="dropdown"
- isExporting={isExporting}
- onEdit={handleEditOpen}
- onDuplicate={handleDuplicateOpen}
- onExport={handleExport}
- onDelete={handleDeleteOpen}
+ </ContextMenuContent>
+ )}
+ </ContextMenu>
+ {hasActions && (
+ <div className="pointer-events-none absolute top-[-0.5px] right-[-0.5px] flex h-16 w-30 items-start justify-end bg-[linear-gradient(67deg,var(--color-components-card-bg-alt-transparent)_0%,var(--color-components-card-bg-alt)_75%)] p-2 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 has-data-popup-open:opacity-100 [@media(hover:none)]:opacity-100">
+ <div className="pointer-events-none flex items-center overflow-hidden rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-lg backdrop-blur-xs group-focus-within:pointer-events-auto group-hover:pointer-events-auto has-data-popup-open:pointer-events-auto [@media(hover:none)]:pointer-events-auto">
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ aria-label={t(($) => $['roster.moreActions'], { name: agent.name })}
+ size="lg"
+ className="data-popup-open:bg-state-base-hover"
+ >
+ <span aria-hidden className="i-ri-more-fill size-4.5" />
+ </IconButton>
+ }
/>
- </DropdownMenuContent>
- </DropdownMenu>
+ <DropdownMenuContent placement="bottom-end" sideOffset={4} className="w-40">
+ <AgentCardActionMenuItems
+ kind="dropdown"
+ isExporting={isExporting}
+ onEdit={capabilities.canEdit ? handleEditOpen : undefined}
+ onDuplicate={canDuplicate ? handleDuplicateOpen : undefined}
+ onExport={capabilities.canImportExportDSL ? handleExport : undefined}
+ onDelete={capabilities.canDelete ? handleDeleteOpen : undefined}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
</div>
- </div>
+ )}
<div className="pointer-events-none absolute inset-x-0 bottom-0 flex min-w-0 items-center pt-2 pr-3 pb-3 pl-4 system-xs-regular text-text-tertiary">
<div className="flex min-w-0 flex-1 items-center gap-1.5">
{hasPublishedReferences ? (
@@ -380,22 +415,28 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
)}
</div>
</div>
- <EditAgentDialog
- agent={agent}
- open={activeDialog === 'edit'}
- onOpenChange={handleDialogOpenChange}
- />
- <DuplicateAgentDialog
- agent={agent}
- open={activeDialog === 'duplicate'}
- onOpenChange={handleDialogOpenChange}
- />
- <DeleteAgentDialog
- agentId={agent.id}
- agentName={agent.name}
- open={activeDialog === 'delete'}
- onOpenChange={handleDialogOpenChange}
- />
+ {capabilities.canEdit && (
+ <EditAgentDialog
+ agent={agent}
+ open={activeDialog === 'edit'}
+ onOpenChange={handleDialogOpenChange}
+ />
+ )}
+ {canDuplicate && (
+ <DuplicateAgentDialog
+ agent={agent}
+ open={activeDialog === 'duplicate'}
+ onOpenChange={handleDialogOpenChange}
+ />
+ )}
+ {capabilities.canDelete && (
+ <DeleteAgentDialog
+ agentId={agent.id}
+ agentName={agent.name}
+ open={activeDialog === 'delete'}
+ onOpenChange={handleDialogOpenChange}
+ />
+ )}
</li>
)
}
diff --git a/web/features/agent-v2/roster/components/roster-create-menu.tsx b/web/features/agent-v2/roster/components/roster-create-menu.tsx
index cbd56206792..d0407041ec7 100644
--- a/web/features/agent-v2/roster/components/roster-create-menu.tsx
+++ b/web/features/agent-v2/roster/components/roster-create-menu.tsx
@@ -4,6 +4,7 @@ import { useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { CreateAppDropdown } from '@/app/components/app/create-app-dropdown'
import CreateFromDSLModal from '@/app/components/app/create-from-dsl-modal'
+import { useCanCreateAgents, useCanImportAgents } from '@/features/agent-v2/permissions'
import { consoleQuery } from '@/service/console'
import { CreateAgentDialog } from './create-agent-dialog'
@@ -11,15 +12,21 @@ export function RosterCreateMenu() {
const queryClient = useQueryClient()
const [createDialogOpen, setCreateDialogOpen] = useState(false)
const [importDialogOpen, setImportDialogOpen] = useState(false)
+ const canCreate = useCanCreateAgents()
+ const canImport = useCanImportAgents()
+
+ if (!canCreate && !canImport) return null
return (
<>
<CreateAppDropdown
- onCreateBlank={() => setCreateDialogOpen(true)}
- onImportDSL={() => setImportDialogOpen(true)}
+ onCreateBlank={canCreate ? () => setCreateDialogOpen(true) : undefined}
+ onImportDSL={canImport ? () => setImportDialogOpen(true) : undefined}
/>
- <CreateAgentDialog open={createDialogOpen} onOpenChange={setCreateDialogOpen} />
- {importDialogOpen && (
+ {canCreate && (
+ <CreateAgentDialog open={createDialogOpen} onOpenChange={setCreateDialogOpen} />
+ )}
+ {canImport && importDialogOpen && (
<CreateFromDSLModal
show
onClose={() => setImportDialogOpen(false)}
diff --git a/web/i18n/ar-TN/agent-v-2.json b/web/i18n/ar-TN/agent-v-2.json
index 6b09a846c84..0ea495f0052 100644
--- a/web/i18n/ar-TN/agent-v-2.json
+++ b/web/i18n/ar-TN/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "تنقّل الوكيل",
"agentDetail.publish": "نشر",
"agentDetail.sections.access": "نقطة الوصول",
+ "agentDetail.sections.access-config": "الوصول إلى الموارد",
"agentDetail.sections.configure": "تكوين",
"agentDetail.sections.logs": "السجلات",
"agentDetail.sections.monitoring": "المراقبة",
diff --git a/web/i18n/ar-TN/permission.json b/web/i18n/ar-TN/permission.json
index 572f90d55b6..934948c1b2e 100644
--- a/web/i18n/ar-TN/permission.json
+++ b/web/i18n/ar-TN/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "الإجراءات",
"accessRule.addMemberAria": "إضافة {{name}}",
"accessRule.addMembersTitle": "إضافة أعضاء",
+ "accessRule.agentDescription": "إدارة من يمكنه الوصول إلى هذا الوكيل وأذوناتهم.",
+ "accessRule.agentTitle": "مجموعة أذونات الوكيل",
"accessRule.allowedMembers": "الأعضاء المسموح لهم",
"accessRule.appDescription": "حدّد من يمكنه الوصول إلى هذا التطبيق ودرجة تفصيل أذونات الوصول.",
"accessRule.appTitle": "مجموعة أذونات التطبيق",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "مالك مساحة العمل",
"common.duplicateAction": "تكرار",
"group.agent": "الوكلاء",
+ "group.agent_acl": "أذونات الوصول إلى الوكيل",
"group.app": "التطبيقات",
"group.app_acl": "أذونات الوصول إلى التطبيق",
"group.billing": "الفوترة",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "الوصف",
"permissionSet.descriptionPlaceholder": "صف ما تمنحه مجموعة الأذونات هذه",
"permissionSet.learnMore": "تعرّف على المزيد حول الأذونات",
+ "permissionSet.modal.create.agent.description": "أنشئ مجموعة أذونات وكيل يمكن الرجوع إليها في قواعد الوصول للتفويض السريع.",
+ "permissionSet.modal.create.agent.title": "إنشاء مجموعة أذونات الوكيل",
"permissionSet.modal.create.app.description": "أنشئ مجموعة أذونات تطبيق يمكن الرجوع إليها في قواعد الوصول للتفويض السريع.",
"permissionSet.modal.create.app.title": "إنشاء مجموعة أذونات التطبيق",
"permissionSet.modal.create.dataset.description": "أنشئ مجموعة أذونات قاعدة معرفة يمكن الرجوع إليها في قواعد الوصول للتفويض السريع.",
"permissionSet.modal.create.dataset.title": "إنشاء مجموعة أذونات قاعدة المعرفة",
+ "permissionSet.modal.edit.agent.description": "عدّل الاسم والوصف والأذونات الممنوحة لمجموعة الأذونات هذه.",
+ "permissionSet.modal.edit.agent.title": "تعديل مجموعة أذونات الوكيل",
"permissionSet.modal.edit.app.description": "عدّل الاسم والوصف والأذونات الممنوحة لمجموعة الأذونات هذه.",
"permissionSet.modal.edit.app.title": "تعديل مجموعة أذونات التطبيق",
"permissionSet.modal.edit.dataset.description": "عدّل الاسم والوصف والأذونات الممنوحة لمجموعة الأذونات هذه.",
"permissionSet.modal.edit.dataset.title": "تعديل مجموعة أذونات قاعدة المعرفة",
+ "permissionSet.modal.view.agent.description": "اعرض الاسم والوصف والأذونات الممنوحة لمجموعة الأذونات هذه.",
+ "permissionSet.modal.view.agent.title": "عرض مجموعة أذونات الوكيل",
"permissionSet.modal.view.app.description": "اعرض الاسم والوصف والأذونات الممنوحة لمجموعة الأذونات هذه.",
"permissionSet.modal.view.app.title": "عرض مجموعة أذونات التطبيق",
"permissionSet.modal.view.dataset.description": "اعرض الاسم والوصف والأذونات الممنوحة لمجموعة الأذونات هذه.",
diff --git a/web/i18n/de-DE/agent-v-2.json b/web/i18n/de-DE/agent-v-2.json
index 1a66c8afafb..c241b8ca8ad 100644
--- a/web/i18n/de-DE/agent-v-2.json
+++ b/web/i18n/de-DE/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Agenten-Navigation",
"agentDetail.publish": "Veröffentlichen",
"agentDetail.sections.access": "Zugangspunkt",
+ "agentDetail.sections.access-config": "Ressourcenzugriff",
"agentDetail.sections.configure": "Konfigurieren",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoring",
diff --git a/web/i18n/de-DE/permission.json b/web/i18n/de-DE/permission.json
index 3515bf694c1..f041ea7388e 100644
--- a/web/i18n/de-DE/permission.json
+++ b/web/i18n/de-DE/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Aktionen",
"accessRule.addMemberAria": "{{name}} hinzufügen",
"accessRule.addMembersTitle": "Mitglieder hinzufügen",
+ "accessRule.agentDescription": "Verwalte, wer auf diesen Agenten zugreifen kann und welche Berechtigungen diese Personen haben.",
+ "accessRule.agentTitle": "Agent-Berechtigungssatz",
"accessRule.allowedMembers": "Zulässige Mitglieder",
"accessRule.appDescription": "Legen Sie fest, wer auf diese App zugreifen kann und wie granular die Zugriffsberechtigungen sind.",
"accessRule.appTitle": "App-Berechtigungssatz",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Workspace-Inhaber",
"common.duplicateAction": "Duplizieren",
"group.agent": "Agenten",
+ "group.agent_acl": "Agent-Zugriffsberechtigungen",
"group.app": "Anwendungen",
"group.app_acl": "App-Zugriffsberechtigungen",
"group.billing": "Abrechnung",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Beschreibung",
"permissionSet.descriptionPlaceholder": "Beschreiben Sie, was dieser Berechtigungssatz gewährt",
"permissionSet.learnMore": "Mehr über Berechtigungen erfahren",
+ "permissionSet.modal.create.agent.description": "Erstellen Sie einen Agent-Berechtigungssatz, der in Zugriffsregeln zur schnellen Autorisierung referenziert werden kann.",
+ "permissionSet.modal.create.agent.title": "Agent-Berechtigungssatz erstellen",
"permissionSet.modal.create.app.description": "Erstellen Sie einen App-Berechtigungssatz, der in Zugriffsregeln zur schnellen Autorisierung referenziert werden kann.",
"permissionSet.modal.create.app.title": "App-Berechtigungssatz erstellen",
"permissionSet.modal.create.dataset.description": "Erstellen Sie einen Wissensdatenbank-Berechtigungssatz, der in Zugriffsregeln zur schnellen Autorisierung referenziert werden kann.",
"permissionSet.modal.create.dataset.title": "Wissensdatenbank-Berechtigungssatz erstellen",
+ "permissionSet.modal.edit.agent.description": "Ändern Sie den Namen, die Beschreibung und die für diesen Berechtigungssatz gewährten Berechtigungen.",
+ "permissionSet.modal.edit.agent.title": "Agent-Berechtigungssatz bearbeiten",
"permissionSet.modal.edit.app.description": "Ändern Sie den Namen, die Beschreibung und die für diesen Berechtigungssatz gewährten Berechtigungen.",
"permissionSet.modal.edit.app.title": "App-Berechtigungssatz bearbeiten",
"permissionSet.modal.edit.dataset.description": "Ändern Sie den Namen, die Beschreibung und die für diesen Berechtigungssatz gewährten Berechtigungen.",
"permissionSet.modal.edit.dataset.title": "Wissensdatenbank-Berechtigungssatz bearbeiten",
+ "permissionSet.modal.view.agent.description": "Sehen Sie den Namen, die Beschreibung und die für diesen Berechtigungssatz gewährten Berechtigungen.",
+ "permissionSet.modal.view.agent.title": "Agent-Berechtigungssatz anzeigen",
"permissionSet.modal.view.app.description": "Sehen Sie den Namen, die Beschreibung und die für diesen Berechtigungssatz gewährten Berechtigungen.",
"permissionSet.modal.view.app.title": "App-Berechtigungssatz anzeigen",
"permissionSet.modal.view.dataset.description": "Sehen Sie den Namen, die Beschreibung und die für diesen Berechtigungssatz gewährten Berechtigungen.",
diff --git a/web/i18n/en-US/agent-v-2.json b/web/i18n/en-US/agent-v-2.json
index 5ca7c4790c7..2c7542ed717 100644
--- a/web/i18n/en-US/agent-v-2.json
+++ b/web/i18n/en-US/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Agent navigation",
"agentDetail.publish": "Publish",
"agentDetail.sections.access": "Access Point",
+ "agentDetail.sections.access-config": "Resource Access",
"agentDetail.sections.configure": "Configure",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoring",
diff --git a/web/i18n/en-US/permission.json b/web/i18n/en-US/permission.json
index 82f7caa37e5..22c7f48c5be 100644
--- a/web/i18n/en-US/permission.json
+++ b/web/i18n/en-US/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Actions",
"accessRule.addMemberAria": "Add {{name}}",
"accessRule.addMembersTitle": "Add members",
+ "accessRule.agentDescription": "Manage who can access this agent and their permissions.",
+ "accessRule.agentTitle": "Agent Permission Set",
"accessRule.allowedMembers": "Allowed members",
"accessRule.appDescription": "Set who can access this app and the granularity of access permissions.",
"accessRule.appTitle": "App Permission Set",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Workspace Owner",
"common.duplicateAction": "Duplicate",
"group.agent": "Agents",
+ "group.agent_acl": "Agent access permissions",
"group.app": "Applications",
"group.app_acl": "App access permissions",
"group.billing": "Billing",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Description",
"permissionSet.descriptionPlaceholder": "Describe what this permission set grants",
"permissionSet.learnMore": "Learn more about permissions",
+ "permissionSet.modal.create.agent.description": "Create an agent permission set that can be referenced in access rules for quick authorization.",
+ "permissionSet.modal.create.agent.title": "Create Agent permission set",
"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.agent.description": "Modify the name, description, and permissions granted for this permission set.",
+ "permissionSet.modal.edit.agent.title": "Edit Agent 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.agent.description": "View the name, description, and permissions granted for this permission set.",
+ "permissionSet.modal.view.agent.title": "View Agent 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.",
diff --git a/web/i18n/es-ES/agent-v-2.json b/web/i18n/es-ES/agent-v-2.json
index 7a372d7a636..5a25fcf4528 100644
--- a/web/i18n/es-ES/agent-v-2.json
+++ b/web/i18n/es-ES/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Navegación del agente",
"agentDetail.publish": "Publicar",
"agentDetail.sections.access": "Punto de acceso",
+ "agentDetail.sections.access-config": "Acceso a recursos",
"agentDetail.sections.configure": "Configurar",
"agentDetail.sections.logs": "Registros",
"agentDetail.sections.monitoring": "Monitoreo",
diff --git a/web/i18n/es-ES/permission.json b/web/i18n/es-ES/permission.json
index bedfd13f146..163de1bd87a 100644
--- a/web/i18n/es-ES/permission.json
+++ b/web/i18n/es-ES/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Acciones",
"accessRule.addMemberAria": "Añadir {{name}}",
"accessRule.addMembersTitle": "Añadir miembros",
+ "accessRule.agentDescription": "Gestiona quién puede acceder a este agente y sus permisos.",
+ "accessRule.agentTitle": "Conjunto de permisos de agente",
"accessRule.allowedMembers": "Miembros permitidos",
"accessRule.appDescription": "Configura quién puede acceder a esta app y la granularidad de los permisos de acceso.",
"accessRule.appTitle": "Conjunto de permisos de app",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Propietario del espacio de trabajo",
"common.duplicateAction": "Duplicar",
"group.agent": "Agentes",
+ "group.agent_acl": "Permisos de acceso del agente",
"group.app": "Aplicaciones",
"group.app_acl": "Permisos de acceso de la app",
"group.billing": "Facturación",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Descripción",
"permissionSet.descriptionPlaceholder": "Describe qué concede este conjunto de permisos",
"permissionSet.learnMore": "Más información sobre los permisos",
+ "permissionSet.modal.create.agent.description": "Crea un conjunto de permisos de agente que se pueda referenciar en las reglas de acceso para una autorización rápida.",
+ "permissionSet.modal.create.agent.title": "Crear conjunto de permisos de agente",
"permissionSet.modal.create.app.description": "Crea un conjunto de permisos de app que se pueda referenciar en las reglas de acceso para una autorización rápida.",
"permissionSet.modal.create.app.title": "Crear conjunto de permisos de app",
"permissionSet.modal.create.dataset.description": "Crea un conjunto de permisos de base de conocimiento que se pueda referenciar en las reglas de acceso para una autorización rápida.",
"permissionSet.modal.create.dataset.title": "Crear conjunto de permisos de base de conocimiento",
+ "permissionSet.modal.edit.agent.description": "Modifica el nombre, la descripción y los permisos concedidos para este conjunto de permisos.",
+ "permissionSet.modal.edit.agent.title": "Editar conjunto de permisos de agente",
"permissionSet.modal.edit.app.description": "Modifica el nombre, la descripción y los permisos concedidos para este conjunto de permisos.",
"permissionSet.modal.edit.app.title": "Editar conjunto de permisos de app",
"permissionSet.modal.edit.dataset.description": "Modifica el nombre, la descripción y los permisos concedidos para este conjunto de permisos.",
"permissionSet.modal.edit.dataset.title": "Editar conjunto de permisos de base de conocimiento",
+ "permissionSet.modal.view.agent.description": "Consulta el nombre, la descripción y los permisos concedidos para este conjunto de permisos.",
+ "permissionSet.modal.view.agent.title": "Ver conjunto de permisos de agente",
"permissionSet.modal.view.app.description": "Consulta el nombre, la descripción y los permisos concedidos para este conjunto de permisos.",
"permissionSet.modal.view.app.title": "Ver conjunto de permisos de app",
"permissionSet.modal.view.dataset.description": "Consulta el nombre, la descripción y los permisos concedidos para este conjunto de permisos.",
diff --git a/web/i18n/fa-IR/agent-v-2.json b/web/i18n/fa-IR/agent-v-2.json
index df3e025e71d..72522584459 100644
--- a/web/i18n/fa-IR/agent-v-2.json
+++ b/web/i18n/fa-IR/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "ناوبری عامل",
"agentDetail.publish": "انتشار",
"agentDetail.sections.access": "نقطه دسترسی",
+ "agentDetail.sections.access-config": "دسترسی به منابع",
"agentDetail.sections.configure": "پیکربندی",
"agentDetail.sections.logs": "گزارش‌ها",
"agentDetail.sections.monitoring": "نظارت",
diff --git a/web/i18n/fa-IR/permission.json b/web/i18n/fa-IR/permission.json
index 696b9a841d4..4b957ed4d88 100644
--- a/web/i18n/fa-IR/permission.json
+++ b/web/i18n/fa-IR/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "اقدامات",
"accessRule.addMemberAria": "افزودن {{name}}",
"accessRule.addMembersTitle": "افزودن اعضا",
+ "accessRule.agentDescription": "دسترسی کاربران به این عامل و مجوزهای آن‌ها را مدیریت کنید.",
+ "accessRule.agentTitle": "مجموعه مجوز عامل",
"accessRule.allowedMembers": "اعضای مجاز",
"accessRule.appDescription": "مشخص کنید چه کسانی می‌توانند به این برنامه دسترسی داشته باشند و سطح جزئیات مجوزهای دسترسی را تعیین کنید.",
"accessRule.appTitle": "مجموعه مجوز برنامه",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "مالک فضای کاری",
"common.duplicateAction": "تکثیر",
"group.agent": "عامل‌ها",
+ "group.agent_acl": "مجوزهای دسترسی عامل",
"group.app": "برنامه‌ها",
"group.app_acl": "مجوزهای دسترسی برنامه",
"group.billing": "صورت‌حساب",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "توضیحات",
"permissionSet.descriptionPlaceholder": "توضیح دهید این مجموعه مجوز چه چیزی را اعطا می‌کند",
"permissionSet.learnMore": "درباره مجوزها بیشتر بدانید",
+ "permissionSet.modal.create.agent.description": "یک مجموعه مجوز عامل ایجاد کنید که بتوان برای مجوزدهی سریع در قوانین دسترسی به آن ارجاع داد.",
+ "permissionSet.modal.create.agent.title": "ایجاد مجموعه مجوز عامل",
"permissionSet.modal.create.app.description": "یک مجموعه مجوز برنامه ایجاد کنید که بتوان برای مجوزدهی سریع در قوانین دسترسی به آن ارجاع داد.",
"permissionSet.modal.create.app.title": "ایجاد مجموعه مجوز برنامه",
"permissionSet.modal.create.dataset.description": "یک مجموعه مجوز پایگاه دانش ایجاد کنید که بتوان برای مجوزدهی سریع در قوانین دسترسی به آن ارجاع داد.",
"permissionSet.modal.create.dataset.title": "ایجاد مجموعه مجوز پایگاه دانش",
+ "permissionSet.modal.edit.agent.description": "نام، توضیحات و مجوزهای اعطاشده برای این مجموعه مجوز را اصلاح کنید.",
+ "permissionSet.modal.edit.agent.title": "ویرایش مجموعه مجوز عامل",
"permissionSet.modal.edit.app.description": "نام، توضیحات و مجوزهای اعطاشده برای این مجموعه مجوز را اصلاح کنید.",
"permissionSet.modal.edit.app.title": "ویرایش مجموعه مجوز برنامه",
"permissionSet.modal.edit.dataset.description": "نام، توضیحات و مجوزهای اعطاشده برای این مجموعه مجوز را اصلاح کنید.",
"permissionSet.modal.edit.dataset.title": "ویرایش مجموعه مجوز پایگاه دانش",
+ "permissionSet.modal.view.agent.description": "نام، توضیحات و مجوزهای اعطاشده برای این مجموعه مجوز را مشاهده کنید.",
+ "permissionSet.modal.view.agent.title": "مشاهده مجموعه مجوز عامل",
"permissionSet.modal.view.app.description": "نام، توضیحات و مجوزهای اعطاشده برای این مجموعه مجوز را مشاهده کنید.",
"permissionSet.modal.view.app.title": "مشاهده مجموعه مجوز برنامه",
"permissionSet.modal.view.dataset.description": "نام، توضیحات و مجوزهای اعطاشده برای این مجموعه مجوز را مشاهده کنید.",
diff --git a/web/i18n/fr-FR/agent-v-2.json b/web/i18n/fr-FR/agent-v-2.json
index ec9c54132e2..4109ab0fa1c 100644
--- a/web/i18n/fr-FR/agent-v-2.json
+++ b/web/i18n/fr-FR/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Navigation de l’agent",
"agentDetail.publish": "Publier",
"agentDetail.sections.access": "Point d’accès",
+ "agentDetail.sections.access-config": "Accès aux ressources",
"agentDetail.sections.configure": "Configurer",
"agentDetail.sections.logs": "Journaux",
"agentDetail.sections.monitoring": "Surveillance",
diff --git a/web/i18n/fr-FR/permission.json b/web/i18n/fr-FR/permission.json
index 5b12f52d3b5..0feceabe3c9 100644
--- a/web/i18n/fr-FR/permission.json
+++ b/web/i18n/fr-FR/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Actions",
"accessRule.addMemberAria": "Ajouter {{name}}",
"accessRule.addMembersTitle": "Ajouter des membres",
+ "accessRule.agentDescription": "Gérez les personnes pouvant accéder à cet agent et leurs autorisations.",
+ "accessRule.agentTitle": "Ensemble d'autorisations d’agent",
"accessRule.allowedMembers": "Membres autorisés",
"accessRule.appDescription": "Définissez qui peut accéder à cette application et la granularité des autorisations d’accès.",
"accessRule.appTitle": "Ensemble d'autorisations d'application",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Propriétaire de l’espace de travail",
"common.duplicateAction": "Dupliquer",
"group.agent": "Agents",
+ "group.agent_acl": "Autorisations d'accès à l’agent",
"group.app": "Applications",
"group.app_acl": "Autorisations d'accès à l'application",
"group.billing": "Facturation",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Description",
"permissionSet.descriptionPlaceholder": "Décrivez ce que cet ensemble d'autorisations accorde",
"permissionSet.learnMore": "En savoir plus sur les autorisations",
+ "permissionSet.modal.create.agent.description": "Créez un ensemble d'autorisations d’agent qui peut être référencé dans les règles d'accès pour une autorisation rapide.",
+ "permissionSet.modal.create.agent.title": "Créer un ensemble d'autorisations d’agent",
"permissionSet.modal.create.app.description": "Créez un ensemble d'autorisations d'application qui peut être référencé dans les règles d'accès pour une autorisation rapide.",
"permissionSet.modal.create.app.title": "Créer un ensemble d'autorisations d'application",
"permissionSet.modal.create.dataset.description": "Créez un ensemble d'autorisations de base de connaissances qui peut être référencé dans les règles d'accès pour une autorisation rapide.",
"permissionSet.modal.create.dataset.title": "Créer un ensemble d'autorisations de base de connaissances",
+ "permissionSet.modal.edit.agent.description": "Modifiez le nom, la description et les autorisations accordées pour cet ensemble d'autorisations.",
+ "permissionSet.modal.edit.agent.title": "Modifier l'ensemble d'autorisations d’agent",
"permissionSet.modal.edit.app.description": "Modifiez le nom, la description et les autorisations accordées pour cet ensemble d'autorisations.",
"permissionSet.modal.edit.app.title": "Modifier l'ensemble d'autorisations d'application",
"permissionSet.modal.edit.dataset.description": "Modifiez le nom, la description et les autorisations accordées pour cet ensemble d'autorisations.",
"permissionSet.modal.edit.dataset.title": "Modifier l'ensemble d'autorisations de base de connaissances",
+ "permissionSet.modal.view.agent.description": "Affichez le nom, la description et les autorisations accordées pour cet ensemble d'autorisations.",
+ "permissionSet.modal.view.agent.title": "Afficher l'ensemble d'autorisations d’agent",
"permissionSet.modal.view.app.description": "Affichez le nom, la description et les autorisations accordées pour cet ensemble d'autorisations.",
"permissionSet.modal.view.app.title": "Afficher l'ensemble d'autorisations d'application",
"permissionSet.modal.view.dataset.description": "Affichez le nom, la description et les autorisations accordées pour cet ensemble d'autorisations.",
diff --git a/web/i18n/hi-IN/agent-v-2.json b/web/i18n/hi-IN/agent-v-2.json
index 98527fb3fb0..e85880e2891 100644
--- a/web/i18n/hi-IN/agent-v-2.json
+++ b/web/i18n/hi-IN/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "एजेंट नेविगेशन",
"agentDetail.publish": "प्रकाशित करें",
"agentDetail.sections.access": "एक्सेस पॉइंट",
+ "agentDetail.sections.access-config": "संसाधन पहुँच",
"agentDetail.sections.configure": "कॉन्फ़िगर करें",
"agentDetail.sections.logs": "लॉग",
"agentDetail.sections.monitoring": "निगरानी",
diff --git a/web/i18n/hi-IN/permission.json b/web/i18n/hi-IN/permission.json
index 6c4859f7111..9cb3fdd0b54 100644
--- a/web/i18n/hi-IN/permission.json
+++ b/web/i18n/hi-IN/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "क्रियाएं",
"accessRule.addMemberAria": "{{name}} जोड़ें",
"accessRule.addMembersTitle": "सदस्य जोड़ें",
+ "accessRule.agentDescription": "इस एजेंट तक किसकी पहुँच है और उनकी अनुमतियाँ प्रबंधित करें।",
+ "accessRule.agentTitle": "एजेंट अनुमति सेट",
"accessRule.allowedMembers": "अनुमत सदस्य",
"accessRule.appDescription": "निर्धारित करें कि इस ऐप को कौन एक्सेस कर सकता है और पहुँच अनुमतियाँ कितनी विस्तृत होंगी।",
"accessRule.appTitle": "ऐप अनुमति सेट",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "वर्कस्पेस का मालिक",
"common.duplicateAction": "डुप्लिकेट करें",
"group.agent": "एजेंट",
+ "group.agent_acl": "एजेंट एक्सेस अनुमतियाँ",
"group.app": "अनुप्रयोग",
"group.app_acl": "ऐप एक्सेस अनुमतियाँ",
"group.billing": "बिलिंग",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "विवरण",
"permissionSet.descriptionPlaceholder": "वर्णन करें कि यह अनुमति सेट क्या प्रदान करता है",
"permissionSet.learnMore": "अनुमतियों के बारे में अधिक जानें",
+ "permissionSet.modal.create.agent.description": "एक एजेंट अनुमति सेट बनाएं जिसे त्वरित प्राधिकरण के लिए एक्सेस नियमों में संदर्भित किया जा सके।",
+ "permissionSet.modal.create.agent.title": "एजेंट अनुमति सेट बनाएं",
"permissionSet.modal.create.app.description": "एक ऐप अनुमति सेट बनाएं जिसे त्वरित प्राधिकरण के लिए एक्सेस नियमों में संदर्भित किया जा सके।",
"permissionSet.modal.create.app.title": "ऐप अनुमति सेट बनाएं",
"permissionSet.modal.create.dataset.description": "एक ज्ञान आधार अनुमति सेट बनाएं जिसे त्वरित प्राधिकरण के लिए एक्सेस नियमों में संदर्भित किया जा सके।",
"permissionSet.modal.create.dataset.title": "ज्ञान आधार अनुमति सेट बनाएं",
+ "permissionSet.modal.edit.agent.description": "इस अनुमति सेट के लिए नाम, विवरण और प्रदान की गई अनुमतियों को संशोधित करें।",
+ "permissionSet.modal.edit.agent.title": "एजेंट अनुमति सेट संपादित करें",
"permissionSet.modal.edit.app.description": "इस अनुमति सेट के लिए नाम, विवरण और प्रदान की गई अनुमतियों को संशोधित करें।",
"permissionSet.modal.edit.app.title": "ऐप अनुमति सेट संपादित करें",
"permissionSet.modal.edit.dataset.description": "इस अनुमति सेट के लिए नाम, विवरण और प्रदान की गई अनुमतियों को संशोधित करें।",
"permissionSet.modal.edit.dataset.title": "ज्ञान आधार अनुमति सेट संपादित करें",
+ "permissionSet.modal.view.agent.description": "इस अनुमति सेट के लिए नाम, विवरण और प्रदान की गई अनुमतियों को देखें।",
+ "permissionSet.modal.view.agent.title": "एजेंट अनुमति सेट देखें",
"permissionSet.modal.view.app.description": "इस अनुमति सेट के लिए नाम, विवरण और प्रदान की गई अनुमतियों को देखें।",
"permissionSet.modal.view.app.title": "ऐप अनुमति सेट देखें",
"permissionSet.modal.view.dataset.description": "इस अनुमति सेट के लिए नाम, विवरण और प्रदान की गई अनुमतियों को देखें।",
diff --git a/web/i18n/id-ID/agent-v-2.json b/web/i18n/id-ID/agent-v-2.json
index 27867573c0e..a4cff778845 100644
--- a/web/i18n/id-ID/agent-v-2.json
+++ b/web/i18n/id-ID/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Navigasi agen",
"agentDetail.publish": "Terbitkan",
"agentDetail.sections.access": "Titik Akses",
+ "agentDetail.sections.access-config": "Akses Sumber Daya",
"agentDetail.sections.configure": "Konfigurasikan",
"agentDetail.sections.logs": "Log",
"agentDetail.sections.monitoring": "Pemantauan",
diff --git a/web/i18n/id-ID/permission.json b/web/i18n/id-ID/permission.json
index 73fcb0b89f7..ec11135070e 100644
--- a/web/i18n/id-ID/permission.json
+++ b/web/i18n/id-ID/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Tindakan",
"accessRule.addMemberAria": "Tambahkan {{name}}",
"accessRule.addMembersTitle": "Tambahkan anggota",
+ "accessRule.agentDescription": "Kelola siapa yang dapat mengakses agen ini beserta izinnya.",
+ "accessRule.agentTitle": "Set izin Agen",
"accessRule.allowedMembers": "Anggota yang diizinkan",
"accessRule.appDescription": "Atur siapa yang dapat mengakses aplikasi ini dan tingkat perincian izin aksesnya.",
"accessRule.appTitle": "Set izin Aplikasi",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Pemilik Workspace",
"common.duplicateAction": "Duplikat",
"group.agent": "Agen",
+ "group.agent_acl": "Izin akses agen",
"group.app": "Aplikasi",
"group.app_acl": "Izin akses aplikasi",
"group.billing": "Penagihan",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Deskripsi",
"permissionSet.descriptionPlaceholder": "Jelaskan apa yang diberikan oleh set izin ini",
"permissionSet.learnMore": "Pelajari lebih lanjut tentang izin",
+ "permissionSet.modal.create.agent.description": "Buat set izin agen yang dapat dirujuk dalam aturan akses untuk otorisasi cepat.",
+ "permissionSet.modal.create.agent.title": "Buat set izin Agen",
"permissionSet.modal.create.app.description": "Buat set izin aplikasi yang dapat dirujuk dalam aturan akses untuk otorisasi cepat.",
"permissionSet.modal.create.app.title": "Buat set izin Aplikasi",
"permissionSet.modal.create.dataset.description": "Buat set izin basis pengetahuan yang dapat dirujuk dalam aturan akses untuk otorisasi cepat.",
"permissionSet.modal.create.dataset.title": "Buat set izin Basis Pengetahuan",
+ "permissionSet.modal.edit.agent.description": "Ubah nama, deskripsi, dan izin yang diberikan untuk set izin ini.",
+ "permissionSet.modal.edit.agent.title": "Edit set izin Agen",
"permissionSet.modal.edit.app.description": "Ubah nama, deskripsi, dan izin yang diberikan untuk set izin ini.",
"permissionSet.modal.edit.app.title": "Edit set izin Aplikasi",
"permissionSet.modal.edit.dataset.description": "Ubah nama, deskripsi, dan izin yang diberikan untuk set izin ini.",
"permissionSet.modal.edit.dataset.title": "Edit set izin Basis Pengetahuan",
+ "permissionSet.modal.view.agent.description": "Lihat nama, deskripsi, dan izin yang diberikan untuk set izin ini.",
+ "permissionSet.modal.view.agent.title": "Lihat set izin Agen",
"permissionSet.modal.view.app.description": "Lihat nama, deskripsi, dan izin yang diberikan untuk set izin ini.",
"permissionSet.modal.view.app.title": "Lihat set izin Aplikasi",
"permissionSet.modal.view.dataset.description": "Lihat nama, deskripsi, dan izin yang diberikan untuk set izin ini.",
diff --git a/web/i18n/it-IT/agent-v-2.json b/web/i18n/it-IT/agent-v-2.json
index b42095b5d70..db01e854827 100644
--- a/web/i18n/it-IT/agent-v-2.json
+++ b/web/i18n/it-IT/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Navigazione dell’agente",
"agentDetail.publish": "Pubblica",
"agentDetail.sections.access": "Punto di accesso",
+ "agentDetail.sections.access-config": "Accesso alle risorse",
"agentDetail.sections.configure": "Configura",
"agentDetail.sections.logs": "Log",
"agentDetail.sections.monitoring": "Monitoraggio",
diff --git a/web/i18n/it-IT/permission.json b/web/i18n/it-IT/permission.json
index 330dd67001b..d45cb5c6082 100644
--- a/web/i18n/it-IT/permission.json
+++ b/web/i18n/it-IT/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Azioni",
"accessRule.addMemberAria": "Aggiungi {{name}}",
"accessRule.addMembersTitle": "Aggiungi membri",
+ "accessRule.agentDescription": "Gestisci chi può accedere a questo agente e i relativi permessi.",
+ "accessRule.agentTitle": "Set di permessi per agente",
"accessRule.allowedMembers": "Membri autorizzati",
"accessRule.appDescription": "Imposta chi può accedere a questa app e il livello di granularità dei permessi di accesso.",
"accessRule.appTitle": "Set di permessi per app",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Proprietario del workspace",
"common.duplicateAction": "Duplica",
"group.agent": "Agenti",
+ "group.agent_acl": "Permessi di accesso all'agente",
"group.app": "Applicazioni",
"group.app_acl": "Permessi di accesso all'app",
"group.billing": "Fatturazione",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Descrizione",
"permissionSet.descriptionPlaceholder": "Descrivi cosa concede questo set di permessi",
"permissionSet.learnMore": "Scopri di più sui permessi",
+ "permissionSet.modal.create.agent.description": "Crea un set di permessi per agente che può essere referenziato nelle regole di accesso per un'autorizzazione rapida.",
+ "permissionSet.modal.create.agent.title": "Crea set di permessi per agente",
"permissionSet.modal.create.app.description": "Crea un set di permessi per app che può essere referenziato nelle regole di accesso per un'autorizzazione rapida.",
"permissionSet.modal.create.app.title": "Crea set di permessi per app",
"permissionSet.modal.create.dataset.description": "Crea un set di permessi per knowledge base che può essere referenziato nelle regole di accesso per un'autorizzazione rapida.",
"permissionSet.modal.create.dataset.title": "Crea set di permessi per knowledge base",
+ "permissionSet.modal.edit.agent.description": "Modifica il nome, la descrizione e i permessi concessi per questo set di permessi.",
+ "permissionSet.modal.edit.agent.title": "Modifica set di permessi per agente",
"permissionSet.modal.edit.app.description": "Modifica il nome, la descrizione e i permessi concessi per questo set di permessi.",
"permissionSet.modal.edit.app.title": "Modifica set di permessi per app",
"permissionSet.modal.edit.dataset.description": "Modifica il nome, la descrizione e i permessi concessi per questo set di permessi.",
"permissionSet.modal.edit.dataset.title": "Modifica set di permessi per knowledge base",
+ "permissionSet.modal.view.agent.description": "Visualizza il nome, la descrizione e i permessi concessi per questo set di permessi.",
+ "permissionSet.modal.view.agent.title": "Visualizza set di permessi per agente",
"permissionSet.modal.view.app.description": "Visualizza il nome, la descrizione e i permessi concessi per questo set di permessi.",
"permissionSet.modal.view.app.title": "Visualizza set di permessi per app",
"permissionSet.modal.view.dataset.description": "Visualizza il nome, la descrizione e i permessi concessi per questo set di permessi.",
diff --git a/web/i18n/ja-JP/agent-v-2.json b/web/i18n/ja-JP/agent-v-2.json
index c2123ba8a32..37089f8aaa7 100644
--- a/web/i18n/ja-JP/agent-v-2.json
+++ b/web/i18n/ja-JP/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "エージェントナビゲーション",
"agentDetail.publish": "公開",
"agentDetail.sections.access": "アクセスポイント",
+ "agentDetail.sections.access-config": "リソースアクセス",
"agentDetail.sections.configure": "設定",
"agentDetail.sections.logs": "ログ",
"agentDetail.sections.monitoring": "モニタリング",
diff --git a/web/i18n/ja-JP/permission.json b/web/i18n/ja-JP/permission.json
index a69cb7cb49b..26d18dc7728 100644
--- a/web/i18n/ja-JP/permission.json
+++ b/web/i18n/ja-JP/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "アクション",
"accessRule.addMemberAria": "{{name}} を追加",
"accessRule.addMembersTitle": "メンバーを追加",
+ "accessRule.agentDescription": "このエージェントにアクセスできるメンバーと権限を管理します。",
+ "accessRule.agentTitle": "エージェント権限セット",
"accessRule.allowedMembers": "許可されたメンバー",
"accessRule.appDescription": "このアプリにアクセスできるメンバーと、アクセス権限の粒度を設定します。",
"accessRule.appTitle": "アプリ権限セット",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "ワークスペースのオーナー",
"common.duplicateAction": "複製",
"group.agent": "エージェント",
+ "group.agent_acl": "エージェントアクセス権限",
"group.app": "アプリ",
"group.app_acl": "アプリアクセス権限",
"group.billing": "請求",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "説明",
"permissionSet.descriptionPlaceholder": "この権限セットが付与する内容を説明",
"permissionSet.learnMore": "権限について詳しく見る",
+ "permissionSet.modal.create.agent.description": "アクセスルールで参照できるエージェント権限セットを作成し、すばやく認可します。",
+ "permissionSet.modal.create.agent.title": "エージェント権限セットを作成",
"permissionSet.modal.create.app.description": "アクセスルールで参照できるアプリ権限セットを作成し、すばやく認可します。",
"permissionSet.modal.create.app.title": "アプリ権限セットを作成",
"permissionSet.modal.create.dataset.description": "アクセスルールで参照できるナレッジベース権限セットを作成し、すばやく認可します。",
"permissionSet.modal.create.dataset.title": "ナレッジベース権限セットを作成",
+ "permissionSet.modal.edit.agent.description": "この権限セットの名前、説明、付与される権限を変更します。",
+ "permissionSet.modal.edit.agent.title": "エージェント権限セットを編集",
"permissionSet.modal.edit.app.description": "この権限セットの名前、説明、付与される権限を変更します。",
"permissionSet.modal.edit.app.title": "アプリ権限セットを編集",
"permissionSet.modal.edit.dataset.description": "この権限セットの名前、説明、付与される権限を変更します。",
"permissionSet.modal.edit.dataset.title": "ナレッジベース権限セットを編集",
+ "permissionSet.modal.view.agent.description": "この権限セットの名前、説明、付与される権限を表示します。",
+ "permissionSet.modal.view.agent.title": "エージェント権限セットを表示",
"permissionSet.modal.view.app.description": "この権限セットの名前、説明、付与される権限を表示します。",
"permissionSet.modal.view.app.title": "アプリ権限セットを表示",
"permissionSet.modal.view.dataset.description": "この権限セットの名前、説明、付与される権限を表示します。",
diff --git a/web/i18n/ko-KR/agent-v-2.json b/web/i18n/ko-KR/agent-v-2.json
index 153b386096e..c1c06ca66dc 100644
--- a/web/i18n/ko-KR/agent-v-2.json
+++ b/web/i18n/ko-KR/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "에이전트 탐색",
"agentDetail.publish": "게시",
"agentDetail.sections.access": "액세스 지점",
+ "agentDetail.sections.access-config": "리소스 접근",
"agentDetail.sections.configure": "구성",
"agentDetail.sections.logs": "로그",
"agentDetail.sections.monitoring": "모니터링",
diff --git a/web/i18n/ko-KR/permission.json b/web/i18n/ko-KR/permission.json
index 1b9114dc05b..0da49432ace 100644
--- a/web/i18n/ko-KR/permission.json
+++ b/web/i18n/ko-KR/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "작업",
"accessRule.addMemberAria": "{{name}} 추가",
"accessRule.addMembersTitle": "멤버 추가",
+ "accessRule.agentDescription": "이 에이전트에 접근할 수 있는 멤버와 권한을 관리합니다.",
+ "accessRule.agentTitle": "에이전트 권한 집합",
"accessRule.allowedMembers": "허용된 멤버",
"accessRule.appDescription": "이 앱에 접근할 수 있는 대상과 접근 권한의 세분화 수준을 설정합니다.",
"accessRule.appTitle": "앱 권한 집합",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "워크스페이스 소유자",
"common.duplicateAction": "복제",
"group.agent": "에이전트",
+ "group.agent_acl": "에이전트 접근 권한",
"group.app": "애플리케이션",
"group.app_acl": "앱 접근 권한",
"group.billing": "결제",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "설명",
"permissionSet.descriptionPlaceholder": "이 권한 집합이 부여하는 내용을 설명하세요",
"permissionSet.learnMore": "권한에 대해 자세히 알아보기",
+ "permissionSet.modal.create.agent.description": "빠른 권한 부여를 위해 접근 규칙에서 참조할 수 있는 에이전트 권한 집합을 생성합니다.",
+ "permissionSet.modal.create.agent.title": "에이전트 권한 집합 생성",
"permissionSet.modal.create.app.description": "빠른 권한 부여를 위해 접근 규칙에서 참조할 수 있는 앱 권한 집합을 생성합니다.",
"permissionSet.modal.create.app.title": "앱 권한 집합 생성",
"permissionSet.modal.create.dataset.description": "빠른 권한 부여를 위해 접근 규칙에서 참조할 수 있는 지식 베이스 권한 집합을 생성합니다.",
"permissionSet.modal.create.dataset.title": "지식 베이스 권한 집합 생성",
+ "permissionSet.modal.edit.agent.description": "이 권한 집합의 이름, 설명 및 부여된 권한을 수정합니다.",
+ "permissionSet.modal.edit.agent.title": "에이전트 권한 집합 편집",
"permissionSet.modal.edit.app.description": "이 권한 집합의 이름, 설명 및 부여된 권한을 수정합니다.",
"permissionSet.modal.edit.app.title": "앱 권한 집합 편집",
"permissionSet.modal.edit.dataset.description": "이 권한 집합의 이름, 설명 및 부여된 권한을 수정합니다.",
"permissionSet.modal.edit.dataset.title": "지식 베이스 권한 집합 편집",
+ "permissionSet.modal.view.agent.description": "이 권한 집합의 이름, 설명 및 부여된 권한을 봅니다.",
+ "permissionSet.modal.view.agent.title": "에이전트 권한 집합 보기",
"permissionSet.modal.view.app.description": "이 권한 집합의 이름, 설명 및 부여된 권한을 봅니다.",
"permissionSet.modal.view.app.title": "앱 권한 집합 보기",
"permissionSet.modal.view.dataset.description": "이 권한 집합의 이름, 설명 및 부여된 권한을 봅니다.",
diff --git a/web/i18n/lo-LA/agent-v-2.json b/web/i18n/lo-LA/agent-v-2.json
index 4c9ebb25443..b6d62f45b27 100644
--- a/web/i18n/lo-LA/agent-v-2.json
+++ b/web/i18n/lo-LA/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "ການນຳທາງຕົວແທນ",
"agentDetail.publish": "ເຜີຍແຜ່",
"agentDetail.sections.access": "ຈຸດເຂົ້າເຖິງ",
+ "agentDetail.sections.access-config": "ການເຂົ້າເຖິງຊັບພະຍາກອນ",
"agentDetail.sections.configure": "ຕັ້ງຄ່າ",
"agentDetail.sections.logs": "ບັນທຶກ (Logs)",
"agentDetail.sections.monitoring": "ການຕິດຕາມ",
diff --git a/web/i18n/lo-LA/permission.json b/web/i18n/lo-LA/permission.json
index c820c0b6383..cfb16d624cd 100644
--- a/web/i18n/lo-LA/permission.json
+++ b/web/i18n/lo-LA/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "ການຈັດການ",
"accessRule.addMemberAria": "ເພີ່ມ {{name}}",
"accessRule.addMembersTitle": "ເພີ່ມສະມາຊິກ",
+ "accessRule.agentDescription": "ຈັດການຜູ້ທີ່ສາມາດເຂົ້າເຖິງຕົວແທນນີ້ ແລະ ສິດຂອງພວກເຂົາ.",
+ "accessRule.agentTitle": "ຊຸດການກຳນົດສິດຕົວແທນ",
"accessRule.allowedMembers": "ສະມາຊິກທີ່ອະນຸຍາດ",
"accessRule.appDescription": "ກຳນົດວ່າໃຜສາມາດເຂົ້າເຖິງແອັບນີ້ໄດ້ ແລະ ລະດັບຄວາມລະອຽດຂອງສິດການເຂົ້າເຖິງ.",
"accessRule.appTitle": "ຊຸດການກຳນົດສິດແອັບຯ",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "ເຈົ້າຂອງພື້ນທີ່ເຮັດວຽກ",
"common.duplicateAction": "ເຮັດສຳເນົາ",
"group.agent": "ຕົວແທນ",
+ "group.agent_acl": "ສິດການເຂົ້າເຖິງຕົວແທນ",
"group.app": "ແອັບພລິເຄຊັນ",
"group.app_acl": "ສິດການເຂົ້າເຖິງແອັບຯ",
"group.billing": "ການຊຳລະເງິນ",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "ຄຳອະທິບາຍ",
"permissionSet.descriptionPlaceholder": "ອະທິບາຍວ່າຊຸດສິດນີ້ອະນຸຍາດຫຍັງແດ່",
"permissionSet.learnMore": "ສຶກສາເພີ່ມເຕີມກ່ຽວກັບສິດການນຳໃຊ້",
+ "permissionSet.modal.create.agent.description": "ສ້າງຊຸດສິດຕົວແທນທີ່ສາມາດອ້າງອີງໃນກົດລະບຽບການເຂົ້າເຖິງເພື່ອການອະນຸຍາດທີ່ວ່ອງໄວ.",
+ "permissionSet.modal.create.agent.title": "ສ້າງຊຸດສິດຕົວແທນ",
"permissionSet.modal.create.app.description": "ສ້າງຊຸດສິດແອັບຯທີ່ສາມາດອ້າງອີງໃນກົດລະບຽບການເຂົ້າເຖິງເພື່ອການອະນຸຍາດທີ່ວ່ອງໄວ.",
"permissionSet.modal.create.app.title": "ສ້າງຊຸດສິດແອັບຯ",
"permissionSet.modal.create.dataset.description": "ສ້າງຊຸດສິດຖານຄວາມຮູ້ທີ່ສາມາດອ້າງອີງໃນກົດລະບຽບການເຂົ້າເຖິງເພື່ອການອະນຸຍາດທີ່ວ່ອງໄວ.",
"permissionSet.modal.create.dataset.title": "ສ້າງຊຸດສິດຖານຄວາມຮູ້",
+ "permissionSet.modal.edit.agent.description": "ແກ້ໄຂຊື່, ຄຳອະທິບາຍ ແລະ ສິດທີ່ໄດ້ຮັບສຳລັບຊຸດສິດນີ້.",
+ "permissionSet.modal.edit.agent.title": "ແກ້ໄຂຊຸດສິດຕົວແທນ",
"permissionSet.modal.edit.app.description": "ແກ້ໄຂຊື່, ຄຳອະທິບາຍ ແລະ ສິດທີ່ໄດ້ຮັບສຳລັບຊຸດສິດນີ້.",
"permissionSet.modal.edit.app.title": "ແກ້ໄຂຊຸດສິດແອັບຯ",
"permissionSet.modal.edit.dataset.description": "ແກ້ໄຂຊື່, ຄຳອະທິບາຍ ແລະ ສິດທີ່ໄດ້ຮັບສຳລັບຊຸດສິດນີ້.",
"permissionSet.modal.edit.dataset.title": "ແກ້ໄຂຊຸດສິດຖານຄວາມຮູ້",
+ "permissionSet.modal.view.agent.description": "ເບິ່ງຊື່, ຄຳອະທິບາຍ ແລະ ສິດທີ່ໄດ້ຮັບສຳລັບຊຸດສິດນີ້.",
+ "permissionSet.modal.view.agent.title": "ເບິ່ງຊຸດສິດຕົວແທນ",
"permissionSet.modal.view.app.description": "ເບິ່ງຊື່, ຄຳອະທິບາຍ ແລະ ສິດທີ່ໄດ້ຮັບສຳລັບຊຸດສິດນີ້.",
"permissionSet.modal.view.app.title": "ເບິ່ງຊຸດສິດແອັບຯ",
"permissionSet.modal.view.dataset.description": "ເບິ່ງຊື່, ຄຳອະທິບາຍ ແລະ ສິດທີ່ໄດ້ຮັບສຳລັບຊຸດສິດນີ້.",
diff --git a/web/i18n/nl-NL/agent-v-2.json b/web/i18n/nl-NL/agent-v-2.json
index 2ca6feeaaed..c83dee850fc 100644
--- a/web/i18n/nl-NL/agent-v-2.json
+++ b/web/i18n/nl-NL/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Agentnavigatie",
"agentDetail.publish": "Publiceren",
"agentDetail.sections.access": "Toegangspunt",
+ "agentDetail.sections.access-config": "Toegang tot bronnen",
"agentDetail.sections.configure": "Configureren",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoring",
diff --git a/web/i18n/nl-NL/permission.json b/web/i18n/nl-NL/permission.json
index dff5798020b..2602df5e6de 100644
--- a/web/i18n/nl-NL/permission.json
+++ b/web/i18n/nl-NL/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Acties",
"accessRule.addMemberAria": "{{name}} toevoegen",
"accessRule.addMembersTitle": "Leden toevoegen",
+ "accessRule.agentDescription": "Beheer wie toegang heeft tot deze agent en welke rechten zij hebben.",
+ "accessRule.agentTitle": "Agent-rechtenset",
"accessRule.allowedMembers": "Toegestane leden",
"accessRule.appDescription": "Stel in wie toegang heeft tot deze app en hoe gedetailleerd de toegangsrechten zijn.",
"accessRule.appTitle": "App-rechtenset",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Eigenaar van de workspace",
"common.duplicateAction": "Dupliceren",
"group.agent": "Agenten",
+ "group.agent_acl": "Toegangsrechten voor agent",
"group.app": "Applicaties",
"group.app_acl": "Toegangsrechten voor app",
"group.billing": "Facturering",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Beschrijving",
"permissionSet.descriptionPlaceholder": "Beschrijf wat deze rechtenset verleent",
"permissionSet.learnMore": "Meer informatie over rechten",
+ "permissionSet.modal.create.agent.description": "Maak een agent-rechtenset die in toegangsregels kan worden gebruikt voor snelle autorisatie.",
+ "permissionSet.modal.create.agent.title": "Agent-rechtenset maken",
"permissionSet.modal.create.app.description": "Maak een app-rechtenset die in toegangsregels kan worden gebruikt voor snelle autorisatie.",
"permissionSet.modal.create.app.title": "App-rechtenset maken",
"permissionSet.modal.create.dataset.description": "Maak een kennisbank-rechtenset die in toegangsregels kan worden gebruikt voor snelle autorisatie.",
"permissionSet.modal.create.dataset.title": "Kennisbank-rechtenset maken",
+ "permissionSet.modal.edit.agent.description": "Wijzig de naam, beschrijving en verleende rechten voor deze rechtenset.",
+ "permissionSet.modal.edit.agent.title": "Agent-rechtenset bewerken",
"permissionSet.modal.edit.app.description": "Wijzig de naam, beschrijving en verleende rechten voor deze rechtenset.",
"permissionSet.modal.edit.app.title": "App-rechtenset bewerken",
"permissionSet.modal.edit.dataset.description": "Wijzig de naam, beschrijving en verleende rechten voor deze rechtenset.",
"permissionSet.modal.edit.dataset.title": "Kennisbank-rechtenset bewerken",
+ "permissionSet.modal.view.agent.description": "Bekijk de naam, beschrijving en verleende rechten voor deze rechtenset.",
+ "permissionSet.modal.view.agent.title": "Agent-rechtenset bekijken",
"permissionSet.modal.view.app.description": "Bekijk de naam, beschrijving en verleende rechten voor deze rechtenset.",
"permissionSet.modal.view.app.title": "App-rechtenset bekijken",
"permissionSet.modal.view.dataset.description": "Bekijk de naam, beschrijving en verleende rechten voor deze rechtenset.",
diff --git a/web/i18n/pl-PL/agent-v-2.json b/web/i18n/pl-PL/agent-v-2.json
index 7e2d294d5b1..5e1f825a29c 100644
--- a/web/i18n/pl-PL/agent-v-2.json
+++ b/web/i18n/pl-PL/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Nawigacja agenta",
"agentDetail.publish": "Opublikuj",
"agentDetail.sections.access": "Punkt dostępu",
+ "agentDetail.sections.access-config": "Dostęp do zasobów",
"agentDetail.sections.configure": "Skonfiguruj",
"agentDetail.sections.logs": "Logi",
"agentDetail.sections.monitoring": "Monitorowanie",
diff --git a/web/i18n/pl-PL/permission.json b/web/i18n/pl-PL/permission.json
index a54c224992b..124e4e2d46c 100644
--- a/web/i18n/pl-PL/permission.json
+++ b/web/i18n/pl-PL/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Akcje",
"accessRule.addMemberAria": "Dodaj {{name}}",
"accessRule.addMembersTitle": "Dodaj członków",
+ "accessRule.agentDescription": "Zarządzaj dostępem do tego agenta i uprawnieniami użytkowników.",
+ "accessRule.agentTitle": "Zestaw uprawnień agenta",
"accessRule.allowedMembers": "Dozwoleni członkowie",
"accessRule.appDescription": "Określ, kto może uzyskać dostęp do tej aplikacji, oraz poziom szczegółowości uprawnień dostępu.",
"accessRule.appTitle": "Zestaw uprawnień aplikacji",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Właściciel obszaru roboczego",
"common.duplicateAction": "Duplikuj",
"group.agent": "Agenci",
+ "group.agent_acl": "Uprawnienia dostępu do agenta",
"group.app": "Aplikacje",
"group.app_acl": "Uprawnienia dostępu do aplikacji",
"group.billing": "Rozliczenia",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Opis",
"permissionSet.descriptionPlaceholder": "Opisz, co przyznaje ten zestaw uprawnień",
"permissionSet.learnMore": "Dowiedz się więcej o uprawnieniach",
+ "permissionSet.modal.create.agent.description": "Utwórz zestaw uprawnień agenta, do którego można się odwoływać w regułach dostępu w celu szybkiej autoryzacji.",
+ "permissionSet.modal.create.agent.title": "Utwórz zestaw uprawnień agenta",
"permissionSet.modal.create.app.description": "Utwórz zestaw uprawnień aplikacji, do którego można się odwoływać w regułach dostępu w celu szybkiej autoryzacji.",
"permissionSet.modal.create.app.title": "Utwórz zestaw uprawnień aplikacji",
"permissionSet.modal.create.dataset.description": "Utwórz zestaw uprawnień bazy wiedzy, do którego można się odwoływać w regułach dostępu w celu szybkiej autoryzacji.",
"permissionSet.modal.create.dataset.title": "Utwórz zestaw uprawnień bazy wiedzy",
+ "permissionSet.modal.edit.agent.description": "Zmodyfikuj nazwę, opis i uprawnienia przyznane dla tego zestawu uprawnień.",
+ "permissionSet.modal.edit.agent.title": "Edytuj zestaw uprawnień agenta",
"permissionSet.modal.edit.app.description": "Zmodyfikuj nazwę, opis i uprawnienia przyznane dla tego zestawu uprawnień.",
"permissionSet.modal.edit.app.title": "Edytuj zestaw uprawnień aplikacji",
"permissionSet.modal.edit.dataset.description": "Zmodyfikuj nazwę, opis i uprawnienia przyznane dla tego zestawu uprawnień.",
"permissionSet.modal.edit.dataset.title": "Edytuj zestaw uprawnień bazy wiedzy",
+ "permissionSet.modal.view.agent.description": "Wyświetl nazwę, opis i uprawnienia przyznane dla tego zestawu uprawnień.",
+ "permissionSet.modal.view.agent.title": "Wyświetl zestaw uprawnień agenta",
"permissionSet.modal.view.app.description": "Wyświetl nazwę, opis i uprawnienia przyznane dla tego zestawu uprawnień.",
"permissionSet.modal.view.app.title": "Wyświetl zestaw uprawnień aplikacji",
"permissionSet.modal.view.dataset.description": "Wyświetl nazwę, opis i uprawnienia przyznane dla tego zestawu uprawnień.",
diff --git a/web/i18n/pt-BR/agent-v-2.json b/web/i18n/pt-BR/agent-v-2.json
index 178ac285b7e..309448a5f77 100644
--- a/web/i18n/pt-BR/agent-v-2.json
+++ b/web/i18n/pt-BR/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Navegação do agente",
"agentDetail.publish": "Publicar",
"agentDetail.sections.access": "Ponto de acesso",
+ "agentDetail.sections.access-config": "Acesso a Recursos",
"agentDetail.sections.configure": "Configurar",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoramento",
diff --git a/web/i18n/pt-BR/permission.json b/web/i18n/pt-BR/permission.json
index 93c2b13ff2d..804967d985e 100644
--- a/web/i18n/pt-BR/permission.json
+++ b/web/i18n/pt-BR/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Ações",
"accessRule.addMemberAria": "Adicionar {{name}}",
"accessRule.addMembersTitle": "Adicionar membros",
+ "accessRule.agentDescription": "Gerencie quem pode acessar este agente e suas permissões.",
+ "accessRule.agentTitle": "Conjunto de permissões de Agente",
"accessRule.allowedMembers": "Membros permitidos",
"accessRule.appDescription": "Defina quem pode acessar este aplicativo e o nível de granularidade das permissões de acesso.",
"accessRule.appTitle": "Conjunto de permissões de Aplicativo",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Proprietário do workspace",
"common.duplicateAction": "Duplicar",
"group.agent": "Agentes",
+ "group.agent_acl": "Permissões de acesso ao agente",
"group.app": "Aplicativos",
"group.app_acl": "Permissões de acesso ao aplicativo",
"group.billing": "Faturamento",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Descrição",
"permissionSet.descriptionPlaceholder": "Descreva o que este conjunto de permissões concede",
"permissionSet.learnMore": "Saiba mais sobre permissões",
+ "permissionSet.modal.create.agent.description": "Crie um conjunto de permissões de agente que pode ser referenciado em regras de acesso para autorização rápida.",
+ "permissionSet.modal.create.agent.title": "Criar conjunto de permissões de Agente",
"permissionSet.modal.create.app.description": "Crie um conjunto de permissões de aplicativo que pode ser referenciado em regras de acesso para autorização rápida.",
"permissionSet.modal.create.app.title": "Criar conjunto de permissões de Aplicativo",
"permissionSet.modal.create.dataset.description": "Crie um conjunto de permissões de Conhecimento que pode ser referenciado em regras de acesso para autorização rápida.",
"permissionSet.modal.create.dataset.title": "Criar conjunto de permissões de Conhecimento",
+ "permissionSet.modal.edit.agent.description": "Modifique o nome, a descrição e as permissões concedidas para este conjunto de permissões.",
+ "permissionSet.modal.edit.agent.title": "Editar conjunto de permissões de Agente",
"permissionSet.modal.edit.app.description": "Modifique o nome, a descrição e as permissões concedidas para este conjunto de permissões.",
"permissionSet.modal.edit.app.title": "Editar conjunto de permissões de Aplicativo",
"permissionSet.modal.edit.dataset.description": "Modifique o nome, a descrição e as permissões concedidas para este conjunto de permissões.",
"permissionSet.modal.edit.dataset.title": "Editar conjunto de permissões de Conhecimento",
+ "permissionSet.modal.view.agent.description": "Visualize o nome, a descrição e as permissões concedidas para este conjunto de permissões.",
+ "permissionSet.modal.view.agent.title": "Visualizar conjunto de permissões de Agente",
"permissionSet.modal.view.app.description": "Visualize o nome, a descrição e as permissões concedidas para este conjunto de permissões.",
"permissionSet.modal.view.app.title": "Visualizar conjunto de permissões de Aplicativo",
"permissionSet.modal.view.dataset.description": "Visualize o nome, a descrição e as permissões concedidas para este conjunto de permissões.",
diff --git a/web/i18n/ro-RO/agent-v-2.json b/web/i18n/ro-RO/agent-v-2.json
index 02e44f9353a..df9564cd05a 100644
--- a/web/i18n/ro-RO/agent-v-2.json
+++ b/web/i18n/ro-RO/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Navigarea agentului",
"agentDetail.publish": "Publică",
"agentDetail.sections.access": "Punct de acces",
+ "agentDetail.sections.access-config": "Acces la resurse",
"agentDetail.sections.configure": "Configurează",
"agentDetail.sections.logs": "Jurnale",
"agentDetail.sections.monitoring": "Monitorizare",
diff --git a/web/i18n/ro-RO/permission.json b/web/i18n/ro-RO/permission.json
index 6f4e684b12d..23acabe0b4e 100644
--- a/web/i18n/ro-RO/permission.json
+++ b/web/i18n/ro-RO/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Acțiuni",
"accessRule.addMemberAria": "Adaugă {{name}}",
"accessRule.addMembersTitle": "Adaugă membri",
+ "accessRule.agentDescription": "Gestionează cine poate accesa acest agent și permisiunile acestora.",
+ "accessRule.agentTitle": "Set de permisiuni pentru agent",
"accessRule.allowedMembers": "Membri permiși",
"accessRule.appDescription": "Stabilește cine poate accesa această aplicație și nivelul de granularitate al permisiunilor de acces.",
"accessRule.appTitle": "Set de permisiuni pentru aplicație",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Proprietarul spațiului de lucru",
"common.duplicateAction": "Duplică",
"group.agent": "Agenți",
+ "group.agent_acl": "Permisiuni de acces ale agentului",
"group.app": "Aplicații",
"group.app_acl": "Permisiuni de acces ale aplicației",
"group.billing": "Facturare",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Descriere",
"permissionSet.descriptionPlaceholder": "Descrie ce acordă acest set de permisiuni",
"permissionSet.learnMore": "Află mai multe despre permisiuni",
+ "permissionSet.modal.create.agent.description": "Creează un set de permisiuni pentru agent care poate fi referențiat în regulile de acces pentru autorizare rapidă.",
+ "permissionSet.modal.create.agent.title": "Creează set de permisiuni pentru agent",
"permissionSet.modal.create.app.description": "Creează un set de permisiuni pentru aplicație care poate fi referențiat în regulile de acces pentru autorizare rapidă.",
"permissionSet.modal.create.app.title": "Creează set de permisiuni pentru aplicație",
"permissionSet.modal.create.dataset.description": "Creează un set de permisiuni pentru baza de cunoștințe care poate fi referențiat în regulile de acces pentru autorizare rapidă.",
"permissionSet.modal.create.dataset.title": "Creează set de permisiuni pentru baza de cunoștințe",
+ "permissionSet.modal.edit.agent.description": "Modifică numele, descrierea și permisiunile acordate pentru acest set de permisiuni.",
+ "permissionSet.modal.edit.agent.title": "Editează set de permisiuni pentru agent",
"permissionSet.modal.edit.app.description": "Modifică numele, descrierea și permisiunile acordate pentru acest set de permisiuni.",
"permissionSet.modal.edit.app.title": "Editează set de permisiuni pentru aplicație",
"permissionSet.modal.edit.dataset.description": "Modifică numele, descrierea și permisiunile acordate pentru acest set de permisiuni.",
"permissionSet.modal.edit.dataset.title": "Editează set de permisiuni pentru baza de cunoștințe",
+ "permissionSet.modal.view.agent.description": "Vizualizează numele, descrierea și permisiunile acordate pentru acest set de permisiuni.",
+ "permissionSet.modal.view.agent.title": "Vizualizează set de permisiuni pentru agent",
"permissionSet.modal.view.app.description": "Vizualizează numele, descrierea și permisiunile acordate pentru acest set de permisiuni.",
"permissionSet.modal.view.app.title": "Vizualizează set de permisiuni pentru aplicație",
"permissionSet.modal.view.dataset.description": "Vizualizează numele, descrierea și permisiunile acordate pentru acest set de permisiuni.",
diff --git a/web/i18n/ru-RU/agent-v-2.json b/web/i18n/ru-RU/agent-v-2.json
index 9b8bef33ece..e6e2f15d93b 100644
--- a/web/i18n/ru-RU/agent-v-2.json
+++ b/web/i18n/ru-RU/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Навигация агента",
"agentDetail.publish": "Опубликовать",
"agentDetail.sections.access": "Точка доступа",
+ "agentDetail.sections.access-config": "Доступ к ресурсам",
"agentDetail.sections.configure": "Настроить",
"agentDetail.sections.logs": "Журналы",
"agentDetail.sections.monitoring": "Мониторинг",
diff --git a/web/i18n/ru-RU/permission.json b/web/i18n/ru-RU/permission.json
index ff632dccdf6..7b77737087b 100644
--- a/web/i18n/ru-RU/permission.json
+++ b/web/i18n/ru-RU/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Действия",
"accessRule.addMemberAria": "Добавить {{name}}",
"accessRule.addMembersTitle": "Добавить участников",
+ "accessRule.agentDescription": "Управляйте доступом к этому агенту и правами пользователей.",
+ "accessRule.agentTitle": "Набор прав агента",
"accessRule.allowedMembers": "Разрешённые участники",
"accessRule.appDescription": "Настройте, кто может получить доступ к этому приложению, и степень детализации прав доступа.",
"accessRule.appTitle": "Набор прав приложения",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Владелец рабочего пространства",
"common.duplicateAction": "Дублировать",
"group.agent": "Агенты",
+ "group.agent_acl": "Права доступа к агенту",
"group.app": "Приложения",
"group.app_acl": "Права доступа к приложению",
"group.billing": "Биллинг",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Описание",
"permissionSet.descriptionPlaceholder": "Опишите, что предоставляет этот набор прав",
"permissionSet.learnMore": "Подробнее о правах",
+ "permissionSet.modal.create.agent.description": "Создайте набор прав агента, на который можно ссылаться в правилах доступа для быстрой авторизации.",
+ "permissionSet.modal.create.agent.title": "Создать набор прав агента",
"permissionSet.modal.create.app.description": "Создайте набор прав приложения, на который можно ссылаться в правилах доступа для быстрой авторизации.",
"permissionSet.modal.create.app.title": "Создать набор прав приложения",
"permissionSet.modal.create.dataset.description": "Создайте набор прав базы знаний, на который можно ссылаться в правилах доступа для быстрой авторизации.",
"permissionSet.modal.create.dataset.title": "Создать набор прав базы знаний",
+ "permissionSet.modal.edit.agent.description": "Измените имя, описание и предоставляемые права для этого набора прав.",
+ "permissionSet.modal.edit.agent.title": "Редактировать набор прав агента",
"permissionSet.modal.edit.app.description": "Измените имя, описание и предоставляемые права для этого набора прав.",
"permissionSet.modal.edit.app.title": "Редактировать набор прав приложения",
"permissionSet.modal.edit.dataset.description": "Измените имя, описание и предоставляемые права для этого набора прав.",
"permissionSet.modal.edit.dataset.title": "Редактировать набор прав базы знаний",
+ "permissionSet.modal.view.agent.description": "Просмотрите имя, описание и предоставляемые права для этого набора прав.",
+ "permissionSet.modal.view.agent.title": "Просмотр набора прав агента",
"permissionSet.modal.view.app.description": "Просмотрите имя, описание и предоставляемые права для этого набора прав.",
"permissionSet.modal.view.app.title": "Просмотр набора прав приложения",
"permissionSet.modal.view.dataset.description": "Просмотрите имя, описание и предоставляемые права для этого набора прав.",
diff --git a/web/i18n/sl-SI/agent-v-2.json b/web/i18n/sl-SI/agent-v-2.json
index ab61f9a7958..de265bcbda0 100644
--- a/web/i18n/sl-SI/agent-v-2.json
+++ b/web/i18n/sl-SI/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Navigacija agenta",
"agentDetail.publish": "Objavi",
"agentDetail.sections.access": "Dostopna točka",
+ "agentDetail.sections.access-config": "Dostop do virov",
"agentDetail.sections.configure": "Konfiguriraj",
"agentDetail.sections.logs": "Dnevniki",
"agentDetail.sections.monitoring": "Spremljanje",
diff --git a/web/i18n/sl-SI/permission.json b/web/i18n/sl-SI/permission.json
index 24714af80a5..f04eae00883 100644
--- a/web/i18n/sl-SI/permission.json
+++ b/web/i18n/sl-SI/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Dejanja",
"accessRule.addMemberAria": "Dodaj {{name}}",
"accessRule.addMembersTitle": "Dodaj člane",
+ "accessRule.agentDescription": "Upravljajte dostop do tega agenta in dovoljenja uporabnikov.",
+ "accessRule.agentTitle": "Nabor dovoljenj za agenta",
"accessRule.allowedMembers": "Dovoljeni člani",
"accessRule.appDescription": "Določite, kdo lahko dostopa do te aplikacije, in raven podrobnosti dovoljenj za dostop.",
"accessRule.appTitle": "Nabor dovoljenj za aplikacijo",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Lastnik delovnega prostora",
"common.duplicateAction": "Podvoji",
"group.agent": "Agenti",
+ "group.agent_acl": "Dovoljenja za dostop do agenta",
"group.app": "Aplikacije",
"group.app_acl": "Dovoljenja za dostop do aplikacije",
"group.billing": "Obračunavanje",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Opis",
"permissionSet.descriptionPlaceholder": "Opišite, kaj ta nabor dovoljenj podeljuje",
"permissionSet.learnMore": "Več o dovoljenjih",
+ "permissionSet.modal.create.agent.description": "Ustvarite nabor dovoljenj za agenta, na katerega se je mogoče sklicevati v pravilih za dostop za hitro avtorizacijo.",
+ "permissionSet.modal.create.agent.title": "Ustvari nabor dovoljenj za agenta",
"permissionSet.modal.create.app.description": "Ustvarite nabor dovoljenj za aplikacijo, na katerega se je mogoče sklicevati v pravilih za dostop za hitro avtorizacijo.",
"permissionSet.modal.create.app.title": "Ustvari nabor dovoljenj za aplikacijo",
"permissionSet.modal.create.dataset.description": "Ustvarite nabor dovoljenj za bazo znanja, na katerega se je mogoče sklicevati v pravilih za dostop za hitro avtorizacijo.",
"permissionSet.modal.create.dataset.title": "Ustvari nabor dovoljenj za bazo znanja",
+ "permissionSet.modal.edit.agent.description": "Spremenite ime, opis in dovoljenja, podeljena za ta nabor dovoljenj.",
+ "permissionSet.modal.edit.agent.title": "Uredi nabor dovoljenj za agenta",
"permissionSet.modal.edit.app.description": "Spremenite ime, opis in dovoljenja, podeljena za ta nabor dovoljenj.",
"permissionSet.modal.edit.app.title": "Uredi nabor dovoljenj za aplikacijo",
"permissionSet.modal.edit.dataset.description": "Spremenite ime, opis in dovoljenja, podeljena za ta nabor dovoljenj.",
"permissionSet.modal.edit.dataset.title": "Uredi nabor dovoljenj za bazo znanja",
+ "permissionSet.modal.view.agent.description": "Oglejte si ime, opis in dovoljenja, podeljena za ta nabor dovoljenj.",
+ "permissionSet.modal.view.agent.title": "Ogled nabora dovoljenj za agenta",
"permissionSet.modal.view.app.description": "Oglejte si ime, opis in dovoljenja, podeljena za ta nabor dovoljenj.",
"permissionSet.modal.view.app.title": "Ogled nabora dovoljenj za aplikacijo",
"permissionSet.modal.view.dataset.description": "Oglejte si ime, opis in dovoljenja, podeljena za ta nabor dovoljenj.",
diff --git a/web/i18n/th-TH/agent-v-2.json b/web/i18n/th-TH/agent-v-2.json
index afcc8b89c22..a75e19f09b1 100644
--- a/web/i18n/th-TH/agent-v-2.json
+++ b/web/i18n/th-TH/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "การนำทางตัวแทน",
"agentDetail.publish": "เผยแพร่",
"agentDetail.sections.access": "จุดเข้าถึง",
+ "agentDetail.sections.access-config": "การเข้าถึงทรัพยากร",
"agentDetail.sections.configure": "กําหนดค่า",
"agentDetail.sections.logs": "บันทึก",
"agentDetail.sections.monitoring": "การมอนิเตอร์",
diff --git a/web/i18n/th-TH/permission.json b/web/i18n/th-TH/permission.json
index 017e2ccf1e0..ffdeafef52d 100644
--- a/web/i18n/th-TH/permission.json
+++ b/web/i18n/th-TH/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "การดําเนินการ",
"accessRule.addMemberAria": "เพิ่ม {{name}}",
"accessRule.addMembersTitle": "เพิ่มสมาชิก",
+ "accessRule.agentDescription": "จัดการผู้ที่เข้าถึงตัวแทนนี้ได้และสิทธิ์ของผู้ใช้",
+ "accessRule.agentTitle": "ชุดสิทธิ์ตัวแทน",
"accessRule.allowedMembers": "สมาชิกที่ได้รับอนุญาต",
"accessRule.appDescription": "กำหนดว่าใครสามารถเข้าถึงแอปนี้ได้ และระดับความละเอียดของสิทธิ์การเข้าถึง",
"accessRule.appTitle": "ชุดสิทธิ์แอป",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "เจ้าของเวิร์กสเปซ",
"common.duplicateAction": "ทําซ้ํา",
"group.agent": "ตัวแทน",
+ "group.agent_acl": "สิทธิ์การเข้าถึงตัวแทน",
"group.app": "แอปพลิเคชัน",
"group.app_acl": "สิทธิ์การเข้าถึงแอป",
"group.billing": "การเรียกเก็บเงิน",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "คําอธิบาย",
"permissionSet.descriptionPlaceholder": "อธิบายว่าชุดสิทธิ์นี้ให้สิทธิ์อะไรบ้าง",
"permissionSet.learnMore": "เรียนรู้เพิ่มเติมเกี่ยวกับสิทธิ์",
+ "permissionSet.modal.create.agent.description": "สร้างชุดสิทธิ์ตัวแทนที่สามารถอ้างอิงในกฎการเข้าถึงเพื่อการอนุญาตที่รวดเร็ว",
+ "permissionSet.modal.create.agent.title": "สร้างชุดสิทธิ์ตัวแทน",
"permissionSet.modal.create.app.description": "สร้างชุดสิทธิ์แอปที่สามารถอ้างอิงในกฎการเข้าถึงเพื่อการอนุญาตที่รวดเร็ว",
"permissionSet.modal.create.app.title": "สร้างชุดสิทธิ์แอป",
"permissionSet.modal.create.dataset.description": "สร้างชุดสิทธิ์ฐานความรู้ที่สามารถอ้างอิงในกฎการเข้าถึงเพื่อการอนุญาตที่รวดเร็ว",
"permissionSet.modal.create.dataset.title": "สร้างชุดสิทธิ์ฐานความรู้",
+ "permissionSet.modal.edit.agent.description": "แก้ไขชื่อ คําอธิบาย และสิทธิ์ที่ให้สําหรับชุดสิทธิ์นี้",
+ "permissionSet.modal.edit.agent.title": "แก้ไขชุดสิทธิ์ตัวแทน",
"permissionSet.modal.edit.app.description": "แก้ไขชื่อ คําอธิบาย และสิทธิ์ที่ให้สําหรับชุดสิทธิ์นี้",
"permissionSet.modal.edit.app.title": "แก้ไขชุดสิทธิ์แอป",
"permissionSet.modal.edit.dataset.description": "แก้ไขชื่อ คําอธิบาย และสิทธิ์ที่ให้สําหรับชุดสิทธิ์นี้",
"permissionSet.modal.edit.dataset.title": "แก้ไขชุดสิทธิ์ฐานความรู้",
+ "permissionSet.modal.view.agent.description": "ดูชื่อ คําอธิบาย และสิทธิ์ที่ให้สําหรับชุดสิทธิ์นี้",
+ "permissionSet.modal.view.agent.title": "ดูชุดสิทธิ์ตัวแทน",
"permissionSet.modal.view.app.description": "ดูชื่อ คําอธิบาย และสิทธิ์ที่ให้สําหรับชุดสิทธิ์นี้",
"permissionSet.modal.view.app.title": "ดูชุดสิทธิ์แอป",
"permissionSet.modal.view.dataset.description": "ดูชื่อ คําอธิบาย และสิทธิ์ที่ให้สําหรับชุดสิทธิ์นี้",
diff --git a/web/i18n/tr-TR/agent-v-2.json b/web/i18n/tr-TR/agent-v-2.json
index 52ae1bd9f86..b1432bb31e1 100644
--- a/web/i18n/tr-TR/agent-v-2.json
+++ b/web/i18n/tr-TR/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Ajan gezinmesi",
"agentDetail.publish": "Yayınla",
"agentDetail.sections.access": "Erişim Noktası",
+ "agentDetail.sections.access-config": "Kaynak Erişimi",
"agentDetail.sections.configure": "Yapılandır",
"agentDetail.sections.logs": "Günlükler",
"agentDetail.sections.monitoring": "İzleme",
diff --git a/web/i18n/tr-TR/permission.json b/web/i18n/tr-TR/permission.json
index d2122408cb9..7bc6dd918c4 100644
--- a/web/i18n/tr-TR/permission.json
+++ b/web/i18n/tr-TR/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Eylemler",
"accessRule.addMemberAria": "{{name}} ekle",
"accessRule.addMembersTitle": "Üye ekle",
+ "accessRule.agentDescription": "Bu ajana kimlerin erişebileceğini ve izinlerini yönetin.",
+ "accessRule.agentTitle": "Ajan izin kümesi",
"accessRule.allowedMembers": "İzin verilen üyeler",
"accessRule.appDescription": "Bu uygulamaya kimlerin erişebileceğini ve erişim izinlerinin ayrıntı düzeyini ayarlayın.",
"accessRule.appTitle": "Uygulama izin kümesi",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Çalışma alanı sahibi",
"common.duplicateAction": "Çoğalt",
"group.agent": "Ajanlar",
+ "group.agent_acl": "Ajan erişim izinleri",
"group.app": "Uygulamalar",
"group.app_acl": "Uygulama erişim izinleri",
"group.billing": "Faturalandırma",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Açıklama",
"permissionSet.descriptionPlaceholder": "Bu izin kümesinin ne sağladığını açıklayın",
"permissionSet.learnMore": "İzinler hakkında daha fazla bilgi edinin",
+ "permissionSet.modal.create.agent.description": "Hızlı yetkilendirme için erişim kurallarında başvurulabilen bir ajan izin kümesi oluşturun.",
+ "permissionSet.modal.create.agent.title": "Ajan izin kümesi oluştur",
"permissionSet.modal.create.app.description": "Hızlı yetkilendirme için erişim kurallarında başvurulabilen bir uygulama izin kümesi oluşturun.",
"permissionSet.modal.create.app.title": "Uygulama izin kümesi oluştur",
"permissionSet.modal.create.dataset.description": "Hızlı yetkilendirme için erişim kurallarında başvurulabilen bir bilgi tabanı izin kümesi oluşturun.",
"permissionSet.modal.create.dataset.title": "Bilgi Tabanı izin kümesi oluştur",
+ "permissionSet.modal.edit.agent.description": "Bu izin kümesi için verilen adı, açıklamayı ve izinleri değiştirin.",
+ "permissionSet.modal.edit.agent.title": "Ajan izin kümesini düzenle",
"permissionSet.modal.edit.app.description": "Bu izin kümesi için verilen adı, açıklamayı ve izinleri değiştirin.",
"permissionSet.modal.edit.app.title": "Uygulama izin kümesini düzenle",
"permissionSet.modal.edit.dataset.description": "Bu izin kümesi için verilen adı, açıklamayı ve izinleri değiştirin.",
"permissionSet.modal.edit.dataset.title": "Bilgi Tabanı izin kümesini düzenle",
+ "permissionSet.modal.view.agent.description": "Bu izin kümesi için verilen adı, açıklamayı ve izinleri görüntüleyin.",
+ "permissionSet.modal.view.agent.title": "Ajan izin kümesini görüntüle",
"permissionSet.modal.view.app.description": "Bu izin kümesi için verilen adı, açıklamayı ve izinleri görüntüleyin.",
"permissionSet.modal.view.app.title": "Uygulama izin kümesini görüntüle",
"permissionSet.modal.view.dataset.description": "Bu izin kümesi için verilen adı, açıklamayı ve izinleri görüntüleyin.",
diff --git a/web/i18n/uk-UA/agent-v-2.json b/web/i18n/uk-UA/agent-v-2.json
index 0c7103ea2b9..6245109c514 100644
--- a/web/i18n/uk-UA/agent-v-2.json
+++ b/web/i18n/uk-UA/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Навігація агента",
"agentDetail.publish": "Опублікувати",
"agentDetail.sections.access": "Точка доступу",
+ "agentDetail.sections.access-config": "Доступ до ресурсів",
"agentDetail.sections.configure": "Налаштувати",
"agentDetail.sections.logs": "Журнали",
"agentDetail.sections.monitoring": "Моніторинг",
diff --git a/web/i18n/uk-UA/permission.json b/web/i18n/uk-UA/permission.json
index 40935c7be12..1c93455d54f 100644
--- a/web/i18n/uk-UA/permission.json
+++ b/web/i18n/uk-UA/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Дії",
"accessRule.addMemberAria": "Додати {{name}}",
"accessRule.addMembersTitle": "Додати учасників",
+ "accessRule.agentDescription": "Керуйте доступом до цього агента та дозволами користувачів.",
+ "accessRule.agentTitle": "Набір дозволів агента",
"accessRule.allowedMembers": "Дозволені учасники",
"accessRule.appDescription": "Налаштуйте, хто може отримати доступ до цього застосунку, і рівень деталізації дозволів доступу.",
"accessRule.appTitle": "Набір дозволів застосунку",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Власник робочого простору",
"common.duplicateAction": "Дублювати",
"group.agent": "Агенти",
+ "group.agent_acl": "Дозволи доступу до агента",
"group.app": "Застосунки",
"group.app_acl": "Дозволи доступу до застосунку",
"group.billing": "Оплата",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Опис",
"permissionSet.descriptionPlaceholder": "Опишіть, що надає цей набір дозволів",
"permissionSet.learnMore": "Дізнатися більше про дозволи",
+ "permissionSet.modal.create.agent.description": "Створіть набір дозволів агента, на який можна посилатися в правилах доступу для швидкої авторизації.",
+ "permissionSet.modal.create.agent.title": "Створити набір дозволів агента",
"permissionSet.modal.create.app.description": "Створіть набір дозволів застосунку, на який можна посилатися в правилах доступу для швидкої авторизації.",
"permissionSet.modal.create.app.title": "Створити набір дозволів застосунку",
"permissionSet.modal.create.dataset.description": "Створіть набір дозволів бази знань, на який можна посилатися в правилах доступу для швидкої авторизації.",
"permissionSet.modal.create.dataset.title": "Створити набір дозволів бази знань",
+ "permissionSet.modal.edit.agent.description": "Змініть назву, опис та надані дозволи для цього набору дозволів.",
+ "permissionSet.modal.edit.agent.title": "Редагувати набір дозволів агента",
"permissionSet.modal.edit.app.description": "Змініть назву, опис та надані дозволи для цього набору дозволів.",
"permissionSet.modal.edit.app.title": "Редагувати набір дозволів застосунку",
"permissionSet.modal.edit.dataset.description": "Змініть назву, опис та надані дозволи для цього набору дозволів.",
"permissionSet.modal.edit.dataset.title": "Редагувати набір дозволів бази знань",
+ "permissionSet.modal.view.agent.description": "Перегляньте назву, опис та надані дозволи для цього набору дозволів.",
+ "permissionSet.modal.view.agent.title": "Переглянути набір дозволів агента",
"permissionSet.modal.view.app.description": "Перегляньте назву, опис та надані дозволи для цього набору дозволів.",
"permissionSet.modal.view.app.title": "Переглянути набір дозволів застосунку",
"permissionSet.modal.view.dataset.description": "Перегляньте назву, опис та надані дозволи для цього набору дозволів.",
diff --git a/web/i18n/vi-VN/agent-v-2.json b/web/i18n/vi-VN/agent-v-2.json
index 88bfba23e28..40398a85ff5 100644
--- a/web/i18n/vi-VN/agent-v-2.json
+++ b/web/i18n/vi-VN/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Điều hướng tác nhân",
"agentDetail.publish": "Xuất bản",
"agentDetail.sections.access": "Điểm truy cập",
+ "agentDetail.sections.access-config": "Quyền truy cập tài nguyên",
"agentDetail.sections.configure": "Cấu hình",
"agentDetail.sections.logs": "Nhật ký",
"agentDetail.sections.monitoring": "Giám sát",
diff --git a/web/i18n/vi-VN/permission.json b/web/i18n/vi-VN/permission.json
index 0b807c34e79..4bd0029fc16 100644
--- a/web/i18n/vi-VN/permission.json
+++ b/web/i18n/vi-VN/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "Hành động",
"accessRule.addMemberAria": "Thêm {{name}}",
"accessRule.addMembersTitle": "Thêm thành viên",
+ "accessRule.agentDescription": "Quản lý những ai có thể truy cập tác nhân này và quyền của họ.",
+ "accessRule.agentTitle": "Bộ quyền tác nhân",
"accessRule.allowedMembers": "Thành viên được phép",
"accessRule.appDescription": "Thiết lập ai có thể truy cập ứng dụng này và mức độ chi tiết của quyền truy cập.",
"accessRule.appTitle": "Bộ quyền ứng dụng",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "Chủ sở hữu workspace",
"common.duplicateAction": "Nhân bản",
"group.agent": "Tác nhân",
+ "group.agent_acl": "Quyền truy cập tác nhân",
"group.app": "Ứng dụng",
"group.app_acl": "Quyền truy cập ứng dụng",
"group.billing": "Thanh toán",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "Mô tả",
"permissionSet.descriptionPlaceholder": "Mô tả những gì bộ quyền này cấp",
"permissionSet.learnMore": "Tìm hiểu thêm về quyền",
+ "permissionSet.modal.create.agent.description": "Tạo một bộ quyền tác nhân có thể được tham chiếu trong các quy tắc truy cập để ủy quyền nhanh chóng.",
+ "permissionSet.modal.create.agent.title": "Tạo bộ quyền tác nhân",
"permissionSet.modal.create.app.description": "Tạo một bộ quyền ứng dụng có thể được tham chiếu trong các quy tắc truy cập để ủy quyền nhanh chóng.",
"permissionSet.modal.create.app.title": "Tạo bộ quyền ứng dụng",
"permissionSet.modal.create.dataset.description": "Tạo một bộ quyền cơ sở tri thức có thể được tham chiếu trong các quy tắc truy cập để ủy quyền nhanh chóng.",
"permissionSet.modal.create.dataset.title": "Tạo bộ quyền cơ sở tri thức",
+ "permissionSet.modal.edit.agent.description": "Sửa đổi tên, mô tả và các quyền được cấp cho bộ quyền này.",
+ "permissionSet.modal.edit.agent.title": "Chỉnh sửa bộ quyền tác nhân",
"permissionSet.modal.edit.app.description": "Sửa đổi tên, mô tả và các quyền được cấp cho bộ quyền này.",
"permissionSet.modal.edit.app.title": "Chỉnh sửa bộ quyền ứng dụng",
"permissionSet.modal.edit.dataset.description": "Sửa đổi tên, mô tả và các quyền được cấp cho bộ quyền này.",
"permissionSet.modal.edit.dataset.title": "Chỉnh sửa bộ quyền cơ sở tri thức",
+ "permissionSet.modal.view.agent.description": "Xem tên, mô tả và các quyền được cấp cho bộ quyền này.",
+ "permissionSet.modal.view.agent.title": "Xem bộ quyền tác nhân",
"permissionSet.modal.view.app.description": "Xem tên, mô tả và các quyền được cấp cho bộ quyền này.",
"permissionSet.modal.view.app.title": "Xem bộ quyền ứng dụng",
"permissionSet.modal.view.dataset.description": "Xem tên, mô tả và các quyền được cấp cho bộ quyền này.",
diff --git a/web/i18n/zh-Hans/agent-v-2.json b/web/i18n/zh-Hans/agent-v-2.json
index b5ae8f1a003..094c924d878 100644
--- a/web/i18n/zh-Hans/agent-v-2.json
+++ b/web/i18n/zh-Hans/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Agent 导航",
"agentDetail.publish": "发布",
"agentDetail.sections.access": "访问点",
+ "agentDetail.sections.access-config": "访问权限",
"agentDetail.sections.configure": "配置",
"agentDetail.sections.logs": "日志",
"agentDetail.sections.monitoring": "监控",
diff --git a/web/i18n/zh-Hans/permission.json b/web/i18n/zh-Hans/permission.json
index 4e1ab0c1c0e..8a6ff1bdc6e 100644
--- a/web/i18n/zh-Hans/permission.json
+++ b/web/i18n/zh-Hans/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "操作",
"accessRule.addMemberAria": "添加 {{name}}",
"accessRule.addMembersTitle": "添加成员",
+ "accessRule.agentDescription": "管理可访问此 Agent 的成员及其权限。",
+ "accessRule.agentTitle": "Agent 权限集",
"accessRule.allowedMembers": "允许访问的成员",
"accessRule.appDescription": "设置谁可以访问此应用,以及访问权限粒度",
"accessRule.appTitle": "应用权限集",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "工作区所有者",
"common.duplicateAction": "创建副本",
"group.agent": "Agent",
+ "group.agent_acl": "Agent 访问权限",
"group.app": "应用",
"group.app_acl": "应用访问权限",
"group.billing": "账单",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "描述",
"permissionSet.descriptionPlaceholder": "描述此权限集授予的能力",
"permissionSet.learnMore": "了解更多权限说明",
+ "permissionSet.modal.create.agent.description": "创建可在访问规则中引用的 Agent 权限集,以便快速授权。",
+ "permissionSet.modal.create.agent.title": "创建Agent 权限集",
"permissionSet.modal.create.app.description": "创建可在访问规则中引用的应用权限集,以便快速授权。",
"permissionSet.modal.create.app.title": "创建应用权限集",
"permissionSet.modal.create.dataset.description": "创建可在访问规则中引用的知识库权限集,以便快速授权。",
"permissionSet.modal.create.dataset.title": "创建知识库权限集",
+ "permissionSet.modal.edit.agent.description": "修改此权限集的名称、描述和授予的权限。",
+ "permissionSet.modal.edit.agent.title": "编辑Agent 权限集",
"permissionSet.modal.edit.app.description": "修改此权限集的名称、描述和授予的权限。",
"permissionSet.modal.edit.app.title": "编辑应用权限集",
"permissionSet.modal.edit.dataset.description": "修改此权限集的名称、描述和授予的权限。",
"permissionSet.modal.edit.dataset.title": "编辑知识库权限集",
+ "permissionSet.modal.view.agent.description": "查看此权限集的名称、描述和授予的权限。",
+ "permissionSet.modal.view.agent.title": "查看Agent 权限集",
"permissionSet.modal.view.app.description": "查看此权限集的名称、描述和授予的权限。",
"permissionSet.modal.view.app.title": "查看应用权限集",
"permissionSet.modal.view.dataset.description": "查看此权限集的名称、描述和授予的权限。",
diff --git a/web/i18n/zh-Hant/agent-v-2.json b/web/i18n/zh-Hant/agent-v-2.json
index 607d8bdd8c0..c36fddbe8de 100644
--- a/web/i18n/zh-Hant/agent-v-2.json
+++ b/web/i18n/zh-Hant/agent-v-2.json
@@ -343,6 +343,7 @@
"agentDetail.navigationLabel": "Agent 導覽",
"agentDetail.publish": "發佈",
"agentDetail.sections.access": "存取點",
+ "agentDetail.sections.access-config": "訪問權限",
"agentDetail.sections.configure": "配置",
"agentDetail.sections.logs": "日誌",
"agentDetail.sections.monitoring": "監控",
diff --git a/web/i18n/zh-Hant/permission.json b/web/i18n/zh-Hant/permission.json
index f09543c1986..38dbe610513 100644
--- a/web/i18n/zh-Hant/permission.json
+++ b/web/i18n/zh-Hant/permission.json
@@ -3,6 +3,8 @@
"accessRule.actions": "操作",
"accessRule.addMemberAria": "新增 {{name}}",
"accessRule.addMembersTitle": "新增成員",
+ "accessRule.agentDescription": "管理可存取此 Agent 的成員及其權限。",
+ "accessRule.agentTitle": "Agent 權限集",
"accessRule.allowedMembers": "允許存取的成員",
"accessRule.appDescription": "設定誰可以存取此應用,以及存取權限粒度",
"accessRule.appTitle": "應用權限集",
@@ -35,6 +37,7 @@
"accessRule.workspaceOwner": "工作空間擁有者",
"common.duplicateAction": "建立副本",
"group.agent": "Agent",
+ "group.agent_acl": "Agent 訪問權限",
"group.app": "應用",
"group.app_acl": "應用訪問權限",
"group.billing": "帳單",
@@ -53,14 +56,20 @@
"permissionSet.descriptionLabel": "描述",
"permissionSet.descriptionPlaceholder": "描述此權限集授予的能力",
"permissionSet.learnMore": "了解更多權限說明",
+ "permissionSet.modal.create.agent.description": "建立可在訪問規則中引用的 Agent 權限集,以便快速授權。",
+ "permissionSet.modal.create.agent.title": "建立Agent 權限集",
"permissionSet.modal.create.app.description": "建立可在訪問規則中引用的應用權限集,以便快速授權。",
"permissionSet.modal.create.app.title": "建立應用權限集",
"permissionSet.modal.create.dataset.description": "建立可在訪問規則中引用的知識庫權限集,以便快速授權。",
"permissionSet.modal.create.dataset.title": "建立知識庫權限集",
+ "permissionSet.modal.edit.agent.description": "修改此權限集的名稱、描述和授予的權限。",
+ "permissionSet.modal.edit.agent.title": "編輯Agent 權限集",
"permissionSet.modal.edit.app.description": "修改此權限集的名稱、描述和授予的權限。",
"permissionSet.modal.edit.app.title": "編輯應用權限集",
"permissionSet.modal.edit.dataset.description": "修改此權限集的名稱、描述和授予的權限。",
"permissionSet.modal.edit.dataset.title": "編輯知識庫權限集",
+ "permissionSet.modal.view.agent.description": "查看此權限集的名稱、描述和授予的權限。",
+ "permissionSet.modal.view.agent.title": "查看Agent 權限集",
"permissionSet.modal.view.app.description": "查看此權限集的名稱、描述和授予的權限。",
"permissionSet.modal.view.app.title": "查看應用權限集",
"permissionSet.modal.view.dataset.description": "查看此權限集的名稱、描述和授予的權限。",
diff --git a/web/models/access-control.ts b/web/models/access-control.ts
index b32cb29ee7b..72b7a1a4457 100644
--- a/web/models/access-control.ts
+++ b/web/models/access-control.ts
@@ -120,11 +120,7 @@ export type CopyWorkspaceRoleRequest = {
copy_member: boolean
}
-export type WorkspaceAccessRulesRequest = {
- language?: AccessControlTemplateLanguage
-} & PaginationParameters
-
-export type AccessPolicyResourceType = 'app' | 'dataset'
+export type AccessPolicyResourceType = 'app' | 'dataset' | 'agent'
type AccessPolicyCategory = 'global_system_default' | 'global_custom'
@@ -142,19 +138,6 @@ export type AccessPolicy = {
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
@@ -186,16 +169,6 @@ export type GetDatasetAccessPolicyByDatasetIdResponse = {
items: AccessPolicyWithBindings[]
}
-export type GetAppAccessPoliciesResponse = {
- items: AccessPolicyWithBindings[]
- pagination: Pagination
-}
-
-export type GetDatasetAccessPoliciesResponse = {
- items: AccessPolicyWithBindings[]
- pagination: Pagination
-}
-
export type RolesOfMemberResponse = {
account_id: string
roles: Role[]
diff --git a/web/service/access-control/use-workspace-access-rules.ts b/web/service/access-control/use-workspace-access-rules.ts
deleted file mode 100644
index fc87f963f86..00000000000
--- a/web/service/access-control/use-workspace-access-rules.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-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/console/client.spec.ts b/web/service/console/client.spec.ts
index 8dedf8a1409..17b7cc7ccf8 100644
--- a/web/service/console/client.spec.ts
+++ b/web/service/console/client.spec.ts
@@ -97,6 +97,7 @@ const createAgent = (overrides: Partial<AgentMutationResponse> = {}): AgentMutat
icon_url: overrides.icon_url ?? null,
mode: overrides.mode ?? 'agent',
name: overrides.name ?? 'Agent',
+ permission_keys: overrides.permission_keys ?? [],
role: overrides.role ?? 'Assistant',
})
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index a972b6af987..48f35dc0e72 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -5,7 +5,7 @@ import type {
import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'
import type { TagResponse as Tag } from '@dify/contracts/api/console/tags/types.gen'
import type { RouterUtils } from '@orpc/tanstack-query'
-import type { InfiniteData } from '@tanstack/react-query'
+import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query'
import type { ConsoleClient } from './index'
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
@@ -13,6 +13,104 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
const consoleQuery: RouterUtils<ConsoleClient> = createTanstackQueryUtils(consoleClient, {
path: ['console'],
experimental_defaults: {
+ workspaces: {
+ current: {
+ rbac: {
+ accessPolicies: {
+ post: {
+ mutationOptions: {
+ onSettled: (_data, error, _variables, _result, context) => {
+ if (error) return
+ return invalidateAccessPolicyQueries(consoleQuery, context.client)
+ },
+ },
+ },
+ byPolicyId: {
+ put: {
+ mutationOptions: {
+ onSettled: (_data, error, _variables, _result, context) => {
+ if (error) return
+ return invalidateAccessPolicyQueries(consoleQuery, context.client)
+ },
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSettled: (_data, error, _variables, _result, context) => {
+ if (error) return
+ return invalidateAccessPolicyQueries(consoleQuery, context.client)
+ },
+ },
+ },
+ copy: {
+ post: {
+ mutationOptions: {
+ onSettled: (_data, error, _variables, _result, context) => {
+ if (error) return
+ return invalidateAccessPolicyQueries(consoleQuery, context.client)
+ },
+ },
+ },
+ },
+ },
+ },
+ agents: {
+ byAgentId: {
+ whitelist: {
+ put: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return invalidateAgentAccessQueries(
+ consoleQuery,
+ context.client,
+ variables.params.agent_id,
+ )
+ },
+ },
+ },
+ },
+ users: {
+ byTargetAccountId: {
+ accessPolicies: {
+ put: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return invalidateAgentAccessQueries(
+ consoleQuery,
+ context.client,
+ variables.params.agent_id,
+ )
+ },
+ },
+ },
+ },
+ },
+ },
+ accessPolicies: {
+ byPolicyId: {
+ memberBindings: {
+ delete: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return invalidateAgentAccessQueries(
+ consoleQuery,
+ context.client,
+ variables.params.agent_id,
+ )
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
account: {
education: {
get: {
@@ -1139,3 +1237,33 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
return consoleQuery
}
+
+function invalidateQueryKeys(client: QueryClient, queryKeys: QueryKey[]) {
+ return Promise.all(queryKeys.map((queryKey) => client.invalidateQueries({ queryKey })))
+}
+
+function invalidateAccessPolicyQueries(query: RouterUtils<ConsoleClient>, client: QueryClient) {
+ return invalidateQueryKeys(client, [
+ query.workspaces.current.rbac.key(),
+ query.agent.get.key(),
+ query.agent.byAgentId.get.key(),
+ query.apps.byAppId.get.key(),
+ query.datasets.byDatasetId.get.key(),
+ ])
+}
+
+function invalidateAgentAccessQueries(
+ query: RouterUtils<ConsoleClient>,
+ client: QueryClient,
+ agentId: string,
+) {
+ return invalidateQueryKeys(client, [
+ query.workspaces.current.rbac.agents.byAgentId.key({
+ input: { params: { agent_id: agentId } },
+ }),
+ query.workspaces.current.rbac.myPermissions.get.key(),
+ query.agent.get.key(),
+ query.agent.inviteOptions.get.key(),
+ query.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
+ ])
+}
diff --git a/web/test/fixtures/access-policy.ts b/web/test/fixtures/access-policy.ts
new file mode 100644
index 00000000000..c376f5b07e7
--- /dev/null
+++ b/web/test/fixtures/access-policy.ts
@@ -0,0 +1,19 @@
+import type { AccessPolicy } from '@dify/contracts/api/console/workspaces/types.gen'
+import { zAccessPolicy } from '@dify/contracts/api/console/workspaces/zod.gen'
+
+export function createAccessPolicyFixture(overrides: Partial<AccessPolicy> = {}) {
+ return zAccessPolicy.parse({
+ id: 'policy-1',
+ tenant_id: 'tenant-1',
+ resource_type: 'agent',
+ policy_key: 'custom-agent-policy',
+ name: 'Agent editors',
+ description: 'Edit Agent configuration',
+ permission_keys: ['agent.acl.edit'],
+ is_builtin: false,
+ category: 'global_custom',
+ created_at: 1,
+ updated_at: 1,
+ ...overrides,
+ })
+}
diff --git a/web/test/fixtures/agent.ts b/web/test/fixtures/agent.ts
new file mode 100644
index 00000000000..d510f6b660f
--- /dev/null
+++ b/web/test/fixtures/agent.ts
@@ -0,0 +1,17 @@
+import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'
+import { zAgentAppDetailWithSite } from '@dify/contracts/api/console/agent/zod.gen'
+import { AgentPermission } from '@/features/agent-v2/acl'
+
+export function createAgentFixture(overrides: Partial<AgentAppDetailWithSite> = {}) {
+ return zAgentAppDetailWithSite.parse({
+ id: 'agent-1',
+ app_id: 'app-1',
+ name: 'Agent',
+ mode: 'agent',
+ icon_url: null,
+ enable_api: true,
+ enable_site: true,
+ permission_keys: Object.values(AgentPermission).filter((key) => key !== AgentPermission.Create),
+ ...overrides,
+ })
+}