diff --git a/.agents/skills/backend-code-review/references/architecture-rule.md b/.agents/skills/backend-code-review/references/architecture-rule.md index 02ee49d8fd9..0db073adbbe 100644 --- a/.agents/skills/backend-code-review/references/architecture-rule.md +++ b/.agents/skills/backend-code-review/references/architecture-rule.md @@ -41,6 +41,7 @@ # core/policy/publish_policy.py from controllers.console.app import request_context + def can_publish() -> bool: return request_context.current_user.is_admin ``` @@ -50,6 +51,7 @@ def can_publish(role: str) -> bool: return role == "admin" + # service layer adapts web/user context to domain input allowed = can_publish(role=current_user.role) ``` @@ -66,6 +68,7 @@ # api/libs/conversation_filter.py from services.conversation_service import ConversationService + def should_archive_conversation(conversation, tenant_id: str) -> bool: # Domain policy and service dependency are leaking into libs. service = ConversationService() @@ -79,9 +82,11 @@ def older_than_days(idle_days: int, threshold_days: int) -> bool: return idle_days > threshold_days + # services/conversation_service.py (business logic stays in service/core) from libs.datetime_utils import older_than_days + def should_archive_conversation(conversation, tenant_id: str) -> bool: threshold_days = 90 if has_paid_plan(tenant_id) else 30 return older_than_days(conversation.idle_days, threshold_days) diff --git a/.agents/skills/backend-code-review/references/db-schema-rule.md b/.agents/skills/backend-code-review/references/db-schema-rule.md index 8f922bc3dc0..23c5f9f28ab 100644 --- a/.agents/skills/backend-code-review/references/db-schema-rule.md +++ b/.agents/skills/backend-code-review/references/db-schema-rule.md @@ -50,6 +50,7 @@ ```python from sqlalchemy.orm import Mapped + class Dataset(TypeBase): __tablename__ = "datasets" id: Mapped[str] = mapped_column(StringUUID, primary_key=True) @@ -59,6 +60,7 @@ ```python from sqlalchemy.orm import Mapped + class Dataset(TypeBase): __tablename__ = "datasets" id: Mapped[str] = mapped_column(StringUUID, primary_key=True) @@ -101,6 +103,7 @@ from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm import Mapped + class ToolConfig(TypeBase): __tablename__ = "tool_configs" config: Mapped[dict] = mapped_column(JSONB, nullable=False) @@ -111,6 +114,7 @@ from models.types import AdjustedJSON + class ToolConfig(TypeBase): __tablename__ = "tool_configs" config: Mapped[dict] = mapped_column(AdjustedJSON(), nullable=False) @@ -146,7 +150,5 @@ default_expr = sa.text("'database'::character varying") if _is_pg(conn) else sa.text("'database'") with op.batch_alter_table("dataset_keyword_tables") as batch_op: - batch_op.add_column( - sa.Column("data_source_type", sa.String(255), server_default=default_expr, nullable=False) - ) + batch_op.add_column(sa.Column("data_source_type", sa.String(255), server_default=default_expr, nullable=False)) ``` diff --git a/.agents/skills/backend-code-review/references/repositories-rule.md b/.agents/skills/backend-code-review/references/repositories-rule.md index c0f16a21282..c00d25cb7c7 100644 --- a/.agents/skills/backend-code-review/references/repositories-rule.md +++ b/.agents/skills/backend-code-review/references/repositories-rule.md @@ -18,9 +18,7 @@ # Existing repository is ignored and service uses ad-hoc table queries. class AppService: def archive_app(self, app_id: str, tenant_id: str) -> None: - app = self.session.execute( - select(App).where(App.id == app_id, App.tenant_id == tenant_id) - ).scalar_one() + app = self.session.execute(select(App).where(App.id == app_id, App.tenant_id == tenant_id)).scalar_one() app.archived = True self.session.commit() ``` @@ -33,6 +31,7 @@ app.archived = True self.app_repo.save(app) + # If the query is missing, extend the existing abstraction. active_apps = self.app_repo.list_active_for_tenant(tenant_id=tenant_id) ``` @@ -50,9 +49,10 @@ class ConversationRepository(Protocol): def list_recent_for_app(self, app_id: str, tenant_id: str, limit: int) -> list[Conversation]: ... + class SqlAlchemyConversationRepository: - def list_recent_for_app(self, app_id: str, tenant_id: str, limit: int) -> list[Conversation]: - ... + def list_recent_for_app(self, app_id: str, tenant_id: str, limit: int) -> list[Conversation]: ... + class ConversationService: def __init__(self, conversation_repo: ConversationRepository): diff --git a/.agents/skills/backend-code-review/references/sqlalchemy-rule.md b/.agents/skills/backend-code-review/references/sqlalchemy-rule.md index 2ed3be4bbb5..a56bf79ec49 100644 --- a/.agents/skills/backend-code-review/references/sqlalchemy-rule.md +++ b/.agents/skills/backend-code-review/references/sqlalchemy-rule.md @@ -126,9 +126,7 @@ # 3) Pessimistic lock with SELECT ... FOR UPDATE (high contention) run = session.execute( - select(WorkflowRun) - .where(WorkflowRun.id == run_id, WorkflowRun.tenant_id == tenant_id) - .with_for_update() + select(WorkflowRun).where(WorkflowRun.id == run_id, WorkflowRun.tenant_id == tenant_id).with_for_update() ).scalar_one() run.status = "cancelled" session.commit() diff --git a/.agents/skills/frontend-code-review/references/accessibility-ui.md b/.agents/skills/frontend-code-review/references/accessibility-ui.md index e8a841502e0..ed3dc42b6e2 100644 --- a/.agents/skills/frontend-code-review/references/accessibility-ui.md +++ b/.agents/skills/frontend-code-review/references/accessibility-ui.md @@ -26,6 +26,14 @@ Flag: Prefer semantic HTML before ARIA. +## Page Landmarks + +When reviewing Web page layouts, navigation, or landmark changes, read [Page landmarks]. +Inspect the composed page with its parent layouts for missing or duplicate main regions, +inappropriate nesting or roles, and ambiguous or broken landmark names. Check affected +unit and E2E locators when semantic elements change. Web owns these composition rules; +use the existing naming contract for label-source decisions. + ## Accessible Names And Descriptions Read [Accessible names and descriptions] when a change affects labels, ARIA naming, help/error relationships, or hidden text. That document owns the shared implementation and review contract. @@ -123,4 +131,5 @@ Flag: - Hardcoded dates, times, numbers, or currency formats instead of `Intl.*`. [Accessible names and descriptions]: ../../../../packages/dify-ui/docs/accessible-names-and-descriptions.md +[Page landmarks]: ../../../../web/docs/landmarks.md [Web Interface Guidelines]: https://raw.githubusercontent.com/vercel-labs/web-interface-guidelines/main/command.md diff --git a/.agents/skills/how-to-write-component/references/data.md b/.agents/skills/how-to-write-component/references/data.md index 57c23a8f284..009f14c5c52 100644 --- a/.agents/skills/how-to-write-component/references/data.md +++ b/.agents/skills/how-to-write-component/references/data.md @@ -28,7 +28,7 @@ Read this document when a component consumes generated contracts, nullable API v - Use generated `mutationOptions()` directly for owner-local mutations. - Do not introduce deprecated `useInvalid` or `useReset` APIs. -- Put shared invalidation, retries, and cache behavior in `createTanstackQueryUtils(...experimental_defaults...)`. Local callbacks may own toast, close, and navigation effects but must not replace shared cache policy. +- Put shared invalidation, retries, and cache behavior in `createTanstackQueryUtils(...experimental_defaults...)`. In oRPC v1, caller options override defaults, including callbacks. Local callbacks may own toast, close, and navigation effects but must preserve shared cache behavior. - Prefer `mutate(...)`. Use `mutateAsync(...)` only when Promise composition is required, and catch awaited failures. - Preserve intentional empty values and current list/detail ownership when updating data. Do not add optimistic updates without a verified owner contract. diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml index 11fb97b6963..e7e167ffef9 100644 --- a/.github/workflows/style.yml +++ b/.github/workflows/style.yml @@ -175,7 +175,7 @@ jobs: uses: ./.github/actions/setup-web - name: Static check - run: pnpm -w check + run: vp run -w check superlinter: name: SuperLinter diff --git a/.github/workflows/translate-i18n-claude.yml b/.github/workflows/translate-i18n-claude.yml index e24e98f356f..639f2d62fd9 100644 --- a/.github/workflows/translate-i18n-claude.yml +++ b/.github/workflows/translate-i18n-claude.yml @@ -162,7 +162,7 @@ jobs: - name: Run Claude Code for Translation Sync if: steps.context.outputs.CHANGED_FILES != '' - uses: anthropics/claude-code-action@833fb0f8c9f6686b33d963a8bae0a94f4936ab2a # v1.0.211 + uses: anthropics/claude-code-action@d75b94d5ad426cb8546e6628b6f5f19b84e5cce1 # v1.0.216 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.vite-hooks/pre-commit b/.vite-hooks/pre-commit index 9de19c91ef8..604e73a9c8f 100755 --- a/.vite-hooks/pre-commit +++ b/.vite-hooks/pre-commit @@ -1,11 +1,5 @@ #!/bin/sh -# get the list of modified files -files=$(git diff --cached --name-only) - -# check if api or web directory is modified - -api_modified=false -skip_web_checks=false +set -eu git_path() { git rev-parse --git-path "$1" @@ -17,42 +11,7 @@ if [ -f "$(git_path MERGE_HEAD)" ] || \ [ -f "$(git_path SQUASH_MSG)" ] || \ [ -d "$(git_path rebase-merge)" ] || \ [ -d "$(git_path rebase-apply)" ]; then - skip_web_checks=true -fi - -for file in $files -do - # Use POSIX compliant pattern matching - case "$file" in - api/*.py) - # set api_modified flag to true - api_modified=true - ;; - esac -done - -# run linters based on the modified modules - -if $api_modified; then - echo "Running Ruff linter on api module" - - # run Ruff linter auto-fixing - uv run --project api --dev ruff check --fix ./api - - # run Ruff linter checks - uv run --project api --dev ruff check ./api || status=$? - - status=${status:-0} - - if [ $status -ne 0 ]; then - echo "Ruff linter on api module error, exit code: $status" - echo "Please run 'dev/reformat' to fix the fixable linting errors." - exit 1 - fi -fi - -if $skip_web_checks; then - echo "Git operation in progress, skipping web checks" + echo "Git operation in progress, skipping staged checks; CI validates the result." exit 0 fi diff --git a/api/.importlinter b/api/.importlinter index b29dd9cc4ae..d9796d56504 100644 --- a/api/.importlinter +++ b/api/.importlinter @@ -279,6 +279,34 @@ forbidden_modules = sqlalchemy werkzeug +[importlinter:contract:message-file-preview-service-boundary] +name = Message file preview application service is framework and persistence neutral +type = forbidden +source_modules = + services.message_file_preview_service +forbidden_modules = + controllers + extensions + flask + models + repositories + sqlalchemy + werkzeug + +[importlinter:contract:upload-file-delivery-service-boundary] +name = Upload file delivery application service is framework and persistence neutral +type = forbidden +source_modules = + services.upload_file_delivery_service +forbidden_modules = + controllers + extensions + flask + models + repositories + sqlalchemy + werkzeug + [importlinter:contract:webapp-access-query-service-boundary] name = Web app access query application service is framework and persistence neutral type = forbidden @@ -456,6 +484,20 @@ forbidden_modules = sqlalchemy werkzeug +[importlinter:contract:plugin-file-upload-service-boundary] +name = Plugin file upload application service is framework and persistence neutral +type = forbidden +source_modules = + services.plugin_file_upload_service +forbidden_modules = + controllers + extensions + flask + models + repositories + sqlalchemy + werkzeug + [importlinter:contract:account-activation-service-boundary] name = Account activation application service is framework and persistence neutral type = forbidden @@ -487,6 +529,20 @@ forbidden_modules = sqlalchemy werkzeug +[importlinter:contract:tool-file-download-service-boundary] +name = Tool file download application service is framework and persistence neutral +type = forbidden +source_modules = + services.tool_file_download_service +forbidden_modules = + controllers + extensions + flask + models + repositories + sqlalchemy + werkzeug + [importlinter:contract:recommended-app-query-service-boundary] name = Recommended app query application service is framework and persistence neutral type = forbidden diff --git a/api/clients/agent_backend/request_builder.py b/api/clients/agent_backend/request_builder.py index 2f4d09ae9d5..d7a3b8ddc38 100644 --- a/api/clients/agent_backend/request_builder.py +++ b/api/clients/agent_backend/request_builder.py @@ -36,6 +36,11 @@ from dify_agent.layers.knowledge import DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID, DifyK from dify_agent.layers.output import DIFY_OUTPUT_LAYER_TYPE_ID, DifyOutputLayerConfig from dify_agent.layers.runtime import DIFY_RUNTIME_LAYER_TYPE_ID, DifyRuntimeLayerConfig from dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig +from dify_agent.layers.user_prompt import ( + DIFY_USER_PROMPT_LAYER_TYPE_ID, + DifyUserPromptFileConfig, + DifyUserPromptLayerConfig, +) from dify_agent.protocol import ( DIFY_AGENT_HISTORY_LAYER_ID, DIFY_AGENT_MODEL_LAYER_ID, @@ -246,6 +251,7 @@ class AgentBackendAgentAppRunInput(BaseModel): execution_context: DifyExecutionContextLayerConfig backend_binding_ref: str = Field(min_length=1) user_prompt: str + user_files: list[DifyUserPromptFileConfig] = Field(default_factory=list) agent_soul_prompt: str | None = None agent_config_version_kind: AgentConfigVersionKind = "snapshot" idempotency_key: str | None = None @@ -310,9 +316,9 @@ class AgentBackendRunRequestBuilder: [ RunLayerSpec( name=AGENT_APP_USER_PROMPT_LAYER_ID, - type=PLAIN_PROMPT_LAYER_TYPE_ID, + type=DIFY_USER_PROMPT_LAYER_TYPE_ID, metadata={**run_input.metadata, "origin": "agent_app_user_prompt"}, - config=PromptLayerConfig(user=run_input.user_prompt), + config=DifyUserPromptLayerConfig(text=run_input.user_prompt, files=run_input.user_files), ), RunLayerSpec( name=DIFY_EXECUTION_CONTEXT_LAYER_ID, @@ -632,7 +638,7 @@ class AgentBackendRunRequestBuilder: ) -_SENSITIVE_KEY_PARTS = ("secret", "credential", "token", "password", "api_key") +_SENSITIVE_KEY_PARTS = ("secret", "credential", "token", "password", "api_key", "base64_data") def redact_for_agent_backend_log(value: object) -> object: @@ -641,9 +647,10 @@ def redact_for_agent_backend_log(value: object) -> object: return redact_for_agent_backend_log(value.model_dump(mode="json", warnings=False)) if isinstance(value, dict): redacted: dict[object, object] = {} + is_multimodal_file = value.get("type") == "image" and "filename" in value and "mime_type" in value for key, item in value.items(): key_text = str(key).lower() - if any(part in key_text for part in _SENSITIVE_KEY_PARTS): + if any(part in key_text for part in _SENSITIVE_KEY_PARTS) or (is_multimodal_file and key_text == "url"): redacted[key] = "[REDACTED]" else: redacted[key] = redact_for_agent_backend_log(item) diff --git a/api/commands/__init__.py b/api/commands/__init__.py index 73009124062..14bffa072e3 100644 --- a/api/commands/__init__.py +++ b/api/commands/__init__.py @@ -23,6 +23,7 @@ from .plugin import ( transform_datasource_credentials, ) from .rbac import ( + migrate_agent_permissions_to_rbac, migrate_dataset_permissions_to_rbac, migrate_member_roles_to_rbac, migrate_only_me_resource_whitelist_scopes_to_automatic_include, @@ -81,6 +82,7 @@ __all__ = [ "install_plugins", "install_rag_pipeline_plugins", "legacy_model_types", + "migrate_agent_permissions_to_rbac", "migrate_annotation_vector_database", "migrate_data_for_plugin", "migrate_dataset_permissions_to_rbac", diff --git a/api/commands/rbac.py b/api/commands/rbac.py index 5c10c77a1dd..ada2f9606d9 100644 --- a/api/commands/rbac.py +++ b/api/commands/rbac.py @@ -3,6 +3,8 @@ from __future__ import annotations import json from collections.abc import Iterator from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass +from enum import StrEnum import click from sqlalchemy import select @@ -11,12 +13,34 @@ from sqlalchemy.orm import Session from configs import dify_config from core.db.session_factory import session_factory from core.rbac import RBACResourceWhitelistScope -from models import App, Dataset, DatasetPermission, DatasetPermissionEnum, TenantAccountJoin, TenantAccountRole -from services.enterprise.rbac_service import ListOption, RBACService, ReplaceMemberBindings, ReplaceUserAccessPolicies +from models import ( + Agent, + AgentStatus, + App, + Dataset, + DatasetPermission, + DatasetPermissionEnum, + Tenant, + TenantAccountJoin, + TenantAccountRole, +) +from services.enterprise.rbac_service import ( + LegacyAgentRoleMigration, + ListOption, + RBACResourceType, + RBACService, + ReplaceMemberBindings, + ReplaceUserAccessPolicies, +) _RBAC_DEFAULT_ACCESS_POLICY_ID = "default" _RBAC_RESOURCE_ACCESS_POLICY_BATCH_SIZE = 500 +_AGENT_MIGRATION_STATE_LABEL = { + False: "would change", + True: "changed", +} + _LEGACY_ROLE_TO_BUILTIN_TAG = { TenantAccountRole.OWNER.value: "owner", TenantAccountRole.ADMIN.value: "admin", @@ -67,6 +91,88 @@ def _resolve_builtin_role_id(tenant_id: str, operator_account_id: str, legacy_ro return _resolve_builtin_role_ids(tenant_id, operator_account_id)[legacy_role] +def _iter_tenant_ids(tenant_id: str | None, *, batch_size: int) -> Iterator[str]: + if tenant_id: + yield tenant_id + return + last_id: str | None = None + while True: + with session_factory.create_session() as session: + stmt = select(Tenant.id).order_by(Tenant.id.asc()).limit(batch_size) + if last_id is not None: + stmt = stmt.where(Tenant.id > last_id) + rows = session.execute(stmt).scalars().all() + if not rows: + return + for row in rows: + yield str(row) + last_id = str(rows[-1]) + + +def _emit_agent_migration_event(payload: dict[str, object]) -> None: + click.echo(json.dumps(payload, sort_keys=True)) + + +@dataclass(frozen=True) +class _AgentMigrationEventKind: + event_stem: str + include_tenant_id: bool = True + + @property + def skipped(self) -> str: + return f"{self.event_stem}_skipped" + + @property + def failed(self) -> str: + return f"{self.event_stem}_failed" + + def outcome(self, *, apply: bool) -> str: + return f"{self.event_stem}_applied" if apply else f"{self.event_stem}_proposed_change" + + +_AGENT_ROLE_MIGRATION_EVENT_KIND = _AgentMigrationEventKind(event_stem="agent_manage_role_migration") +_AGENT_ROLE_TEMPLATE_MIGRATION_EVENT_KIND = _AgentMigrationEventKind( + event_stem="agent_manage_role_template_migration", include_tenant_id=False +) +_AGENT_ACCESS_BOOTSTRAP_EVENT_KIND = _AgentMigrationEventKind(event_stem="agent_access_bootstrap") + +_AGENT_BACKING_APP_SPECIFIC_WHITELIST_EVENT = "agent_backing_app_has_specific_whitelist" +_AGENT_ACCESS_BOOTSTRAP_MEMBER_SOURCE = "workspace_members" + + +class _AgentAccessBootstrapReason(StrEnum): + ALREADY_INITIALIZED = "already_initialized" + MISSING_WHITELIST_SCOPE = "missing_whitelist_scope" + NO_CREATOR = "no_creator" + + +def _agent_manage_role_event( + tenant_id: str | None, + entry: LegacyAgentRoleMigration, + *, + apply: bool, + kind: _AgentMigrationEventKind, +) -> dict[str, object]: + base: dict[str, object] = { + "dry_run": not apply, + "role_id": entry.role_id, + "role_name": entry.role_name, + } + if kind.include_tenant_id: + base["tenant_id"] = tenant_id + if entry.skipped: + return {**base, "event": kind.skipped, "reason": entry.skipped} + return { + **base, + "event": kind.outcome(apply=apply), + "after": { + "added_keys": entry.added_keys, + "removed_keys": entry.removed_keys, + "bound_policies": entry.bound_policies, + }, + } + + def _iter_tenant_member_batches( tenant_id: str | None, *, @@ -1005,3 +1111,302 @@ def migrate_dataset_permissions_to_rbac( fg="green", ) ) + + +_AgentRow = tuple[str, str | None, str | None] + + +def _iter_agent_row_batches(tenant_id: str, batch_size: int) -> Iterator[list[_AgentRow]]: + last_agent_id: str | None = None + while True: + with session_factory.create_session() as session: + stmt = ( + select(Agent.id, Agent.created_by, Agent.backing_app_id) + .where(Agent.tenant_id == tenant_id, Agent.status != AgentStatus.ARCHIVED) + .order_by(Agent.id.asc()) + .limit(batch_size) + ) + if last_agent_id: + stmt = stmt.where(Agent.id > last_agent_id) + + rows = list(session.execute(stmt).all()) + if not rows: + return + + yield [ + ( + str(row.id), + str(row.created_by) if row.created_by else None, + str(row.backing_app_id) if row.backing_app_id else None, + ) + for row in rows + ] + + last_agent_id = str(rows[-1].id) + + +@dataclass +class _AgentAccessBootstrapCounts: + changed: int = 0 + already_initialized: int = 0 + + +@dataclass(frozen=True) +class _AgentAccessBootstrapOptions: + tenant_id: str + agent_id: str + creator_account_id: str | None + backing_app_id: str | None + operator_account_id: str + member_batch_size: int + apply: bool + initialized: bool + + +def _report_backing_app_specific_whitelist(options: _AgentAccessBootstrapOptions) -> None: + if not options.backing_app_id: + return + app_config = _resource_legacy_whitelist_config( + "app", + tenant_id=options.tenant_id, + operator_account_id=options.operator_account_id, + resource_id=options.backing_app_id, + ) + if _normalize_rbac_whitelist_scope(app_config.rbac_whitelist_scope) is not RBACResourceWhitelistScope.SPECIFIC: + return + _emit_agent_migration_event( + { + "event": _AGENT_BACKING_APP_SPECIFIC_WHITELIST_EVENT, + "dry_run": not options.apply, + "tenant_id": options.tenant_id, + "agent_id": options.agent_id, + "app_id": options.backing_app_id, + "backing_app_account_ids": sorted(set(app_config.account_ids)), + } + ) + + +def _write_agent_access_rows(options: _AgentAccessBootstrapOptions) -> None: + for batch in _workspace_member_account_id_batches(options.tenant_id, options.member_batch_size): + RBACService.AgentAccess.replace_user_access_policies( + tenant_id=options.tenant_id, + account_id=options.operator_account_id, + agent_id=options.agent_id, + target_account_id=None, + payload=ReplaceUserAccessPolicies( + access_policy_ids=[_RBAC_DEFAULT_ACCESS_POLICY_ID], + account_ids=batch, + ), + ) + if options.creator_account_id: + RBACService.AccessPolicies.sync_creator_access_policy_member_bindings( + tenant_id=options.tenant_id, + account_id=options.creator_account_id, + resource_type=RBACResourceType.AGENT, + resource_id=options.agent_id, + ) + RBACService.AgentAccess.replace_whitelist( + tenant_id=options.tenant_id, + account_id=options.operator_account_id, + agent_id=options.agent_id, + payload=ReplaceMemberBindings(automatic_include_workspace_members=True), + ) + + +def _emit_agent_access_bootstrap_skipped( + options: _AgentAccessBootstrapOptions, + reason: _AgentAccessBootstrapReason, +) -> None: + _emit_agent_migration_event( + { + "event": _AGENT_ACCESS_BOOTSTRAP_EVENT_KIND.skipped, + "reason": reason.value, + "dry_run": not options.apply, + "tenant_id": options.tenant_id, + "agent_id": options.agent_id, + "operator_account_id": options.operator_account_id, + } + ) + + +def _agent_access_bootstrap_failure( + options: _AgentAccessBootstrapOptions, + exc: Exception, +) -> click.ClickException: + _emit_agent_migration_event( + { + "event": _AGENT_ACCESS_BOOTSTRAP_EVENT_KIND.failed, + "tenant_id": options.tenant_id, + "agent_id": options.agent_id, + "error": str(exc), + } + ) + return click.ClickException(f"tenant {options.tenant_id} agent {options.agent_id}: {exc}") + + +def _bootstrap_agent_access(options: _AgentAccessBootstrapOptions, counts: _AgentAccessBootstrapCounts) -> None: + if options.initialized: + counts.already_initialized += 1 + _emit_agent_access_bootstrap_skipped(options, _AgentAccessBootstrapReason.ALREADY_INITIALIZED) + return + + config = RBACService.AgentAccess.legacy_whitelist_config( + tenant_id=options.tenant_id, + account_id=options.operator_account_id, + agent_id=options.agent_id, + ) + try: + scope = _normalize_rbac_whitelist_scope(config.rbac_whitelist_scope) + except ValueError as exc: + raise _agent_access_bootstrap_failure(options, exc) from exc + if scope is None: + _emit_agent_access_bootstrap_skipped(options, _AgentAccessBootstrapReason.MISSING_WHITELIST_SCOPE) + return + + account_ids = sorted(set(config.account_ids)) + _report_backing_app_specific_whitelist(options) + + if options.apply: + try: + _write_agent_access_rows(options) + except Exception as exc: + raise _agent_access_bootstrap_failure(options, exc) from exc + counts.changed += 1 + + event: dict[str, object] = { + "event": _AGENT_ACCESS_BOOTSTRAP_EVENT_KIND.outcome(apply=options.apply), + "dry_run": not options.apply, + "tenant_id": options.tenant_id, + "agent_id": options.agent_id, + "operator_account_id": options.operator_account_id, + "before": {"rbac_whitelist_scope": scope.value, "whitelist_account_ids": account_ids}, + "after": { + "automatic_include_workspace_members": True, + "default_policy_member_source": _AGENT_ACCESS_BOOTSTRAP_MEMBER_SOURCE, + "creator_access_policy_synced": bool(options.creator_account_id), + }, + } + if not options.creator_account_id: + event["reason"] = _AgentAccessBootstrapReason.NO_CREATOR.value + _emit_agent_migration_event(event) + + +def _bootstrap_tenant_agent_access( + tenant_id: str, + *, + agent_batch_size: int, + member_batch_size: int, + apply: bool, + counts: _AgentAccessBootstrapCounts, +) -> None: + owner_account_id: str | None = None + for rows in _iter_agent_row_batches(tenant_id, agent_batch_size): + initialized_agent_ids = set( + RBACService.Migrations.list_configured_agent_ids(tenant_id, [agent_id for agent_id, _, _ in rows]) + ) + for agent_id, creator_account_id, backing_app_id in rows: + if creator_account_id: + operator_account_id = creator_account_id + else: + if owner_account_id is None: + with session_factory.create_session() as session: + owner_account_id = _owner_account_id(tenant_id, session=session) + operator_account_id = owner_account_id + _bootstrap_agent_access( + _AgentAccessBootstrapOptions( + tenant_id=tenant_id, + agent_id=agent_id, + creator_account_id=creator_account_id, + backing_app_id=backing_app_id, + operator_account_id=operator_account_id, + member_batch_size=member_batch_size, + apply=apply, + initialized=agent_id in initialized_agent_ids, + ), + counts, + ) + + +@click.command( + "rbac-migrate-agent-permissions", + help=( + "Upgrade step for agent RBAC. Phase 1 asks the RBAC service to replace agent.manage on every " + "custom role with agent.create plus the agent.full_access binding. Phase 2 bootstraps the access " + "rows pre-existing agents never got, so they stay visible to workspace members. Agents that " + "already have a whitelist scope row are skipped. Dry run by default." + ), +) +@click.option("--tenant-id", help="Only migrate a single workspace.") +@click.option( + "--batch-size", + default=500, + show_default=True, + type=click.IntRange(min=1), + help="Tenants fetched per database batch.", +) +@click.option( + "--agent-batch-size", + default=500, + show_default=True, + type=click.IntRange(min=1), + help="Agents fetched per database batch.", +) +@click.option( + "--member-batch-size", + default=_RBAC_RESOURCE_ACCESS_POLICY_BATCH_SIZE, + show_default=True, + type=click.IntRange(min=1), + help="Workspace members written per default-policy call when bootstrapping an agent.", +) +@click.option("--apply", is_flag=True, default=False, help="Write changes. Without it nothing is written.") +def migrate_agent_permissions_to_rbac( + tenant_id: str | None, + batch_size: int, + agent_batch_size: int, + member_batch_size: int, + apply: bool, +) -> None: + click.echo(click.style("Starting agent RBAC migration: custom roles holding agent.manage.", fg="green")) + tenant_count = 0 + role_count = 0 + skipped_count = 0 + seen_template_ids: set[str] = set() + template_count = 0 + agent_counts = _AgentAccessBootstrapCounts() + for workspace_id in _iter_tenant_ids(tenant_id, batch_size=batch_size): + tenant_count += 1 + try: + report = RBACService.Migrations.migrate_agent_manage_roles(workspace_id, apply=apply) + except Exception as exc: + raise click.ClickException(f"tenant {workspace_id}: {exc}") from exc + for entry in report.roles: + role_count += 1 + if entry.skipped: + skipped_count += 1 + _emit_agent_migration_event( + _agent_manage_role_event(workspace_id, entry, apply=apply, kind=_AGENT_ROLE_MIGRATION_EVENT_KIND) + ) + for template in report.role_templates: + if template.role_id in seen_template_ids: + continue + seen_template_ids.add(template.role_id) + template_count += 1 + _emit_agent_migration_event( + _agent_manage_role_event(None, template, apply=apply, kind=_AGENT_ROLE_TEMPLATE_MIGRATION_EVENT_KIND) + ) + _bootstrap_tenant_agent_access( + workspace_id, + agent_batch_size=agent_batch_size, + member_batch_size=member_batch_size, + apply=apply, + counts=agent_counts, + ) + role_state = _AGENT_MIGRATION_STATE_LABEL[apply] + click.echo( + f"{tenant_count} tenant(s), {role_count} role(s) {role_state}, {skipped_count} skipped, " + f"{template_count} template(s) {role_state}, " + f"{agent_counts.changed} agent(s) {role_state}, " + f"{agent_counts.already_initialized} already initialised" + ) + if not apply: + click.echo(click.style("Dry run: no changes written. Re-run with --apply.", fg="yellow")) diff --git a/api/controllers/API_SCHEMA_GUIDE.md b/api/controllers/API_SCHEMA_GUIDE.md index 30e6ddc0a8d..b9587b9f8f8 100644 --- a/api/controllers/API_SCHEMA_GUIDE.md +++ b/api/controllers/API_SCHEMA_GUIDE.md @@ -239,12 +239,12 @@ to the legacy area and avoid importing RESTX model objects from controllers. ## Verifying Swagger -For schema and documentation changes, run focused tests and generate Swagger JSON: +For schema and documentation changes, run focused tests and generate Swagger JSON from the repository root: ```bash -uv run --project . pytest tests/unit_tests/controllers/common/test_schema.py -uv run --project . pytest tests/unit_tests/commands/test_generate_swagger_specs.py tests/unit_tests/controllers/test_swagger.py -uv run --project . dev/generate_swagger_specs.py --output-dir /tmp/dify-openapi-check +uv run --project api pytest api/tests/unit_tests/controllers/common/test_schema.py +uv run --project api pytest api/tests/unit_tests/commands/test_generate_swagger_specs.py api/tests/unit_tests/controllers/test_swagger.py +uv run --project api python api/dev/generate_swagger_specs.py --output-dir /tmp/dify-openapi-check ``` Inspect affected endpoints with `jq`. Check that: @@ -253,3 +253,17 @@ Inspect affected endpoints with `jq`. Check that: - Request bodies appear only where the endpoint has a body. - Responses reference the expected `*Response` schema. - Response schemas use public serialized names, not internal validation aliases like `inputs_dict`. + +## Service API Documentation Handoff + +The `dify-docs` repository imports `service-openapi.json` for the `/v1` API. It keeps a pinned export and adds +descriptions, examples, translations, and existing page URLs through documentation annotations. Fields, constraints, +references, response statuses, and security come from this repository's export. + +Verify the public schema against request validation and response serialization, including intentional schema overrides +and excluded fields. Fix an inaccurate contract here and regenerate it before updating the documentation snapshot. +Record the full source commit SHA when handing off the export. For coordinated changes that are not committed yet, +also provide the source patch used to produce it; replace that patch with a clean committed export after merging. + +The manual import, annotation review, build, and validation commands live in `tools/api-pipeline/README.md` in +`dify-docs`. Regenerate this repository's OpenAPI Markdown and TypeScript/Zod contracts whenever their inputs change. diff --git a/api/controllers/common/rbac/__init__.py b/api/controllers/common/rbac/__init__.py new file mode 100644 index 00000000000..6f227d5034d --- /dev/null +++ b/api/controllers/common/rbac/__init__.py @@ -0,0 +1,29 @@ +from core.rbac import RBACPermission, RBACResourceScope + +from .checks import RBAC_CHECKS_ATTR, RBACCheck, enforce_rbac_checks +from .locators import ( + AgentBehindApp, + AgentId, + DatasetByPipeline, + DatasetId, + PlainApp, + ResourceIdentity, + ResourceLocator, + Workspace, +) + +__all__ = [ + "RBAC_CHECKS_ATTR", + "AgentBehindApp", + "AgentId", + "DatasetByPipeline", + "DatasetId", + "PlainApp", + "RBACCheck", + "RBACPermission", + "RBACResourceScope", + "ResourceIdentity", + "ResourceLocator", + "Workspace", + "enforce_rbac_checks", +] diff --git a/api/controllers/common/rbac/checks.py b/api/controllers/common/rbac/checks.py new file mode 100644 index 00000000000..5cd1ee74159 --- /dev/null +++ b/api/controllers/common/rbac/checks.py @@ -0,0 +1,65 @@ +from collections.abc import Mapping, Sequence +from dataclasses import dataclass + +from flask import request +from werkzeug.exceptions import Forbidden, NotFound + +from configs import dify_config +from core.rbac import RBACPermission, RBACResourceScope +from services.enterprise.rbac_service import RBACService + +from .locators import ResourceLocator, Workspace + +__all__ = ["RBAC_CHECKS_ATTR", "RBACCheck", "enforce_rbac_checks"] + +RBAC_CHECKS_ATTR = "rbac_checks" + + +@dataclass(frozen=True) +class RBACCheck: + scene: RBACPermission + locator: ResourceLocator + + def __post_init__(self) -> None: + if isinstance(self.locator, Workspace) or self.scene.scope is RBACResourceScope.WORKSPACE: + return + if self.locator.scope is not self.scene.scope: + raise ValueError( + f"{self.scene} is a {self.scene.scope} scene but {self.locator!r} locates {self.locator.scope}" + ) + + +def enforce_rbac_checks( + *, + tenant_id: str, + account_id: str, + checks: Sequence[RBACCheck], + path_args: Mapping[str, object] | None = None, +) -> None: + if not dify_config.RBAC_ENABLED: + return + try: + view_args = request.view_args or {} + except RuntimeError: + view_args = {} + merged: dict[str, object] = {**view_args, **(path_args or {})} + applicable = [ + (check, identity) for check in checks if (identity := check.locator.locate(tenant_id, merged)) is not None + ] + if not applicable: + raise NotFound() + for check, identity in applicable: + is_workspace = identity.scope is RBACResourceScope.WORKSPACE + owner = None if is_workspace else check.locator.owner_id(tenant_id, identity) + if owner is not None and owner == account_id: + return + allowed = RBACService.CheckAccess.check( + tenant_id, + account_id, + scene=check.scene, + resource_type=None if is_workspace else identity.scope, + resource_id=None if is_workspace else identity.id, + ) + if allowed: + return + raise Forbidden() diff --git a/api/controllers/common/rbac/locators.py b/api/controllers/common/rbac/locators.py new file mode 100644 index 00000000000..9fcf88bc3f1 --- /dev/null +++ b/api/controllers/common/rbac/locators.py @@ -0,0 +1,144 @@ +from collections.abc import Mapping +from dataclasses import dataclass +from typing import TYPE_CHECKING, Protocol, override, runtime_checkable + +from flask import g +from werkzeug.exceptions import NotFound + +from core.rbac import RBACResourceScope +from services.rbac_resource_service import RBACResourceService + +if TYPE_CHECKING: + from models.agent import Agent + +__all__ = [ + "AgentBehindApp", + "AgentId", + "DatasetByPipeline", + "DatasetId", + "PlainApp", + "ResourceIdentity", + "ResourceLocator", + "Workspace", + "agent_binding", +] + +_AGENT_BINDING_CACHE_KEY = "_rbac_agent_bindings" + + +@dataclass(frozen=True) +class ResourceIdentity: + scope: RBACResourceScope + id: str + + +@runtime_checkable +class ResourceLocator(Protocol): + scope: RBACResourceScope + + def locate(self, tenant_id: str, path_args: Mapping[str, object]) -> ResourceIdentity | None: ... + + def owner_id(self, tenant_id: str, identity: ResourceIdentity) -> str | None: ... + + +def _required(path_args: Mapping[str, object], param: str) -> str: + value = path_args.get(param) + if not value: + raise ValueError(f"Missing {param} in request path") + return str(value) + + +def agent_binding(tenant_id: str, app_id: str) -> "Agent | None": + cache: dict[tuple[str, str], Agent | None] = g.setdefault(_AGENT_BINDING_CACHE_KEY, {}) + key = (tenant_id, app_id) + if key not in cache: + cache[key] = RBACResourceService.get_app_agent_binding(tenant_id, app_id) + return cache[key] + + +class Workspace: + scope = RBACResourceScope.WORKSPACE + + def locate(self, tenant_id: str, path_args: Mapping[str, object]) -> ResourceIdentity | None: + return ResourceIdentity(self.scope, "") + + def owner_id(self, tenant_id: str, identity: ResourceIdentity) -> str | None: + return None + + def __repr__(self) -> str: + return "Workspace()" + + +class _ParamLocator: + scope: RBACResourceScope + default_param: str + + def __init__(self, param: str | None = None): + self.param = param or self.default_param + + def __repr__(self) -> str: + return f"{type(self).__name__}({self.param!r})" + + +class AgentId(_ParamLocator): + scope = RBACResourceScope.AGENT + default_param = "agent_id" + + def locate(self, tenant_id: str, path_args: Mapping[str, object]) -> ResourceIdentity | None: + return ResourceIdentity(self.scope, _required(path_args, self.param)) + + def owner_id(self, tenant_id: str, identity: ResourceIdentity) -> str | None: + return None + + +class PlainApp(_ParamLocator): + scope = RBACResourceScope.APP + default_param = "app_id" + + def locate(self, tenant_id: str, path_args: Mapping[str, object]) -> ResourceIdentity | None: + app_id = _required(path_args, self.param) + if agent_binding(tenant_id, app_id) is not None: + return None + return ResourceIdentity(self.scope, app_id) + + def owner_id(self, tenant_id: str, identity: ResourceIdentity) -> str | None: + return RBACResourceService.get_app_maintainer(tenant_id, identity.id) + + +class AgentBehindApp(_ParamLocator): + scope = RBACResourceScope.AGENT + default_param = "app_id" + + def locate(self, tenant_id: str, path_args: Mapping[str, object]) -> ResourceIdentity | None: + from models.agent import AgentScope + + binding = agent_binding(tenant_id, _required(path_args, self.param)) + if binding is None or binding.scope == AgentScope.WORKFLOW_ONLY: + return None + return ResourceIdentity(self.scope, str(binding.id)) + + def owner_id(self, tenant_id: str, identity: ResourceIdentity) -> str | None: + return None + + +class DatasetId(_ParamLocator): + scope = RBACResourceScope.DATASET + default_param = "dataset_id" + + def locate(self, tenant_id: str, path_args: Mapping[str, object]) -> ResourceIdentity | None: + return ResourceIdentity(self.scope, _required(path_args, self.param)) + + def owner_id(self, tenant_id: str, identity: ResourceIdentity) -> str | None: + return RBACResourceService.get_dataset_maintainer(tenant_id, identity.id) + + +class DatasetByPipeline(DatasetId): + default_param = "pipeline_id" + + @override + def locate(self, tenant_id: str, path_args: Mapping[str, object]) -> ResourceIdentity | None: + pipeline_id = _required(path_args, self.param) + dataset_id = RBACResourceService.get_dataset_id_by_pipeline(tenant_id, pipeline_id) + if dataset_id is None: + raise NotFound("Dataset not found for pipeline") + return ResourceIdentity(self.scope, dataset_id) diff --git a/api/controllers/common/wraps.py b/api/controllers/common/wraps.py index 236423dd351..688e36959a7 100644 --- a/api/controllers/common/wraps.py +++ b/api/controllers/common/wraps.py @@ -1,181 +1,32 @@ from collections.abc import Callable from functools import wraps -from sqlalchemy import select -from werkzeug.exceptions import Forbidden, NotFound - from configs import dify_config -from core.rbac import RBACPermission, RBACResourceScope -from extensions.ext_database import db +from controllers.common.rbac import RBAC_CHECKS_ATTR, RBACCheck, enforce_rbac_checks from libs.login import current_account_with_tenant -from models.dataset import Dataset -from models.model import App -from services.agent.roster_service import AgentRosterService -from services.enterprise.rbac_service import RBACService -__all__ = ["RBACPermission", "RBACResourceScope", "enforce_rbac_access", "rbac_permission_required"] +__all__ = ["rbac_permission_required"] -def enforce_rbac_access( - *, - tenant_id: str, - account_id: str, - resource_type: RBACResourceScope, - scene: RBACPermission, - resource_required: bool = True, - path_args: dict[str, object] | None = None, -) -> None: - """Enforce enterprise RBAC for an explicit account/tenant pair. - - This is the flask-login-independent core of the RBAC gate so it can run - inside request-handling layers that resolve the caller themselves (e.g. the - openapi auth pipeline, which has the account on ``AuthData`` before - flask-login is mounted). - - No-op when ``RBAC_ENABLED`` is ``False``. For resource-scoped checks the - resource ID is taken from ``path_args`` merged with ``request.view_args``; - resource ownership short-circuits the check. Raises ``Forbidden`` when - access is denied. For workspace-level checks pass ``resource_required=False`` - so the RBAC request omits ``resource_id``. - - Args: - tenant_id: The tenant the access is evaluated against. - account_id: The account requesting access. - resource_type: The :class:`RBACResourceScope` member (app/dataset/workspace). - scene: The :class:`RBACPermission` permission point, e.g. ``RBACPermission.APP_DELETE``. - resource_required: Whether a concrete resource ID is required. - path_args: Extra path arguments to merge with ``request.view_args``. - """ - if not dify_config.RBAC_ENABLED: - return - - check_resource_type = None if resource_type == RBACResourceScope.WORKSPACE else resource_type - resource_id = None - if resource_required and check_resource_type: - resource_id = _extract_resource_id(resource_type, tenant_id, path_args) - if _is_resource_owned_by_current_user(tenant_id, account_id, resource_type, resource_id): - return - allowed = RBACService.CheckAccess.check( - tenant_id, - account_id, - scene=scene, - resource_type=check_resource_type, - resource_id=resource_id, - ) - if not allowed: - raise Forbidden() - - -def rbac_permission_required[**P, R]( - resource_type: RBACResourceScope, - scene: RBACPermission, - *, - resource_required: bool = True, -) -> Callable[[Callable[P, R]], Callable[P, R]]: - """Check enterprise RBAC permissions for the current flask-login user. - - When ``RBAC_ENABLED`` is ``False`` the decorator is a no-op and the - request passes through unchanged. When enabled it resolves the current - account/tenant and delegates to :func:`enforce_rbac_access`, raising - ``Forbidden`` if access is denied. - - Args: - resource_type: The :class:`RBACResourceScope` member (app/dataset/workspace). - scene: The :class:`RBACPermission` permission point, e.g. ``RBACPermission.APP_DELETE``. - resource_required: Whether a concrete resource ID is required. - """ +def rbac_permission_required[**P, R](*checks: RBACCheck) -> Callable[[Callable[P, R]], Callable[P, R]]: + if not checks: + raise ValueError("rbac_permission_required requires at least one RBACCheck") def decorator(view: Callable[P, R]) -> Callable[P, R]: - @wraps(view) + @wraps(view, updated=()) def decorated(*args: P.args, **kwargs: P.kwargs) -> R: if not dify_config.RBAC_ENABLED: return view(*args, **kwargs) - current_user, current_tenant_id = current_account_with_tenant() - enforce_rbac_access( + enforce_rbac_checks( tenant_id=current_tenant_id, account_id=current_user.id, - resource_type=resource_type, - scene=scene, - resource_required=resource_required, + checks=checks, path_args=kwargs, ) return view(*args, **kwargs) + setattr(decorated, RBAC_CHECKS_ATTR, checks) return decorated return decorator - - -def _is_resource_owned_by_current_user( - tenant_id: str, account_id: str, resource_type: RBACResourceScope, resource_id: str -) -> bool: - if resource_type == RBACResourceScope.APP: - maintainer = db.session.scalar( - select(App.maintainer).where( - App.id == resource_id, - App.tenant_id == tenant_id, - App.status == "normal", - ) - ) - return maintainer == account_id - - if resource_type == RBACResourceScope.DATASET: - maintainer = db.session.scalar( - select(Dataset.maintainer).where( - Dataset.id == resource_id, - Dataset.tenant_id == tenant_id, - ) - ) - return maintainer == account_id - - return False - - -def _extract_resource_id( - resource_type: RBACResourceScope, tenant_id: str, path_args: dict[str, object] | None = None -) -> str: - """Extract the resource ID from matched path arguments. - - Some legacy route classes use neutral names such as ``resource_id`` for - app/dataset resources, and Agent routes carry ``agent_id``, which is - resolved to the App backing that Agent. - Dataset endpoints behind a rag-pipeline route contain ``pipeline_id`` - instead of ``dataset_id``. In that case we look up the associated - ``Dataset`` row via ``Dataset.pipeline_id``. - """ - from flask import request - - view_args = request.view_args or {} - matched_args = {**view_args, **(path_args or {})} - - if resource_type == RBACResourceScope.APP: - app_id = matched_args.get("app_id") - if app_id: - return str(app_id) # pyrefly: ignore[unnecessary-type-conversion] - - agent_id = matched_args.get("agent_id") - if agent_id: - authz_app_id = AgentRosterService(db.session).peek_authz_app_id(tenant_id=tenant_id, agent_id=str(agent_id)) - return authz_app_id or str(agent_id) - - resource_id = matched_args.get("resource_id") - if resource_id: - return str(resource_id) # pyrefly: ignore[unnecessary-type-conversion] - raise ValueError("Missing app_id in request path") - - if resource_type == RBACResourceScope.DATASET: - dataset_id = matched_args.get("dataset_id") or matched_args.get("resource_id") - if dataset_id: - return str(dataset_id) - - pipeline_id = matched_args.get("pipeline_id") - if pipeline_id: - dataset = db.session.scalar( - select(Dataset).where(Dataset.pipeline_id == str(pipeline_id), Dataset.tenant_id == tenant_id) - ) - if not dataset: - raise NotFound("Dataset not found for pipeline") - return str(dataset.id) # pyrefly: ignore[unnecessary-type-conversion] - raise ValueError("Missing dataset_id or pipeline_id in request path") - raise ValueError(f"Unknown resource_type: {resource_type}") diff --git a/api/controllers/console/agent/composer.py b/api/controllers/console/agent/composer.py index e5ed3ed31e9..2ee9933309e 100644 --- a/api/controllers/console/agent/composer.py +++ b/api/controllers/console/agent/composer.py @@ -4,13 +4,13 @@ from flask_restx import Resource from sqlalchemy.orm import Session from werkzeug.exceptions import NotFound +from controllers.common.rbac import AgentId, PlainApp, RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns -from controllers.console.app.wraps import agent_manage_required_for_agent_app, get_app_model +from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -94,7 +94,7 @@ class WorkflowAgentComposerApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user_id @with_current_tenant_id @with_session @@ -134,7 +134,7 @@ class WorkflowAgentComposerCopyFromRosterApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user_id @with_current_tenant_id @with_session @@ -246,8 +246,8 @@ class WorkflowAgentComposerSaveToRosterApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_CREATE, Workspace())) @with_current_user_id @with_current_tenant_id @with_session @@ -323,9 +323,7 @@ class SnippetAgentComposerApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_user_id @with_current_tenant_id @with_session @@ -362,9 +360,7 @@ class SnippetAgentComposerCopyFromRosterApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_user_id @with_current_tenant_id @with_session @@ -476,10 +472,8 @@ class SnippetAgentComposerSaveToRosterApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_CREATE, Workspace())) @with_current_user_id @with_current_tenant_id @with_session @@ -512,7 +506,7 @@ class AgentComposerApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_tenant_id @with_session def get(self, session: Session, tenant_id: str, agent_id: UUID): @@ -527,7 +521,7 @@ class AgentComposerApi(Resource): @login_required @account_initialization_required @edit_permission_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user_id @with_current_tenant_id @with_session @@ -554,6 +548,7 @@ class AgentComposerValidateApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_tenant_id @with_session @model_validate(ComposerSavePayload) @@ -575,6 +570,7 @@ class AgentComposerCandidatesApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user_id @with_current_tenant_id @with_session(write=False) diff --git a/api/controllers/console/agent/roster.py b/api/controllers/console/agent/roster.py index 6c2798a2017..a8ba32477af 100644 --- a/api/controllers/console/agent/roster.py +++ b/api/controllers/console/agent/roster.py @@ -7,6 +7,7 @@ from pydantic import AliasChoices, BaseModel, Field, field_validator from sqlalchemy import func, or_, select from sqlalchemy.orm import Session +from controllers.common.rbac import AgentId, RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, query_params_from_request, @@ -32,10 +33,8 @@ from controllers.console.app.app import ( from controllers.console.app.app import ( UpdateAppPayload as GenericUpdateAppPayload, ) -from controllers.console.app.wraps import agent_manage_required_for_agent_app from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, enterprise_license_required, @@ -608,7 +607,7 @@ class AgentAppListApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, Workspace())) @with_current_user @with_current_tenant_id @with_session @@ -668,7 +667,7 @@ class AgentAppListApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_CREATE, Workspace())) @with_current_user @with_current_tenant_id @with_session @@ -694,7 +693,7 @@ class AgentAppApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @enterprise_license_required @with_current_user @with_current_tenant_id @@ -711,7 +710,7 @@ class AgentAppApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -744,7 +743,7 @@ class AgentAppApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_DELETE, AgentId())) @with_current_tenant_id @with_session def delete(self, session: Session, tenant_id: str, agent_id: UUID): @@ -765,6 +764,7 @@ class AgentDebugConversationRefreshApi(Resource): @login_required @account_initialization_required @edit_permission_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -790,7 +790,7 @@ class AgentPublishApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_RELEASE_AND_VERSION, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -820,7 +820,7 @@ class AgentBuildDraftCheckoutApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -850,6 +850,7 @@ class AgentBuildDraftApi(Resource): @login_required @account_initialization_required @edit_permission_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -867,6 +868,7 @@ class AgentBuildDraftApi(Resource): @login_required @account_initialization_required @edit_permission_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -892,6 +894,7 @@ class AgentBuildDraftApi(Resource): @login_required @account_initialization_required @edit_permission_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -911,7 +914,7 @@ class AgentBuildDraftApplyApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -934,7 +937,8 @@ class AgentAppCopyApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_CREATE, Workspace())) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -967,7 +971,7 @@ class AgentApiAccessApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_ACCESS_POINT_VIEW, AgentId())) @with_current_tenant_id @with_session(write=False) def get(self, session: Session, tenant_id: str, agent_id: UUID): @@ -984,7 +988,7 @@ class AgentApiStatusApi(Resource): @login_required @is_admin_or_owner_required @account_initialization_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_RELEASE_AND_VERSION) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentId())) @with_current_tenant_id @with_session @model_validate(AgentApiStatusPayload) @@ -1002,7 +1006,7 @@ class AgentApiKeyListApi(BaseApiKeyListResource): token_prefix = "app-" @console_ns.response(200, "Agent service API keys", console_ns.models[ApiKeyList.__name__]) - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_RELEASE_AND_VERSION) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_ACCESS_POINT_VIEW, AgentId())) @with_current_tenant_id @edit_permission_required @with_session(write=False) @@ -1014,7 +1018,7 @@ class AgentApiKeyListApi(BaseApiKeyListResource): @console_ns.response(400, "Maximum keys exceeded") @with_current_tenant_id @edit_permission_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_RELEASE_AND_VERSION) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentId())) @with_session def post(self, session: Session, tenant_id: str, agent_id: UUID) -> tuple[dict[str, object], int]: app_model = _resolve_agent_app_model(session, tenant_id=tenant_id, agent_id=agent_id) @@ -1033,7 +1037,7 @@ class AgentApiKeyApi(BaseApiKeyResource): @console_ns.response(204, "Agent service API key deleted") @with_current_user @with_current_tenant_id - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_RELEASE_AND_VERSION) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentId())) @with_session def delete( self, @@ -1055,6 +1059,7 @@ class AgentInviteOptionsApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, Workspace())) @with_current_tenant_id @with_session(write=False) @model_validate(AgentInviteOptionsQuery) @@ -1078,7 +1083,7 @@ class AgentLogsApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_LOG_MANAGE, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -1117,7 +1122,7 @@ class AgentLogMessagesApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_LOG_MANAGE, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -1156,7 +1161,7 @@ class AgentLogSourcesApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_LOG_MANAGE, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -1177,7 +1182,7 @@ class AgentStatisticsSummaryApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_MONITOR, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -1210,7 +1215,7 @@ class AgentRosterVersionsApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_RELEASE_AND_VERSION, AgentId())) @with_current_tenant_id @with_session(write=False) def get(self, session: Session, tenant_id: str, agent_id: UUID): @@ -1226,7 +1231,7 @@ class AgentRosterVersionDetailApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_RELEASE_AND_VERSION, AgentId())) @with_current_tenant_id @with_session(write=False) def get(self, session: Session, tenant_id: str, agent_id: UUID, version_id: UUID): @@ -1247,7 +1252,7 @@ class AgentRosterVersionRestoreApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.AGENT_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_RELEASE_AND_VERSION, AgentId())) @with_current_user @with_current_tenant_id @with_session diff --git a/api/controllers/console/apikey.py b/api/controllers/console/apikey.py index 98ba57d45c3..7519d0caa8f 100644 --- a/api/controllers/console/apikey.py +++ b/api/controllers/console/apikey.py @@ -11,9 +11,9 @@ from sqlalchemy.orm import Session from werkzeug.exceptions import Forbidden from configs import dify_config +from controllers.common.rbac import AgentBehindApp, DatasetId, PlainApp, RBACCheck from controllers.common.schema import register_response_schema_models from controllers.common.session import with_session -from controllers.console.app.wraps import agent_manage_required_for_agent_app from fields.base import ResponseModel from libs.helper import dump_response, to_timestamp from libs.login import login_required @@ -27,7 +27,6 @@ from services.app_service import AppService from . import console_ns from .wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, rbac_permission_required, @@ -242,8 +241,10 @@ class AppApiKeyListResource(BaseApiKeyListResource): @console_ns.response(200, "API keys retrieved successfully", console_ns.models[ApiKeyList.__name__]) @with_current_tenant_id @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp("resource_id")), + RBACCheck(RBACPermission.AGENT_ACCESS_POINT_VIEW, AgentBehindApp("resource_id")), + ) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, resource_id: UUID) -> dict[str, object]: """Get all API keys for an app""" @@ -259,8 +260,10 @@ class AppApiKeyListResource(BaseApiKeyListResource): @console_ns.response(400, "Maximum keys exceeded") @with_current_tenant_id @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp("resource_id")), + RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentBehindApp("resource_id")), + ) @with_session def post(self, session: Session, current_tenant_id: str, resource_id: UUID) -> tuple[dict[str, object], int]: """Create a new API key for an app""" @@ -283,8 +286,10 @@ class AppApiKeyResource(BaseApiKeyResource): @console_ns.response(204, "API key deleted successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp("resource_id")), + RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentBehindApp("resource_id")), + ) @with_session def delete( self, @@ -321,7 +326,7 @@ class DatasetApiKeyListResource(BaseApiKeyListResource): @console_ns.response(200, "API keys retrieved successfully", console_ns.models[ApiKeyList.__name__]) @with_current_tenant_id @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_API_KEY_MANAGE, DatasetId("resource_id"))) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, resource_id: UUID) -> dict[str, object]: """Get all API keys for a dataset""" @@ -337,7 +342,7 @@ class DatasetApiKeyListResource(BaseApiKeyListResource): @console_ns.response(400, "Maximum keys exceeded") @with_current_tenant_id @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_API_KEY_MANAGE, DatasetId("resource_id"))) @with_session def post(self, session: Session, current_tenant_id: str, resource_id: UUID) -> tuple[dict[str, object], int]: """Create a new API key for a dataset""" @@ -360,7 +365,7 @@ class DatasetApiKeyResource(BaseApiKeyResource): @console_ns.response(204, "API key deleted successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_API_KEY_MANAGE, DatasetId("resource_id"))) @with_session def delete( self, diff --git a/api/controllers/console/app/agent.py b/api/controllers/console/app/agent.py index 4fc9c7f6a6e..619d7da6371 100644 --- a/api/controllers/console/app/agent.py +++ b/api/controllers/console/app/agent.py @@ -4,13 +4,13 @@ from flask_restx import Resource from pydantic import BaseModel, Field, field_validator from sqlalchemy.orm import Session +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, model_validate, rbac_permission_required, @@ -84,7 +84,7 @@ class AgentLogApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @get_app_model(mode=[AppMode.AGENT_CHAT]) @model_validate(AgentLogQuery) diff --git a/api/controllers/console/app/agent_app_access.py b/api/controllers/console/app/agent_app_access.py index 14c049d2f89..b8b81d26bc3 100644 --- a/api/controllers/console/app/agent_app_access.py +++ b/api/controllers/console/app/agent_app_access.py @@ -11,11 +11,18 @@ from flask_restx import Resource from pydantic import Field from sqlalchemy.orm import Session +from controllers.common.rbac import AgentId, RBACCheck from controllers.common.schema import register_response_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.agent.app_helpers import resolve_agent_app_model -from controllers.console.wraps import account_initialization_required, setup_required, with_current_tenant_id +from controllers.console.wraps import ( + RBACPermission, + account_initialization_required, + rbac_permission_required, + setup_required, + with_current_tenant_id, +) from fields.base import ResponseModel from libs.login import login_required from services.agent.roster_service import AgentRosterService @@ -55,6 +62,7 @@ class AgentAppReferencingWorkflowsResource(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_tenant_id @with_session(write=False) def get(self, session: Session, tenant_id: str, agent_id: UUID): diff --git a/api/controllers/console/app/agent_app_feature.py b/api/controllers/console/app/agent_app_feature.py index d88496cbb06..a826177f8d5 100644 --- a/api/controllers/console/app/agent_app_feature.py +++ b/api/controllers/console/app/agent_app_feature.py @@ -16,13 +16,13 @@ from pydantic import BaseModel, Field from sqlalchemy.orm import Session from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import AgentId, RBACCheck from controllers.common.schema import register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -83,7 +83,7 @@ class AgentAppFeatureConfigResource(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @account_initialization_required @with_current_user @with_current_tenant_id diff --git a/api/controllers/console/app/agent_app_sandbox.py b/api/controllers/console/app/agent_app_sandbox.py index b306d570e9e..165994d5a4e 100644 --- a/api/controllers/console/app/agent_app_sandbox.py +++ b/api/controllers/console/app/agent_app_sandbox.py @@ -15,6 +15,7 @@ from flask_restx import Resource from pydantic import BaseModel, Field from clients.agent_backend.errors import backend_error_detail, backend_reported_failure +from controllers.common.rbac import AgentId, PlainApp, RBACCheck from controllers.common.schema import ( query_params_from_model, query_params_from_request, @@ -23,10 +24,9 @@ from controllers.common.schema import ( ) from controllers.console import console_ns from controllers.console.app.error import AppNotFoundError -from controllers.console.app.wraps import agent_manage_required_for_agent_app, get_app_model +from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, model_validate, rbac_permission_required, @@ -153,7 +153,7 @@ class AgentAppSandboxInfoResource(Resource): @setup_required @login_required @account_initialization_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_tenant_id @with_current_user def get(self, current_user: Account, tenant_id: str, agent_id: UUID): @@ -183,7 +183,7 @@ class AgentAppSandboxListResource(Resource): @setup_required @login_required @account_initialization_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_tenant_id @with_current_user def get(self, current_user: Account, tenant_id: str, agent_id: UUID): @@ -214,7 +214,7 @@ class AgentAppSandboxReadResource(Resource): @setup_required @login_required @account_initialization_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_tenant_id @with_current_user def get(self, current_user: Account, tenant_id: str, agent_id: UUID): @@ -245,7 +245,7 @@ class AgentAppSandboxDownloadResource(Resource): @setup_required @login_required @account_initialization_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_tenant_id @with_current_user @model_validate(AgentSandboxDownloadPayload) @@ -289,7 +289,7 @@ class WorkflowAgentSandboxListResource(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_tenant_id def get(self, tenant_id: str, app_model: App, workflow_run_id: UUID, node_id: str): @@ -327,7 +327,7 @@ class WorkflowAgentSandboxReadResource(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_tenant_id def get(self, tenant_id: str, app_model: App, workflow_run_id: UUID, node_id: str): @@ -358,7 +358,7 @@ class WorkflowAgentSandboxDownloadResource(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_current_user @with_current_tenant_id @model_validate(WorkflowAgentSandboxDownloadPayload) diff --git a/api/controllers/console/app/agent_config_inspector.py b/api/controllers/console/app/agent_config_inspector.py index fe211db7218..33503512907 100644 --- a/api/controllers/console/app/agent_config_inspector.py +++ b/api/controllers/console/app/agent_config_inspector.py @@ -15,6 +15,7 @@ from flask_restx import Resource from pydantic import BaseModel, Field from sqlalchemy.orm import Session +from controllers.common.rbac import AgentId, PlainApp, RBACCheck from controllers.common.schema import ( query_params_from_model, query_params_from_request, @@ -27,7 +28,6 @@ from controllers.console.agent.app_helpers import resolve_agent_runtime_app_mode from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -659,6 +659,7 @@ class AgentConfigManifestByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -704,6 +705,7 @@ class AgentConfigSkillUploadByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -733,7 +735,7 @@ class AgentConfigSkillUploadApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @with_session @get_app_model(mode=_WORKFLOW_APP_MODES) @@ -751,6 +753,7 @@ class AgentConfigSkillsByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -789,6 +792,7 @@ class AgentConfigFilesByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -808,6 +812,7 @@ class AgentConfigFilesByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -853,7 +858,7 @@ class AgentConfigFilesApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @with_session @get_app_model(mode=_WORKFLOW_APP_MODES) @@ -877,6 +882,7 @@ class AgentConfigSkillInspectByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -928,6 +934,7 @@ class AgentConfigSkillFilePreviewByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -988,6 +995,7 @@ class AgentConfigSkillDownloadByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -1037,6 +1045,7 @@ class AgentConfigSkillFileDownloadByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -1106,6 +1115,7 @@ class AgentConfigSkillFileDownloadContentByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -1158,6 +1168,7 @@ class AgentConfigSkillByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -1182,7 +1193,7 @@ class AgentConfigSkillApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @with_session @get_app_model(mode=_WORKFLOW_APP_MODES) @@ -1205,6 +1216,7 @@ class AgentConfigFilePreviewByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -1250,6 +1262,7 @@ class AgentConfigFileDownloadByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -1295,6 +1308,7 @@ class AgentConfigFileByAgentApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -1319,7 +1333,7 @@ class AgentConfigFileApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @with_session @get_app_model(mode=_WORKFLOW_APP_MODES) diff --git a/api/controllers/console/app/annotation.py b/api/controllers/console/app/annotation.py index dcad58593a0..ad35cd16aa8 100644 --- a/api/controllers/console/app/annotation.py +++ b/api/controllers/console/app/annotation.py @@ -9,12 +9,12 @@ from sqlalchemy.orm import Session from werkzeug.exceptions import NotFound from controllers.common.errors import NoFileUploadedError, TooManyFilesError +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, annotation_import_concurrency_limit, annotation_import_rate_limit, @@ -180,7 +180,7 @@ class AnnotationReplyActionApi(Resource): @account_initialization_required @cloud_edition_billing_resource_check("annotation") @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @model_validate(AnnotationReplyPayload) def post(self, req_data: AnnotationReplyPayload, app_id: UUID, action: Literal["enable", "disable"]): match action: @@ -211,7 +211,7 @@ class AppAnnotationSettingDetailApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) def get(self, session: Session, app_id: UUID): result = AppAnnotationService.get_app_annotation_setting_by_app_id(str(app_id), session) @@ -230,7 +230,7 @@ class AppAnnotationSettingUpdateApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_session @model_validate(AnnotationSettingUpdatePayload) def post( @@ -263,7 +263,7 @@ class AnnotationReplyActionStatusApi(Resource): @account_initialization_required @cloud_edition_billing_resource_check("annotation") @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, app_id: UUID, job_id: UUID, action: str): job_id_str = str(job_id) app_annotation_job_key = f"{action}_app_annotation_job_{job_id_str}" @@ -294,7 +294,7 @@ class AnnotationApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @model_validate(AnnotationListQuery) def get(self, req_data: AnnotationListQuery, session: Session, app_id: UUID): @@ -321,7 +321,7 @@ class AnnotationApi(Resource): @account_initialization_required @cloud_edition_billing_resource_check("annotation") @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_session @model_validate(CreateAnnotationPayload) def post(self, req_data: CreateAnnotationPayload, session: Session, app_id: UUID): @@ -341,7 +341,7 @@ class AnnotationApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())) @console_ns.response(204, "Annotations deleted successfully") @with_session def delete(self, session: Session, app_id: UUID): @@ -382,7 +382,7 @@ class AnnotationExportApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) def get(self, session: Session, app_id: UUID): annotation_list = AppAnnotationService.export_annotation_list_by_app_id(str(app_id), session) @@ -411,7 +411,7 @@ class AnnotationUpdateDeleteApi(Resource): @account_initialization_required @cloud_edition_billing_resource_check("annotation") @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_session @model_validate(UpdateAnnotationPayload) def post(self, req_data: UpdateAnnotationPayload, session: Session, app_id: UUID, annotation_id: UUID): @@ -429,7 +429,7 @@ class AnnotationUpdateDeleteApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @console_ns.response(204, "Annotation deleted successfully") @with_session def delete(self, session: Session, app_id: UUID, annotation_id: UUID): @@ -458,7 +458,7 @@ class AnnotationBatchImportApi(Resource): @annotation_import_rate_limit @annotation_import_concurrency_limit @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_session def post(self, session: Session, app_id: UUID): from configs import dify_config @@ -513,7 +513,7 @@ class AnnotationBatchImportStatusApi(Resource): @account_initialization_required @cloud_edition_billing_resource_check("annotation") @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, app_id: UUID, job_id: UUID): indexing_cache_key = f"app_annotation_batch_import_{str(job_id)}" cache_result = redis_client.get(indexing_cache_key) @@ -546,7 +546,7 @@ class AnnotationHitHistoryListApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) def get(self, session: Session, app_id: UUID, annotation_id: UUID): page = request.args.get("page", default=1, type=int) diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.py index 87ff0317971..a750dc4bd96 100644 --- a/api/controllers/console/app/app.py +++ b/api/controllers/console/app/app.py @@ -13,6 +13,7 @@ from werkzeug.exceptions import BadRequest, Forbidden, NotFound from configs import dify_config from controllers.common.app_access import resolve_app_access_filter from controllers.common.fields import RedirectUrlResponse, SimpleResultResponse +from controllers.common.rbac import AgentBehindApp, PlainApp, RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, query_params_from_request, @@ -21,11 +22,10 @@ from controllers.common.schema import ( register_schema_models, ) from controllers.console import console_ns -from controllers.console.app.wraps import agent_manage_required_for_agent_app, get_app_model, with_session +from controllers.console.app.wraps import get_app_model, with_session from controllers.console.workspace.models import LoadBalancingPayload from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, cloud_edition_billing_resource_check, edit_permission_required, @@ -691,7 +691,7 @@ class AppListApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, Workspace())) @cloud_edition_billing_resource_check("apps") @edit_permission_required @with_current_user @@ -868,7 +868,7 @@ class AppApi(Resource): @enterprise_license_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @get_app_model(mode=None) def get(self, session: Session, current_tenant_id: str, current_user: Account, app_model: App): @@ -907,8 +907,9 @@ class AppApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_EDIT, PlainApp()), RBACCheck(RBACPermission.AGENT_EDIT, AgentBehindApp()) + ) @with_session @get_app_model(mode=None) @model_validate(UpdateAppPayload) @@ -942,8 +943,9 @@ class AppApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_DELETE) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_DELETE, PlainApp()), RBACCheck(RBACPermission.AGENT_DELETE, AgentBehindApp()) + ) @with_session @get_app_model def delete(self, session: Session, app_model: App): @@ -967,8 +969,7 @@ class AppCopyApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT) - @agent_manage_required_for_agent_app + @rbac_permission_required(RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())) @with_current_user @with_current_tenant_id @get_app_model(mode=None) @@ -1045,8 +1046,10 @@ class AppExportApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, PlainApp()), + RBACCheck(RBACPermission.AGENT_IMPORT_EXPORT_DSL, AgentBehindApp()), + ) @get_app_model @model_validate(AppExportQuery) def get(self, req_data: AppExportQuery, app_model: App): @@ -1070,8 +1073,10 @@ class AppPublishToCreatorsPlatformApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, PlainApp()), + RBACCheck(RBACPermission.AGENT_RELEASE_AND_VERSION, AgentBehindApp()), + ) @with_current_user_id @get_app_model(mode=None) def post(self, current_user_id: str, app_model: App): @@ -1111,8 +1116,9 @@ class AppNameApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_EDIT, PlainApp()), RBACCheck(RBACPermission.AGENT_EDIT, AgentBehindApp()) + ) @with_session @get_app_model(mode=None) @model_validate(AppNamePayload) @@ -1139,8 +1145,9 @@ class AppIconApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_EDIT, PlainApp()), RBACCheck(RBACPermission.AGENT_EDIT, AgentBehindApp()) + ) @with_session @get_app_model(mode=None) @model_validate(AppIconPayload) @@ -1173,7 +1180,10 @@ class AppSiteStatus(Resource): @login_required @account_initialization_required @edit_permission_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_RELEASE_AND_VERSION) + @rbac_permission_required( + RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp()), + RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentBehindApp()), + ) @with_session @get_app_model(mode=None) @model_validate(AppSiteStatusPayload) @@ -1200,8 +1210,10 @@ class AppApiStatus(Resource): @login_required @is_admin_or_owner_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION) - @agent_manage_required_for_agent_app + @rbac_permission_required( + RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp()), + RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentBehindApp()), + ) @with_session @get_app_model(mode=None) @model_validate(AppApiStatusPayload) @@ -1230,7 +1242,7 @@ class AppTraceApi(Resource): @login_required @account_initialization_required @with_session - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model def get(self, session: Session, app_model: App): """Get app trace""" @@ -1252,7 +1264,7 @@ class AppTraceApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TRACING_CONFIG) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TRACING_CONFIG, PlainApp())) @get_app_model @model_validate(AppTracePayload) def post(self, req_data: AppTracePayload, app_model: App): diff --git a/api/controllers/console/app/app_import.py b/api/controllers/console/app/app_import.py index f8fa63a7fba..18de98f8d9a 100644 --- a/api/controllers/console/app/app_import.py +++ b/api/controllers/console/app/app_import.py @@ -4,11 +4,11 @@ from sqlalchemy.orm import Session from werkzeug.exceptions import Forbidden from configs import dify_config +from controllers.common.rbac import PlainApp, RBACCheck, Workspace from controllers.common.schema import register_enum_models, register_schema_models from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, cloud_edition_billing_resource_check, edit_permission_required, @@ -82,7 +82,7 @@ class AppImportApi(Resource): @account_initialization_required @cloud_edition_billing_resource_check("apps") @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, Workspace())) @with_current_user @model_validate(AppImportPayload) def post(self, req_data: AppImportPayload, current_user: Account | None = None): @@ -149,7 +149,7 @@ class AppImportConfirmApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_IMPORT_EXPORT_DSL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, Workspace())) @with_current_user def post(self, current_user: Account | None = None, import_id: str = ""): current_user = current_user if current_user is not None else _current_user_and_tenant_id(None)[0] @@ -208,7 +208,7 @@ class AppImportCheckDependenciesApi(Resource): @get_app_model @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, app_model: App): with Session(db.engine, expire_on_commit=False) as session: import_service = AppDslService(session) diff --git a/api/controllers/console/app/audio.py b/api/controllers/console/app/audio.py index b476817cf08..f6c8cc43ed6 100644 --- a/api/controllers/console/app/audio.py +++ b/api/controllers/console/app/audio.py @@ -9,8 +9,8 @@ from werkzeug.datastructures import FileStorage from werkzeug.exceptions import HTTPException, InternalServerError import services +from controllers.common.rbac import PlainApp, RBACCheck, enforce_rbac_checks from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models -from controllers.common.wraps import enforce_rbac_access from controllers.console import console_ns from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model from controllers.console.app.error import ( @@ -28,7 +28,6 @@ from controllers.console.app.error import ( from controllers.console.app.wraps import get_app_model, with_session from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -242,11 +241,10 @@ class AgentChatMessageAudioApi(Resource): agent_id=agent_id, ) # Agent routes expose Agent ids, while APP RBAC is keyed by the resolved runtime App id. - enforce_rbac_access( + enforce_rbac_checks( tenant_id=current_tenant_id, account_id=current_user.id, - resource_type=RBACResourceScope.APP, - scene=RBACPermission.APP_TEST_AND_RUN, + checks=[RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())], path_args={"app_id": app_model.id}, ) agent_soul = AgentComposerService.load_agent_soul_for_debug( @@ -338,7 +336,7 @@ class TextModesApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model @model_validate(TextToSpeechVoiceQuery) def get(self, req_data: TextToSpeechVoiceQuery, app_model: App): diff --git a/api/controllers/console/app/completion.py b/api/controllers/console/app/completion.py index 53509d00f26..61ce63e7d6b 100644 --- a/api/controllers/console/app/completion.py +++ b/api/controllers/console/app/completion.py @@ -12,6 +12,7 @@ from werkzeug.exceptions import BadRequest, InternalServerError, NotFound import services from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import AgentId, PlainApp, RBACCheck from controllers.common.schema import register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model @@ -24,10 +25,9 @@ from controllers.console.app.error import ( ProviderNotInitializeError, ProviderQuotaExceededError, ) -from controllers.console.app.wraps import agent_manage_required_for_agent_app, get_app_model, with_session +from controllers.console.app.wraps import get_app_model, with_session from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -159,7 +159,7 @@ class CompletionMessageApi(Resource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @with_session @get_app_model(mode=AppMode.COMPLETION) @model_validate(CompletionMessagePayload) @@ -241,7 +241,7 @@ class ChatMessageApi(Resource): @edit_permission_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @with_session @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.AGENT]) def post(self, session: Session, current_tenant_id: str, current_user: Account, app_model: App): @@ -263,7 +263,7 @@ class AgentChatMessageApi(Resource): @login_required @account_initialization_required @edit_permission_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -292,7 +292,7 @@ class AgentBuildChatFinalizeApi(Resource): @login_required @account_initialization_required @edit_permission_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_user @with_current_tenant_id @with_session @@ -333,6 +333,7 @@ class AgentChatMessageStopApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_user_id @with_current_tenant_id @with_session(write=False) diff --git a/api/controllers/console/app/conversation.py b/api/controllers/console/app/conversation.py index 325f3ef22d7..b41b03f2e90 100644 --- a/api/controllers/console/app/conversation.py +++ b/api/controllers/console/app/conversation.py @@ -9,13 +9,13 @@ from sqlalchemy import func, or_ from sqlalchemy.orm import Session, selectinload from werkzeug.exceptions import NotFound +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -106,7 +106,7 @@ class CompletionConversationApi(Resource): @account_initialization_required @edit_permission_required @with_current_user - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @get_app_model(mode=AppMode.COMPLETION) @model_validate(CompletionConversationQuery) @@ -187,7 +187,7 @@ class CompletionConversationDetailApi(Resource): @account_initialization_required @edit_permission_required @with_current_user - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session @get_app_model(mode=AppMode.COMPLETION) def get(self, session: Session, current_user: Account, app_model: App, conversation_id: UUID): @@ -209,7 +209,7 @@ class CompletionConversationDetailApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @with_session @get_app_model(mode=AppMode.COMPLETION) @@ -236,7 +236,7 @@ class ChatConversationApi(Resource): @account_initialization_required @edit_permission_required @with_current_user - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT]) @model_validate(ChatConversationQuery) @@ -356,7 +356,7 @@ class ChatConversationDetailApi(Resource): @account_initialization_required @edit_permission_required @with_current_user - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT]) def get(self, session: Session, current_user: Account, app_model: App, conversation_id: UUID): @@ -378,7 +378,7 @@ class ChatConversationDetailApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @with_session @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT]) diff --git a/api/controllers/console/app/conversation_variables.py b/api/controllers/console/app/conversation_variables.py index ff0727039aa..00c9620d96e 100644 --- a/api/controllers/console/app/conversation_variables.py +++ b/api/controllers/console/app/conversation_variables.py @@ -8,12 +8,12 @@ from pydantic import BaseModel, Field, field_validator from sqlalchemy import select from sqlalchemy.orm import sessionmaker +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_schema_models from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, model_validate, rbac_permission_required, @@ -99,7 +99,7 @@ class ConversationVariablesApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())) @get_app_model(mode=AppMode.ADVANCED_CHAT) @model_validate(ConversationVariablesQuery) def get(self, req_data: ConversationVariablesQuery, app_model: App): diff --git a/api/controllers/console/app/mcp_server.py b/api/controllers/console/app/mcp_server.py index 6d232451043..8a6ab77b3dd 100644 --- a/api/controllers/console/app/mcp_server.py +++ b/api/controllers/console/app/mcp_server.py @@ -7,12 +7,12 @@ from pydantic import BaseModel, Field, field_validator from sqlalchemy import select from werkzeug.exceptions import NotFound +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import register_schema_models from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -87,7 +87,7 @@ class AppMCPServerController(Resource): @login_required @account_initialization_required @setup_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model def get(self, app_model: App): server = db.session.scalar(select(AppMCPServer).where(AppMCPServer.app_id == app_model.id).limit(1)) @@ -107,7 +107,7 @@ class AppMCPServerController(Resource): @login_required @setup_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_tenant_id @get_app_model @model_validate(MCPServerCreatePayload) @@ -142,7 +142,7 @@ class AppMCPServerController(Resource): @setup_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @get_app_model @model_validate(MCPServerUpdatePayload) def put(self, req_data: MCPServerUpdatePayload, app_model: App): @@ -190,7 +190,7 @@ class AppMCPServerRefreshController(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_tenant_id @get_app_model def post(self, current_tenant_id: str, app_model: App): diff --git a/api/controllers/console/app/message.py b/api/controllers/console/app/message.py index 1c5a74e5172..c5bbba1f738 100644 --- a/api/controllers/console/app/message.py +++ b/api/controllers/console/app/message.py @@ -2,7 +2,6 @@ import logging from typing import Literal from uuid import UUID -from flask import request from flask_restx import Resource from pydantic import BaseModel, Field, field_validator from sqlalchemy import exists, func, select @@ -11,6 +10,7 @@ from werkzeug.exceptions import InternalServerError, NotFound from controllers.common.controller_schemas import MessageFeedbackPayload as _MessageFeedbackPayloadBase from controllers.common.fields import SimpleResultResponse, TextFileResponse +from controllers.common.rbac import AgentId, PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns @@ -21,11 +21,10 @@ from controllers.console.app.error import ( ProviderNotInitializeError, ProviderQuotaExceededError, ) -from controllers.console.app.wraps import agent_manage_required_for_agent_app, get_app_model +from controllers.console.app.wraps import get_app_model from controllers.console.explore.error import AppSuggestedQuestionsAfterAnswerDisabledError from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -155,11 +154,17 @@ class ChatMessageListApi(Resource): @setup_required @edit_permission_required @with_current_user - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT]) - def get(self, session: Session, current_user: Account, app_model: App): - return _list_chat_messages(session=session, app_model=app_model, current_user=current_user) + @model_validate(ChatMessagesQuery) + def get(self, req_data: ChatMessagesQuery, session: Session, current_user: Account, app_model: App): + return _list_chat_messages( + args=req_data, + session=session, + app_model=app_model, + current_user=current_user, + ) @console_ns.route("/agent//chat-messages") @@ -174,17 +179,30 @@ class AgentChatMessageListApi(Resource): @account_initialization_required @setup_required @edit_permission_required - @agent_manage_required_for_agent_app(scene=RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) - def get(self, session: Session, current_tenant_id: str, current_user: Account, agent_id: UUID): + @model_validate(ChatMessagesQuery) + def get( + self, + req_data: ChatMessagesQuery, + session: Session, + current_tenant_id: str, + current_user: Account, + agent_id: UUID, + ): app_model = resolve_agent_runtime_app_model( session=session, tenant_id=current_tenant_id, agent_id=agent_id, ) - return _list_chat_messages(session=session, app_model=app_model, current_user=current_user) + return _list_chat_messages( + args=req_data, + session=session, + app_model=app_model, + current_user=current_user, + ) @console_ns.route("/apps//feedbacks") @@ -202,8 +220,14 @@ class MessageFeedbackApi(Resource): @with_current_user @with_session @get_app_model - def post(self, session: Session, current_user: Account, app_model: App): - return _update_message_feedback(session=session, current_user=current_user, app_model=app_model) + @model_validate(MessageFeedbackPayload) + def post(self, req_data: MessageFeedbackPayload, session: Session, current_user: Account, app_model: App): + return _update_message_feedback( + args=req_data, + session=session, + current_user=current_user, + app_model=app_model, + ) @console_ns.route("/agent//feedbacks") @@ -217,16 +241,30 @@ class AgentMessageFeedbackApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_user @with_current_tenant_id @with_session - def post(self, session: Session, current_tenant_id: str, current_user: Account, agent_id: UUID): + @model_validate(MessageFeedbackPayload) + def post( + self, + req_data: MessageFeedbackPayload, + session: Session, + current_tenant_id: str, + current_user: Account, + agent_id: UUID, + ): app_model = resolve_agent_runtime_app_model( session=session, tenant_id=current_tenant_id, agent_id=agent_id, ) - return _update_message_feedback(session=session, current_user=current_user, app_model=app_model) + return _update_message_feedback( + args=req_data, + session=session, + current_user=current_user, + app_model=app_model, + ) @console_ns.route("/apps//annotations/count") @@ -242,7 +280,7 @@ class MessageAnnotationCountApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model def get(self, app_model: App): count = db.session.scalar( @@ -267,7 +305,7 @@ class MessageSuggestedQuestionApi(Resource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT]) def get(self, session: Session, current_user: Account, app_model: App, message_id: UUID): @@ -290,6 +328,7 @@ class AgentMessageSuggestedQuestionApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -319,7 +358,7 @@ class MessageFeedbackExportApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model @model_validate(FeedbackExportQuery) def get(self, req_data: FeedbackExportQuery, app_model: App): @@ -358,7 +397,7 @@ class MessageApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @with_session(write=False) @get_app_model def get(self, session: Session, app_model: App, message_id: UUID): @@ -375,6 +414,7 @@ class AgentMessageApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.AGENT_TEST_AND_RUN, AgentId())) @with_current_tenant_id @with_session(write=False) def get(self, session: Session, current_tenant_id: str, agent_id: UUID, message_id: UUID): @@ -386,9 +426,13 @@ class AgentMessageApi(Resource): return _get_message_detail(session=session, app_model=app_model, message_id=message_id) -def _list_chat_messages(*, session: Session, app_model: App, current_user: Account | None = None): - args = ChatMessagesQuery.model_validate(request.args.to_dict()) - +def _list_chat_messages( + *, + args: ChatMessagesQuery, + session: Session, + app_model: App, + current_user: Account | None = None, +): if AppMode.value_of(app_model.mode) == AppMode.AGENT and current_user is not None: try: conversation = ConversationService.get_conversation( @@ -465,9 +509,13 @@ def _list_chat_messages(*, session: Session, app_model: App, current_user: Accou ) -def _update_message_feedback(*, session: Session, current_user: Account, app_model: App): - args = MessageFeedbackPayload.model_validate(console_ns.payload) - +def _update_message_feedback( + *, + args: MessageFeedbackPayload, + session: Session, + current_user: Account, + app_model: App, +): message_id = args.message_id message = session.scalar(select(Message).where(Message.id == message_id, Message.app_id == app_model.id).limit(1)) diff --git a/api/controllers/console/app/model_config.py b/api/controllers/console/app/model_config.py index 15298366414..1b44c4c64ec 100644 --- a/api/controllers/console/app/model_config.py +++ b/api/controllers/console/app/model_config.py @@ -7,13 +7,13 @@ from pydantic import BaseModel, Field from sqlalchemy.orm import Session from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, rbac_permission_required, @@ -90,7 +90,7 @@ class ModelConfigResource(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @account_initialization_required @with_current_user_id @with_current_tenant_id diff --git a/api/controllers/console/app/ops_trace.py b/api/controllers/console/app/ops_trace.py index 9f9cdfb48f2..4dbe8bc8d07 100644 --- a/api/controllers/console/app/ops_trace.py +++ b/api/controllers/console/app/ops_trace.py @@ -4,6 +4,7 @@ from uuid import UUID from flask_restx import Resource from pydantic import BaseModel, Field +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.app.error import ( @@ -18,7 +19,6 @@ from controllers.console.app.error import ( from controllers.console.flask_admission import console_account_admission from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, model_validate, ) from extensions.ext_application_services import application_services @@ -106,8 +106,7 @@ class TraceAppConfigApi(Resource): @console_ns.response(404, "Application not found") @console_ns.response(500, "Tracing configuration processing failed") @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_TRACING_CONFIG, + rbac_checks=[RBACCheck(RBACPermission.APP_TRACING_CONFIG, PlainApp())], ) @model_validate(TraceProviderQuery) def get( @@ -155,8 +154,7 @@ class TraceAppConfigApi(Resource): @console_ns.response(500, "Tracing configuration processing failed") @console_account_admission( allowed_roles=_APP_TRACING_CONFIG_EDIT_ROLES, - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_TRACING_CONFIG, + rbac_checks=[RBACCheck(RBACPermission.APP_TRACING_CONFIG, PlainApp())], ) @model_validate(TraceConfigPayload) def post( @@ -205,8 +203,7 @@ class TraceAppConfigApi(Resource): @console_ns.response(500, "Tracing configuration processing failed") @console_account_admission( allowed_roles=_APP_TRACING_CONFIG_EDIT_ROLES, - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_TRACING_CONFIG, + rbac_checks=[RBACCheck(RBACPermission.APP_TRACING_CONFIG, PlainApp())], ) @model_validate(TraceConfigPayload) def patch( @@ -251,8 +248,7 @@ class TraceAppConfigApi(Resource): @console_ns.response(500, "Tracing configuration processing failed") @console_account_admission( allowed_roles=_APP_TRACING_CONFIG_EDIT_ROLES, - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_TRACING_CONFIG, + rbac_checks=[RBACCheck(RBACPermission.APP_TRACING_CONFIG, PlainApp())], ) @model_validate(TraceProviderQuery) def delete( diff --git a/api/controllers/console/app/site.py b/api/controllers/console/app/site.py index 7d1d7efc616..c1e0636ac0f 100644 --- a/api/controllers/console/app/site.py +++ b/api/controllers/console/app/site.py @@ -5,13 +5,13 @@ from pydantic import BaseModel, Field, field_validator from werkzeug.exceptions import NotFound from constants.languages import supported_language +from controllers.common.rbac import AgentBehindApp, PlainApp, RBACCheck from controllers.common.schema import register_schema_models from controllers.console import console_ns from controllers.console.app.error import AppNotFoundError from controllers.console.flask_admission import console_account_admission from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, model_validate, ) from extensions.ext_application_services import application_services @@ -105,9 +105,10 @@ class AppSite(Resource): @console_ns.response(404, "App not found") @console_account_admission( allowed_roles=_APP_SITE_EDIT_ROLES, - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_RELEASE_AND_VERSION, - agent_manage_fallback=True, + rbac_checks=[ + RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp()), + RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentBehindApp()), + ], ) @model_validate(AppSiteUpdatePayload) def post( @@ -136,9 +137,10 @@ class AppSiteAccessTokenReset(Resource): @console_ns.response(404, "App or site not found") @console_account_admission( allowed_roles=_APP_SITE_TOKEN_RESET_ROLES, - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_RELEASE_AND_VERSION, - agent_manage_fallback=True, + rbac_checks=[ + RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp()), + RBACCheck(RBACPermission.AGENT_ACCESS_POINT_MANAGE, AgentBehindApp()), + ], ) def post(self, request_context: RequestContext, app_id: UUID): try: diff --git a/api/controllers/console/app/statistic.py b/api/controllers/console/app/statistic.py index 2ebf60bdcfe..195af05e5fa 100644 --- a/api/controllers/console/app/statistic.py +++ b/api/controllers/console/app/statistic.py @@ -5,11 +5,12 @@ from flask_restx import Resource from pydantic import BaseModel, Field, field_validator from werkzeug.exceptions import BadRequest +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.flask_admission import console_account_admission -from controllers.console.wraps import RBACPermission, RBACResourceScope, model_validate +from controllers.console.wraps import RBACPermission, model_validate from extensions.ext_application_services import application_services from fields.base import ResponseModel from libs.datetime_utils import parse_time_range @@ -158,8 +159,7 @@ class DailyMessageStatistic(Resource): console_ns.models[DailyMessageStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(StatisticTimeRangeQuery) @@ -186,8 +186,7 @@ class DailyConversationStatistic(Resource): console_ns.models[DailyConversationStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(StatisticTimeRangeQuery) @@ -214,8 +213,7 @@ class DailyTerminalsStatistic(Resource): console_ns.models[DailyTerminalStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(StatisticTimeRangeQuery) @@ -242,8 +240,7 @@ class DailyTokenCostStatistic(Resource): console_ns.models[DailyTokenCostStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(StatisticTimeRangeQuery) @@ -270,8 +267,7 @@ class AverageSessionInteractionStatistic(Resource): console_ns.models[AverageSessionInteractionStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT]) @model_validate(StatisticTimeRangeQuery) @@ -298,8 +294,7 @@ class UserSatisfactionRateStatistic(Resource): console_ns.models[UserSatisfactionRateStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(StatisticTimeRangeQuery) @@ -326,8 +321,7 @@ class AverageResponseTimeStatistic(Resource): console_ns.models[AverageResponseTimeStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model(mode=AppMode.COMPLETION) @model_validate(StatisticTimeRangeQuery) @@ -354,8 +348,7 @@ class TokensPerSecondStatistic(Resource): console_ns.models[TokensPerSecondStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(StatisticTimeRangeQuery) diff --git a/api/controllers/console/app/workflow.py b/api/controllers/console/app/workflow.py index c7e51f663a4..aa596e39a8e 100644 --- a/api/controllers/console/app/workflow.py +++ b/api/controllers/console/app/workflow.py @@ -25,6 +25,7 @@ from controllers.common.app_access import resolve_app_access_filter from controllers.common.controller_schemas import DefaultBlockConfigQuery, WorkflowListQuery, WorkflowUpdatePayload from controllers.common.errors import InvalidArgumentError from controllers.common.fields import GeneratedAppResponse, NewAppResponse, SimpleResultResponse +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import ( query_params_from_model, register_response_schema_model, @@ -41,7 +42,6 @@ from controllers.console.app.permission_keys import get_app_permission_keys from controllers.console.app.wraps import get_app_model, with_session from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -582,7 +582,7 @@ class DraftWorkflowApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App): """ @@ -625,7 +625,7 @@ class DraftWorkflowApi(Resource): @console_ns.response(403, "Permission denied") @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def post(self, current_user: Account, app_model: App): """ Sync draft workflow @@ -704,7 +704,7 @@ class AdvancedChatDraftWorkflowRunApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @with_current_user @edit_permission_required @with_session @@ -760,7 +760,7 @@ class AdvancedChatDraftRunIterationNodeApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT]) @with_current_user @edit_permission_required @@ -809,7 +809,7 @@ class WorkflowDraftRunIterationNodeApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.WORKFLOW]) @with_current_user @edit_permission_required @@ -854,7 +854,7 @@ class AdvancedChatDraftRunLoopNodeApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT]) @with_current_user @edit_permission_required @@ -902,7 +902,7 @@ class WorkflowDraftRunLoopNodeApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.WORKFLOW]) @with_current_user @edit_permission_required @@ -982,7 +982,7 @@ class AdvancedChatDraftHumanInputFormPreviewApi(Resource): @get_app_model(mode=[AppMode.ADVANCED_CHAT]) @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @model_validate(HumanInputFormPreviewPayload) def post(self, args: HumanInputFormPreviewPayload, current_user: Account, app_model: App, node_id: str): """ @@ -1015,7 +1015,7 @@ class AdvancedChatDraftHumanInputFormRunApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT]) @with_current_user @edit_permission_required @@ -1050,7 +1050,7 @@ class WorkflowDraftHumanInputFormPreviewApi(Resource): @get_app_model(mode=[AppMode.WORKFLOW]) @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @model_validate(HumanInputFormPreviewPayload) def post(self, args: HumanInputFormPreviewPayload, current_user: Account, app_model: App, node_id: str): """ @@ -1083,7 +1083,7 @@ class WorkflowDraftHumanInputFormRunApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.WORKFLOW]) @with_current_user @edit_permission_required @@ -1118,7 +1118,7 @@ class WorkflowDraftHumanInputDeliveryTestApi(Resource): @get_app_model(mode=[AppMode.WORKFLOW, AppMode.ADVANCED_CHAT]) @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @model_validate(HumanInputDeliveryTestPayload) def post(self, args: HumanInputDeliveryTestPayload, current_user: Account, app_model: App, node_id: str): """ @@ -1151,7 +1151,7 @@ class DraftWorkflowRunApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @with_current_user @edit_permission_required @with_session @@ -1194,7 +1194,7 @@ class WorkflowTaskStopApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def post(self, app_model: App, task_id: str): """ @@ -1226,7 +1226,7 @@ class DraftWorkflowNodeRunApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required @@ -1278,7 +1278,7 @@ class PublishedWorkflowApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App): """ @@ -1300,7 +1300,7 @@ class PublishedWorkflowApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION) + @rbac_permission_required(RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required @@ -1349,7 +1349,7 @@ class DefaultBlockConfigsApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App): """ @@ -1376,7 +1376,7 @@ class DefaultBlockConfigApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @model_validate(DefaultBlockConfigQuery) def get(self, args: DefaultBlockConfigQuery, app_model: App, block_type: str): @@ -1416,7 +1416,7 @@ class ConvertToWorkflowApi(Resource): @with_current_user @with_current_tenant_id @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @model_validate(ConvertToWorkflowPayload) def post(self, payload: ConvertToWorkflowPayload, current_tenant_id: str, current_user: Account, app_model: App): """ @@ -1458,7 +1458,7 @@ class WorkflowFeaturesApi(Resource): @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @model_validate(WorkflowFeaturesPayload) def post(self, args: WorkflowFeaturesPayload, current_user: Account, app_model: App): features = args.features.model_dump(mode="json", exclude_unset=True) @@ -1485,7 +1485,7 @@ class PublishedAllWorkflowApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required @@ -1538,7 +1538,7 @@ class DraftWorkflowRestoreApi(Resource): @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION) + @rbac_permission_required(RBACCheck(RBACPermission.APP_RELEASE_AND_VERSION, PlainApp())) def post(self, current_user: Account, app_model: App, workflow_id: str): workflow_service = WorkflowService() @@ -1578,7 +1578,7 @@ class WorkflowByIdApi(Resource): @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @model_validate(WorkflowUpdatePayload) def patch(self, args: WorkflowUpdatePayload, current_user: Account, app_model: App, workflow_id: str): """ @@ -1620,7 +1620,7 @@ class WorkflowByIdApi(Resource): @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @console_ns.response(204, "Workflow deleted successfully") def delete(self, current_user: Account, app_model: App, workflow_id: str): """ @@ -1666,7 +1666,7 @@ class DraftWorkflowNodeLastRunApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, node_id: str): srv = WorkflowService() @@ -1711,7 +1711,7 @@ class DraftWorkflowTriggerRunApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @with_current_user @edit_permission_required @with_session @@ -1782,7 +1782,7 @@ class DraftWorkflowTriggerNodeApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @get_app_model(mode=[AppMode.WORKFLOW]) @with_current_user @edit_permission_required @@ -1865,7 +1865,7 @@ class DraftWorkflowTriggerRunAllApi(Resource): @account_initialization_required @with_current_user @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TEST_AND_RUN) + @rbac_permission_required(RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp())) @with_session @get_app_model(mode=[AppMode.WORKFLOW]) @model_validate(DraftWorkflowTriggerRunAllPayload) diff --git a/api/controllers/console/app/workflow_app_log.py b/api/controllers/console/app/workflow_app_log.py index e74abd03f66..6271c1fe64a 100644 --- a/api/controllers/console/app/workflow_app_log.py +++ b/api/controllers/console/app/workflow_app_log.py @@ -5,15 +5,12 @@ from dateutil.parser import isoparse from flask_restx import Resource from pydantic import BaseModel, Field, field_validator +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_schema_models from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.flask_admission import console_account_admission -from controllers.console.wraps import ( - RBACPermission, - RBACResourceScope, - model_validate, -) +from controllers.console.wraps import RBACPermission, model_validate from extensions.ext_application_services import application_services from fields.base import ResponseModel from fields.end_user_fields import SimpleEndUser @@ -133,8 +130,7 @@ class WorkflowAppLogApi(Resource): console_ns.models[WorkflowAppLogPaginationResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_LOG_AND_ANNOTATION, + rbac_checks=[RBACCheck(RBACPermission.APP_LOG_AND_ANNOTATION, PlainApp())], ) @get_app_model(mode=[AppMode.WORKFLOW]) @model_validate(WorkflowAppLogQuery) diff --git a/api/controllers/console/app/workflow_draft_variable.py b/api/controllers/console/app/workflow_draft_variable.py index 6d52419f88c..32deabfae19 100644 --- a/api/controllers/console/app/workflow_draft_variable.py +++ b/api/controllers/console/app/workflow_draft_variable.py @@ -11,6 +11,7 @@ from sqlalchemy.orm import sessionmaker from controllers.common.errors import InvalidArgumentError, NotFoundError from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.app.error import ( @@ -19,7 +20,6 @@ from controllers.console.app.error import ( from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -337,7 +337,7 @@ def _api_prerequisite[T, **P, R]( @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @wraps(f) @@ -359,7 +359,7 @@ class WorkflowVariableCollectionApi(Resource): ) @_api_prerequisite @marshal_with(workflow_draft_variable_list_without_value_model) - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @model_validate(WorkflowDraftVariableListQuery) def get(self, req_data: WorkflowDraftVariableListQuery, current_user: Account, app_model: App): """ @@ -424,7 +424,7 @@ class NodeVariableCollectionApi(Resource): @console_ns.response(200, "Node variables retrieved successfully", workflow_draft_variable_list_model) @_api_prerequisite @marshal_with(workflow_draft_variable_list_model) - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, current_user: Account, app_model: App, node_id: str): validate_node_id(node_id) with sessionmaker(bind=db.engine, expire_on_commit=False).begin() as session: @@ -459,7 +459,7 @@ class VariableApi(Resource): @console_ns.response(404, "Variable not found") @_api_prerequisite @marshal_with(workflow_draft_variable_model) - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, current_user: Account, app_model: App, variable_id: UUID): draft_var_srv = WorkflowDraftVariableService( session=db.session(), @@ -638,7 +638,7 @@ class ConversationVariableCollectionApi(Resource): @console_ns.response(404, "Draft workflow not found") @_api_prerequisite @marshal_with(workflow_draft_variable_list_model) - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, current_user: Account, app_model: App): # NOTE(QuantumGhost): Prefill conversation variables into the draft variables table # so their IDs can be returned to the caller. @@ -664,7 +664,7 @@ class ConversationVariableCollectionApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @get_app_model(mode=AppMode.ADVANCED_CHAT) @model_validate(ConversationVariableUpdatePayload) @@ -697,7 +697,7 @@ class SystemVariableCollectionApi(Resource): @console_ns.response(200, "System variables retrieved successfully", workflow_draft_variable_list_model) @_api_prerequisite @marshal_with(workflow_draft_variable_list_model) - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, current_user: Account, app_model: App): return _get_variable_list(app_model, SYSTEM_VARIABLE_NODE_ID, current_user.id) @@ -714,7 +714,7 @@ class EnvironmentVariableCollectionApi(Resource): ) @console_ns.response(404, "Draft workflow not found") @_api_prerequisite - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) def get(self, _current_user: Account, app_model: App): """ Get draft workflow @@ -759,7 +759,7 @@ class EnvironmentVariableCollectionApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @with_current_user @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @model_validate(EnvironmentVariableUpdatePayload) diff --git a/api/controllers/console/app/workflow_node_output_inspector.py b/api/controllers/console/app/workflow_node_output_inspector.py index ea45a718a02..ae16bbd3865 100644 --- a/api/controllers/console/app/workflow_node_output_inspector.py +++ b/api/controllers/console/app/workflow_node_output_inspector.py @@ -31,12 +31,12 @@ from flask import Response from flask_restx import Resource from controllers.common.fields import EventStreamResponse +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import register_response_schema_models from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, rbac_permission_required, setup_required, @@ -157,7 +157,7 @@ class WorkflowDraftRunNodeOutputsApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID): return _serve_snapshot(app_model, run_id) @@ -181,7 +181,7 @@ class WorkflowDraftRunNodeOutputDetailApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID, node_id: str): return _serve_node_detail(app_model, run_id, node_id) @@ -208,7 +208,7 @@ class WorkflowDraftRunNodeOutputPreviewApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID, node_id: str, output_name: str): return _serve_output_preview(app_model, run_id, node_id, output_name) @@ -353,7 +353,7 @@ class WorkflowDraftRunNodeOutputEventsApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID): return Response( @@ -384,7 +384,7 @@ class WorkflowPublishedRunNodeOutputsApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID): return _serve_snapshot(app_model, run_id) @@ -408,7 +408,7 @@ class WorkflowPublishedRunNodeOutputDetailApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID, node_id: str): return _serve_node_detail(app_model, run_id, node_id) @@ -436,7 +436,7 @@ class WorkflowPublishedRunNodeOutputPreviewApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID, node_id: str, output_name: str): return _serve_output_preview(app_model, run_id, node_id, output_name) @@ -458,7 +458,7 @@ class WorkflowPublishedRunNodeOutputEventsApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, app_model: App, run_id: UUID): return Response( diff --git a/api/controllers/console/app/workflow_run.py b/api/controllers/console/app/workflow_run.py index 8a4b179439c..66873a9b523 100644 --- a/api/controllers/console/app/workflow_run.py +++ b/api/controllers/console/app/workflow_run.py @@ -6,13 +6,13 @@ from pydantic import BaseModel, Field, field_validator from configs import dify_config from controllers.common.errors import NotFoundError +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.flask_admission import console_account_admission from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, model_validate, ) from extensions.ext_application_services import application_services @@ -143,8 +143,7 @@ class AdvancedChatAppWorkflowRunListApi(Resource): console_ns.models[AdvancedChatWorkflowRunPaginationResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_CREATE_AND_MANAGEMENT, + rbac_checks=[RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())], ) @get_app_model(mode=[AppMode.ADVANCED_CHAT]) @model_validate(WorkflowRunListQuery) @@ -174,8 +173,7 @@ class AdvancedChatAppWorkflowRunCountApi(Resource): console_ns.models[WorkflowRunCountResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_CREATE_AND_MANAGEMENT, + rbac_checks=[RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())], ) @get_app_model(mode=[AppMode.ADVANCED_CHAT]) @model_validate(WorkflowRunCountQuery) @@ -206,8 +204,7 @@ class WorkflowRunListApi(Resource): console_ns.models[WorkflowRunPaginationResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_CREATE_AND_MANAGEMENT, + rbac_checks=[RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())], ) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @model_validate(WorkflowRunListQuery) @@ -237,8 +234,7 @@ class WorkflowRunCountApi(Resource): console_ns.models[WorkflowRunCountResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_CREATE_AND_MANAGEMENT, + rbac_checks=[RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())], ) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @model_validate(WorkflowRunCountQuery) @@ -269,8 +265,7 @@ class WorkflowRunDetailApi(Resource): ) @console_ns.response(404, "Workflow run not found") @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_CREATE_AND_MANAGEMENT, + rbac_checks=[RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())], ) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, request_context: RequestContext, app_model: App, run_id: UUID): @@ -300,8 +295,7 @@ class WorkflowRunNodeExecutionListApi(Resource): ) @console_ns.response(404, "Workflow run not found") @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_CREATE_AND_MANAGEMENT, + rbac_checks=[RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())], ) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) def get(self, request_context: RequestContext, app_model: App, run_id: UUID): diff --git a/api/controllers/console/app/workflow_statistic.py b/api/controllers/console/app/workflow_statistic.py index 48661472584..af5f057dccf 100644 --- a/api/controllers/console/app/workflow_statistic.py +++ b/api/controllers/console/app/workflow_statistic.py @@ -4,13 +4,13 @@ from flask_restx import Resource from pydantic import BaseModel, Field, field_validator from werkzeug.exceptions import BadRequest +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.app.wraps import get_app_model from controllers.console.flask_admission import console_account_admission from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, model_validate, ) from extensions.ext_application_services import application_services @@ -106,8 +106,7 @@ class WorkflowDailyRunsStatistic(Resource): console_ns.models[WorkflowDailyRunsStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(WorkflowStatisticQuery) @@ -136,8 +135,7 @@ class WorkflowDailyTerminalsStatistic(Resource): console_ns.models[WorkflowDailyTerminalsStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(WorkflowStatisticQuery) @@ -166,8 +164,7 @@ class WorkflowDailyTokenCostStatistic(Resource): console_ns.models[WorkflowDailyTokenCostStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model @model_validate(WorkflowStatisticQuery) @@ -196,8 +193,7 @@ class WorkflowAverageAppInteractionStatistic(Resource): console_ns.models[WorkflowAverageAppInteractionStatisticResponse.__name__], ) @console_account_admission( - rbac_resource_scope=RBACResourceScope.APP, - rbac_permission=RBACPermission.APP_MONITOR, + rbac_checks=[RBACCheck(RBACPermission.APP_MONITOR, PlainApp())], ) @get_app_model(mode=[AppMode.WORKFLOW]) @model_validate(WorkflowStatisticQuery) diff --git a/api/controllers/console/app/workflow_trigger.py b/api/controllers/console/app/workflow_trigger.py index 4f544db7c46..98260b3734d 100644 --- a/api/controllers/console/app/workflow_trigger.py +++ b/api/controllers/console/app/workflow_trigger.py @@ -8,6 +8,7 @@ from sqlalchemy.orm import sessionmaker from werkzeug.exceptions import NotFound from configs import dify_config +from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_schema_models from extensions.ext_database import db from fields.base import ResponseModel @@ -21,7 +22,6 @@ from .. import console_ns from ..app.wraps import get_app_model from ..wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -100,7 +100,7 @@ class WebhookTriggerApi(Resource): @login_required @account_initialization_required @console_ns.response(200, "Success", console_ns.models[WebhookTriggerResponse.__name__]) - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=AppMode.WORKFLOW) @model_validate(Parser) def get(self, req_data: Parser, app_model: App): @@ -134,7 +134,7 @@ class AppTriggersApi(Resource): @account_initialization_required @console_ns.response(200, "Success", console_ns.models[WorkflowTriggerListResponse.__name__]) @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) @get_app_model(mode=AppMode.WORKFLOW) def get(self, current_tenant_id: str, app_model: App): """Get app triggers list""" @@ -171,7 +171,7 @@ class AppTriggerEnableApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @console_ns.response(200, "Success", console_ns.models[WorkflowTriggerResponse.__name__]) @with_current_tenant_id @get_app_model(mode=AppMode.WORKFLOW) diff --git a/api/controllers/console/app/wraps.py b/api/controllers/console/app/wraps.py index 8e18c6af01e..2c8f66bc053 100644 --- a/api/controllers/console/app/wraps.py +++ b/api/controllers/console/app/wraps.py @@ -11,35 +11,37 @@ from functools import wraps from typing import cast, overload from sqlalchemy import select -from sqlalchemy.orm import Session -from werkzeug.exceptions import Forbidden +from sqlalchemy.orm import Session, scoped_session -from configs import dify_config from controllers.common.session import with_session -from controllers.common.wraps import RBACPermission, RBACResourceScope, _extract_resource_id, enforce_rbac_access from controllers.console.app.error import AppNotFoundError from extensions.ext_application_services import application_services from extensions.ext_database import db from libs.login import current_account_with_tenant from models import App, AppMode -from models.agent import Agent, AgentScope +from models.agent import AgentScope from services.app_service import AppService __all__ = [ - "agent_manage_required_for_agent_app", - "enforce_agent_manage_or_app_scene", "get_app_model", "get_previewable_app_model", "with_session", ] +def _is_hidden_backing_app(app_model: App, session: Session | scoped_session) -> bool: + binding = app_model.agent_app_binding_with_session(session=session, include_archived=True) + return binding is not None and binding.scope == AgentScope.WORKFLOW_ONLY + + def _load_app_model(session: Session, app_id: str) -> App | None: """Load the tenant-scoped app row with the request session owned by `with_session`.""" _, current_tenant_id = current_account_with_tenant() app_model = session.scalar( select(App).where(App.id == app_id, App.tenant_id == current_tenant_id, App.status == "normal").limit(1) ) + if app_model is not None and _is_hidden_backing_app(app_model, session): + return None return app_model @@ -49,6 +51,8 @@ def _load_app_model_from_scoped_session(app_id: str) -> App | None: app_model = db.session.scalar( select(App).where(App.id == app_id, App.tenant_id == current_tenant_id, App.status == "normal").limit(1) ) + if app_model is not None and _is_hidden_backing_app(app_model, db.session): + return None return app_model @@ -59,118 +63,6 @@ def _load_previewable_app_model(session: Session, app_id: str) -> App | None: return AppService.get_normal_app_by_id(app_id, session) -def _agent_app_binding(app_id: str) -> Agent | None: - app_model = _load_app_model_from_scoped_session(app_id) - if app_model is None: - return None - return app_model.agent_app_binding_with_session(session=db.session(), include_archived=True) - - -def _reject_hidden_agent_backing_app(path_args: dict[str, object]) -> None: - raw_app_id = path_args.get("app_id") or path_args.get("resource_id") - if raw_app_id is None: - return - binding = _agent_app_binding(str(raw_app_id)) - if binding is not None and binding.scope == AgentScope.WORKFLOW_ONLY: - raise AppNotFoundError() - - -def enforce_agent_manage_or_app_scene( - *, - tenant_id: str, - account_id: str, - scene: RBACPermission, - path_args: dict[str, object], -) -> None: - # Must run before the RBAC_ENABLED check below: a hidden workflow-only - # backing App has to stay unreachable regardless of RBAC_ENABLED. - _reject_hidden_agent_backing_app(path_args) - - if not dify_config.RBAC_ENABLED: - return - - binding = _agent_app_binding(_extract_resource_id(RBACResourceScope.APP, tenant_id, path_args)) - - if binding is not None: - if binding.scope == AgentScope.WORKFLOW_ONLY: - raise AppNotFoundError() - try: - enforce_rbac_access( - tenant_id=tenant_id, - account_id=account_id, - resource_type=RBACResourceScope.WORKSPACE, - scene=RBACPermission.AGENT_MANAGE, - resource_required=False, - ) - return - except Forbidden: - pass # not an agent.manage holder — fall through to the normal scene check - - enforce_rbac_access( - tenant_id=tenant_id, - account_id=account_id, - resource_type=RBACResourceScope.APP, - scene=scene, - path_args=path_args, - ) - - -@overload -def agent_manage_required_for_agent_app[**P, R](view: Callable[P, R]) -> Callable[P, R]: ... - - -@overload -def agent_manage_required_for_agent_app[**P, R]( - view: None = None, *, scene: RBACPermission | None = None -) -> Callable[[Callable[P, R]], Callable[P, R]]: ... - - -def agent_manage_required_for_agent_app[**P, R]( - view: Callable[P, R] | None = None, *, scene: RBACPermission | None = None -) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]: - # Must sit above get_app_model in the decorator stack — get_app_model - # deletes app_id from kwargs, and this decorator needs it. - # TODO: this is a workaround, remove this after ACL for agent app is available - def decorator(view_func: Callable[P, R]) -> Callable[P, R]: - @wraps(view_func) - def decorated(*args: P.args, **kwargs: P.kwargs) -> R: - if scene is not None: - if not dify_config.RBAC_ENABLED: - _reject_hidden_agent_backing_app(kwargs) - return view_func(*args, **kwargs) - current_user, current_tenant_id = current_account_with_tenant() - enforce_agent_manage_or_app_scene( - tenant_id=current_tenant_id, - account_id=current_user.id, - scene=scene, - path_args=kwargs, - ) - return view_func(*args, **kwargs) - - raw_app_id = kwargs.get("app_id") or kwargs.get("resource_id") - if raw_app_id is not None: - binding = _agent_app_binding(str(raw_app_id)) - if binding is not None: - if binding.scope == AgentScope.WORKFLOW_ONLY: - raise AppNotFoundError() - if dify_config.RBAC_ENABLED: - current_user, current_tenant_id = current_account_with_tenant() - enforce_rbac_access( - tenant_id=current_tenant_id, - account_id=current_user.id, - resource_type=RBACResourceScope.WORKSPACE, - scene=RBACPermission.AGENT_MANAGE, - resource_required=False, - ) - return view_func(*args, **kwargs) - - return decorated - - if view is None: - return decorator - return decorator(view) - - def _get_injected_session(args: tuple[object, ...]) -> Session | None: """Return the request session inserted by `with_session`, if this handler has been migrated.""" if len(args) < 2: diff --git a/api/controllers/console/auth/data_source_bearer_auth.py b/api/controllers/console/auth/data_source_bearer_auth.py index 808fae53b91..f42aca2997e 100644 --- a/api/controllers/console/auth/data_source_bearer_auth.py +++ b/api/controllers/console/auth/data_source_bearer_auth.py @@ -5,6 +5,7 @@ from flask_restx import Resource from pydantic import BaseModel, ConfigDict, Field from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.auth.error import ( @@ -14,7 +15,7 @@ from controllers.console.auth.error import ( InvalidDataSourceApiKeyAuthCredentialsRequestError, ) from controllers.console.flask_admission import console_account_admission -from controllers.console.wraps import RBACPermission, RBACResourceScope, model_validate +from controllers.console.wraps import RBACPermission, model_validate from extensions.ext_application_services import application_services from fields.base import ResponseModel from libs.helper import dump_response @@ -104,9 +105,7 @@ class ApiKeyAuthDataSourceBinding(Resource): @console_ns.expect(console_ns.models[ApiKeyAuthBindingPayload.__name__]) @console_account_admission( allowed_roles=_ADMIN_OR_OWNER_ROLES, - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.CREDENTIAL_CREATE, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.CREDENTIAL_CREATE, Workspace())], ) @model_validate(ApiKeyAuthBindingPayload) def post(self, req_data: ApiKeyAuthBindingPayload, request_context: RequestContext): @@ -138,9 +137,7 @@ class ApiKeyAuthDataSourceBindingDelete(Resource): @console_ns.response(HTTPStatus.NO_CONTENT, "Binding deleted successfully") @console_account_admission( allowed_roles=_ADMIN_OR_OWNER_ROLES, - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.CREDENTIAL_MANAGE, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())], ) def delete(self, request_context: RequestContext, binding_id: UUID): application_services().data_source_api_key_auth.delete_binding(request_context, str(binding_id)) diff --git a/api/controllers/console/auth/data_source_oauth.py b/api/controllers/console/auth/data_source_oauth.py index 792e698fab9..8c4147ea7fa 100644 --- a/api/controllers/console/auth/data_source_oauth.py +++ b/api/controllers/console/auth/data_source_oauth.py @@ -9,6 +9,7 @@ from pydantic import BaseModel, Field, ValidationError from configs import dify_config from controllers.common.fields import RedirectResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, query_params_from_request, @@ -17,7 +18,7 @@ from controllers.common.schema import ( register_schema_models, ) from controllers.console.flask_admission import console_account_admission -from core.rbac import RBACPermission, RBACResourceScope +from core.rbac import RBACPermission from extensions.ext_application_services import application_services from fields.base import ResponseModel from libs.helper import dump_response @@ -111,9 +112,7 @@ class OAuthDataSource(Resource): @console_ns.response(HTTPStatus.FORBIDDEN, "Admin privileges required") @console_account_admission( allowed_roles=_ADMIN_OR_OWNER_ROLES, - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.CREDENTIAL_MANAGE, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())], ) def get(self, request_context: RequestContext, provider: str): try: diff --git a/api/controllers/console/datasets/data_source.py b/api/controllers/console/datasets/data_source.py index 62a7ea84415..f5506e36850 100644 --- a/api/controllers/console/datasets/data_source.py +++ b/api/controllers/console/datasets/data_source.py @@ -12,6 +12,7 @@ from sqlalchemy.orm import Session from werkzeug.exceptions import NotFound from controllers.common.fields import SimpleResultResponse, TextContentResponse +from controllers.common.rbac import DatasetId, RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from core.datasource.entities.datasource_entities import DatasourceProviderType, OnlineDocumentPagesMessage @@ -34,7 +35,6 @@ from tasks.document_indexing_sync_task import document_indexing_sync_task from .. import console_ns from ..wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, is_admin_or_owner_required, model_validate, @@ -140,7 +140,7 @@ class DataSourceApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @console_ns.response(200, "Success", console_ns.models[DataSourceIntegrateListResponse.__name__]) @with_current_tenant_id @@ -191,7 +191,7 @@ class DataSourceApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) @with_current_tenant_id @@ -420,7 +420,7 @@ class DataSourceNotionDatasetSyncApi(Resource): @login_required @account_initialization_required @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, dataset_id: UUID) -> tuple[dict[str, str], int]: dataset_id_str = str(dataset_id) @@ -440,7 +440,7 @@ class DataSourceNotionDocumentSyncApi(Resource): @login_required @account_initialization_required @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, dataset_id: UUID, document_id: UUID) -> tuple[dict[str, str], int]: dataset_id_str = str(dataset_id) diff --git a/api/controllers/console/datasets/datasets.py b/api/controllers/console/datasets/datasets.py index 9a2711f4732..b85ea3bc9eb 100644 --- a/api/controllers/console/datasets/datasets.py +++ b/api/controllers/console/datasets/datasets.py @@ -13,6 +13,7 @@ from werkzeug.exceptions import Forbidden, NotFound import services from configs import dify_config from controllers.common.fields import ApiBaseUrlResponse, SimpleResultResponse, UsageCheckResponse +from controllers.common.rbac import DatasetId, RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns @@ -21,7 +22,6 @@ from controllers.console.app.error import ProviderNotInitializeError from controllers.console.datasets.error import DatasetInUseError, DatasetNameDuplicateError, IndexingEstimateError from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, cloud_edition_billing_rate_limit_check, enterprise_license_required, @@ -589,9 +589,7 @@ class DatasetListApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required( - RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, Workspace())) @cloud_edition_billing_rate_limit_check("knowledge") @with_current_user @with_current_tenant_id @@ -662,7 +660,7 @@ class DatasetApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_current_user @with_current_tenant_id @with_session(write=False) @@ -731,7 +729,7 @@ class DatasetApi(Resource): @cloud_edition_billing_rate_limit_check("knowledge") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(DatasetUpdatePayload) def patch( @@ -798,7 +796,7 @@ class DatasetApi(Resource): @cloud_edition_billing_rate_limit_check("knowledge") @console_ns.response(204, "Dataset deleted successfully") @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def delete(self, session: Session, current_user: Account, dataset_id: UUID): dataset_id_str = str(dataset_id) @@ -831,7 +829,7 @@ class DatasetUseCheckApi(Resource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): dataset = _get_accessible_dataset(dataset_id, current_tenant_id, current_user, session) @@ -853,7 +851,7 @@ class DatasetQueryApi(Resource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_user: Account, dataset_id: UUID): dataset_id_str = str(dataset_id) @@ -1009,7 +1007,7 @@ class DatasetRelatedAppListApi(Resource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_user: Account, dataset_id: UUID): dataset_id_str = str(dataset_id) @@ -1048,7 +1046,7 @@ class DatasetIndexingStatusApi(Resource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): dataset = _get_accessible_dataset(dataset_id, current_tenant_id, current_user, session) @@ -1112,7 +1110,7 @@ class DatasetApiKeyApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_API_KEY_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @with_session(write=False) @@ -1130,7 +1128,7 @@ class DatasetApiKeyApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_API_KEY_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @with_session @@ -1191,7 +1189,7 @@ class DatasetApiDeleteApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_API_KEY_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @with_session @@ -1228,7 +1226,7 @@ class DatasetEnableApiApi(Resource): @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def post(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, status: str): dataset = _get_accessible_dataset(dataset_id, current_tenant_id, current_user, session) @@ -1303,7 +1301,7 @@ class DatasetErrorDocs(Resource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): dataset = _get_accessible_dataset(dataset_id, current_tenant_id, current_user, session) @@ -1330,7 +1328,7 @@ class DatasetPermissionUserListApi(Resource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_user: Account, dataset_id: UUID): dataset_id_str = str(dataset_id) @@ -1363,7 +1361,7 @@ class DatasetAutoDisableLogApi(Resource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): dataset = _get_accessible_dataset(dataset_id, current_tenant_id, current_user, session) diff --git a/api/controllers/console/datasets/datasets_document.py b/api/controllers/console/datasets/datasets_document.py index a514d913550..dd02a4011d8 100644 --- a/api/controllers/console/datasets/datasets_document.py +++ b/api/controllers/console/datasets/datasets_document.py @@ -19,10 +19,11 @@ import services from configs import dify_config from controllers.common.controller_schemas import DocumentBatchDownloadZipPayload from controllers.common.fields import SimpleResultMessageResponse, SimpleResultResponse, UrlResponse +from controllers.common.rbac import DatasetId, RBACCheck from controllers.common.schema import register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns -from controllers.console.wraps import RBACPermission, RBACResourceScope, model_validate, rbac_permission_required +from controllers.console.wraps import RBACPermission, model_validate, rbac_permission_required from core.entities.knowledge_entities import IndexingEstimate from core.errors.error import ( LLMBadRequestError, @@ -405,7 +406,7 @@ class DatasetDocumentListApi(Resource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): dataset_id_str = str(dataset_id) @@ -534,7 +535,7 @@ class DatasetDocumentListApi(Resource): @console_ns.expect(console_ns.models[KnowledgeConfig.__name__]) @console_ns.response(200, "Documents created successfully", console_ns.models[DatasetAndDocumentResponse.__name__]) @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def post(self, session: Session, current_user: Account, dataset_id: UUID): dataset_id_str = str(dataset_id) @@ -585,7 +586,7 @@ class DatasetDocumentListApi(Resource): @console_ns.response(204, "Documents deleted successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def delete( self, @@ -719,7 +720,7 @@ class DocumentIndexingEstimateApi(DocumentResource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID): dataset_id_str = str(dataset_id) @@ -811,7 +812,7 @@ class DocumentBatchIndexingEstimateApi(DocumentResource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, batch: str): dataset_id_str = str(dataset_id) @@ -933,7 +934,7 @@ class DocumentBatchIndexingStatusApi(DocumentResource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, current_user: Account, dataset_id: UUID, batch: str): dataset_id_str = str(dataset_id) @@ -993,7 +994,7 @@ class DocumentIndexingStatusApi(DocumentResource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID): dataset_id_str = str(dataset_id) @@ -1059,7 +1060,7 @@ class DocumentApi(DocumentResource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID): dataset_id_str = str(dataset_id) @@ -1133,7 +1134,7 @@ class DocumentApi(DocumentResource): @console_ns.response(204, "Document deleted successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def delete( self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID @@ -1169,7 +1170,7 @@ class DocumentDownloadApi(DocumentResource): @cloud_edition_billing_rate_limit_check("knowledge") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_DOCUMENT_DOWNLOAD) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_DOCUMENT_DOWNLOAD, DatasetId())) @with_session(write=False) def get( self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID @@ -1193,7 +1194,7 @@ class DocumentBatchDownloadZipApi(DocumentResource): @console_ns.expect(console_ns.models[DocumentBatchDownloadZipPayload.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session(write=False) def post(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): """Stream a ZIP archive containing the requested uploaded documents.""" @@ -1245,7 +1246,7 @@ class DocumentProcessingApi(DocumentResource): @cloud_edition_billing_rate_limit_check("knowledge") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def patch( self, @@ -1302,7 +1303,7 @@ class DocumentMetadataApi(DocumentResource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(DocumentMetadataUpdatePayload) def put( @@ -1361,7 +1362,7 @@ class DocumentStatusApi(DocumentResource): @cloud_edition_billing_rate_limit_check("knowledge") @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def patch( self, @@ -1407,7 +1408,7 @@ class DocumentPauseApi(DocumentResource): @console_ns.response(204, "Document paused successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def patch( self, @@ -1447,7 +1448,7 @@ class DocumentRecoverApi(DocumentResource): @console_ns.response(204, "Document resumed successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def patch( self, @@ -1487,7 +1488,7 @@ class DocumentRetryApi(DocumentResource): @console_ns.response(204, "Documents retry started successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(DocumentRetryPayload) def post( @@ -1552,7 +1553,7 @@ class DocumentRenameApi(DocumentResource): @console_ns.response(200, "Document renamed successfully", console_ns.models[DocumentResponse.__name__]) @console_ns.expect(console_ns.models[DocumentRenamePayload.__name__]) @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(DocumentRenamePayload) def post( @@ -1587,7 +1588,7 @@ class WebsiteDocumentSyncApi(DocumentResource): @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def get( self, @@ -1629,7 +1630,7 @@ class DocumentPipelineExecutionLogApi(DocumentResource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get( self, @@ -1681,7 +1682,7 @@ class DocumentGenerateSummaryApi(Resource): @account_initialization_required @cloud_edition_billing_rate_limit_check("knowledge") @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(GenerateSummaryPayload) def post(self, req_data: GenerateSummaryPayload, session: Session, current_user: Account, dataset_id: UUID): @@ -1782,7 +1783,7 @@ class DocumentSummaryStatusApi(DocumentResource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, current_user: Account, dataset_id: UUID, document_id: UUID): """ diff --git a/api/controllers/console/datasets/datasets_segments.py b/api/controllers/console/datasets/datasets_segments.py index 35b2256a118..fdaa47c13f5 100644 --- a/api/controllers/console/datasets/datasets_segments.py +++ b/api/controllers/console/datasets/datasets_segments.py @@ -15,6 +15,7 @@ import services from configs import dify_config from controllers.common.controller_schemas import ChildChunkCreatePayload, ChildChunkUpdatePayload from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import DatasetId, RBACCheck from controllers.common.schema import ( query_params_from_model, query_params_from_request, @@ -31,7 +32,6 @@ from controllers.console.datasets.error import ( ) from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, cloud_edition_billing_knowledge_limit_check, cloud_edition_billing_rate_limit_check, @@ -191,7 +191,7 @@ class DatasetDocumentSegmentListApi(Resource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID, document_id: UUID): dataset_id_str = str(dataset_id) @@ -302,7 +302,7 @@ class DatasetDocumentSegmentListApi(Resource): @console_ns.doc(params=query_params_from_model(SegmentIdListQuery)) @console_ns.response(204, "Segments deleted successfully") @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def delete(self, session: Session, current_user: Account, dataset_id: UUID, document_id: UUID): # check dataset @@ -342,7 +342,7 @@ class DatasetDocumentSegmentApi(Resource): @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def patch( self, @@ -413,7 +413,7 @@ class DatasetDocumentSegmentAddApi(Resource): @console_ns.response(200, "Segment created successfully", console_ns.models[SegmentDetailResponse.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(SegmentCreatePayload) def post( @@ -485,7 +485,7 @@ class DatasetDocumentSegmentUpdateApi(Resource): @console_ns.response(200, "Segment updated successfully", console_ns.models[SegmentDetailResponse.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(SegmentUpdatePayload) def patch( @@ -566,7 +566,7 @@ class DatasetDocumentSegmentUpdateApi(Resource): @console_ns.response(204, "Segment deleted successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def delete( self, @@ -617,7 +617,7 @@ class DatasetDocumentSegmentBatchImportApi(Resource): @console_ns.expect(console_ns.models[BatchImportPayload.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(BatchImportPayload) def post( @@ -676,7 +676,7 @@ class DatasetDocumentSegmentBatchImportApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) def get(self, job_id=None, dataset_id: UUID | None = None, document_id: UUID | None = None): if job_id is None: raise NotFound("The job does not exist.") @@ -703,7 +703,7 @@ class ChildChunkAddApi(Resource): @console_ns.response(200, "Child chunk created successfully", console_ns.models[ChildChunkDetailResponse.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(ChildChunkCreatePayload) def post( @@ -764,7 +764,7 @@ class ChildChunkAddApi(Resource): @login_required @account_initialization_required @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, dataset_id: UUID, document_id: UUID, segment_id: UUID): # check dataset @@ -819,7 +819,7 @@ class ChildChunkAddApi(Resource): @console_ns.expect(console_ns.models[ChildChunkBatchUpdatePayload.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(ChildChunkBatchUpdatePayload) def patch( @@ -873,7 +873,7 @@ class ChildChunkUpdateApi(Resource): @console_ns.response(204, "Child chunk deleted successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def delete( self, @@ -926,7 +926,7 @@ class ChildChunkUpdateApi(Resource): @console_ns.response(200, "Child chunk updated successfully", console_ns.models[ChildChunkDetailResponse.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(ChildChunkUpdatePayload) def patch( diff --git a/api/controllers/console/datasets/external.py b/api/controllers/console/datasets/external.py index 51a9cebb2f5..371b9d537c0 100644 --- a/api/controllers/console/datasets/external.py +++ b/api/controllers/console/datasets/external.py @@ -12,6 +12,7 @@ from werkzeug.exceptions import Forbidden, InternalServerError, NotFound import services from controllers.common.fields import UsageCountResponse +from controllers.common.rbac import DatasetId, RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, register_response_schema_models, @@ -22,7 +23,6 @@ from controllers.console import console_ns from controllers.console.datasets.error import DatasetNameDuplicateError from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -350,9 +350,7 @@ class ExternalDatasetCreateApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.DATASET, RBACPermission.DATASET_EXTERNAL_CONNECT, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EXTERNAL_CONNECT, Workspace())) @with_current_user @with_current_tenant_id @with_session @@ -411,7 +409,7 @@ class ExternalKnowledgeHitTestingApi(Resource): @login_required @account_initialization_required @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_PIPELINE_TEST) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_PIPELINE_TEST, DatasetId())) @with_session @model_validate(ExternalHitTestingPayload) def post(self, req_data: ExternalHitTestingPayload, session: Session, current_user: Account, dataset_id: UUID): diff --git a/api/controllers/console/datasets/hit_testing.py b/api/controllers/console/datasets/hit_testing.py index 8018343b01f..3cc0066009f 100644 --- a/api/controllers/console/datasets/hit_testing.py +++ b/api/controllers/console/datasets/hit_testing.py @@ -5,9 +5,10 @@ from uuid import UUID from flask_restx import Resource from sqlalchemy.orm import Session +from controllers.common.rbac import DatasetId, RBACCheck from controllers.common.schema import register_response_schema_models, register_schema_models from controllers.console.app.wraps import with_session -from controllers.console.wraps import RBACPermission, RBACResourceScope, rbac_permission_required +from controllers.console.wraps import RBACPermission, rbac_permission_required from fields.hit_testing_fields import HitTestingResponse from libs.helper import dump_response from libs.login import login_required @@ -46,7 +47,7 @@ class HitTestingApi(Resource, DatasetsHitTestingBase): @cloud_edition_billing_rate_limit_check("knowledge") @with_current_tenant_id @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_PIPELINE_TEST) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_PIPELINE_TEST, DatasetId())) @with_session def post( self, session: Session, current_user: Account, current_tenant_id: str, dataset_id: UUID diff --git a/api/controllers/console/datasets/metadata.py b/api/controllers/console/datasets/metadata.py index c076d455f49..f0cec5c014d 100644 --- a/api/controllers/console/datasets/metadata.py +++ b/api/controllers/console/datasets/metadata.py @@ -8,12 +8,12 @@ from werkzeug.exceptions import Forbidden, NotFound import services from configs import dify_config from controllers.common.controller_schemas import MetadataUpdatePayload +from controllers.common.rbac import DatasetId, RBACCheck from controllers.common.schema import register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, enterprise_license_required, model_validate, @@ -61,7 +61,7 @@ class DatasetMetadataCreateApi(Resource): @console_ns.expect(console_ns.models[MetadataArgs.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(MetadataArgs) def post( @@ -92,7 +92,7 @@ class DatasetMetadataCreateApi(Resource): ) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, DatasetId())) @with_session(write=False) def get(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): dataset_id_str = str(dataset_id) @@ -118,7 +118,7 @@ class DatasetMetadataApi(Resource): @console_ns.expect(console_ns.models[MetadataUpdatePayload.__name__]) @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(MetadataUpdatePayload) def patch( @@ -149,7 +149,7 @@ class DatasetMetadataApi(Resource): @console_ns.response(204, "Metadata deleted successfully") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def delete( self, @@ -195,7 +195,7 @@ class DatasetMetadataBuiltInFieldActionApi(Resource): @enterprise_license_required @console_ns.response(204, "Action completed successfully") @with_current_user - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def post(self, session: Session, current_user: Account, dataset_id: UUID, action: Literal["enable", "disable"]): dataset_id_str = str(dataset_id) @@ -227,7 +227,7 @@ class DocumentMetadataEditApi(Resource): @console_ns.response(404, "Dataset, document, or metadata not found") @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session @model_validate(MetadataOperationData) def post( diff --git a/api/controllers/console/datasets/rag_pipeline/datasource_auth.py b/api/controllers/console/datasets/rag_pipeline/datasource_auth.py index 95f19e11fd8..672a8a3d83a 100644 --- a/api/controllers/console/datasets/rag_pipeline/datasource_auth.py +++ b/api/controllers/console/datasets/rag_pipeline/datasource_auth.py @@ -7,11 +7,11 @@ from werkzeug.exceptions import Forbidden, NotFound from configs import dify_config from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -167,7 +167,7 @@ class DatasourcePluginOAuthAuthorizationUrl(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @with_current_user @with_current_tenant_id def get(self, current_tenant_id: str, current_user: Account, provider_id: str): @@ -310,7 +310,7 @@ class DatasourceAuth(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_CREATE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_CREATE, Workspace())) @with_current_tenant_id @model_validate(DatasourceCredentialPayload) def post(self, req_data: DatasourceCredentialPayload, current_tenant_id: str, provider_id: str): @@ -337,7 +337,7 @@ class DatasourceAuth(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @with_current_user @with_current_tenant_id def get(self, current_tenant_id: str, user: Account, provider_id: str): @@ -362,7 +362,7 @@ class DatasourceAuthDeleteApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @with_current_tenant_id @model_validate(DatasourceCredentialDeletePayload) def post(self, req_data: DatasourceCredentialDeletePayload, current_tenant_id: str, provider_id: str): @@ -391,7 +391,7 @@ class DatasourceAuthUpdateApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @with_current_tenant_id @model_validate(DatasourceCredentialUpdatePayload) def post(self, req_data: DatasourceCredentialUpdatePayload, current_tenant_id: str, provider_id: str): @@ -459,7 +459,7 @@ class DatasourceAuthOauthCustomClient(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @with_current_tenant_id @model_validate(DatasourceCustomClientPayload) def post(self, req_data: DatasourceCustomClientPayload, current_tenant_id: str, provider_id: str): @@ -477,7 +477,7 @@ class DatasourceAuthOauthCustomClient(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__]) @with_current_tenant_id def delete(self, current_tenant_id: str, provider_id: str): @@ -498,7 +498,7 @@ class DatasourceAuthDefaultApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @with_current_tenant_id @model_validate(DatasourceDefaultPayload) def post(self, req_data: DatasourceDefaultPayload, current_tenant_id: str, provider_id: str): @@ -520,7 +520,7 @@ class DatasourceUpdateProviderNameApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @with_current_tenant_id @model_validate(DatasourceUpdateNamePayload) def post(self, req_data: DatasourceUpdateNamePayload, current_tenant_id: str, provider_id: str): diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline.py index d2a80cadf26..a3d49f149b2 100644 --- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline.py +++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline.py @@ -8,6 +8,7 @@ from werkzeug.exceptions import Forbidden, NotFound from configs import dify_config from controllers.common.fields import SimpleDataResponse +from controllers.common.rbac import DatasetByPipeline, RBACCheck from controllers.common.schema import ( JsonResponseWithStatus, query_params_from_model, @@ -19,7 +20,6 @@ from controllers.console.app.wraps import with_session from controllers.console.datasets.wraps import get_rag_pipeline from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, enterprise_license_required, knowledge_pipeline_publish_enabled, @@ -223,7 +223,7 @@ class PublishCustomizedPipelineTemplateApi(Resource): @knowledge_pipeline_publish_enabled @with_current_user @get_rag_pipeline - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_PIPELINE_RELEASE) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_PIPELINE_RELEASE, DatasetByPipeline())) @model_validate(CustomizedPipelineTemplatePayload) def post( self, diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py index b272506052d..b6953cd0696 100644 --- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py +++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py @@ -10,6 +10,7 @@ from pydantic import BaseModel, Field from sqlalchemy.orm import sessionmaker from controllers.common.errors import InvalidArgumentError, NotFoundError +from controllers.common.rbac import DatasetByPipeline, RBACCheck from controllers.common.schema import query_params_from_model, register_schema_models from controllers.console import console_ns from controllers.console.app.error import ( @@ -26,7 +27,6 @@ from controllers.console.app.workflow_draft_variable import ( from controllers.console.datasets.wraps import get_rag_pipeline from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -82,7 +82,7 @@ def _api_prerequisite[T, **P, R]( @account_initialization_required @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @wraps(f) def wrapper(self: T, current_user: Account, *args: P.args, **kwargs: P.kwargs) -> R | Response: diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.py index d55b5b6a366..5af74390ab1 100644 --- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.py +++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_import.py @@ -3,6 +3,7 @@ from pydantic import BaseModel, Field from sqlalchemy.orm import Session from controllers.common.fields import SimpleDataResponse +from controllers.common.rbac import DatasetByPipeline, RBACCheck, Workspace from controllers.common.schema import ( JsonResponseWithStatus, query_params_from_model, @@ -13,7 +14,6 @@ from controllers.console import console_ns from controllers.console.datasets.wraps import get_rag_pipeline from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -81,9 +81,7 @@ class RagPipelineImportApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, Workspace())) @with_current_user @model_validate(RagPipelineImportPayload) def post(self, req_data: RagPipelineImportPayload, current_user: Account) -> JsonResponseWithStatus: @@ -128,9 +126,7 @@ class RagPipelineImportConfirmApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, Workspace())) @with_current_user def post(self, current_user: Account, import_id: str) -> JsonResponseWithStatus: with Session(db.engine, expire_on_commit=False) as session: @@ -160,7 +156,7 @@ class RagPipelineImportCheckDependenciesApi(Resource): @get_rag_pipeline @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_READONLY) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_READONLY, DatasetByPipeline())) def get(self, pipeline: Pipeline) -> JsonResponseWithStatus: with Session(db.engine, expire_on_commit=False) as session: import_service = RagPipelineDslService(session) @@ -178,7 +174,7 @@ class RagPipelineExportApi(Resource): @get_rag_pipeline @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_IMPORT_EXPORT_DSL) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_IMPORT_EXPORT_DSL, DatasetByPipeline())) @model_validate(IncludeSecretQuery) def get(self, req_data: IncludeSecretQuery, pipeline: Pipeline) -> JsonResponseWithStatus: # Add include_secret params diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py index 432e83cc099..a8e98298eb5 100644 --- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py +++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py @@ -13,6 +13,7 @@ import services from configs import dify_config from controllers.common.controller_schemas import DefaultBlockConfigQuery, WorkflowListQuery, WorkflowUpdatePayload from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import DatasetByPipeline, DatasetId, RBACCheck from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.app.error import ( @@ -32,7 +33,6 @@ from controllers.console.app.wraps import with_session from controllers.console.datasets.wraps import get_rag_pipeline, load_rag_pipeline from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -197,7 +197,7 @@ class DraftRagPipelineApi(Resource): @account_initialization_required @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) def get(self, pipeline: Pipeline): """ Get draft rag pipeline's workflow @@ -219,7 +219,7 @@ class DraftRagPipelineApi(Resource): @with_current_user @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @console_ns.expect(console_ns.models[DraftWorkflowSyncPayload.__name__]) @console_ns.response(200, "Success", console_ns.models[RagPipelineWorkflowSyncResponse.__name__]) def post(self, current_user: Account, pipeline: Pipeline): @@ -280,7 +280,7 @@ class RagPipelineDraftRunIterationNodeApi(Resource): @with_current_user @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @model_validate(NodeRunPayload) def post(self, req_data: NodeRunPayload, current_user: Account, pipeline: Pipeline, node_id: str): """ @@ -313,7 +313,7 @@ class RagPipelineDraftRunLoopNodeApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @get_rag_pipeline @model_validate(NodeRunPayload) @@ -348,7 +348,7 @@ class DraftRagPipelineRunApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @with_session @model_validate(DraftWorkflowRunPayload) @@ -382,7 +382,7 @@ class PublishedRagPipelineRunApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @with_session @model_validate(PublishedWorkflowRunPayload) @@ -417,7 +417,7 @@ class RagPipelinePublishedDatasourceNodeRunApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @get_rag_pipeline @model_validate(DatasourceNodeRunPayload) @@ -449,7 +449,7 @@ class RagPipelineDraftDatasourceNodeRunApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @account_initialization_required @with_current_user @get_rag_pipeline @@ -486,7 +486,7 @@ class RagPipelineDraftNodeRunApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @account_initialization_required @with_current_user @get_rag_pipeline @@ -516,7 +516,7 @@ class RagPipelineTaskStopApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @account_initialization_required @with_current_user @get_rag_pipeline @@ -540,7 +540,7 @@ class PublishedRagPipelineApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @get_rag_pipeline def get(self, pipeline: Pipeline): """ @@ -565,7 +565,7 @@ class PublishedRagPipelineApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @get_rag_pipeline def post(self, current_user: Account, pipeline: Pipeline): @@ -600,7 +600,7 @@ class DefaultRagPipelineBlockConfigsApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @get_rag_pipeline def get(self, pipeline: Pipeline): """ @@ -623,7 +623,7 @@ class DefaultRagPipelineBlockConfigApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @get_rag_pipeline @model_validate(DefaultBlockConfigQuery) def get(self, req_data: DefaultBlockConfigQuery, pipeline: Pipeline, block_type: str): @@ -656,7 +656,7 @@ class PublishedAllRagPipelineApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @get_rag_pipeline @model_validate(WorkflowListQuery) @@ -702,7 +702,7 @@ class RagPipelineDraftWorkflowRestoreApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @get_rag_pipeline def post(self, current_user: Account, pipeline: Pipeline, workflow_id: str): @@ -737,7 +737,7 @@ class RagPipelineByIdApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @get_rag_pipeline @console_ns.expect(console_ns.models[WorkflowUpdatePayload.__name__]) @@ -773,7 +773,7 @@ class RagPipelineByIdApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @with_current_user @get_rag_pipeline def delete(self, current_user: Account, pipeline: Pipeline, workflow_id: str): @@ -816,7 +816,7 @@ class PublishedRagPipelineSecondStepApi(Resource): @account_initialization_required @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @model_validate(NodeIdQuery) def get(self, req_data: NodeIdQuery, pipeline: Pipeline): """ @@ -839,7 +839,7 @@ class PublishedRagPipelineFirstStepApi(Resource): @account_initialization_required @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @model_validate(NodeIdQuery) def get(self, req_data: NodeIdQuery, pipeline: Pipeline): """ @@ -862,7 +862,7 @@ class DraftRagPipelineFirstStepApi(Resource): @account_initialization_required @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @model_validate(NodeIdQuery) def get(self, req_data: NodeIdQuery, pipeline: Pipeline): """ @@ -885,7 +885,7 @@ class DraftRagPipelineSecondStepApi(Resource): @account_initialization_required @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @model_validate(NodeIdQuery) def get(self, req_data: NodeIdQuery, pipeline: Pipeline): """ @@ -1035,7 +1035,7 @@ class RagPipelineTransformApi(Resource): @account_initialization_required @with_current_user @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) @with_session def post(self, session: Session, current_tenant_id: str, current_user: Account, dataset_id: UUID): dataset = DatasetService.get_dataset_for_tenant(str(dataset_id), current_tenant_id, session=session) @@ -1070,7 +1070,7 @@ class RagPipelineDatasourceVariableApi(Resource): @with_current_user @get_rag_pipeline @edit_permission_required - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetByPipeline())) @model_validate(DatasourceVariablesPayload) def post(self, req_data: DatasourceVariablesPayload, current_user: Account, pipeline: Pipeline): """ diff --git a/api/controllers/console/feature.py b/api/controllers/console/feature.py index c735420c476..38e904cd6af 100644 --- a/api/controllers/console/feature.py +++ b/api/controllers/console/feature.py @@ -41,7 +41,7 @@ register_response_schema_models( @console_ns.route("/features") class FeatureApi(Resource): @console_ns.doc("get_tenant_features") - @console_ns.doc(description="Get feature configuration for current tenant") + @console_ns.doc(description="Get feature availability and limits for the current workspace") @console_ns.response( 200, "Success", @@ -50,10 +50,8 @@ class FeatureApi(Resource): @console_account_admission() @cloud_utm_record def get(self, request_context: RequestContext): - """Get feature configuration for current tenant""" - payload = application_services().feature_queries.get_features(request_context).model_dump() - payload.pop("vector_space", None) - return payload + """Get current workspace features.""" + return dump_response(FeatureModel, application_services().feature_queries.get_features(request_context)) @console_ns.route("/features/vector-space") diff --git a/api/controllers/console/flask_admission.py b/api/controllers/console/flask_admission.py index b8e3cc1ce16..d9017bf1736 100644 --- a/api/controllers/console/flask_admission.py +++ b/api/controllers/console/flask_admission.py @@ -1,6 +1,6 @@ """Flask adapter for Console API admission.""" -from collections.abc import Callable +from collections.abc import Callable, Sequence from functools import wraps from typing import Concatenate @@ -8,8 +8,7 @@ from flask import Response, abort, request from werkzeug.exceptions import Forbidden from configs import dify_config -from controllers.common.wraps import enforce_rbac_access -from controllers.console.app.wraps import enforce_agent_manage_or_app_scene +from controllers.common.rbac import RBAC_CHECKS_ATTR, RBACCheck, enforce_rbac_checks from controllers.console.wraps import ( account_initialization_required, enable_change_email, @@ -17,11 +16,9 @@ from controllers.console.wraps import ( setup_required, ) from core.logging.context import get_request_id, get_trace_id -from core.rbac import RBACPermission, RBACResourceScope from enums import DeploymentEdition from libs.login import current_account_with_tenant, login_required from machinery.context import RequestContext -from machinery.errors import AdmissionConfigurationError from models.account import TenantAccountRole from services.system_feature_service import SystemFeatureService @@ -50,10 +47,7 @@ def console_account_admission[T, **P, R]( require_initialized: bool = True, require_valid_enterprise_license: bool = False, allowed_roles: frozenset[TenantAccountRole] | None = None, - rbac_resource_scope: RBACResourceScope | None = None, - rbac_permission: RBACPermission | None = None, - rbac_resource_required: bool = True, - agent_manage_fallback: bool = False, + rbac_checks: Sequence[RBACCheck] | None = None, ) -> Callable[ [Callable[Concatenate[T, RequestContext, P], R]], Callable[Concatenate[T, P], R | Response], @@ -66,40 +60,23 @@ def console_account_admission[T, **P, R]( context construction. """ - if (rbac_resource_scope is None) != (rbac_permission is None): - raise AdmissionConfigurationError("RBAC resource scope and permission must be configured together") - if agent_manage_fallback and rbac_resource_scope != RBACResourceScope.APP: - raise AdmissionConfigurationError("agent_manage_fallback requires rbac_resource_scope=RBACResourceScope.APP") - if agent_manage_fallback and not rbac_resource_required: - raise AdmissionConfigurationError("agent_manage_fallback requires rbac_resource_required=True") - def decorator( view: Callable[Concatenate[T, RequestContext, P], R], ) -> Callable[Concatenate[T, P], R | Response]: - @wraps(view) + @wraps(view, updated=()) def inject_request_context(self: T, /, *args: P.args, **kwargs: P.kwargs) -> R: account_with_tenant = current_account_with_tenant() account = account_with_tenant.account tenant_id = account_with_tenant.tenant_id if allowed_roles is not None and not dify_config.RBAC_ENABLED and account.role not in allowed_roles: raise Forbidden() - if rbac_resource_scope is not None and rbac_permission is not None: - if agent_manage_fallback: - enforce_agent_manage_or_app_scene( - tenant_id=tenant_id, - account_id=account.id, - scene=rbac_permission, - path_args=kwargs, - ) - else: - enforce_rbac_access( - tenant_id=tenant_id, - account_id=account.id, - resource_type=rbac_resource_scope, - scene=rbac_permission, - resource_required=rbac_resource_required, - path_args=kwargs, - ) + if rbac_checks is not None: + enforce_rbac_checks( + tenant_id=tenant_id, + account_id=account.id, + checks=rbac_checks, + path_args=kwargs, + ) request_context = RequestContext( account_id=account.id, active_workspace_id=tenant_id, @@ -108,6 +85,9 @@ def console_account_admission[T, **P, R]( ) return view(self, request_context, *args, **kwargs) + if rbac_checks is not None: + setattr(inject_request_context, RBAC_CHECKS_ATTR, rbac_checks) + admitted: Callable[Concatenate[T, P], R | Response] = inject_request_context if require_change_email_enabled: admitted = enable_change_email(admitted) diff --git a/api/controllers/console/snippets/snippet_workflow.py b/api/controllers/console/snippets/snippet_workflow.py index c293dc60e77..c90d75384f8 100644 --- a/api/controllers/console/snippets/snippet_workflow.py +++ b/api/controllers/console/snippets/snippet_workflow.py @@ -10,6 +10,7 @@ from werkzeug.exceptions import BadRequest, InternalServerError, NotFound from controllers.common.controller_schemas import WorkflowUpdatePayload from controllers.common.fields import GeneratedAppResponse, SimpleResultResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.app.error import DraftWorkflowNotExist, DraftWorkflowNotSync @@ -34,7 +35,6 @@ from controllers.console.snippets.payloads import ( ) from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -205,9 +205,7 @@ class SnippetDraftWorkflowApi(Resource): @with_current_user @get_snippet @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @model_validate(SnippetDraftSyncPayload) def post(self, req_data: SnippetDraftSyncPayload, current_user: Account, snippet: CustomizedSnippet): """Sync draft workflow for snippet.""" @@ -294,9 +292,7 @@ class SnippetPublishedWorkflowApi(Resource): @with_current_user @get_snippet @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) def post(self, current_user: Account, snippet: CustomizedSnippet): """Publish snippet workflow.""" snippet_service = _snippet_service() @@ -355,9 +351,7 @@ class SnippetPublishedAllWorkflowApi(Resource): @account_initialization_required @get_snippet @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @model_validate(SnippetWorkflowListQuery) def get(self, req_data: SnippetWorkflowListQuery, snippet: CustomizedSnippet): """Get all published workflow versions for snippet.""" @@ -399,9 +393,7 @@ class SnippetDraftWorkflowRestoreApi(Resource): @with_current_user @get_snippet @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) def post(self, current_user: Account, snippet: CustomizedSnippet, workflow_id: str): """Restore a published snippet workflow version into the draft workflow.""" snippet_service = _snippet_service() @@ -441,9 +433,7 @@ class SnippetWorkflowByIdApi(Resource): @with_current_user @get_snippet @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @model_validate(WorkflowUpdatePayload) def patch( self, @@ -487,9 +477,7 @@ class SnippetWorkflowByIdApi(Resource): @account_initialization_required @get_snippet @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) def delete(self, snippet: CustomizedSnippet, workflow_id: str): """Delete a published snippet workflow version.""" snippet_service = _snippet_service() diff --git a/api/controllers/console/tag/tags.py b/api/controllers/console/tag/tags.py index db336df5c58..7649ada8741 100644 --- a/api/controllers/console/tag/tags.py +++ b/api/controllers/console/tag/tags.py @@ -7,13 +7,12 @@ from werkzeug.exceptions import Forbidden, NotFound from configs import dify_config from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import RBACCheck, Workspace, enforce_rbac_checks from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models -from controllers.common.wraps import enforce_rbac_access from controllers.console import console_ns from controllers.console.flask_admission import console_account_admission from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, model_validate, ) from extensions.ext_application_services import application_services @@ -102,12 +101,10 @@ def _enforce_snippet_tag_rbac_if_needed(tag_type: TagType | str | None, context: if not dify_config.RBAC_ENABLED: return - enforce_rbac_access( + enforce_rbac_checks( tenant_id=context.active_workspace_id, account_id=context.account_id, - resource_type=RBACResourceScope.WORKSPACE, - scene=RBACPermission.SNIPPETS_CREATE_AND_MODIFY, - resource_required=False, + checks=[RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())], ) diff --git a/api/controllers/console/workspace/endpoint.py b/api/controllers/console/workspace/endpoint.py index ef87c6c4571..001327047e6 100644 --- a/api/controllers/console/workspace/endpoint.py +++ b/api/controllers/console/workspace/endpoint.py @@ -15,11 +15,11 @@ from flask_restx import Resource from pydantic import BaseModel, Field from controllers.common.fields import SuccessResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, is_admin_or_owner_required, model_validate, @@ -235,7 +235,7 @@ class EndpointCollectionApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -267,7 +267,7 @@ class DeprecatedEndpointCreateApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -291,7 +291,7 @@ class EndpointListApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -321,7 +321,7 @@ class EndpointListForSinglePluginApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -355,7 +355,7 @@ class EndpointItemApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -377,7 +377,7 @@ class EndpointItemApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -410,7 +410,7 @@ class DeprecatedEndpointDeleteApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -443,7 +443,7 @@ class DeprecatedEndpointUpdateApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -468,7 +468,7 @@ class EndpointEnableApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id @@ -493,7 +493,7 @@ class EndpointDisableApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user_id @with_current_tenant_id diff --git a/api/controllers/console/workspace/members.py b/api/controllers/console/workspace/members.py index f32bc47cc42..6587cce55fe 100644 --- a/api/controllers/console/workspace/members.py +++ b/api/controllers/console/workspace/members.py @@ -142,10 +142,10 @@ register_response_schema_models( ) -def _is_role_enabled(role: TenantAccountRole | str, tenant_id: str) -> bool: +def _is_role_enabled(role: TenantAccountRole | str) -> bool: if role != TenantAccountRole.DATASET_OPERATOR: return True - return FeatureService.get_features(tenant_id=tenant_id, exclude_vector_space=True).dataset_operator_enabled + return dify_config.DATASET_OPERATOR_ENABLED def _count_new_member_invites(tenant_id: str, emails: list[str]) -> tuple[int, int]: @@ -254,7 +254,7 @@ class MemberInviteEmailApi(Resource): inviter = current_user if not inviter.current_tenant: raise ValueError("No current tenant") - if not _is_role_enabled(invitee_role, inviter.current_tenant.id): + if not _is_role_enabled(invitee_role): raise InvalidMemberRoleError() # Check workspace permission for member invitations @@ -374,7 +374,7 @@ class MemberUpdateRoleApi(Resource): return {"code": "invalid-role", "message": "Invalid role"}, HTTPStatus.BAD_REQUEST if not current_user.current_tenant: raise ValueError("No current tenant") - if not _is_role_enabled(new_role, current_user.current_tenant.id): + if not _is_role_enabled(new_role): return {"code": "invalid-role", "message": "Invalid role"}, HTTPStatus.BAD_REQUEST member = db.session.get(Account, str(member_id)) if not member: diff --git a/api/controllers/console/workspace/model_providers.py b/api/controllers/console/workspace/model_providers.py index fe844204d27..dd67b9ec131 100644 --- a/api/controllers/console/workspace/model_providers.py +++ b/api/controllers/console/workspace/model_providers.py @@ -7,12 +7,12 @@ from pydantic import BaseModel, Field, field_validator from sqlalchemy.orm import Session from controllers.common.fields import SimpleResultResponse, ValidationResultResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, is_admin_or_owner_required, model_validate, @@ -208,7 +208,7 @@ class ModelProviderCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserCredentialId) @@ -226,7 +226,7 @@ class ModelProviderCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_CREATE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_CREATE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserCredentialCreate) @@ -250,7 +250,7 @@ class ModelProviderCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserCredentialUpdate) @@ -275,7 +275,7 @@ class ModelProviderCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserCredentialDelete) @@ -295,7 +295,7 @@ class ModelProviderCredentialSwitchApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_USE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_USE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserCredentialSwitch) @@ -372,7 +372,7 @@ class PreferredProviderTypeUpdateApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_USE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_USE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserPreferredProviderType) diff --git a/api/controllers/console/workspace/models.py b/api/controllers/console/workspace/models.py index 02b5a68f9c8..23b38bca57f 100644 --- a/api/controllers/console/workspace/models.py +++ b/api/controllers/console/workspace/models.py @@ -5,6 +5,7 @@ from flask_restx import Resource from pydantic import BaseModel, Field, field_validator from controllers.common.fields import SimpleResultResponse, ValidationResultResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, register_enum_models, @@ -14,7 +15,6 @@ from controllers.common.schema import ( from controllers.console import console_ns from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, is_admin_or_owner_required, model_validate, @@ -227,7 +227,7 @@ class DefaultModelApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserPostDefault) @@ -276,7 +276,7 @@ class ModelProviderModelApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserPostModels) @@ -325,7 +325,7 @@ class ModelProviderModelApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserDeleteModels) @@ -350,7 +350,7 @@ class ModelProviderModelCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -413,7 +413,7 @@ class ModelProviderModelCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_CREATE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_CREATE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserCreateCredential) @@ -446,7 +446,7 @@ class ModelProviderModelCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserUpdateCredential) @@ -474,7 +474,7 @@ class ModelProviderModelCredentialApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserDeleteCredential) @@ -499,7 +499,7 @@ class ModelProviderModelCredentialSwitchApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_USE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_USE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ParserSwitch) @@ -526,7 +526,7 @@ class ModelProviderModelEnableApi(Resource): @login_required @account_initialization_required @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @model_validate(ParserDeleteModels) def patch(self, req_data: ParserDeleteModels, tenant_id: str, provider: str): @@ -548,7 +548,7 @@ class ModelProviderModelDisableApi(Resource): @login_required @account_initialization_required @with_current_tenant_id - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @model_validate(ParserDeleteModels) def patch(self, req_data: ParserDeleteModels, tenant_id: str, provider: str): diff --git a/api/controllers/console/workspace/plugin.py b/api/controllers/console/workspace/plugin.py index 236d6ac1f24..2f35e42d334 100644 --- a/api/controllers/console/workspace/plugin.py +++ b/api/controllers/console/workspace/plugin.py @@ -11,6 +11,7 @@ from werkzeug.exceptions import Forbidden from configs import dify_config from controllers.common.fields import BinaryFileResponse, SuccessResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, register_enum_models, @@ -21,7 +22,6 @@ from controllers.console import console_ns from controllers.console.workspace import plugin_permission_required from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, is_admin_or_owner_required, model_validate, @@ -570,7 +570,7 @@ class PluginDebuggingKeyApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_DEBUG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_DEBUG, Workspace())) @plugin_permission_required(debug_required=True) @with_current_tenant_id def get(self, tenant_id: str): @@ -750,7 +750,7 @@ class PluginUploadFromPkgApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id def post(self, tenant_id: str): @@ -771,7 +771,7 @@ class PluginUploadFromGithubApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserGithubUpload) @@ -793,7 +793,7 @@ class PluginUploadFromBundleApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id def post(self, tenant_id: str): @@ -814,7 +814,7 @@ class PluginInstallFromPkgApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserPluginIdentifiers) @@ -835,7 +835,7 @@ class PluginInstallFromGithubApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserGithubInstall) @@ -862,7 +862,7 @@ class PluginInstallFromMarketplaceApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserPluginIdentifiers) @@ -883,7 +883,7 @@ class PluginFetchMarketplacePkgApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserPluginIdentifierQuery) @@ -909,7 +909,7 @@ class PluginFetchManifestApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_INSTALL, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_INSTALL, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserPluginIdentifierQuery) @@ -1014,7 +1014,7 @@ class PluginUpgradeFromMarketplaceApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserMarketplaceUpgrade) @@ -1037,7 +1037,7 @@ class PluginUpgradeFromGithubApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserGithubUpgrade) @@ -1065,7 +1065,7 @@ class PluginUninstallApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_DELETE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_DELETE, Workspace())) @plugin_permission_required(install_required=True) @with_current_tenant_id @model_validate(ParserUninstall) @@ -1138,7 +1138,7 @@ class PluginFetchDynamicSelectOptionsApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_MODEL_CONFIG, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_MODEL_CONFIG, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -1169,7 +1169,7 @@ class PluginFetchDynamicSelectOptionsWithCredentialsApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -1201,7 +1201,7 @@ class PluginChangeAutoUpgradeApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @with_current_user @with_current_tenant_id @model_validate(ParserAutoUpgradeChange) @@ -1256,7 +1256,7 @@ class PluginAutoUpgradeExcludePluginApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @with_current_tenant_id @model_validate(ParserExcludePlugin) def post(self, req_data: ParserExcludePlugin, tenant_id: str): diff --git a/api/controllers/console/workspace/rbac.py b/api/controllers/console/workspace/rbac.py index 96b882871bf..9a036af6122 100644 --- a/api/controllers/console/workspace/rbac.py +++ b/api/controllers/console/workspace/rbac.py @@ -1,5 +1,7 @@ from __future__ import annotations +from collections.abc import Callable, Mapping +from dataclasses import dataclass from typing import Any, Literal from flask import request @@ -9,9 +11,10 @@ from sqlalchemy import select from werkzeug.exceptions import NotFound from configs import dify_config +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.console import console_ns -from controllers.console.wraps import RBACPermission, RBACResourceScope, model_validate, rbac_permission_required +from controllers.console.wraps import RBACPermission, model_validate, rbac_permission_required from core.db.session_factory import session_factory from enums import DeploymentEdition from extensions.ext_database import db @@ -50,6 +53,7 @@ register_response_schema_models( svc.MyPermissionsResponse, svc.AppAccessMatrix, svc.DatasetAccessMatrix, + svc.AgentAccessMatrix, svc.WorkspaceAccessMatrix, svc.ResourceWhitelist, svc.ResourceWhitelistConfig, @@ -282,24 +286,6 @@ class RBACWorkspaceCatalogApi(Resource): return _dump(svc.RBACService.Catalog.workspace(tenant_id, account_id)) -@console_ns.route("/workspaces/current/rbac/role-permissions/catalog/app") -class RBACAppCatalogApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.PermissionCatalogResponse.__name__]) - def get(self): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.Catalog.app(tenant_id, account_id)) - - -@console_ns.route("/workspaces/current/rbac/role-permissions/catalog/dataset") -class RBACDatasetCatalogApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.PermissionCatalogResponse.__name__]) - def get(self): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.Catalog.dataset(tenant_id, account_id)) - - # --------------------------------------------------------------------------- # Roles. # --------------------------------------------------------------------------- @@ -323,9 +309,7 @@ class _RoleUpsertRequest(BaseModel): @console_ns.route("/workspaces/current/rbac/roles") class RBACRolesApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[_RBACRoleList.__name__]) @model_validate(_RolesListQuery) def get(self, req_data: _RolesListQuery): @@ -349,9 +333,7 @@ class RBACRolesApi(Resource): return _dump(result) @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(201, "Role created", console_ns.models[svc.RBACRole.__name__]) def post(self): tenant_id, account_id = _current_ids() @@ -363,9 +345,7 @@ class RBACRolesApi(Resource): @console_ns.route("/workspaces/current/rbac/roles/") class RBACRoleItemApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[svc.RBACRole.__name__]) def get(self, role_id): tenant_id, account_id = _current_ids() @@ -379,9 +359,7 @@ class RBACRoleItemApi(Resource): ) @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[svc.RBACRole.__name__]) def put(self, role_id): tenant_id, account_id = _current_ids() @@ -390,9 +368,7 @@ class RBACRoleItemApi(Resource): return _dump(role) @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[svc.RBACRole.__name__]) def delete(self, role_id): tenant_id, account_id = _current_ids() @@ -403,9 +379,7 @@ class RBACRoleItemApi(Resource): @console_ns.route("/workspaces/current/rbac/roles//copy") class RBACRoleCopyApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(201, "Role copied", console_ns.models[svc.RBACRole.__name__]) def post(self, role_id): tenant_id, account_id = _current_ids() @@ -430,9 +404,7 @@ class _AccessPolicyUpdateRequest(BaseModel): @console_ns.route("/workspaces/current/rbac/access-policies") class RBACAccessPoliciesApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[_AccessPolicyList.__name__]) def get(self): tenant_id, account_id = _current_ids() @@ -449,9 +421,7 @@ class RBACAccessPoliciesApi(Resource): ) @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @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() @@ -472,18 +442,14 @@ class RBACAccessPoliciesApi(Resource): @console_ns.route("/workspaces/current/rbac/access-policies/") class RBACAccessPolicyItemApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicy.__name__]) def get(self, policy_id): tenant_id, account_id = _current_ids() return _dump(svc.RBACService.AccessPolicies.get(tenant_id, account_id, str(policy_id))) @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @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() @@ -501,9 +467,7 @@ class RBACAccessPolicyItemApi(Resource): return _dump(policy) @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicy.__name__]) def delete(self, policy_id): tenant_id, account_id = _current_ids() @@ -514,9 +478,7 @@ class RBACAccessPolicyItemApi(Resource): @console_ns.route("/workspaces/current/rbac/access-policies//copy") class RBACAccessPolicyCopyApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(201, "Policy copied", console_ns.models[svc.AccessPolicy.__name__]) def post(self, policy_id): tenant_id, account_id = _current_ids() @@ -527,9 +489,7 @@ class RBACAccessPolicyCopyApi(Resource): @console_ns.route("/workspaces/current/rbac/access-policy-bindings//lock") class RBACAccessPolicyBindingLockApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicyBindingState.__name__]) def put(self, binding_id): tenant_id, account_id = _current_ids() @@ -539,20 +499,13 @@ class RBACAccessPolicyBindingLockApi(Resource): @console_ns.route("/workspaces/current/rbac/access-policy-bindings//unlock") class RBACAccessPolicyBindingUnlockApi(Resource): @login_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) @console_ns.response(200, "Success", console_ns.models[svc.AccessPolicyBindingState.__name__]) def put(self, binding_id): tenant_id, account_id = _current_ids() return _dump(svc.RBACService.AccessPolicyBindings.unlock(tenant_id, account_id, str(binding_id))) -# --------------------------------------------------------------------------- -# Per-app access (App Access Config). -# --------------------------------------------------------------------------- - - class _ResourceAccessScopeRequest(BaseModel): automatic_include_workspace_members: bool @@ -611,346 +564,337 @@ class RBACMyPermissionsApi(Resource): account_id, app_id=request.args.get("app_id") or None, dataset_id=request.args.get("dataset_id") or None, + agent_id=request.args.get("agent_id") or None, session=db.session(), ) ) -@console_ns.route("/workspaces/current/rbac/apps//access-policy") -class RBACAppMatrixApi(Resource): - @login_required - @console_ns.doc(params=query_params_from_model(_AccessControlLanguageQuery)) - @console_ns.response(200, "Success", console_ns.models[svc.AppAccessMatrix.__name__]) - def get(self, app_id): - tenant_id, account_id = _current_ids() - result = svc.RBACService.AppAccess.matrix(tenant_id, account_id, str(app_id)) - _hydrate_access_matrix_account_names(result.items) - return _dump(result) - - -@console_ns.route("/workspaces/current/rbac/apps//whitelist") -class RBACAppWhitelistApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__]) - def get(self, app_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.AppAccess.whitelist(tenant_id, account_id, str(app_id))) - - @login_required - @console_ns.expect(console_ns.models[_ResourceAccessScopeRequest.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__]) - def put(self, app_id): - tenant_id, account_id = _current_ids() - request = _payload(_ResourceAccessScopeRequest) - result = svc.RBACService.AppAccess.replace_whitelist( - tenant_id, - account_id, - str(app_id), - svc.ReplaceMemberBindings(automatic_include_workspace_members=request.automatic_include_workspace_members), - ) - if request.automatic_include_workspace_members: - initialize_created_app_rbac_access_task.delay(tenant_id, account_id, app_id=str(app_id)) - return _dump(result) - - -@console_ns.route("/workspaces/current/rbac/apps//whitelist_config") -class RBACAppWhitelistConfigApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelistConfig.__name__]) - def get(self, app_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.AppAccess.whitelist_config(tenant_id, account_id, str(app_id))) - - -@console_ns.route("/workspaces/current/rbac/apps//user-access-policies") -class RBACAppUserAccessPoliciesApi(Resource): - @login_required - @console_ns.doc(params=query_params_from_model(_ResourceUserAccessPoliciesQuery)) - @console_ns.response(200, "Success", console_ns.models[svc.ResourceUserAccessPoliciesResponse.__name__]) - def get(self, app_id): - tenant_id, account_id = _current_ids() - options = _pagination_options() - result = svc.RBACService.AppAccess.user_access_policies(tenant_id, account_id, str(app_id), options=options) - _move_resource_maintainer_first(result.data, svc.app_maintainer_id(tenant_id, str(app_id))) - _hydrate_resource_user_account_names(result.data) - return _dump(result) - - -@console_ns.route("/workspaces/current/rbac/apps//users//access-policies") -class RBACAppUserAccessPolicyAssignmentApi(Resource): - @login_required - @console_ns.expect(console_ns.models[svc.ReplaceUserAccessPolicies.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.ReplaceUserAccessPoliciesResponse.__name__]) - def put(self, app_id, target_account_id): - tenant_id, account_id = _current_ids() - payload = _payload(svc.ReplaceUserAccessPolicies) - return _dump( - svc.RBACService.AppAccess.replace_user_access_policies( - tenant_id, - account_id, - app_id, - target_account_id, - payload, - ) - ) - - -@console_ns.route("/workspaces/current/rbac/apps//access-policies//role-bindings") -class RBACAppRoleBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__]) - def get(self, app_id, policy_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.AppAccess.list_role_bindings(tenant_id, account_id, str(app_id), str(policy_id))) - - -@console_ns.route("/workspaces/current/rbac/apps//access-policies//member-bindings") -class RBACAppMemberBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) - def get(self, app_id, policy_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.AppAccess.list_member_bindings(tenant_id, account_id, str(app_id), str(policy_id))) - - @login_required - @console_ns.expect(console_ns.models[_DeleteMemberBindingsRequest.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) - def delete(self, app_id, policy_id): - tenant_id, account_id = _current_ids() - request_body = _payload(_DeleteMemberBindingsRequest) - svc.RBACService.AppAccess.delete_member_bindings( - tenant_id, - account_id, - str(app_id), - str(policy_id), - svc.DeleteMemberBindings(account_ids=request_body.account_ids), - ) - return {"result": "success"} - - -# --------------------------------------------------------------------------- -# Per-dataset access (Knowledge Base Access Config). -# --------------------------------------------------------------------------- - - -@console_ns.route("/workspaces/current/rbac/datasets//access-policy") -class RBACDatasetMatrixApi(Resource): - @login_required - @console_ns.doc(params=query_params_from_model(_AccessControlLanguageQuery)) - @console_ns.response(200, "Success", console_ns.models[svc.DatasetAccessMatrix.__name__]) - def get(self, dataset_id): - tenant_id, account_id = _current_ids() - result = svc.RBACService.DatasetAccess.matrix(tenant_id, account_id, str(dataset_id)) - _hydrate_access_matrix_account_names(result.items) - return _dump(result) - - -@console_ns.route("/workspaces/current/rbac/datasets//whitelist_config") -class RBACDatasetWhitelistConfigApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelistConfig.__name__]) - def get(self, dataset_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.DatasetAccess.whitelist_config(tenant_id, account_id, str(dataset_id))) - - -@console_ns.route("/workspaces/current/rbac/datasets//whitelist") -class RBACDatasetWhitelistApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__]) - def get(self, dataset_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.DatasetAccess.whitelist(tenant_id, account_id, str(dataset_id))) - - @login_required - @console_ns.expect(console_ns.models[_ResourceAccessScopeRequest.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__]) - def put(self, dataset_id): - tenant_id, account_id = _current_ids() - request = _payload(_ResourceAccessScopeRequest) - result = svc.RBACService.DatasetAccess.replace_whitelist( - tenant_id, - account_id, - str(dataset_id), - svc.ReplaceMemberBindings(automatic_include_workspace_members=request.automatic_include_workspace_members), - ) - # Widening the scope only records it: the members still need the default access policy - # before they can reach the dataset, same as the app whitelist route above. - if request.automatic_include_workspace_members: - initialize_created_app_rbac_access_task.delay(tenant_id, account_id, dataset_id=str(dataset_id)) - return _dump(result) - - -@console_ns.route("/workspaces/current/rbac/datasets//user-access-policies") -class RBACDatasetUserAccessPoliciesApi(Resource): - @login_required - @console_ns.doc(params=query_params_from_model(_ResourceUserAccessPoliciesQuery)) - @console_ns.response(200, "Success", console_ns.models[svc.ResourceUserAccessPoliciesResponse.__name__]) - def get(self, dataset_id): - tenant_id, account_id = _current_ids() - options = _pagination_options() - result = svc.RBACService.DatasetAccess.user_access_policies( - tenant_id, account_id, str(dataset_id), options=options - ) - _move_resource_maintainer_first(result.data, svc.dataset_maintainer_id(tenant_id, str(dataset_id))) - _hydrate_resource_user_account_names(result.data) - return _dump(result) - - -@console_ns.route("/workspaces/current/rbac/datasets//users//access-policies") -class RBACDatasetUserAccessPolicyAssignmentApi(Resource): - @login_required - @console_ns.expect(console_ns.models[svc.ReplaceUserAccessPolicies.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.ReplaceUserAccessPoliciesResponse.__name__]) - def put(self, dataset_id, target_account_id): - tenant_id, account_id = _current_ids() - payload = _payload(svc.ReplaceUserAccessPolicies) - return _dump( - svc.RBACService.DatasetAccess.replace_user_access_policies( - tenant_id, - account_id, - str(dataset_id), - str(target_account_id), - payload, - ) - ) - - -@console_ns.route("/workspaces/current/rbac/datasets//access-policies//role-bindings") -class RBACDatasetRoleBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__]) - def get(self, dataset_id, policy_id): - tenant_id, account_id = _current_ids() - return _dump( - svc.RBACService.DatasetAccess.list_role_bindings(tenant_id, account_id, str(dataset_id), str(policy_id)) - ) - - -@console_ns.route( - "/workspaces/current/rbac/datasets//access-policies//member-bindings" +type _ResourceAccessClient = ( + type[svc.RBACService.AppAccess] | type[svc.RBACService.DatasetAccess] | type[svc.RBACService.AgentAccess] ) -class RBACDatasetMemberBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) - def get(self, dataset_id, policy_id): - tenant_id, account_id = _current_ids() - return _dump( - svc.RBACService.DatasetAccess.list_member_bindings(tenant_id, account_id, str(dataset_id), str(policy_id)) - ) - - @login_required - @console_ns.expect(console_ns.models[_DeleteMemberBindingsRequest.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) - def delete(self, dataset_id, policy_id): - tenant_id, account_id = _current_ids() - request_body = _payload(_DeleteMemberBindingsRequest) - svc.RBACService.DatasetAccess.delete_member_bindings( - tenant_id, - account_id, - str(dataset_id), - str(policy_id), - svc.DeleteMemberBindings(account_ids=request_body.account_ids), - ) - return {"result": "success"} -@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policy") -class RBACWorkspaceAppMatrixApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.WorkspaceAccessMatrix.__name__]) - def get(self): - tenant_id, account_id = _current_ids() - options = _pagination_options() - result = svc.RBACService.WorkspaceAccess.app_matrix(tenant_id, account_id, options=options) - _hydrate_access_matrix_account_names(result.items) - return _dump(result) +@dataclass(frozen=True) +class _ResourceAccessRoutes: + resource_type: svc.RBACResourceType + class_prefix: str + matrix_model: type[BaseModel] + access: _ResourceAccessClient + catalog: Callable[[str, str], svc.PermissionCatalogResponse] + workspace_matrix: Callable[[str, str, svc.ListOption], svc.WorkspaceAccessMatrix] + workspace_role_bindings: Callable[[str, str, str], svc.RoleBindingsResponse] + workspace_member_bindings: Callable[[str, str, str], svc.MemberBindingsResponse] + replace_workspace_bindings: Callable[[str, str, str, svc.ReplaceBindings], svc.AccessMatrixItem] + maintainer_id: Callable[[str, str], str | None] | None = None + + @property + def url_segment(self) -> str: + return self.resource_type.route.segment + + @property + def id_param(self) -> str: + return self.resource_type.route.id_param -@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policies//role-bindings") -class RBACWorkspaceAppRoleBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__]) - def get(self, policy_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.WorkspaceAccess.list_app_role_bindings(tenant_id, account_id, str(policy_id))) +@dataclass(frozen=True) +class _ResourceAccessApis: + catalog: type[Resource] + matrix: type[Resource] + whitelist: type[Resource] + whitelist_config: type[Resource] + user_access_policies: type[Resource] + user_access_policy_assignment: type[Resource] + role_bindings: type[Resource] + member_bindings: type[Resource] + workspace_matrix: type[Resource] + workspace_role_bindings: type[Resource] + workspace_bindings: type[Resource] + workspace_member_bindings: type[Resource] -@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policies//bindings") -class RBACWorkspaceAppBindingsApi(Resource): - @login_required - @console_ns.expect(console_ns.models[_ReplaceBindingsRequest.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.AccessMatrixItem.__name__]) - def put(self, policy_id): - tenant_id, account_id = _current_ids() - request = _payload(_ReplaceBindingsRequest) - return _dump( - svc.RBACService.WorkspaceAccess.replace_app_bindings( +_RESOURCE_ACCESS_ROUTES = ( + _ResourceAccessRoutes( + resource_type=svc.RBACResourceType.APP, + class_prefix="App", + matrix_model=svc.AppAccessMatrix, + access=svc.RBACService.AppAccess, + catalog=lambda tenant_id, account_id: svc.RBACService.Catalog.app(tenant_id, account_id), + workspace_matrix=lambda tenant_id, account_id, options: svc.RBACService.WorkspaceAccess.app_matrix( + tenant_id, account_id, options=options + ), + workspace_role_bindings=lambda tenant_id, account_id, policy_id: ( + svc.RBACService.WorkspaceAccess.list_app_role_bindings(tenant_id, account_id, policy_id) + ), + workspace_member_bindings=lambda tenant_id, account_id, policy_id: ( + svc.RBACService.WorkspaceAccess.list_app_member_bindings(tenant_id, account_id, policy_id) + ), + replace_workspace_bindings=lambda tenant_id, account_id, policy_id, payload: ( + svc.RBACService.WorkspaceAccess.replace_app_bindings(tenant_id, account_id, policy_id, payload) + ), + maintainer_id=lambda tenant_id, resource_id: svc.app_maintainer_id(tenant_id, resource_id), + ), + _ResourceAccessRoutes( + resource_type=svc.RBACResourceType.DATASET, + class_prefix="Dataset", + matrix_model=svc.DatasetAccessMatrix, + access=svc.RBACService.DatasetAccess, + catalog=lambda tenant_id, account_id: svc.RBACService.Catalog.dataset(tenant_id, account_id), + workspace_matrix=lambda tenant_id, account_id, options: svc.RBACService.WorkspaceAccess.dataset_matrix( + tenant_id, account_id, options=options + ), + workspace_role_bindings=lambda tenant_id, account_id, policy_id: ( + svc.RBACService.WorkspaceAccess.list_dataset_role_bindings(tenant_id, account_id, policy_id) + ), + workspace_member_bindings=lambda tenant_id, account_id, policy_id: ( + svc.RBACService.WorkspaceAccess.list_dataset_member_bindings(tenant_id, account_id, policy_id) + ), + replace_workspace_bindings=lambda tenant_id, account_id, policy_id, payload: ( + svc.RBACService.WorkspaceAccess.replace_dataset_bindings(tenant_id, account_id, policy_id, payload) + ), + maintainer_id=lambda tenant_id, resource_id: svc.dataset_maintainer_id(tenant_id, resource_id), + ), + _ResourceAccessRoutes( + resource_type=svc.RBACResourceType.AGENT, + class_prefix="Agent", + matrix_model=svc.AgentAccessMatrix, + access=svc.RBACService.AgentAccess, + catalog=lambda tenant_id, account_id: svc.RBACService.Catalog.agent(tenant_id, account_id), + workspace_matrix=lambda tenant_id, account_id, options: svc.RBACService.WorkspaceAccess.agent_matrix( + tenant_id, account_id, options=options + ), + workspace_role_bindings=lambda tenant_id, account_id, policy_id: ( + svc.RBACService.WorkspaceAccess.list_agent_role_bindings(tenant_id, account_id, policy_id) + ), + workspace_member_bindings=lambda tenant_id, account_id, policy_id: ( + svc.RBACService.WorkspaceAccess.list_agent_member_bindings(tenant_id, account_id, policy_id) + ), + replace_workspace_bindings=lambda tenant_id, account_id, policy_id, payload: ( + svc.RBACService.WorkspaceAccess.replace_agent_bindings(tenant_id, account_id, policy_id, payload) + ), + ), +) + + +def _build_resource_access_apis(spec: _ResourceAccessRoutes) -> _ResourceAccessApis: + id_param = spec.id_param + resource_prefix = f"/workspaces/current/rbac/{spec.url_segment}/" + workspace_prefix = f"/workspaces/current/rbac/workspace/{spec.url_segment}" + + def resource_id(path_params: Mapping[str, object]) -> str: + return str(path_params[id_param]) + + def register(resource: type[Resource], name: str, url: str) -> type[Resource]: + resource.__name__ = name + resource.__qualname__ = name + console_ns.route(url)(resource) + return resource + + class CatalogApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.PermissionCatalogResponse.__name__]) + def get(self): + tenant_id, account_id = _current_ids() + return _dump(spec.catalog(tenant_id, account_id)) + + class MatrixApi(Resource): + @login_required + @console_ns.doc(params=query_params_from_model(_AccessControlLanguageQuery)) + @console_ns.response(200, "Success", console_ns.models[spec.matrix_model.__name__]) + def get(self, **path_params): + tenant_id, account_id = _current_ids() + result = spec.access.matrix(tenant_id, account_id, resource_id(path_params)) + _hydrate_access_matrix_account_names(result.items) + return _dump(result) + + class WhitelistApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__]) + def get(self, **path_params): + tenant_id, account_id = _current_ids() + return _dump(spec.access.whitelist(tenant_id, account_id, resource_id(path_params))) + + @login_required + @console_ns.expect(console_ns.models[_ResourceAccessScopeRequest.__name__]) + @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelist.__name__]) + def put(self, **path_params): + tenant_id, account_id = _current_ids() + target_id = resource_id(path_params) + scope = _payload(_ResourceAccessScopeRequest) + result = spec.access.replace_whitelist( tenant_id, account_id, - str(policy_id), - svc.ReplaceBindings(role_ids=list(request.role_ids), account_ids=list(request.account_ids)), + target_id, + svc.ReplaceMemberBindings( + automatic_include_workspace_members=scope.automatic_include_workspace_members + ), ) - ) + if scope.automatic_include_workspace_members: + initialize_created_app_rbac_access_task.delay(tenant_id, account_id, **{id_param: target_id}) + return _dump(result) + class WhitelistConfigApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.ResourceWhitelistConfig.__name__]) + def get(self, **path_params): + tenant_id, account_id = _current_ids() + return _dump(spec.access.whitelist_config(tenant_id, account_id, resource_id(path_params))) -@console_ns.route("/workspaces/current/rbac/workspace/apps/access-policies//member-bindings") -class RBACWorkspaceAppMemberBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) - def get(self, policy_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.WorkspaceAccess.list_app_member_bindings(tenant_id, account_id, str(policy_id))) + class UserAccessPoliciesApi(Resource): + @login_required + @console_ns.doc(params=query_params_from_model(_ResourceUserAccessPoliciesQuery)) + @console_ns.response(200, "Success", console_ns.models[svc.ResourceUserAccessPoliciesResponse.__name__]) + def get(self, **path_params): + tenant_id, account_id = _current_ids() + target_id = resource_id(path_params) + options = _pagination_options() + result = spec.access.user_access_policies(tenant_id, account_id, target_id, options=options) + maintainer_id = spec.maintainer_id(tenant_id, target_id) if spec.maintainer_id else None + _move_resource_maintainer_first(result.data, maintainer_id) + _hydrate_resource_user_account_names(result.data) + return _dump(result) + class UserAccessPolicyAssignmentApi(Resource): + @login_required + @console_ns.expect(console_ns.models[svc.ReplaceUserAccessPolicies.__name__]) + @console_ns.response(200, "Success", console_ns.models[svc.ReplaceUserAccessPoliciesResponse.__name__]) + def put(self, target_account_id, **path_params): + tenant_id, account_id = _current_ids() + payload = _payload(svc.ReplaceUserAccessPolicies) + return _dump( + spec.access.replace_user_access_policies( + tenant_id, + account_id, + resource_id(path_params), + str(target_account_id), + payload, + ) + ) -@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policy") -class RBACWorkspaceDatasetMatrixApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.WorkspaceAccessMatrix.__name__]) - def get(self): - tenant_id, account_id = _current_ids() - options = _pagination_options() - result = svc.RBACService.WorkspaceAccess.dataset_matrix(tenant_id, account_id, options=options) - _hydrate_access_matrix_account_names(result.items) - return _dump(result) + class RoleBindingsApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__]) + def get(self, policy_id, **path_params): + tenant_id, account_id = _current_ids() + return _dump( + spec.access.list_role_bindings(tenant_id, account_id, resource_id(path_params), str(policy_id)) + ) + class MemberBindingsApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) + def get(self, policy_id, **path_params): + tenant_id, account_id = _current_ids() + return _dump( + spec.access.list_member_bindings(tenant_id, account_id, resource_id(path_params), str(policy_id)) + ) -@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policies//role-bindings") -class RBACWorkspaceDatasetRoleBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__]) - def get(self, policy_id): - tenant_id, account_id = _current_ids() - return _dump(svc.RBACService.WorkspaceAccess.list_dataset_role_bindings(tenant_id, account_id, str(policy_id))) - - -@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policies//bindings") -class RBACWorkspaceDatasetBindingsApi(Resource): - @login_required - @console_ns.expect(console_ns.models[_ReplaceBindingsRequest.__name__]) - @console_ns.response(200, "Success", console_ns.models[svc.AccessMatrixItem.__name__]) - def put(self, policy_id): - tenant_id, account_id = _current_ids() - request = _payload(_ReplaceBindingsRequest) - return _dump( - svc.RBACService.WorkspaceAccess.replace_dataset_bindings( + @login_required + @console_ns.expect(console_ns.models[_DeleteMemberBindingsRequest.__name__]) + @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) + def delete(self, policy_id, **path_params): + tenant_id, account_id = _current_ids() + body = _payload(_DeleteMemberBindingsRequest) + spec.access.delete_member_bindings( tenant_id, account_id, + resource_id(path_params), str(policy_id), - svc.ReplaceBindings(role_ids=list(request.role_ids), account_ids=list(request.account_ids)), + svc.DeleteMemberBindings(account_ids=body.account_ids), ) - ) + return {"result": "success"} + + class WorkspaceMatrixApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.WorkspaceAccessMatrix.__name__]) + def get(self): + tenant_id, account_id = _current_ids() + result = spec.workspace_matrix(tenant_id, account_id, _pagination_options()) + _hydrate_access_matrix_account_names(result.items) + return _dump(result) + + class WorkspaceRoleBindingsApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.RoleBindingsResponse.__name__]) + def get(self, policy_id): + tenant_id, account_id = _current_ids() + return _dump(spec.workspace_role_bindings(tenant_id, account_id, str(policy_id))) + + class WorkspaceBindingsApi(Resource): + @login_required + @console_ns.expect(console_ns.models[_ReplaceBindingsRequest.__name__]) + @console_ns.response(200, "Success", console_ns.models[svc.AccessMatrixItem.__name__]) + def put(self, policy_id): + tenant_id, account_id = _current_ids() + body = _payload(_ReplaceBindingsRequest) + return _dump( + spec.replace_workspace_bindings( + tenant_id, + account_id, + str(policy_id), + svc.ReplaceBindings(role_ids=list(body.role_ids), account_ids=list(body.account_ids)), + ) + ) + + class WorkspaceMemberBindingsApi(Resource): + @login_required + @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) + def get(self, policy_id): + tenant_id, account_id = _current_ids() + return _dump(spec.workspace_member_bindings(tenant_id, account_id, str(policy_id))) + + prefix = spec.class_prefix + return _ResourceAccessApis( + catalog=register( + CatalogApi, + f"RBAC{prefix}CatalogApi", + f"/workspaces/current/rbac/role-permissions/catalog/{spec.resource_type.value}", + ), + matrix=register(MatrixApi, f"RBAC{prefix}MatrixApi", f"{resource_prefix}/access-policy"), + whitelist=register(WhitelistApi, f"RBAC{prefix}WhitelistApi", f"{resource_prefix}/whitelist"), + whitelist_config=register( + WhitelistConfigApi, f"RBAC{prefix}WhitelistConfigApi", f"{resource_prefix}/whitelist_config" + ), + user_access_policies=register( + UserAccessPoliciesApi, f"RBAC{prefix}UserAccessPoliciesApi", f"{resource_prefix}/user-access-policies" + ), + user_access_policy_assignment=register( + UserAccessPolicyAssignmentApi, + f"RBAC{prefix}UserAccessPolicyAssignmentApi", + f"{resource_prefix}/users//access-policies", + ), + role_bindings=register( + RoleBindingsApi, + f"RBAC{prefix}RoleBindingsApi", + f"{resource_prefix}/access-policies//role-bindings", + ), + member_bindings=register( + MemberBindingsApi, + f"RBAC{prefix}MemberBindingsApi", + f"{resource_prefix}/access-policies//member-bindings", + ), + workspace_matrix=register( + WorkspaceMatrixApi, f"RBACWorkspace{prefix}MatrixApi", f"{workspace_prefix}/access-policy" + ), + workspace_role_bindings=register( + WorkspaceRoleBindingsApi, + f"RBACWorkspace{prefix}RoleBindingsApi", + f"{workspace_prefix}/access-policies//role-bindings", + ), + workspace_bindings=register( + WorkspaceBindingsApi, + f"RBACWorkspace{prefix}BindingsApi", + f"{workspace_prefix}/access-policies//bindings", + ), + workspace_member_bindings=register( + WorkspaceMemberBindingsApi, + f"RBACWorkspace{prefix}MemberBindingsApi", + f"{workspace_prefix}/access-policies//member-bindings", + ), + ) -@console_ns.route("/workspaces/current/rbac/workspace/datasets/access-policies//member-bindings") -class RBACWorkspaceDatasetMemberBindingsApi(Resource): - @login_required - @console_ns.response(200, "Success", console_ns.models[svc.MemberBindingsResponse.__name__]) - def get(self, policy_id): - tenant_id, account_id = _current_ids() - return _dump( - svc.RBACService.WorkspaceAccess.list_dataset_member_bindings(tenant_id, account_id, str(policy_id)) - ) +_RESOURCE_ACCESS_APIS = {spec.resource_type: _build_resource_access_apis(spec) for spec in _RESOURCE_ACCESS_ROUTES} # --------------------------------------------------------------------------- diff --git a/api/controllers/console/workspace/skills.py b/api/controllers/console/workspace/skills.py index ce1dc6b51c7..05730ac72bf 100644 --- a/api/controllers/console/workspace/skills.py +++ b/api/controllers/console/workspace/skills.py @@ -10,13 +10,13 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError from sqlalchemy.orm import Session from controllers.common.fields import BinaryFileResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models from controllers.common.session import with_session from controllers.console import console_ns from controllers.console.flask_admission import console_account_admission from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, edit_permission_required, ) from fields.base import ResponseModel @@ -298,9 +298,7 @@ class WorkspaceSkillsApi(Resource): @console_ns.doc(params=query_params_from_model(WorkspaceSkillsQuery)) @console_ns.response(200, "Workspace skills", console_ns.models[SkillListResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_VIEW, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_VIEW, Workspace())], ) @with_session(write=False) def get(self, session: Session, request_context: RequestContext): @@ -325,9 +323,7 @@ class WorkspaceSkillsApi(Resource): @console_ns.expect(console_ns.models[SkillCreatePayload.__name__]) @console_ns.response(201, "Skill created", console_ns.models[SkillDetailResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_EDIT, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_EDIT, Workspace())], ) @edit_permission_required @with_session @@ -391,9 +387,7 @@ class WorkspaceSkillImportApi(Resource): @console_ns.doc(description="Import a Skill zip package from multipart form field `file`.") @console_ns.response(201, "Skill imported", console_ns.models[SkillDetailResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_EDIT, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_EDIT, Workspace())], ) @edit_permission_required @with_session @@ -419,9 +413,7 @@ class WorkspaceSkillImportApi(Resource): class WorkspaceSkillApi(Resource): @console_ns.response(200, "Skill detail", console_ns.models[SkillDetailResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_VIEW, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_VIEW, Workspace())], ) @with_session(write=False) def get(self, session: Session, request_context: RequestContext, skill_id: str): @@ -436,9 +428,7 @@ class WorkspaceSkillApi(Resource): @console_ns.expect(console_ns.models[SkillMetadataPayload.__name__]) @console_ns.response(200, "Skill updated", console_ns.models[SkillResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_EDIT, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_EDIT, Workspace())], ) @edit_permission_required @with_session @@ -462,9 +452,7 @@ class WorkspaceSkillApi(Resource): @console_ns.expect(console_ns.models[SkillDeletePayload.__name__]) @console_ns.response(200, "Skill deleted", console_ns.models[SkillDeleteResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_DELETE, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_DELETE, Workspace())], ) @edit_permission_required @with_session @@ -487,9 +475,7 @@ class WorkspaceSkillApi(Resource): class WorkspaceSkillDuplicateApi(Resource): @console_ns.response(201, "Skill duplicated", console_ns.models[SkillDetailResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_EDIT, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_EDIT, Workspace())], ) @edit_permission_required @with_session @@ -509,9 +495,7 @@ class WorkspaceSkillDuplicateApi(Resource): class WorkspaceSkillExportApi(Resource): @console_ns.response(200, "Published Skill zip archive") @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_VIEW, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_VIEW, Workspace())], ) @with_session(write=False) def get(self, session: Session, request_context: RequestContext, skill_id: str): @@ -696,9 +680,7 @@ class WorkspaceSkillPublishApi(Resource): @console_ns.expect(console_ns.models[SkillPublishPayload.__name__]) @console_ns.response(200, "Skill published", console_ns.models[SkillVersionResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_PUBLISH, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_PUBLISH, Workspace())], ) @edit_permission_required @with_session @@ -723,9 +705,7 @@ class WorkspaceSkillRestoreApi(Resource): @console_ns.expect(console_ns.models[SkillRestorePayload.__name__]) @console_ns.response(200, "Skill version restored to draft", console_ns.models[SkillDetailResponse.__name__]) @console_account_admission( - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.SKILL_PUBLISH, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.SKILL_PUBLISH, Workspace())], ) @edit_permission_required @with_session diff --git a/api/controllers/console/workspace/snippets.py b/api/controllers/console/workspace/snippets.py index ba1b3d816b3..2b8f609801e 100644 --- a/api/controllers/console/workspace/snippets.py +++ b/api/controllers/console/workspace/snippets.py @@ -5,9 +5,10 @@ from uuid import UUID from flask import Response, request from flask_restx import Resource from sqlalchemy.orm import Session, sessionmaker -from werkzeug.exceptions import NotFound +from werkzeug.exceptions import BadRequest, NotFound from controllers.common.fields import TextFileResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, register_response_schema_models, @@ -24,7 +25,6 @@ from controllers.console.snippets.payloads import ( ) from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, model_validate, @@ -36,7 +36,13 @@ from controllers.console.wraps import ( from core.plugin.entities.plugin import PluginDependency from extensions.ext_database import db from fields.base import ResponseModel -from fields.snippet_fields import SnippetListItemResponse, SnippetPaginationResponse, SnippetResponse +from fields.snippet_fields import ( + SnippetListItemResponse, + SnippetPaginationResponse, + SnippetResponse, + snippet_list_item_responses, + snippet_response, +) from libs.helper import dump_response from libs.login import login_required from models import Account @@ -112,14 +118,15 @@ class CustomizedSnippetsApi(Resource): @login_required @account_initialization_required @with_current_tenant_id - def get(self, current_tenant_id: str): + @with_session(write=False) + def get(self, session: Session, current_tenant_id: str): """List customized snippets with pagination and search.""" query = _snippet_list_query_from_request() snippet_service = _snippet_service() snippets, total, has_more = snippet_service.get_snippets( tenant_id=current_tenant_id, - session=db.session(), + session=session, page=query.page, limit=query.limit, keyword=query.keyword, @@ -131,7 +138,7 @@ class CustomizedSnippetsApi(Resource): return dump_response( SnippetPaginationResponse, { - "data": snippets, + "data": snippet_list_item_responses(snippets, session=session), "page": query.page, "limit": query.limit, "total": total, @@ -147,13 +154,12 @@ class CustomizedSnippetsApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_user @with_current_tenant_id + @with_session @model_validate(CreateSnippetPayload) - def post(self, req_data: CreateSnippetPayload, current_tenant_id: str, current_user: Account): + def post(self, req_data: CreateSnippetPayload, session: Session, current_tenant_id: str, current_user: Account): """Create a new customized snippet.""" try: snippet_type = SnippetType(req_data.type) @@ -177,7 +183,7 @@ class CustomizedSnippetsApi(Resource): except ValueError as e: return {"message": str(e)}, 400 - return dump_response(SnippetResponse, snippet), 201 + return dump_response(SnippetResponse, snippet_response(snippet, session=session)), 201 @console_ns.route("/workspaces/current/customized-snippets/") @@ -189,7 +195,8 @@ class CustomizedSnippetDetailApi(Resource): @login_required @account_initialization_required @with_current_tenant_id - def get(self, current_tenant_id: str, snippet_id: UUID): + @with_session(write=False) + def get(self, session: Session, current_tenant_id: str, snippet_id: UUID): """Get customized snippet details.""" snippet_service = _snippet_service() snippet = snippet_service.get_snippet_by_id( @@ -200,7 +207,7 @@ class CustomizedSnippetDetailApi(Resource): if not snippet: raise NotFound("Snippet not found") - return dump_response(SnippetResponse, snippet), 200 + return dump_response(SnippetResponse, snippet_response(snippet, session=session)), 200 @console_ns.doc("update_customized_snippet") @console_ns.expect(console_ns.models.get(UpdateSnippetPayload.__name__)) @@ -211,13 +218,19 @@ class CustomizedSnippetDetailApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_user @with_current_tenant_id + @with_session @model_validate(UpdateSnippetPayload) - def patch(self, req_data: UpdateSnippetPayload, current_tenant_id: str, current_user: Account, snippet_id: str): + def patch( + self, + req_data: UpdateSnippetPayload, + session: Session, + current_tenant_id: str, + current_user: Account, + snippet_id: str, + ): """Update customized snippet.""" snippet_service = _snippet_service() snippet = snippet_service.get_snippet_by_id( @@ -237,19 +250,22 @@ class CustomizedSnippetDetailApi(Resource): return {"message": "No valid fields to update"}, 400 try: - with Session(db.engine, expire_on_commit=False) as session: - snippet = session.merge(snippet) - snippet = SnippetService.update_snippet( - session=session, - snippet=snippet, - account_id=current_user.id, - data=update_data, - ) - session.commit() + snippet = session.merge(snippet) + snippet = SnippetService.update_snippet( + session=session, + snippet=snippet, + account_id=current_user.id, + data=update_data, + ) + session.commit() except ValueError as e: - return {"message": str(e)}, 400 + # Raise rather than return: `with_session` commits on a normal return, so returning here + # would persist whatever the update wrote before it rejected the payload. Raising routes + # through the decorator's rollback. Status stays 400 and `message` is unchanged; the body + # picks up the standard error envelope, as on every other BadRequest in the console API. + raise BadRequest(str(e)) from e - return dump_response(SnippetResponse, snippet), 200 + return dump_response(SnippetResponse, snippet_response(snippet, session=session)), 200 @console_ns.doc("delete_customized_snippet") @console_ns.response(204, "Snippet deleted successfully") @@ -258,7 +274,7 @@ class CustomizedSnippetDetailApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_MANAGE, Workspace())) @with_current_user @with_current_tenant_id def delete(self, current_tenant_id: str, current_user: Account, snippet_id: str): @@ -296,9 +312,7 @@ class CustomizedSnippetExportApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_tenant_id def get(self, current_tenant_id: str, snippet_id: str): """Export snippet as DSL.""" @@ -351,9 +365,7 @@ class CustomizedSnippetImportApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_user @with_session @model_validate(SnippetImportPayload) @@ -390,9 +402,7 @@ class CustomizedSnippetImportConfirmApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_user @with_session def post(self, session: Session, current_user: Account, import_id: str): @@ -420,9 +430,7 @@ class CustomizedSnippetCheckDependenciesApi(Resource): @login_required @account_initialization_required @edit_permission_required - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.SNIPPETS_CREATE_AND_MODIFY, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.SNIPPETS_CREATE_AND_MODIFY, Workspace())) @with_current_tenant_id def get(self, current_tenant_id: str, snippet_id: str): """Check dependencies for a snippet.""" diff --git a/api/controllers/console/workspace/tool_providers.py b/api/controllers/console/workspace/tool_providers.py index cb61f1582b6..c35f2b88de8 100644 --- a/api/controllers/console/workspace/tool_providers.py +++ b/api/controllers/console/workspace/tool_providers.py @@ -20,6 +20,7 @@ from werkzeug.exceptions import Forbidden from configs import dify_config from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import ( query_params_from_model, query_params_from_request, @@ -29,7 +30,6 @@ from controllers.common.schema import ( from controllers.console import console_ns from controllers.console.wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, enterprise_license_required, is_admin_or_owner_required, @@ -563,7 +563,7 @@ class ToolBuiltinProviderDeleteApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(BuiltinToolCredentialDeletePayload) @@ -590,7 +590,7 @@ class ToolBuiltinProviderAddApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_CREATE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_CREATE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -621,7 +621,7 @@ class ToolBuiltinProviderUpdateApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -689,7 +689,7 @@ class ToolApiProviderAddApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.TOOL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -769,7 +769,7 @@ class ToolApiProviderUpdateApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.TOOL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -800,7 +800,7 @@ class ToolApiProviderDeleteApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.TOOL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -908,7 +908,7 @@ class ToolWorkflowProviderCreateApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.TOOL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -938,7 +938,7 @@ class ToolWorkflowProviderUpdateApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.TOOL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -968,7 +968,7 @@ class ToolWorkflowProviderDeleteApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.TOOL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.TOOL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -1125,7 +1125,7 @@ class ToolPluginOAuthApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -1251,7 +1251,7 @@ class ToolBuiltinProviderSetDefaultApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_USE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_USE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(BuiltinProviderDefaultCredentialPayload) @@ -1273,7 +1273,7 @@ class ToolOAuthCustomClient(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(ToolOAuthCustomClientPayload) @@ -1297,7 +1297,7 @@ class ToolOAuthCustomClient(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id def get(self, current_tenant_id: str, provider: str): @@ -1309,7 +1309,7 @@ class ToolOAuthCustomClient(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_tenant_id def delete(self, current_tenant_id: str, provider: str): @@ -1379,7 +1379,7 @@ class ToolProviderMCPApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.MCP_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.MCP_MANAGE, Workspace())) @with_current_user @with_current_tenant_id @model_validate(MCPProviderCreatePayload) @@ -1433,7 +1433,7 @@ class ToolProviderMCPApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.MCP_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.MCP_MANAGE, Workspace())) @with_current_tenant_id @model_validate(MCPProviderUpdatePayload) def put(self, req_data: MCPProviderUpdatePayload, current_tenant_id: str): @@ -1487,7 +1487,7 @@ class ToolProviderMCPApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.MCP_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.MCP_MANAGE, Workspace())) @with_current_tenant_id @model_validate(MCPProviderDeletePayload) def delete(self, req_data: MCPProviderDeletePayload, current_tenant_id: str): @@ -1505,7 +1505,7 @@ class ToolMCPAuthApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.MCP_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.MCP_MANAGE, Workspace())) @with_current_tenant_id @model_validate(MCPAuthPayload) def post(self, req_data: MCPAuthPayload, tenant_id: str): @@ -1582,6 +1582,7 @@ class ToolMCPDetailApi(Resource): @setup_required @login_required @account_initialization_required + @rbac_permission_required(RBACCheck(RBACPermission.MCP_MANAGE, Workspace())) @with_current_tenant_id def get(self, tenant_id: str, provider_id: str): with sessionmaker(db.engine).begin() as session: @@ -1617,7 +1618,7 @@ class ToolMCPUpdateApi(Resource): @setup_required @login_required @account_initialization_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.MCP_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.MCP_MANAGE, Workspace())) @with_current_tenant_id def get(self, tenant_id: str, provider_id: str): with sessionmaker(db.engine).begin() as session: diff --git a/api/controllers/console/workspace/trigger_providers.py b/api/controllers/console/workspace/trigger_providers.py index 2bc5b454696..8d15c3a99b4 100644 --- a/api/controllers/console/workspace/trigger_providers.py +++ b/api/controllers/console/workspace/trigger_providers.py @@ -10,6 +10,7 @@ from werkzeug.exceptions import BadRequest, Forbidden from configs import dify_config from controllers.common.errors import NotFoundError from controllers.common.fields import SimpleResultResponse +from controllers.common.rbac import RBACCheck, Workspace from controllers.common.schema import register_response_schema_models, register_schema_models from core.entities.provider_entities import ProviderConfig from core.plugin.entities.plugin_daemon import CredentialType @@ -35,7 +36,6 @@ from services.trigger.trigger_subscription_operator_service import TriggerSubscr from .. import console_ns from ..wraps import ( RBACPermission, - RBACResourceScope, account_initialization_required, edit_permission_required, is_admin_or_owner_required, @@ -199,7 +199,7 @@ class TriggerSubscriptionListApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -235,7 +235,7 @@ class TriggerSubscriptionBuilderCreateApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -271,7 +271,7 @@ class TriggerSubscriptionBuilderGetApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -299,7 +299,7 @@ class TriggerSubscriptionBuilderVerifyApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -344,7 +344,7 @@ class TriggerSubscriptionBuilderUpdateApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.CREDENTIAL_MANAGE, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.CREDENTIAL_MANAGE, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -389,7 +389,7 @@ class TriggerSubscriptionBuilderLogsApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -420,7 +420,7 @@ class TriggerSubscriptionBuilderBuildApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id @@ -464,7 +464,7 @@ class TriggerSubscriptionUpdateApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(TriggerSubscriptionBuilderUpdatePayload) @@ -524,7 +524,7 @@ class TriggerSubscriptionDeleteApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id def post(self, tenant_id: str, subscription_id: str): @@ -716,7 +716,7 @@ class TriggerOAuthClientManageApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id def get(self, tenant_id: str, provider: str): @@ -763,7 +763,7 @@ class TriggerOAuthClientManageApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id @model_validate(TriggerOAuthClientPayload) @@ -792,7 +792,7 @@ class TriggerOAuthClientManageApi(Resource): @setup_required @login_required @is_admin_or_owner_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_tenant_id def delete(self, tenant_id: str, provider: str): @@ -826,7 +826,7 @@ class TriggerSubscriptionVerifyApi(Resource): @setup_required @login_required @edit_permission_required - @rbac_permission_required(RBACResourceScope.WORKSPACE, RBACPermission.PLUGIN_PREFERENCES, resource_required=False) + @rbac_permission_required(RBACCheck(RBACPermission.PLUGIN_PREFERENCES, Workspace())) @account_initialization_required @with_current_user @with_current_tenant_id diff --git a/api/controllers/console/wraps.py b/api/controllers/console/wraps.py index a56a6de5b14..813c8a75a41 100644 --- a/api/controllers/console/wraps.py +++ b/api/controllers/console/wraps.py @@ -11,11 +11,8 @@ from sqlalchemy import select from werkzeug.exceptions import Forbidden, UnprocessableEntity from configs import dify_config -from controllers.common.wraps import ( - RBACPermission, - RBACResourceScope, - rbac_permission_required, -) +from controllers.common.rbac import RBACPermission, RBACResourceScope +from controllers.common.wraps import rbac_permission_required from controllers.console.auth.error import AuthenticationFailedError, EmailCodeError from controllers.console.workspace.error import AccountNotInitializedError from enums import CloudPlan, DeploymentEdition @@ -166,7 +163,7 @@ def cloud_edition_billing_paid_plan_required[**P, R](view: Callable[P, R]) -> Ca def decorated(*args: P.args, **kwargs: P.kwargs): _, current_tenant_id = current_account_with_tenant() billing_info = BillingService.get_info(current_tenant_id, exclude_vector_space=True) - if not billing_info["enabled"] or billing_info["subscription"]["plan"] not in ( + if billing_info["subscription"]["plan"] not in ( CloudPlan.PROFESSIONAL, CloudPlan.TEAM, ): @@ -181,10 +178,10 @@ def cloud_edition_billing_resource_check[**P, R](resource: str) -> Callable[[Cal @wraps(view) def decorated(*args: P.args, **kwargs: P.kwargs): _, current_tenant_id = current_account_with_tenant() - if resource == "vector_space": - if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD: - return view(*args, **kwargs) + if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD: + return view(*args, **kwargs) + if resource == "vector_space": vector_space = application_services().feature_queries.get_workspace_vector_space(current_tenant_id) if 0 < vector_space.limit <= vector_space.size: abort( @@ -194,30 +191,26 @@ def cloud_edition_billing_resource_check[**P, R](resource: str) -> Callable[[Cal return view(*args, **kwargs) features = FeatureService.get_features(current_tenant_id, exclude_vector_space=True) - if features.billing.enabled: - members = features.members - apps = features.apps - documents_upload_quota = features.documents_upload_quota - annotation_quota_limit = features.annotation_quota_limit - if resource == "members" and 0 < members.limit <= members.size: - abort(403, "The number of members has reached the limit of your subscription.") - elif resource == "apps" and 0 < apps.limit <= apps.size: - abort(403, "The number of apps has reached the limit of your subscription.") - elif resource == "documents" and 0 < documents_upload_quota.limit <= documents_upload_quota.size: - # The api of file upload is used in the multiple places, - # so we need to check the source of the request from datasets - source = request.args.get("source") or request.form.get("source") - if source == "datasets": - abort(403, "The number of documents has reached the limit of your subscription.") - else: - return view(*args, **kwargs) - elif resource == "workspace_custom" and not features.can_replace_logo: - abort(403, "The workspace custom feature has reached the limit of your subscription.") - elif resource == "annotation" and 0 < annotation_quota_limit.limit < annotation_quota_limit.size: - abort(403, "The annotation quota has reached the limit of your subscription.") + members = features.members + apps = features.apps + documents_upload_quota = features.documents_upload_quota + annotation_quota_limit = features.annotation_quota_limit + if resource == "members" and 0 < members.limit <= members.size: + abort(403, "The number of members has reached the limit of your subscription.") + elif resource == "apps" and 0 < apps.limit <= apps.size: + abort(403, "The number of apps has reached the limit of your subscription.") + elif resource == "documents" and 0 < documents_upload_quota.limit <= documents_upload_quota.size: + # The api of file upload is used in the multiple places, + # so we need to check the source of the request from datasets + source = request.args.get("source") or request.form.get("source") + if source == "datasets": + abort(403, "The number of documents has reached the limit of your subscription.") else: return view(*args, **kwargs) - + elif resource == "workspace_custom" and not features.can_replace_logo: + abort(403, "The workspace custom feature has reached the limit of your subscription.") + elif resource == "annotation" and 0 < annotation_quota_limit.limit < annotation_quota_limit.size: + abort(403, "The annotation quota has reached the limit of your subscription.") return view(*args, **kwargs) return decorated @@ -232,16 +225,15 @@ def cloud_edition_billing_knowledge_limit_check[**P, R]( @wraps(view) def decorated(*args: P.args, **kwargs: P.kwargs): _, current_tenant_id = current_account_with_tenant() + if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD or resource != "add_segment": + return view(*args, **kwargs) + features = FeatureService.get_features(current_tenant_id, exclude_vector_space=True) - if features.billing.enabled: - if resource == "add_segment": - if features.billing.subscription.plan == CloudPlan.SANDBOX: - abort( - 403, - "To unlock this feature and elevate your Dify experience, please upgrade to a paid plan.", - ) - else: - return view(*args, **kwargs) + if features.billing.subscription.plan == CloudPlan.SANDBOX: + abort( + 403, + "To unlock this feature and elevate your Dify experience, please upgrade to a paid plan.", + ) return view(*args, **kwargs) diff --git a/api/controllers/files/__init__.py b/api/controllers/files/__init__.py index 42b3761b92d..6b4b409d33c 100644 --- a/api/controllers/files/__init__.py +++ b/api/controllers/files/__init__.py @@ -14,7 +14,7 @@ api = ExternalApi( files_ns = Namespace("files", description="File operations", path="/") -from . import appdeploy_files, image_preview, tool_files, upload +from . import appdeploy_files, plugin_file_upload, tool_files, upload_file_delivery api.add_namespace(files_ns) @@ -23,7 +23,7 @@ __all__ = [ "appdeploy_files", "bp", "files_ns", - "image_preview", + "plugin_file_upload", "tool_files", - "upload", + "upload_file_delivery", ] diff --git a/api/controllers/files/plugin_file_upload.py b/api/controllers/files/plugin_file_upload.py new file mode 100644 index 00000000000..6ef5ba3d3f2 --- /dev/null +++ b/api/controllers/files/plugin_file_upload.py @@ -0,0 +1,113 @@ +"""Signed plugin file upload endpoint.""" + +from typing import Literal + +from flask import request +from flask_restx import Resource +from flask_restx.api import HTTPStatus +from pydantic import BaseModel, Field + +from controllers.common.errors import ( + FilenameNotExistsError, + FileTooLargeError, + NoFileUploadedError, + UnsupportedFileTypeError, +) +from controllers.common.schema import ( + JsonResponseWithStatus, + query_params_from_model, + register_response_schema_models, + register_schema_models, +) +from controllers.console.wraps import setup_required +from controllers.files import files_ns +from extensions.ext_application_services import application_services +from fields.file_fields import FileResponse +from libs.exception import BaseHTTPException +from libs.helper import dump_response +from services.errors.file import FileTooLargeError as ServiceFileTooLargeError +from services.errors.file import UnsupportedFileTypeError as ServiceUnsupportedFileTypeError +from services.plugin_file_upload_service import PluginFileUploadAccessDeniedError + + +class PluginUploadQuery(BaseModel): + timestamp: str = Field(..., description="Unix timestamp for signature verification") + nonce: str = Field(..., description="Random nonce for signature verification") + sign: str = Field(..., description="HMAC signature") + tenant_id: str = Field(..., description="Tenant identifier") + user_id: str = Field(..., description="User identifier") + user_from: Literal["account", "end-user"] | None = Field(default=None, description="User identity type") + conversation_id: str | None = Field(default=None, description="Conversation identifier") + max_size: int | None = Field(default=None, ge=0, description="Signed maximum file size in bytes") + + +class InvalidPluginFileUploadError(BaseHTTPException): + error_code = "invalid_plugin_file_upload" + description = "The plugin file upload request is invalid or expired." + code = HTTPStatus.FORBIDDEN + + +_PLUGIN_UPLOAD_PARAMS = { + **query_params_from_model(PluginUploadQuery), + "file": { + "description": "File to upload for plugin usage.", + "in": "formData", + "type": "file", + "required": True, + }, +} + + +register_schema_models(files_ns, PluginUploadQuery) +register_response_schema_models(files_ns, FileResponse) + + +@files_ns.route("/upload/for-plugin") +class PluginUploadFileApi(Resource): + @setup_required + @files_ns.doc("upload_plugin_file") + @files_ns.doc( + description="Upload a file for plugin usage with signature verification", + consumes=["multipart/form-data"], + params=_PLUGIN_UPLOAD_PARAMS, + responses={ + 201: "File uploaded successfully", + 400: "Invalid query parameters, no file was uploaded, or the file has no name", + 403: "The signed upload request is invalid or expired", + 413: "File too large", + 415: "Unsupported file type", + }, + ) + @files_ns.response(HTTPStatus.CREATED, "File uploaded", files_ns.models[FileResponse.__name__]) + def post(self) -> JsonResponseWithStatus: + args = PluginUploadQuery.model_validate(request.args.to_dict(flat=True)) + file = request.files.get("file") + if file is None: + raise NoFileUploadedError() + if not file.filename: + raise FilenameNotExistsError() + if not file.mimetype: + raise UnsupportedFileTypeError() + + try: + result = application_services().plugin_file_uploads.upload( + stream=file.stream, + filename=file.filename, + mimetype=file.mimetype, + tenant_id=args.tenant_id, + user_id=args.user_id, + user_from=args.user_from, + conversation_id=args.conversation_id, + timestamp=args.timestamp, + nonce=args.nonce, + sign=args.sign, + max_size=args.max_size, + ) + except PluginFileUploadAccessDeniedError as error: + raise InvalidPluginFileUploadError() from error + except ServiceFileTooLargeError as error: + raise FileTooLargeError(error.description) from error + except ServiceUnsupportedFileTypeError as error: + raise UnsupportedFileTypeError() from error + + return dump_response(FileResponse, result), HTTPStatus.CREATED diff --git a/api/controllers/files/tool_files.py b/api/controllers/files/tool_files.py index 03f635627de..ce20480bbd6 100644 --- a/api/controllers/files/tool_files.py +++ b/api/controllers/files/tool_files.py @@ -6,12 +6,14 @@ from flask_restx import Resource from pydantic import BaseModel, Field from werkzeug.exceptions import Forbidden, NotFound -from controllers.common.errors import UnsupportedFileTypeError from controllers.common.file_response import enforce_download_for_html -from controllers.common.schema import register_schema_models +from controllers.common.schema import query_params_from_model, register_schema_models from controllers.files import files_ns -from core.tools.signature import verify_tool_file_signature -from core.tools.tool_file_manager import ToolFileManager +from extensions.ext_application_services import application_services +from services.tool_file_download_service import ( + ToolFileDownloadAccessDeniedError, + ToolFileDownloadNotFoundError, +) class ToolFileQuery(BaseModel): @@ -32,10 +34,7 @@ class ToolFileApi(Resource): params={ "file_id": "Tool file identifier", "extension": "Expected file extension", - "timestamp": "Unix timestamp used in the signature", - "nonce": "Random string used in the signature", - "sign": "HMAC signature verifying the request", - "as_attachment": "Whether to download the file as an attachment", + **query_params_from_model(ToolFileQuery), } ) @files_ns.doc( @@ -43,52 +42,38 @@ class ToolFileApi(Resource): 200: "Tool file stream returned successfully", 403: "Forbidden - invalid signature", 404: "File not found", - 415: "Unsupported file type", } ) - def get(self, file_id: UUID, extension: str): - file_id_str = str(file_id) - - args = ToolFileQuery.model_validate(request.args.to_dict()) - if not verify_tool_file_signature( - file_id=file_id_str, timestamp=args.timestamp, nonce=args.nonce, sign=args.sign - ): - raise Forbidden("Invalid request.") - + def get(self, file_id: UUID, extension: str) -> Response: + args = ToolFileQuery.model_validate(request.args.to_dict(flat=True)) try: - tool_file_manager = ToolFileManager() - stream, tool_file = tool_file_manager.get_file_generator_by_tool_file_id( - file_id_str, + download = application_services().tool_file_downloads.get_signed_file( + file_id=str(file_id), + timestamp=args.timestamp, + nonce=args.nonce, + sign=args.sign, ) - - if not stream or not tool_file: - raise NotFound("file is not found") - - except NotFound: - raise - - except Exception as e: - raise UnsupportedFileTypeError() from e - - mime_type = tool_file.mime_type - filename = tool_file.filename + except ToolFileDownloadAccessDeniedError as error: + raise Forbidden("Invalid request.") from error + except ToolFileDownloadNotFoundError as error: + raise NotFound("file is not found") from error response = Response( - stream, - mimetype=mime_type, + download.content, + mimetype=download.mime_type, direct_passthrough=True, headers={}, ) - if tool_file.size > 0: - response.headers["Content-Length"] = str(tool_file.size) - if args.as_attachment and filename: - encoded_filename = quote(filename) + if download.size > 0: + response.headers["Content-Length"] = str(download.size) + if args.as_attachment and download.filename: + encoded_filename = quote(download.filename) response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}" enforce_download_for_html( response, - mime_type=mime_type, - filename=filename, + mime_type=download.mime_type, + filename=download.filename, extension=extension, ) diff --git a/api/controllers/files/upload.py b/api/controllers/files/upload.py deleted file mode 100644 index 1da0d720be3..00000000000 --- a/api/controllers/files/upload.py +++ /dev/null @@ -1,162 +0,0 @@ -from typing import Literal - -from flask import request -from flask_restx import Resource -from flask_restx.api import HTTPStatus -from pydantic import BaseModel, Field -from werkzeug.exceptions import Forbidden - -import services -from core.db.session_factory import session_factory -from core.tools.signature import sign_tool_file, verify_plugin_file_signature -from core.tools.tool_file_manager import ToolFileManager, resolve_extension -from core.workflow.file_reference import build_file_reference -from fields.file_fields import FileResponse -from services.account_service import TenantService - -from ..common.errors import ( - FileTooLargeError, - UnsupportedFileTypeError, -) -from ..common.schema import register_schema_models -from ..console.wraps import setup_required -from ..files import files_ns -from ..inner_api.plugin.wraps import get_user - - -class PluginUploadQuery(BaseModel): - timestamp: str = Field(..., description="Unix timestamp for signature verification") - nonce: str = Field(..., description="Random nonce for signature verification") - sign: str = Field(..., description="HMAC signature") - tenant_id: str = Field(..., description="Tenant identifier") - user_id: str | None = Field(default=None, description="User identifier") - user_from: Literal["account", "end-user"] | None = Field(default=None, description="User identity type") - conversation_id: str | None = Field(default=None, description="Conversation identifier") - max_size: int | None = Field(default=None, ge=0, description="Signed maximum file size in bytes") - - -register_schema_models(files_ns, PluginUploadQuery) - - -register_schema_models(files_ns, FileResponse) - - -@files_ns.route("/upload/for-plugin") -class PluginUploadFileApi(Resource): - @setup_required - @files_ns.expect(files_ns.models[PluginUploadQuery.__name__]) - @files_ns.doc("upload_plugin_file") - @files_ns.doc(description="Upload a file for plugin usage with signature verification") - @files_ns.doc( - responses={ - 201: "File uploaded successfully", - 400: "Invalid request parameters", - 403: "Forbidden - Invalid signature or missing parameters", - 413: "File too large", - 415: "Unsupported file type", - } - ) - @files_ns.response(HTTPStatus.CREATED, "File uploaded", files_ns.models[FileResponse.__name__]) - def post(self): - """Upload a file for plugin usage. - - Accepts a file upload with signature verification for security. - The file must be accompanied by valid timestamp, nonce, and signature parameters. - - Returns: - dict: File metadata including ID, canonical ``reference`` for - output-file reconstruction, URLs, and properties - int: HTTP status code (201 for success) - - Raises: - Forbidden: Invalid signature or missing required parameters - FileTooLargeError: File exceeds size limit - UnsupportedFileTypeError: File type not supported - """ - args = PluginUploadQuery.model_validate(request.args.to_dict(flat=True)) - - file = request.files.get("file") - if file is None: - raise Forbidden("File is required.") - - timestamp = args.timestamp - nonce = args.nonce - sign = args.sign - tenant_id = args.tenant_id - if args.user_from == "account": - if args.user_id is None: - raise Forbidden("Invalid request.") - with session_factory.create_session() as session: - is_tenant_member = TenantService.account_belongs_to_tenant( - args.user_id, - tenant_id, - session=session, - ) - if not is_tenant_member: - raise Forbidden("Invalid request.") - owner_id = args.user_id - else: - owner_id = get_user(tenant_id, args.user_id).id - - filename = file.filename - mimetype = file.mimetype - - if not filename or not mimetype: - raise Forbidden("Invalid request.") - - if not verify_plugin_file_signature( - filename=filename, - mimetype=mimetype, - tenant_id=tenant_id, - user_id=owner_id, - conversation_id=args.conversation_id, - user_from=args.user_from, - timestamp=timestamp, - nonce=nonce, - sign=sign, - max_size=args.max_size, - ): - raise Forbidden("Invalid request.") - - try: - if args.max_size is None: - file_binary = file.stream.read() - else: - file_binary = file.stream.read(args.max_size + 1) - if len(file_binary) > args.max_size: - raise FileTooLargeError("File size exceeds the signed upload limit.") - - tool_file = ToolFileManager().create_file_by_raw( - user_id=owner_id, - tenant_id=tenant_id, - file_binary=file_binary, - mimetype=mimetype, - filename=filename, - conversation_id=args.conversation_id, - ) - - extension = resolve_extension(filename=tool_file.name, mimetype=tool_file.mimetype) - preview_url = sign_tool_file(tool_file_id=tool_file.id, extension=extension, for_external=True) - - # Create a dictionary with all the necessary attributes - result = FileResponse( - id=tool_file.id, - reference=build_file_reference(record_id=tool_file.id), - name=tool_file.name, - size=tool_file.size, - extension=extension, - mime_type=mimetype, - preview_url=preview_url, - source_url=tool_file.original_url, - original_url=tool_file.original_url, - user_id=tool_file.user_id, - tenant_id=tool_file.tenant_id, - conversation_id=tool_file.conversation_id, - file_key=tool_file.file_key, - ) - - return result.model_dump(mode="json"), 201 - except services.errors.file.FileTooLargeError as file_too_large_error: - raise FileTooLargeError(file_too_large_error.description) - except services.errors.file.UnsupportedFileTypeError: - raise UnsupportedFileTypeError() diff --git a/api/controllers/files/image_preview.py b/api/controllers/files/upload_file_delivery.py similarity index 52% rename from api/controllers/files/image_preview.py rename to api/controllers/files/upload_file_delivery.py index e27cf79abe1..044e2c1a8fa 100644 --- a/api/controllers/files/image_preview.py +++ b/api/controllers/files/upload_file_delivery.py @@ -7,14 +7,16 @@ from flask_restx import Resource from pydantic import BaseModel, Field from werkzeug.exceptions import NotFound -import services from controllers.common.errors import UnsupportedFileTypeError from controllers.common.file_response import enforce_download_for_html -from controllers.common.schema import register_schema_models +from controllers.common.schema import query_params_from_model, register_schema_models from controllers.files import files_ns -from extensions.ext_database import db -from services.account_service import TenantService -from services.file_service import FileService +from extensions.ext_application_services import application_services +from services.errors.file import UnsupportedFileTypeError as UnsupportedFileTypeServiceError +from services.upload_file_delivery_service import ( + UploadFileDelivery, + UploadFileDeliveryNotFoundError, +) class FileSignatureQuery(BaseModel): @@ -29,6 +31,21 @@ class FilePreviewQuery(FileSignatureQuery): register_schema_models(files_ns, FileSignatureQuery, FilePreviewQuery) +_RANGE_MEDIA_TYPES = frozenset( + { + "audio/aac", + "audio/flac", + "audio/mp4", + "audio/mpeg", + "audio/ogg", + "audio/wav", + "audio/x-m4a", + "video/mp4", + "video/quicktime", + "video/webm", + } +) + def _is_svg_content(mime_type: str | None, filename: str | None, extension: str | None) -> bool: normalized_mime_type = mime_type.split(";", 1)[0].strip().lower() if mime_type else "" @@ -51,37 +68,32 @@ class ImagePreviewApi(Resource): @files_ns.doc( params={ "file_id": "ID of the file to preview", - "timestamp": "Unix timestamp used in the signature", - "nonce": "Random string used in the signature", - "sign": "HMAC signature verifying the request", + **query_params_from_model(FileSignatureQuery), } ) @files_ns.doc( responses={ 200: "Image preview returned successfully", - 400: "Missing or invalid signature parameters", + 400: "Missing or invalid query parameters", + 404: "File not found or signature is invalid", 415: "Unsupported file type", } ) - def get(self, file_id: UUID): - file_id_str = str(file_id) - + def get(self, file_id: UUID) -> Response: args = FileSignatureQuery.model_validate(request.args.to_dict(flat=True)) - timestamp = args.timestamp - nonce = args.nonce - sign = args.sign - try: - generator, mimetype = FileService(db.engine).get_image_preview( - file_id=file_id_str, - timestamp=timestamp, - nonce=nonce, - sign=sign, + delivery = application_services().upload_file_delivery.get_signed_image_preview( + file_id=str(file_id), + timestamp=args.timestamp, + nonce=args.nonce, + sign=args.sign, ) - except services.errors.file.UnsupportedFileTypeError: - raise UnsupportedFileTypeError() + except UploadFileDeliveryNotFoundError as error: + raise NotFound(str(error) or None) from error + except UnsupportedFileTypeServiceError as error: + raise UnsupportedFileTypeError() from error - return Response(generator, mimetype=mimetype) + return Response(delivery.content, mimetype=delivery.file.mime_type) @files_ns.route("//file-preview") @@ -91,60 +103,42 @@ class FilePreviewApi(Resource): @files_ns.doc( params={ "file_id": "ID of the file to preview", - "timestamp": "Unix timestamp used in the signature", - "nonce": "Random string used in the signature", - "sign": "HMAC signature verifying the request", - "as_attachment": "Whether to download the file as an attachment", + **query_params_from_model(FilePreviewQuery), } ) @files_ns.doc( responses={ 200: "File stream returned successfully", - 400: "Missing or invalid signature parameters", - 404: "File not found", - 415: "Unsupported file type", + 400: "Missing or invalid query parameters", + 404: "File not found or signature is invalid", } ) - def get(self, file_id: UUID): - file_id_str = str(file_id) - + def get(self, file_id: UUID) -> Response: args = FilePreviewQuery.model_validate(request.args.to_dict(flat=True)) try: - generator, upload_file = FileService(db.engine).get_file_generator_by_file_id( - file_id=file_id_str, + delivery = application_services().upload_file_delivery.get_signed_file_preview( + file_id=str(file_id), timestamp=args.timestamp, nonce=args.nonce, sign=args.sign, ) - except services.errors.file.UnsupportedFileTypeError: - raise UnsupportedFileTypeError() + except UploadFileDeliveryNotFoundError as error: + raise NotFound(str(error) or None) from error - response = Response( - generator, - mimetype=upload_file.mime_type, - direct_passthrough=True, - headers={}, - ) - # add Accept-Ranges header for audio/video files - if upload_file.mime_type in [ - "audio/mpeg", - "audio/wav", - "audio/mp4", - "audio/ogg", - "audio/flac", - "audio/aac", - "video/mp4", - "video/webm", - "video/quicktime", - "audio/x-m4a", - ]: + return self._build_response(delivery=delivery, as_attachment=args.as_attachment) + + @staticmethod + def _build_response(*, delivery: UploadFileDelivery, as_attachment: bool) -> Response: + file = delivery.file + response = Response(delivery.content, mimetype=file.mime_type, direct_passthrough=True, headers={}) + if file.mime_type in _RANGE_MEDIA_TYPES: response.headers["Accept-Ranges"] = "bytes" - if upload_file.size > 0: - response.headers["Content-Length"] = str(upload_file.size) - is_svg = _is_svg_content(upload_file.mime_type, upload_file.name, upload_file.extension) - if args.as_attachment or is_svg: - encoded_filename = quote(upload_file.name) + if file.size > 0: + response.headers["Content-Length"] = str(file.size) + is_svg = _is_svg_content(file.mime_type, file.name, file.extension) + if as_attachment or is_svg: + encoded_filename = quote(file.name) response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}" response.headers["Content-Type"] = "application/octet-stream" if is_svg: @@ -152,9 +146,9 @@ class FilePreviewApi(Resource): enforce_download_for_html( response, - mime_type=upload_file.mime_type, - filename=upload_file.name, - extension=upload_file.extension, + mime_type=file.mime_type, + filename=file.name, + extension=file.extension, ) return response @@ -176,20 +170,14 @@ class WorkspaceWebappLogoApi(Resource): 415: "Unsupported file type", } ) - def get(self, workspace_id: UUID): - workspace_id_str = str(workspace_id) - - custom_config = TenantService.get_custom_config(workspace_id_str) - webapp_logo_file_id = custom_config.get("replace_webapp_logo") if custom_config is not None else None - - if not webapp_logo_file_id: - raise NotFound("webapp logo is not found") - + def get(self, workspace_id: UUID) -> Response: try: - generator, mimetype = FileService(db.engine).get_public_image_preview( - webapp_logo_file_id, + delivery = application_services().upload_file_delivery.get_workspace_webapp_logo( + workspace_id=str(workspace_id), ) - except services.errors.file.UnsupportedFileTypeError: - raise UnsupportedFileTypeError() + except UploadFileDeliveryNotFoundError as error: + raise NotFound(str(error) or None) from error + except UnsupportedFileTypeServiceError as error: + raise UnsupportedFileTypeError() from error - return Response(generator, mimetype=mimetype) + return Response(delivery.content, mimetype=delivery.file.mime_type) diff --git a/api/controllers/inner_api/workspace/workspace.py b/api/controllers/inner_api/workspace/workspace.py index e70a517b356..b1d5f82ed9b 100644 --- a/api/controllers/inner_api/workspace/workspace.py +++ b/api/controllers/inner_api/workspace/workspace.py @@ -5,7 +5,7 @@ from pydantic import BaseModel from sqlalchemy import select from controllers.common.schema import register_schema_models -from controllers.console.wraps import setup_required +from controllers.console.wraps import model_validate, setup_required from controllers.inner_api import inner_api_ns from controllers.inner_api.wraps import enterprise_inner_api_only from events.tenant_event import tenant_was_created @@ -54,9 +54,8 @@ class EnterpriseWorkspace(Resource): 404: "Owner account not found or service not available", } ) - def post(self): - args = WorkspaceCreatePayload.model_validate(inner_api_ns.payload or {}) - + @model_validate(WorkspaceCreatePayload) + def post(self, args: WorkspaceCreatePayload): account = db.session.scalar(select(Account).where(Account.email == args.owner_email).limit(1)) if account is None: return {"message": "owner account not found."}, 404 @@ -97,9 +96,8 @@ class EnterpriseWorkspaceNoOwnerEmail(Resource): 404: "Service not available", } ) - def post(self): - args = WorkspaceOwnerlessPayload.model_validate(inner_api_ns.payload or {}) - + @model_validate(WorkspaceOwnerlessPayload) + def post(self, args: WorkspaceOwnerlessPayload): tenant = TenantService.create_tenant(args.name, is_from_dashboard=True, session=db.session()) tenant_was_created.send(tenant) @@ -136,9 +134,8 @@ class EnterpriseWorkspaceMember(Resource): 404: "Workspace or account not found", } ) - def post(self): - args = WorkspaceMemberPayload.model_validate(inner_api_ns.payload or {}) - + @model_validate(WorkspaceMemberPayload) + def post(self, args: WorkspaceMemberPayload): try: role = TenantAccountRole(args.role) except ValueError: diff --git a/api/controllers/openapi/app_dsl.py b/api/controllers/openapi/app_dsl.py index 5d036580654..0978c2c628f 100644 --- a/api/controllers/openapi/app_dsl.py +++ b/api/controllers/openapi/app_dsl.py @@ -6,12 +6,12 @@ from flask_restx import Resource from sqlalchemy.orm import Session from werkzeug.exceptions import Forbidden -from controllers.common.wraps import RBACPermission, RBACResourceScope +from controllers.common.rbac import PlainApp, RBACCheck, RBACPermission, Workspace from controllers.openapi import openapi_ns from controllers.openapi._contract import accepts, returns from controllers.openapi._models import AppDslExportQuery, AppDslExportResponse, AppDslImportPayload from controllers.openapi.auth.composition import auth_router -from controllers.openapi.auth.data import AuthData, RBACRequirement +from controllers.openapi.auth.data import AuthData from extensions.ext_database import db from libs.oauth_bearer import Scope, TokenType from models import Account, App @@ -40,11 +40,7 @@ class AppDslImportApi(Resource): scope=Scope.WORKSPACE_WRITE, allowed_token_types=frozenset({TokenType.OAUTH_ACCOUNT}), allowed_roles=frozenset({TenantAccountRole.EDITOR, TenantAccountRole.ADMIN, TenantAccountRole.OWNER}), - rbac=RBACRequirement( - resource_type=RBACResourceScope.APP, - scene=RBACPermission.APP_IMPORT_EXPORT_DSL, - resource_required=False, - ), + rbac=RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, Workspace()), ) @returns(200, Import, "Import completed") @returns(202, Import, "Import pending confirmation") @@ -100,11 +96,7 @@ class AppDslImportConfirmApi(Resource): scope=Scope.WORKSPACE_WRITE, allowed_token_types=frozenset({TokenType.OAUTH_ACCOUNT}), allowed_roles=frozenset({TenantAccountRole.EDITOR, TenantAccountRole.ADMIN, TenantAccountRole.OWNER}), - rbac=RBACRequirement( - resource_type=RBACResourceScope.APP, - scene=RBACPermission.APP_IMPORT_EXPORT_DSL, - resource_required=False, - ), + rbac=RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, Workspace()), ) @returns(200, Import, "Import confirmed") @returns(400, Import, "Import failed") @@ -144,7 +136,7 @@ class AppDslExportApi(Resource): scope=Scope.APPS_READ, allowed_token_types=frozenset({TokenType.OAUTH_ACCOUNT}), allowed_roles=frozenset({TenantAccountRole.EDITOR, TenantAccountRole.ADMIN, TenantAccountRole.OWNER}), - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_IMPORT_EXPORT_DSL), + rbac=RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, PlainApp()), ) @accepts(query=AppDslExportQuery) @returns(200, AppDslExportResponse, "Export successful") @@ -176,7 +168,7 @@ class AppDslCheckDependenciesApi(Resource): scope=Scope.APPS_READ, allowed_token_types=frozenset({TokenType.OAUTH_ACCOUNT}), allowed_roles=frozenset({TenantAccountRole.EDITOR, TenantAccountRole.ADMIN, TenantAccountRole.OWNER}), - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_IMPORT_EXPORT_DSL), + rbac=RBACCheck(RBACPermission.APP_IMPORT_EXPORT_DSL, PlainApp()), ) @returns(200, CheckDependenciesResult, "Dependencies checked") def get(self, app_id: str, *, auth_data: AuthData): diff --git a/api/controllers/openapi/app_run.py b/api/controllers/openapi/app_run.py index 631a750f0ee..e71d3e72bba 100644 --- a/api/controllers/openapi/app_run.py +++ b/api/controllers/openapi/app_run.py @@ -20,14 +20,14 @@ from werkzeug.exceptions import ( import services from controllers.common.fields import EventStreamResponse -from controllers.common.wraps import RBACPermission, RBACResourceScope +from controllers.common.rbac import PlainApp, RBACCheck, RBACPermission from controllers.console.app.wraps import with_session from controllers.openapi import openapi_ns from controllers.openapi._audit import emit_app_run from controllers.openapi._contract import accepts, returns from controllers.openapi._models import AppRunRequest, TaskStopResponse from controllers.openapi.auth.composition import auth_router -from controllers.openapi.auth.data import AuthData, RBACRequirement +from controllers.openapi.auth.data import AuthData from controllers.service_api.app.error import ( AppUnavailableError, CompletionRequestError, @@ -148,7 +148,7 @@ _DISPATCH: dict[AppMode, Callable[[App, Any, AppRunRequest, Session], Any]] = { class AppRunApi(Resource): @auth_router.guard( scope=Scope.APPS_RUN, - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_TEST_AND_RUN), + rbac=RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp()), ) @openapi_ns.response(200, "Run result (SSE stream)", openapi_ns.models[EventStreamResponse.__name__]) @accepts(body=AppRunRequest) @@ -184,7 +184,7 @@ class AppRunApi(Resource): class AppRunTaskStopApi(Resource): @auth_router.guard( scope=Scope.APPS_RUN, - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_TEST_AND_RUN), + rbac=RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp()), ) @returns(200, TaskStopResponse, description="Task stopped") def post(self, app_id: str, task_id: str, *, auth_data: AuthData): diff --git a/api/controllers/openapi/apps.py b/api/controllers/openapi/apps.py index f6dace6fd56..5e1abe27b98 100644 --- a/api/controllers/openapi/apps.py +++ b/api/controllers/openapi/apps.py @@ -12,8 +12,8 @@ from werkzeug.exceptions import Conflict, NotFound, UnprocessableEntity from configs import dify_config from controllers.common.app_access import AppAccessFilter, resolve_app_access_filter from controllers.common.fields import Parameters +from controllers.common.rbac import PlainApp, RBACCheck, RBACPermission from controllers.common.session import with_session -from controllers.common.wraps import RBACPermission, RBACResourceScope from controllers.openapi import openapi_ns from controllers.openapi._contract import accepts, returns from controllers.openapi._input_schema import EMPTY_INPUT_SCHEMA, build_input_schema, resolve_app_config @@ -27,7 +27,7 @@ from controllers.openapi._models import ( AppListRow, ) from controllers.openapi.auth.composition import auth_router -from controllers.openapi.auth.data import AuthData, CallerKind, RBACRequirement +from controllers.openapi.auth.data import AuthData, CallerKind from controllers.service_api.app.error import AppUnavailableError from core.app.app_config.common.parameters_mapping import get_parameters_from_feature_dict from libs.oauth_bearer import Scope, TokenType @@ -135,7 +135,7 @@ class AppDescribeApi(AppReadResource): @auth_router.guard( scope=Scope.APPS_READ, allowed_token_types=frozenset({TokenType.OAUTH_ACCOUNT}), - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_VIEW_LAYOUT), + rbac=RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()), ) @returns(200, AppDescribeResponse, description="App description") @accepts(query=AppDescribeQuery) diff --git a/api/controllers/openapi/auth/data.py b/api/controllers/openapi/auth/data.py index 79d139841aa..ab1d311fb06 100644 --- a/api/controllers/openapi/auth/data.py +++ b/api/controllers/openapi/auth/data.py @@ -6,7 +6,7 @@ from enum import StrEnum from pydantic import BaseModel, ConfigDict, Field from werkzeug.exceptions import InternalServerError -from core.rbac import RBACPermission, RBACResourceScope +from controllers.common.rbac import RBACCheck from libs.oauth_bearer import Scope, TokenType from models.account import Account, Tenant, TenantAccountRole from models.model import App, EndUser @@ -25,23 +25,15 @@ class ExternalIdentity(BaseModel): issuer: str | None = None -class RBACRequirement(BaseModel): - model_config = ConfigDict(frozen=True) - - resource_type: RBACResourceScope - scene: RBACPermission - resource_required: bool = True - - class RequestContext(BaseModel): - model_config = ConfigDict(frozen=True) + model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True) token_type: TokenType scope: Scope | None = None path_params: dict[str, str] workspace_membership: bool = False allowed_roles: frozenset[TenantAccountRole] | None = None - rbac: RBACRequirement | None = None + rbac: RBACCheck | None = None class AuthData(BaseModel): @@ -58,7 +50,7 @@ class AuthData(BaseModel): path_params: dict[str, str] = Field(default_factory=dict) allowed_roles: frozenset[TenantAccountRole] | None = None - rbac: RBACRequirement | None = None + rbac: RBACCheck | None = None app: App | None = None tenant: Tenant | None = None diff --git a/api/controllers/openapi/auth/pipeline.py b/api/controllers/openapi/auth/pipeline.py index 9f14105a942..12c3c9dce6c 100644 --- a/api/controllers/openapi/auth/pipeline.py +++ b/api/controllers/openapi/auth/pipeline.py @@ -17,11 +17,11 @@ from flask_login import user_logged_in from werkzeug.exceptions import Forbidden, NotFound, Unauthorized from configs import dify_config +from controllers.common.rbac import RBACCheck from controllers.openapi._audit import emit_wrong_surface from controllers.openapi.auth.data import ( AuthData, ExternalIdentity, - RBACRequirement, RequestContext, ) from controllers.openapi.auth.flow import When @@ -61,7 +61,7 @@ class AuthPipeline: scope: Scope | None, workspace_membership: bool = False, allowed_roles: frozenset[TenantAccountRole] | None = None, - rbac: RBACRequirement | None = None, + rbac: RBACCheck | None = None, ) -> Any: req_ctx = RequestContext( token_type=identity.token_type, @@ -135,7 +135,7 @@ class PipelineRouter: require_valid_enterprise_license: bool = False, workspace_membership: bool = False, allowed_roles: frozenset[TenantAccountRole] | None = None, - rbac: RBACRequirement | None = None, + rbac: RBACCheck | None = None, ) -> Callable: return self._make_decorator( scope=scope, @@ -155,7 +155,7 @@ class PipelineRouter: edition: frozenset[DeploymentEdition] | None = None, require_valid_enterprise_license: bool = False, allowed_roles: frozenset[TenantAccountRole] | None = None, - rbac: RBACRequirement | None = None, + rbac: RBACCheck | None = None, ) -> Callable: return self._make_decorator( scope=scope, @@ -176,7 +176,7 @@ class PipelineRouter: require_valid_enterprise_license: bool, workspace_membership: bool, allowed_roles: frozenset[TenantAccountRole] | None, - rbac: RBACRequirement | None, + rbac: RBACCheck | None, ) -> Callable: def decorator(view: Callable) -> Callable: @wraps(view) @@ -210,7 +210,7 @@ class PipelineRouter: require_valid_enterprise_license: bool, workspace_membership: bool = False, allowed_roles: frozenset[TenantAccountRole] | None = None, - rbac: RBACRequirement | None = None, + rbac: RBACCheck | None = None, ) -> Any: # 404 not 403 — this edition doesn't expose the feature at all if edition is not None and dify_config.DEPLOYMENT_EDITION not in edition: diff --git a/api/controllers/openapi/auth/verify.py b/api/controllers/openapi/auth/verify.py index b6ef95e3ea3..7420841a8f3 100644 --- a/api/controllers/openapi/auth/verify.py +++ b/api/controllers/openapi/auth/verify.py @@ -4,7 +4,7 @@ from flask import request from werkzeug.exceptions import Forbidden, NotFound, UnprocessableEntity from configs import dify_config -from controllers.common.wraps import enforce_rbac_access +from controllers.common.rbac import enforce_rbac_checks from controllers.openapi.auth.data import AuthData, CallerKind from extensions.ext_database import db from libs.oauth_bearer import Scope, TokenType @@ -62,12 +62,10 @@ def check_rbac_permission(data: AuthData) -> None: return if data.account_id is None or data.tenant is None: raise Forbidden("rbac context missing") - enforce_rbac_access( + enforce_rbac_checks( tenant_id=str(data.tenant.id), account_id=str(data.account_id), - resource_type=req.resource_type, - scene=req.scene, - resource_required=req.resource_required, + checks=[req], path_args=dict(data.path_params), ) diff --git a/api/controllers/openapi/human_input_form.py b/api/controllers/openapi/human_input_form.py index 593887ffcfc..af3fcb8d85f 100644 --- a/api/controllers/openapi/human_input_form.py +++ b/api/controllers/openapi/human_input_form.py @@ -15,14 +15,14 @@ from flask_restx import Resource from werkzeug.exceptions import BadRequest from controllers.common.human_input import HumanInputFormSubmitPayload, stringify_form_default_values +from controllers.common.rbac import PlainApp, RBACCheck, RBACPermission from controllers.common.schema import register_schema_models -from controllers.common.wraps import RBACPermission, RBACResourceScope from controllers.openapi import openapi_ns from controllers.openapi._contract import accepts, returns from controllers.openapi._errors import HumanInputFormNotFound, RecipientSurfaceMismatch from controllers.openapi._models import FormSubmitResponse, HumanInputFormDefinitionResponse from controllers.openapi.auth.composition import auth_router -from controllers.openapi.auth.data import AuthData, CallerKind, RBACRequirement +from controllers.openapi.auth.data import AuthData, CallerKind from core.workflow.human_input_policy import ( HumanInputSurface, is_recipient_type_allowed_for_surface, @@ -65,7 +65,7 @@ class OpenApiWorkflowHumanInputFormApi(Resource): @openapi_ns.response(200, "Form definition", openapi_ns.models[HumanInputFormDefinitionResponse.__name__]) @auth_router.guard( scope=Scope.APPS_RUN, - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_TEST_AND_RUN), + rbac=RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp()), ) def get(self, app_id: str, form_token: str, *, auth_data: AuthData): app_model, _caller, _caller_kind = auth_data.require_app_context() @@ -84,7 +84,7 @@ class OpenApiWorkflowHumanInputFormApi(Resource): class OpenApiWorkflowHumanInputFormSubmitApi(Resource): @auth_router.guard( scope=Scope.APPS_RUN, - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_TEST_AND_RUN), + rbac=RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp()), ) @returns(200, FormSubmitResponse, description="Form submitted") @accepts(body=HumanInputFormSubmitPayload) diff --git a/api/controllers/openapi/workflow_events.py b/api/controllers/openapi/workflow_events.py index 1a2bef28772..5e54c301fba 100644 --- a/api/controllers/openapi/workflow_events.py +++ b/api/controllers/openapi/workflow_events.py @@ -18,11 +18,11 @@ from sqlalchemy.orm import sessionmaker from werkzeug.exceptions import NotFound, UnprocessableEntity from controllers.common.fields import EventStreamResponse +from controllers.common.rbac import PlainApp, RBACCheck, RBACPermission from controllers.common.schema import query_params_from_model -from controllers.common.wraps import RBACPermission, RBACResourceScope from controllers.openapi import openapi_ns from controllers.openapi.auth.composition import auth_router -from controllers.openapi.auth.data import AuthData, CallerKind, RBACRequirement +from controllers.openapi.auth.data import AuthData, CallerKind from core.app.apps.advanced_chat.app_generator import AdvancedChatAppGenerator from core.app.apps.base_app_generator import BaseAppGenerator from core.app.apps.common.workflow_response_converter import WorkflowResponseConverter @@ -49,7 +49,7 @@ class OpenApiWorkflowEventsApi(Resource): @openapi_ns.response(200, "SSE event stream", openapi_ns.models[EventStreamResponse.__name__]) @auth_router.guard( scope=Scope.APPS_RUN, - rbac=RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_TEST_AND_RUN), + rbac=RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp()), ) def get(self, app_id: str, task_id: str, *, auth_data: AuthData): app_model, caller, caller_kind = auth_data.require_app_context() diff --git a/api/controllers/openapi/workspaces.py b/api/controllers/openapi/workspaces.py index b5fec3bd4ca..6bff0349f78 100644 --- a/api/controllers/openapi/workspaces.py +++ b/api/controllers/openapi/workspaces.py @@ -37,6 +37,7 @@ from controllers.openapi._models import ( ) from controllers.openapi.auth.composition import auth_router from controllers.openapi.auth.data import AuthData +from enums import DeploymentEdition from libs.oauth_bearer import Scope, TokenType from models import Account, Tenant, TenantAccountJoin from models.account import TenantAccountRole, TenantStatus @@ -82,7 +83,7 @@ def _load_account(session: Session, account_id: object) -> Account: def _check_member_invite_quota(tenant_id: str) -> None: features = FeatureService.get_features(tenant_id) - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: members = features.members if 0 < members.limit <= members.size: raise MemberLimitExceeded() diff --git a/api/controllers/service_api/app/annotation.py b/api/controllers/service_api/app/annotation.py index 0b54d133661..9b477e4e5e6 100644 --- a/api/controllers/service_api/app/annotation.py +++ b/api/controllers/service_api/app/annotation.py @@ -150,7 +150,6 @@ class AnnotationReplyActionStatusApi(Resource): responses={ 200: "Job status retrieved successfully", 401: "Unauthorized - invalid API token", - 404: "Job not found", } ) @service_api_ns.response( diff --git a/api/controllers/service_api/app/app.py b/api/controllers/service_api/app/app.py index 8180111a4c1..a08752ba2eb 100644 --- a/api/controllers/service_api/app/app.py +++ b/api/controllers/service_api/app/app.py @@ -60,7 +60,6 @@ class AppParameterApi(Resource): responses={ 200: "Parameters retrieved successfully", 401: "Unauthorized - invalid API token", - 404: "Application not found", } ) @service_api_ns.response(200, "Parameters retrieved successfully", service_api_ns.models[Parameters.__name__]) @@ -88,6 +87,7 @@ class AppMetaApi(Resource): tags=["Applications"], responses={ 200: "Successfully retrieved application meta information.", + 400: "`app_unavailable` : App unavailable or misconfigured.", }, ) @service_api_ns.doc("get_app_meta") @@ -96,7 +96,6 @@ class AppMetaApi(Resource): responses={ 200: "Metadata retrieved successfully", 401: "Unauthorized - invalid API token", - 404: "Application not found", } ) @service_api_ns.response(200, "Metadata retrieved successfully", service_api_ns.models[AppMetaResponse.__name__]) @@ -122,6 +121,7 @@ class AppInfoApi(Resource): tags=["Applications"], responses={ 200: "Basic information of the application.", + 400: "`app_unavailable` : App unavailable or misconfigured.", }, ) @service_api_ns.doc("get_app_info") @@ -130,7 +130,6 @@ class AppInfoApi(Resource): responses={ 200: "Application info retrieved successfully", 401: "Unauthorized - invalid API token", - 404: "Application not found", } ) @service_api_ns.response( diff --git a/api/controllers/service_api/app/completion.py b/api/controllers/service_api/app/completion.py index 50bb033164b..6bd0e2fe8a3 100644 --- a/api/controllers/service_api/app/completion.py +++ b/api/controllers/service_api/app/completion.py @@ -208,7 +208,6 @@ class CompletionApi(Resource): 200: "Completion created successfully", 400: "Bad request - invalid parameters", 401: "Unauthorized - invalid API token", - 404: "Conversation not found", 500: "Internal server error", } ) @@ -399,7 +398,7 @@ class ChatApi(Resource): and dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD ): billing_info = BillingService.get_info(app_model.tenant_id, exclude_vector_space=True) - if billing_info["enabled"] and billing_info["subscription"]["plan"] == CloudPlan.SANDBOX: + if billing_info["subscription"]["plan"] == CloudPlan.SANDBOX: raise WorkflowVersionExecutionNotAllowedError() external_trace_id = get_external_trace_id(request) diff --git a/api/controllers/service_api/app/file_preview.py b/api/controllers/service_api/app/file_preview.py index ad96ac96ce1..561ede3d184 100644 --- a/api/controllers/service_api/app/file_preview.py +++ b/api/controllers/service_api/app/file_preview.py @@ -1,11 +1,9 @@ -import logging from urllib.parse import quote from uuid import UUID from flask import Response from flask_restx import Resource from pydantic import BaseModel, Field -from sqlalchemy import select from controllers.common.fields import BinaryFileResponse from controllers.common.file_response import enforce_download_for_html @@ -18,11 +16,13 @@ from controllers.service_api.app.error import ( ) from controllers.service_api.schema import binary_response from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token -from extensions.ext_database import db -from extensions.ext_storage import storage -from models.model import App, EndUser, Message, MessageFile, UploadFile - -logger = logging.getLogger(__name__) +from extensions.ext_application_services import application_services +from models.model import App, EndUser +from services.message_file_preview_service import ( + MessageFilePreview, + MessageFilePreviewAccessDeniedError, + MessageFilePreviewNotFoundError, +) class FilePreviewQuery(BaseModel): @@ -36,6 +36,20 @@ register_schema_model(service_api_ns, FilePreviewQuery) register_response_schema_model(service_api_ns, BinaryFileResponse) FILE_PREVIEW_RESPONSE_MEDIA_TYPE = "*/*" +_RANGE_MEDIA_TYPES = frozenset( + { + "audio/aac", + "audio/flac", + "audio/mp4", + "audio/mpeg", + "audio/ogg", + "audio/wav", + "audio/x-m4a", + "video/mp4", + "video/quicktime", + "video/webm", + } +) @service_api_ns.route("/files//preview") @@ -88,143 +102,65 @@ class FilePreviewApi(Resource): @service_api_ns.response(200, "File retrieved successfully") @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY)) @model_validate(FilePreviewQuery) - def get(self, args: FilePreviewQuery, app_model: App, end_user: EndUser, file_id: UUID): + def get(self, args: FilePreviewQuery, app_model: App, end_user: EndUser, file_id: UUID) -> Response: """ Preview/Download a file that was uploaded via Service API. Provides secure file preview/download functionality. Files can only be accessed if they belong to messages within the requesting app's context. """ - file_id_str = str(file_id) - - # Validate file ownership and get file objects - _, upload_file = self._validate_file_ownership(file_id_str, app_model.id) - - # Get file content generator try: - generator = storage.load(upload_file.key, stream=True) - except Exception as e: - raise FileNotFoundError(f"Failed to load file content: {str(e)}") - - # Build response with appropriate headers - response = self._build_file_response(generator, upload_file, args.as_attachment) - - return response - - def _validate_file_ownership(self, file_id: str, app_id: str) -> tuple[MessageFile, UploadFile]: - """ - Validate that the file belongs to a message within the requesting app's context - - Security validations performed: - 1. File exists in MessageFile table (was used in a conversation) - 2. Message belongs to the requesting app - 3. UploadFile record exists and is accessible - 4. File tenant matches app tenant (additional security layer) - - Args: - file_id: UUID of the file to validate - app_id: UUID of the requesting app - - Returns: - Tuple of (MessageFile, UploadFile) if validation passes - - Raises: - FileNotFoundError: File or related records not found - FileAccessDeniedError: File does not belong to the app's context - """ - try: - # Input validation - if not file_id or not app_id: - raise FileAccessDeniedError("Invalid file or app identifier") - - # First, find the MessageFile that references this upload file - message_file = db.session.scalar(select(MessageFile).where(MessageFile.upload_file_id == file_id).limit(1)) - - if not message_file: - raise FileNotFoundError("File not found in message context") - - # Get the message and verify it belongs to the requesting app - message = db.session.scalar( - select(Message).where(Message.id == message_file.message_id, Message.app_id == app_id).limit(1) + preview = application_services().message_file_previews.get_preview( + file_id=str(file_id), + app_id=app_model.id, + tenant_id=app_model.tenant_id, ) + except MessageFilePreviewNotFoundError as error: + raise FileNotFoundError() from error + except MessageFilePreviewAccessDeniedError as error: + raise FileAccessDeniedError() from error - if not message: - raise FileAccessDeniedError("File access denied: not owned by requesting app") + return self._build_file_response(preview=preview, as_attachment=args.as_attachment) - # Get the actual upload file record - upload_file = db.session.get(UploadFile, file_id) - - if not upload_file: - raise FileNotFoundError("Upload file record not found") - - # Additional security: verify tenant isolation - app = db.session.get(App, app_id) - if app and upload_file.tenant_id != app.tenant_id: - raise FileAccessDeniedError("File access denied: tenant mismatch") - - return message_file, upload_file - - except (FileNotFoundError, FileAccessDeniedError): - # Re-raise our custom exceptions - raise - except Exception as e: - # Log unexpected errors for debugging - logger.exception( - "Unexpected error during file ownership validation", - extra={"file_id": file_id, "app_id": app_id, "error": str(e)}, - ) - raise FileAccessDeniedError("File access validation failed") - - def _build_file_response(self, generator, upload_file: UploadFile, as_attachment: bool = False) -> Response: + def _build_file_response(self, *, preview: MessageFilePreview, as_attachment: bool = False) -> Response: """ Build Flask Response object with appropriate headers for file streaming Args: - generator: File content generator from storage - upload_file: UploadFile database record + preview: App-scoped file metadata and content stream as_attachment: Whether to set Content-Disposition as attachment Returns: Flask Response object with streaming file content """ + file = preview.file response = Response( - generator, - mimetype=upload_file.mime_type, + preview.content, + mimetype=file.mime_type, direct_passthrough=True, headers={}, ) # Add Content-Length if known - if upload_file.size and upload_file.size > 0: - response.headers["Content-Length"] = str(upload_file.size) + if file.size > 0: + response.headers["Content-Length"] = str(file.size) # Add Accept-Ranges header for audio/video files to support seeking - if upload_file.mime_type in [ - "audio/mpeg", - "audio/wav", - "audio/mp4", - "audio/ogg", - "audio/flac", - "audio/aac", - "video/mp4", - "video/webm", - "video/quicktime", - "audio/x-m4a", - ]: + if file.mime_type in _RANGE_MEDIA_TYPES: response.headers["Accept-Ranges"] = "bytes" # Set Content-Disposition for downloads - if as_attachment and upload_file.name: - encoded_filename = quote(upload_file.name) + if as_attachment and file.name: + encoded_filename = quote(file.name) response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}" # Override content-type for downloads to force download response.headers["Content-Type"] = "application/octet-stream" enforce_download_for_html( response, - mime_type=upload_file.mime_type, - filename=upload_file.name, - extension=upload_file.extension, + mime_type=file.mime_type, + filename=file.name, + extension=file.extension, ) # Add caching headers for performance diff --git a/api/controllers/service_api/app/workflow.py b/api/controllers/service_api/app/workflow.py index d40438e6fa3..b3308c76c46 100644 --- a/api/controllers/service_api/app/workflow.py +++ b/api/controllers/service_api/app/workflow.py @@ -315,7 +315,8 @@ class WorkflowRunApi(Resource): ), 429: ( "- `too_many_requests` : Too many concurrent requests for this app.\n" - "- `rate_limit_error` : The upstream model provider rate limit was exceeded." + "- `rate_limit_error` : The upstream model provider rate limit or the Dify Cloud workflow execution " + "quota was exceeded." ), 500: "`internal_server_error` : Internal server error.", }, @@ -329,7 +330,6 @@ class WorkflowRunApi(Resource): 200: "Workflow executed successfully", 400: "Bad request - invalid parameters or workflow issues", 401: "Unauthorized - invalid API token", - 404: "Workflow not found", 429: "Rate limit exceeded", 500: "Internal server error", } @@ -430,7 +430,8 @@ class WorkflowRunByIdApi(Resource): 404: "`not_found` : Workflow not found.", 429: ( "- `too_many_requests` : Too many concurrent requests for this app.\n" - "- `rate_limit_error` : The upstream model provider rate limit was exceeded." + "- `rate_limit_error` : The upstream model provider rate limit or the Dify Cloud workflow execution " + "quota was exceeded." ), 500: "`internal_server_error` : Internal server error.", }, @@ -476,7 +477,7 @@ class WorkflowRunByIdApi(Resource): if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: billing_info = BillingService.get_info(app_model.tenant_id, exclude_vector_space=True) - if billing_info["enabled"] and billing_info["subscription"]["plan"] == CloudPlan.SANDBOX: + if billing_info["subscription"]["plan"] == CloudPlan.SANDBOX: raise WorkflowVersionExecutionNotAllowedError() payload = WorkflowRunPayload.model_validate(omit_trace_session_id_from_payload(service_api_ns.payload) or {}) diff --git a/api/controllers/service_api/dataset/dataset.py b/api/controllers/service_api/dataset/dataset.py index 32035f539b1..13379b1e5cf 100644 --- a/api/controllers/service_api/dataset/dataset.py +++ b/api/controllers/service_api/dataset/dataset.py @@ -35,7 +35,8 @@ from controllers.service_api.wraps import ( from core.plugin.impl.model_runtime_factory import create_plugin_provider_manager from core.rag.index_processor.constant.index_type import IndexTechniqueType from fields.base import ResponseModel -from fields.dataset_fields import DatasetDetailResponse, dataset_detail_response_source +from fields.dataset_fields import DatasetDetailResponse as BaseDatasetDetailResponse +from fields.dataset_fields import dataset_detail_response_source from graphon.model_runtime.entities.model_entities import ModelType from libs.helper import dump_response from libs.login import current_user @@ -88,6 +89,11 @@ PartialMemberList = Annotated[ ] +class DatasetDetailResponse(BaseDatasetDetailResponse): + # The Service API dump helpers exclude Console permission metadata. + permission_keys: list[str] = Field(default_factory=list, exclude=True) + + _SERVICE_DATASET_DETAIL_EXCLUDE = {"permission_keys"} _SERVICE_DATASET_LIST_EXCLUDE = {"data": {"__all__": _SERVICE_DATASET_DETAIL_EXCLUDE}} @@ -738,18 +744,11 @@ class DatasetApi(DatasetApiResource): @service_api_ns.doc( summary="Delete Knowledge Base", - description=( - "Permanently delete a knowledge base and all its documents. The knowledge base must not be " - "in use by any application." - ), + description="Permanently delete a knowledge base and all its documents.", tags=["Knowledge Bases"], responses={ 204: "Success.", 404: "`not_found` : Dataset not found.", - 409: ( - "`dataset_in_use` : The knowledge base is being used by some apps. Please remove it from the " - "apps before deleting." - ), }, ) @service_api_ns.doc("delete_dataset") @@ -760,7 +759,6 @@ class DatasetApi(DatasetApiResource): 204: "Dataset deleted successfully", 401: "Unauthorized - invalid API token", 404: "Dataset not found", - 409: "Conflict - dataset is in use", } ) @cloud_edition_billing_rate_limit_check("knowledge", "dataset") diff --git a/api/controllers/service_api/dataset/document.py b/api/controllers/service_api/dataset/document.py index a2288a99c43..37170840c93 100644 --- a/api/controllers/service_api/dataset/document.py +++ b/api/controllers/service_api/dataset/document.py @@ -211,7 +211,11 @@ def _non_null_property_schema(property_schema: object) -> dict[str, Any]: ] if len(non_null_candidates) == 1: return { - **{key: value for key, value in property_schema.items() if key != "anyOf"}, + **{ + key: value + for key, value in property_schema.items() + if key != "anyOf" and not (key == "default" and value is None) + }, **deepcopy(non_null_candidates[0]), } @@ -246,7 +250,7 @@ class DocumentGetQuery(BaseModel): default="all", description=( "`all` returns all fields including metadata. `only` returns only `id`, `doc_type`, and " - "`doc_metadata`. `without` returns all fields except `doc_metadata`." + "`doc_metadata`. `without` returns all fields except `doc_type` and `doc_metadata`." ), ) @@ -305,39 +309,53 @@ def _document_and_batch_response(document: Document, batch: str, *, session: Ses ) -# Use SkipJsonSchema to support 3 metadata modes +def _omit_schema_default(schema: dict[str, Any]) -> None: + """Keep omission placeholders out of the public non-null field contract.""" + schema.pop("default", None) + + +# These fields are absent in metadata=only responses. None is an internal +# validation default, not a value returned for these fields when present. class DocumentDetailResponse(ResponseModel): id: str - position: int | SkipJsonSchema[None] = None - data_source_type: str | SkipJsonSchema[None] = None - data_source_info: dict[str, Any] | SkipJsonSchema[None] = None + position: int | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) + data_source_type: str | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) + data_source_info: dict[str, Any] | SkipJsonSchema[None] = Field( + default=None, json_schema_extra=_omit_schema_default + ) dataset_process_rule_id: str | None = None - dataset_process_rule: dict[str, Any] | SkipJsonSchema[None] = None - document_process_rule: dict[str, Any] | SkipJsonSchema[None] = None - name: str | SkipJsonSchema[None] = None - created_from: str | SkipJsonSchema[None] = None - created_by: str | SkipJsonSchema[None] = None - created_at: int | SkipJsonSchema[None] = None + dataset_process_rule: dict[str, Any] | SkipJsonSchema[None] = Field( + default=None, json_schema_extra=_omit_schema_default + ) + document_process_rule: dict[str, Any] | SkipJsonSchema[None] = Field( + default=None, json_schema_extra=_omit_schema_default + ) + name: str | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) + created_from: str | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) + created_by: str | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) + created_at: int | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) tokens: int | None = None - indexing_status: str | SkipJsonSchema[None] = None + indexing_status: str | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) completed_at: int | None = None updated_at: int | None = None indexing_latency: float | None = None error: str | None = None - enabled: bool | SkipJsonSchema[None] = None + enabled: bool | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) disabled_at: int | None = None disabled_by: str | None = None - archived: bool | SkipJsonSchema[None] = None + archived: bool | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) doc_type: str | None = None doc_metadata: list[DocumentMetadataResponse] | dict[str, Any] | None = None - segment_count: int | SkipJsonSchema[None] = None - average_segment_length: int | float | SkipJsonSchema[None] = None - hit_count: int | SkipJsonSchema[None] = None + segment_count: int | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) + average_segment_length: int | float | SkipJsonSchema[None] = Field( + default=None, json_schema_extra=_omit_schema_default + ) + hit_count: int | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) display_status: str | None = None - doc_form: str | SkipJsonSchema[None] = None + doc_form: str | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) doc_language: str | None = None summary_index_status: str | None = None - need_summary: bool | SkipJsonSchema[None] = None + need_summary: bool | SkipJsonSchema[None] = Field(default=None, json_schema_extra=_omit_schema_default) @field_validator("data_source_type", "indexing_status", "display_status", "doc_form", mode="before") @classmethod @@ -1452,7 +1470,6 @@ class DocumentApi(DatasetApiResource): tags=["Documents"], responses={ 204: "Success.", - 400: "`document_indexing` : Cannot delete document during indexing.", 403: "`archived_document_immutable` : The archived document is not editable.", 404: "`not_found` : Document Not Exists.", }, diff --git a/api/controllers/service_api/schema.py b/api/controllers/service_api/schema.py index 393456c0e69..b42ea1c8d7f 100644 --- a/api/controllers/service_api/schema.py +++ b/api/controllers/service_api/schema.py @@ -16,8 +16,8 @@ from pydantic import BaseModel, WithJsonSchema from libs.flask_restx_compat import BINARY_RESPONSE_MEDIA_TYPES_VENDOR_KEY USER_DESCRIPTION = ( - "User identifier, unique within the application. This identifier scopes data access; resources created with " - "one `user` value are only visible when queried with the same `user` value." + "End-user identifier, defined by your app and unique within it. Identifies the end user for this request. " + "See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules." ) SCOPED_TASK_STOP_USER_DESCRIPTION = ( "End-user identifier, defined by your app and unique within it. Send the same `user` value used for the original " diff --git a/api/controllers/service_api/wraps.py b/api/controllers/service_api/wraps.py index 9d29d498a33..77201f96f0c 100644 --- a/api/controllers/service_api/wraps.py +++ b/api/controllers/service_api/wraps.py @@ -194,14 +194,14 @@ def cloud_edition_billing_resource_check[**P, R]( @wraps(view) def decorated(*args: P.args, **kwargs: P.kwargs): api_token = validate_and_get_api_token(api_token_type) - if resource == "vector_space": - if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD: - return view(*args, **kwargs) + if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD: + return view(*args, **kwargs) + if resource == "vector_space": vector_space = application_services().feature_queries.get_workspace_vector_space(api_token.tenant_id) if vector_space.usage_unknown: features = FeatureService.get_features(api_token.tenant_id, exclude_vector_space=True) - if features.billing.enabled and features.billing.subscription.plan == CloudPlan.SANDBOX: + if features.billing.subscription.plan == CloudPlan.SANDBOX: raise ServiceUnavailable( "Unable to verify vector space usage right now. Please try again later." ) @@ -211,20 +211,16 @@ def cloud_edition_billing_resource_check[**P, R]( features = FeatureService.get_features(api_token.tenant_id, exclude_vector_space=True) - if features.billing.enabled: - members = features.members - apps = features.apps - documents_upload_quota = features.documents_upload_quota - - if resource == "members" and 0 < members.limit <= members.size: - raise Forbidden("The number of members has reached the limit of your subscription.") - elif resource == "apps" and 0 < apps.limit <= apps.size: - raise Forbidden("The number of apps has reached the limit of your subscription.") - elif resource == "documents" and 0 < documents_upload_quota.limit <= documents_upload_quota.size: - raise Forbidden("The number of documents has reached the limit of your subscription.") - else: - return view(*args, **kwargs) + members = features.members + apps = features.apps + documents_upload_quota = features.documents_upload_quota + if resource == "members" and 0 < members.limit <= members.size: + raise Forbidden("The number of members has reached the limit of your subscription.") + elif resource == "apps" and 0 < apps.limit <= apps.size: + raise Forbidden("The number of apps has reached the limit of your subscription.") + elif resource == "documents" and 0 < documents_upload_quota.limit <= documents_upload_quota.size: + raise Forbidden("The number of documents has reached the limit of your subscription.") return view(*args, **kwargs) if resource == "vector_space": @@ -245,15 +241,14 @@ def cloud_edition_billing_knowledge_limit_check[**P, R]( @wraps(view) def decorated(*args: P.args, **kwargs: P.kwargs): api_token = validate_and_get_api_token(api_token_type) + if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD or resource != "add_segment": + return view(*args, **kwargs) + features = FeatureService.get_features(api_token.tenant_id, exclude_vector_space=True) - if features.billing.enabled: - if resource == "add_segment": - if features.billing.subscription.plan == CloudPlan.SANDBOX: - raise Forbidden( - "To unlock this feature and elevate your Dify experience, please upgrade to a paid plan." - ) - else: - return view(*args, **kwargs) + if features.billing.subscription.plan == CloudPlan.SANDBOX: + raise Forbidden( + "To unlock this feature and elevate your Dify experience, please upgrade to a paid plan." + ) return view(*args, **kwargs) diff --git a/api/controllers/web/human_input_file_upload.py b/api/controllers/web/human_input_file_upload.py index dcddec8f35b..6b00b60c484 100644 --- a/api/controllers/web/human_input_file_upload.py +++ b/api/controllers/web/human_input_file_upload.py @@ -6,37 +6,50 @@ remote URLs. The caller always submits a multipart form: when a non-empty falls back to the local file upload flow. """ -import httpx +from typing import Any + from flask import request from flask_restx import Resource from pydantic import BaseModel, ConfigDict, Field, HttpUrl -from sqlalchemy.orm import sessionmaker +from werkzeug.datastructures import FileStorage import services from controllers.common.errors import ( BlockedFileExtensionError, + FilenameNotExistsError, FileTooLargeError, NoFileUploadedError, - RemoteFileUploadError, + RemoteFileAccessDeniedError, + RemoteFileInvalidResponseError, + RemoteFileInvalidUrlError, + RemoteFileNotFoundError, + RemoteFileUnavailableError, + RemoteFileUrlBlockedError, TooManyFilesError, UnsupportedFileTypeError, ) -from controllers.common.schema import register_schema_models +from controllers.common.schema import JsonResponseWithStatus, register_schema_models from controllers.web import web_ns -from core.file.remote_file_metadata import guess_file_info_from_response -from core.helper import ssrf_proxy -from extensions.ext_database import db +from extensions.ext_application_services import application_services from fields.file_fields import FileResponse, FileWithSignedUrl -from graphon.file import helpers as file_helpers from libs.exception import BaseHTTPException from libs.helper import dump_response -from repositories.factory import DifyAPIRepositoryFactory -from services.file_service import FileService from services.human_input_file_upload_service import ( HITL_UPLOAD_TOKEN_PREFIX, HumanInputFileUploadService, + HumanInputUploadContext, InvalidUploadTokenError, ) +from services.remote_file_service import ( + RemoteFileAccessDeniedError as RemoteFileAccessDeniedServiceError, +) +from services.remote_file_service import ( + RemoteFileInvalidResponseError as RemoteFileInvalidResponseServiceError, +) +from services.remote_file_service import RemoteFileInvalidUrlError as RemoteFileInvalidUrlServiceError +from services.remote_file_service import RemoteFileNotFoundError as RemoteFileNotFoundServiceError +from services.remote_file_service import RemoteFileUnavailableError as RemoteFileUnavailableServiceError +from services.remote_file_service import RemoteFileUrlBlockedError as RemoteFileUrlBlockedServiceError class InvalidUploadTokenBadRequestError(BaseHTTPException): @@ -68,15 +81,6 @@ class HumanInputFileUploadFormPayload(BaseModel): register_schema_models(web_ns, HumanInputFileUploadFormPayload, FileResponse, FileWithSignedUrl) -def _create_upload_service() -> HumanInputFileUploadService: - session_factory = sessionmaker(bind=db.engine) - workflow_run_repository = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_factory) - return HumanInputFileUploadService( - session_factory=session_factory, - workflow_run_repository=workflow_run_repository, - ) - - def _extract_hitl_upload_token() -> str: """Read HITL upload token from Authorization without invoking other bearer auth chains.""" @@ -98,14 +102,14 @@ def _extract_hitl_upload_token() -> str: return token -def _validate_context(service: HumanInputFileUploadService, token: str): +def _validate_context(service: HumanInputFileUploadService, token: str) -> HumanInputUploadContext: try: return service.validate_upload_token(token) except InvalidUploadTokenError as exc: raise InvalidUploadTokenForbiddenError() from exc -def _parse_local_upload_file(): +def _parse_local_upload_file() -> FileStorage: if "file" not in request.files: raise NoFileUploadedError() if len(request.files) > 1: @@ -113,8 +117,6 @@ def _parse_local_upload_file(): file = request.files["file"] if not file.filename: - from controllers.common.errors import FilenameNotExistsError - raise FilenameNotExistsError() return file @@ -124,79 +126,68 @@ def _parse_upload_form() -> HumanInputFileUploadFormPayload: return HumanInputFileUploadFormPayload.model_validate(request.form.to_dict(flat=True)) -def _upload_local_file(context): +def _upload_local_file( + *, + service: HumanInputFileUploadService, + context: HumanInputUploadContext, +) -> dict[str, Any]: file = _parse_local_upload_file() try: - upload_file = FileService(db.engine).upload_file( + upload_file = service.upload_local_file( + context=context, filename=file.filename or "", content=file.read(), mimetype=file.mimetype, - user=context.owner, - source=None, ) except services.errors.file.FileTooLargeError as file_too_large_error: - raise FileTooLargeError(file_too_large_error.description) - except services.errors.file.UnsupportedFileTypeError: - raise UnsupportedFileTypeError() + raise FileTooLargeError(file_too_large_error.description or "File size exceeded.") from file_too_large_error + except services.errors.file.UnsupportedFileTypeError as error: + raise UnsupportedFileTypeError() from error except services.errors.file.BlockedFileExtensionError as exc: raise BlockedFileExtensionError() from exc - return upload_file.id, dump_response(FileResponse, upload_file) + return dump_response(FileResponse, upload_file) -def _upload_remote_file(context, url: str): +def _upload_remote_file( + *, + service: HumanInputFileUploadService, + context: HumanInputUploadContext, + url: str, +) -> dict[str, Any]: try: - resp = ssrf_proxy.head(url=url) - if resp.status_code != httpx.codes.OK: - resp = ssrf_proxy.get(url=url, timeout=3, follow_redirects=True) - if resp.status_code != httpx.codes.OK: - raise RemoteFileUploadError(f"Failed to fetch file from {url}: {resp.text}") - except httpx.RequestError as exc: - raise RemoteFileUploadError(f"Failed to fetch file from {url}: {str(exc)}") - - file_info = guess_file_info_from_response(resp) - if not FileService.is_file_size_within_limit(extension=file_info.extension, file_size=file_info.size): - raise FileTooLargeError() - - content = resp.content if resp.request.method == "GET" else ssrf_proxy.get(url).content - - try: - upload_file = FileService(db.engine).upload_file( - filename=file_info.filename, - content=content, - mimetype=file_info.mimetype, - user=context.owner, - source_url=url, - ) + upload_file = service.upload_remote_file(context=context, url=url) + except RemoteFileInvalidUrlServiceError as error: + raise RemoteFileInvalidUrlError() from error + except RemoteFileUrlBlockedServiceError as error: + raise RemoteFileUrlBlockedError() from error + except RemoteFileNotFoundServiceError as error: + raise RemoteFileNotFoundError() from error + except RemoteFileAccessDeniedServiceError as error: + raise RemoteFileAccessDeniedError() from error + except RemoteFileUnavailableServiceError as error: + raise RemoteFileUnavailableError() from error + except RemoteFileInvalidResponseServiceError as error: + raise RemoteFileInvalidResponseError() from error except services.errors.file.FileTooLargeError as file_too_large_error: - raise FileTooLargeError(file_too_large_error.description) - except services.errors.file.UnsupportedFileTypeError: - raise UnsupportedFileTypeError() + raise FileTooLargeError(file_too_large_error.description or "File size exceeded.") from file_too_large_error + except services.errors.file.UnsupportedFileTypeError as error: + raise UnsupportedFileTypeError() from error except services.errors.file.BlockedFileExtensionError as exc: raise BlockedFileExtensionError() from exc - response = FileWithSignedUrl( - id=upload_file.id, - name=upload_file.name, - size=upload_file.size, - extension=upload_file.extension, - url=file_helpers.get_signed_file_url(upload_file_id=upload_file.id), - mime_type=upload_file.mime_type, - created_by=upload_file.created_by, - created_at=int(upload_file.created_at.timestamp()), - ) - return upload_file.id, response.model_dump(mode="json") + return dump_response(FileWithSignedUrl, upload_file) @web_ns.route("/human-input-forms/files") @web_ns.response(201, "File uploaded successfully", web_ns.models[FileResponse.__name__]) class HumanInputFileUploadApi(Resource): - def post(self): + def post(self) -> JsonResponseWithStatus: """Upload one local file or remote URL file for a HITL human input form.""" token = _extract_hitl_upload_token() - upload_service = _create_upload_service() + upload_service = application_services().human_input_file_uploads context = _validate_context(upload_service, token) form = _parse_upload_form() @@ -204,10 +195,13 @@ class HumanInputFileUploadApi(Resource): # switches the endpoint into the remote-fetch flow; otherwise the # request must carry a local `file`. if form.url is not None: - file_id, response = _upload_remote_file(context=context, url=str(form.url)) + response = _upload_remote_file( + service=upload_service, + context=context, + url=str(form.url), + ) else: - file_id, response = _upload_local_file(context=context) + response = _upload_local_file(service=upload_service, context=context) - upload_service.record_upload_file(context=context, file_id=file_id) # response-contract:ignore pre-dumped response. See above return response, 201 diff --git a/api/controllers/web/human_input_form.py b/api/controllers/web/human_input_form.py index 5668b97abaa..745b68b7f2d 100644 --- a/api/controllers/web/human_input_form.py +++ b/api/controllers/web/human_input_form.py @@ -9,7 +9,6 @@ from typing import Self from flask import request from flask_restx import Resource from sqlalchemy import select -from sqlalchemy.orm import sessionmaker from werkzeug.exceptions import Forbidden from configs import dify_config @@ -21,14 +20,13 @@ from controllers.web import web_ns from controllers.web.error import WebFormRateLimitExceededError from controllers.web.site import WebAppSiteResponse from core.workflow.nodes.human_input.entities import FormInputConfig, UserActionConfig +from extensions.ext_application_services import application_services from extensions.ext_database import db from fields.base import ResponseModel from libs.helper import RateLimiter, dump_response, extract_remote_ip, to_timestamp from models.account import TenantStatus from models.model import App, AppMode, Site -from repositories.factory import DifyAPIRepositoryFactory from services.feature_service import FeatureService -from services.human_input_file_upload_service import HumanInputFileUploadService from services.human_input_service import Form, FormNotFoundError, HumanInputService logger = logging.getLogger(__name__) @@ -99,15 +97,6 @@ _FORM_UPLOAD_TOKEN_RATE_LIMITER = RateLimiter( ) -def _create_upload_service() -> HumanInputFileUploadService: - session_factory = sessionmaker(bind=db.engine) - workflow_run_repository = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_factory) - return HumanInputFileUploadService( - session_factory=session_factory, - workflow_run_repository=workflow_run_repository, - ) - - @web_ns.route("/form/human_input//upload-token") class HumanInputFormUploadTokenApi(Resource): """API for issuing HITL upload tokens for active human input forms.""" @@ -140,7 +129,7 @@ class HumanInputFormUploadTokenApi(Resource): _FORM_UPLOAD_TOKEN_RATE_LIMITER.increment_rate_limit(ip_address) try: - token = _create_upload_service().issue_upload_token(form_token) + token = application_services().human_input_file_uploads.issue_upload_token(form_token) except FormNotFoundError: raise NotFoundError("Form not found") @@ -155,7 +144,6 @@ class HumanInputFormApi(Resource): # NOTE(QuantumGhost): this endpoint is unauthenticated on purpose for now. - # def get(self, _app_model: App, _end_user: EndUser, form_token: str): @web_ns.doc("get_human_input_form") @web_ns.doc(description="Get a human input form definition by token") @web_ns.doc(params={"form_token": "Human input form token"}) @@ -217,7 +205,6 @@ class HumanInputFormApi(Resource): ), ) - # def post(self, _app_model: App, _end_user: EndUser, form_token: str): @web_ns.expect(web_ns.models[HumanInputFormSubmitPayload.__name__]) @web_ns.doc("submit_human_input_form") @web_ns.doc(description="Submit a human input form by token") @@ -272,7 +259,6 @@ class HumanInputFormApi(Resource): selected_action_id=payload.action, form_data=payload.inputs, submission_end_user_id=None, - # submission_end_user_id=_end_user.id, ) except FormNotFoundError: raise NotFoundError("Form not found") diff --git a/api/controllers/web/saved_message.py b/api/controllers/web/saved_message.py index e085b6ece1a..eed4aed5ed6 100644 --- a/api/controllers/web/saved_message.py +++ b/api/controllers/web/saved_message.py @@ -1,15 +1,16 @@ from uuid import UUID from pydantic import TypeAdapter +from sqlalchemy.orm import Session from werkzeug.exceptions import NotFound from controllers.common.controller_schemas import SavedMessageCreatePayload, SavedMessageListQuery from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models +from controllers.console.app.wraps import with_session from controllers.console.wraps import model_validate from controllers.web import web_ns from controllers.web.error import NotCompletionAppError from controllers.web.wraps import WebApiResource -from extensions.ext_database import db from fields.conversation_fields import MessageResponseSource, ResultResponse from fields.message_fields import SavedMessageInfiniteScrollPagination, SavedMessageItem from models.model import App, EndUser @@ -36,12 +37,12 @@ class SavedMessageListApi(WebApiResource): } ) @web_ns.response(200, "Success", web_ns.models[SavedMessageInfiniteScrollPagination.__name__]) + @with_session(write=False) @model_validate(SavedMessageListQuery) - def get(self, query: SavedMessageListQuery, app_model: App, end_user: EndUser): + def get(self, query: SavedMessageListQuery, session: Session, app_model: App, end_user: EndUser): if app_model.mode != "completion": raise NotCompletionAppError() - session = db.session() pagination = SavedMessageService.pagination_by_last_id( app_model, end_user, query.last_id, query.limit, session=session ) @@ -73,13 +74,14 @@ class SavedMessageListApi(WebApiResource): ) @web_ns.response(200, "Message saved successfully", web_ns.models[ResultResponse.__name__]) @web_ns.expect(web_ns.models[SavedMessageCreatePayload.__name__]) + @with_session @model_validate(SavedMessageCreatePayload) - def post(self, payload: SavedMessageCreatePayload, app_model: App, end_user: EndUser): + def post(self, payload: SavedMessageCreatePayload, session: Session, app_model: App, end_user: EndUser): if app_model.mode != "completion": raise NotCompletionAppError() try: - SavedMessageService.save(app_model, end_user, payload.message_id, session=db.session()) + SavedMessageService.save(app_model, end_user, payload.message_id, session=session) except MessageNotExistsError: raise NotFound("Message Not Exists.") @@ -102,12 +104,13 @@ class SavedMessageApi(WebApiResource): } ) @web_ns.response(204, "Message removed successfully") - def delete(self, app_model: App, end_user: EndUser, message_id: UUID): + @with_session + def delete(self, session: Session, app_model: App, end_user: EndUser, message_id: UUID): message_id_str = str(message_id) if app_model.mode != "completion": raise NotCompletionAppError() - SavedMessageService.delete(app_model, end_user, message_id_str, session=db.session()) + SavedMessageService.delete(app_model, end_user, message_id_str, session=session) return "", 204 diff --git a/api/controllers/web/site.py b/api/controllers/web/site.py index 54914b9bfb4..7b2afe16bcc 100644 --- a/api/controllers/web/site.py +++ b/api/controllers/web/site.py @@ -7,6 +7,7 @@ from configs import dify_config from controllers.common.schema import register_response_schema_models from controllers.web import web_ns from controllers.web.wraps import WebApiResource +from enums import DeploymentEdition from extensions.ext_application_services import application_services from fields.base import ResponseModel from libs.helper import build_icon_url, dump_response @@ -102,7 +103,7 @@ class WebAppSiteResponse(ResponseModel): site_response = WebSiteResponse.model_validate(site, from_attributes=True) site_response.icon_url = icon_url if icon_url is not None else build_icon_url(site.icon_type, site.icon) - if features.billing.enabled and not features.webapp_copyright_enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and not features.webapp_copyright_enabled: site_response.copyright = None site_response.input_placeholder = None diff --git a/api/core/app/apps/agent_app/app_generator.py b/api/core/app/apps/agent_app/app_generator.py index 5381cd4b1c3..2d58ca1b4e4 100644 --- a/api/core/app/apps/agent_app/app_generator.py +++ b/api/core/app/apps/agent_app/app_generator.py @@ -11,15 +11,13 @@ changes the runtime exit policy carried to the backend. from __future__ import annotations import contextvars -import json import logging import threading import uuid -from collections.abc import Generator, Mapping, Sequence +from collections.abc import Generator, Mapping from typing import Any, Literal from flask import Flask, current_app -from pydantic import JsonValue from sqlalchemy import and_, or_, select from sqlalchemy.orm import Session @@ -29,6 +27,7 @@ from configs import dify_config from constants import UUID_NIL from core.agent.publish_visibility import agent_has_workflow_callable_active_snapshot from core.app.app_config.easy_ui_based_app.model_config.converter import ModelConfigConverter +from core.app.app_config.features.file_upload.manager import FileUploadConfigManager from core.app.apps.agent_app.app_config_manager import AgentAppConfigManager from core.app.apps.agent_app.app_runner import AgentAppRunner from core.app.apps.agent_app.errors import ( @@ -52,8 +51,8 @@ from core.app.entities.app_invoke_entities import ( from core.credit_usage import CreditUsageAppType from core.db.session_factory import session_factory from core.ops.ops_trace_manager import TraceQueueManager -from core.workflow.file_reference import build_file_reference, is_canonical_file_reference from extensions.ext_database import db +from factories import file_factory from models import Account, App, AppModelConfig, Conversation, EndUser, Message, MessageAnnotation from models.agent import ( APP_BACKED_AGENT_SOURCES, @@ -75,69 +74,6 @@ from services.conversation_service import ConversationService logger = logging.getLogger(__name__) -_REFERENCE_FILE_TRANSFER_METHODS = {"local_file", "tool_file", "datasource_file"} - - -def _append_prompt_file_mappings(query: str, prompt_file_mappings: Sequence[JsonValue]) -> str: - """Append labeled, prompt-safe file locators to the backend user prompt.""" - prompt_files = _prompt_file_locators(prompt_file_mappings) - if not prompt_files: - return query - payload = json.dumps(prompt_files, ensure_ascii=False, separators=(",", ":")) - return ( - f"{query}\n" - "User provided files: use dify-agent file download with the listed transfer_method and reference/url " - "to get the files and investigate them\n" - f"{payload}" - ) - - -def _prompt_file_locators(prompt_file_mappings: Sequence[JsonValue]) -> list[dict[str, str]]: - locators: list[dict[str, str]] = [] - for file_mapping in prompt_file_mappings: - if not isinstance(file_mapping, Mapping): - continue - locator = _prompt_file_locator(file_mapping) - if locator is not None: - locators.append(locator) - return locators - - -def _prompt_file_locator(file_mapping: Mapping[str, object]) -> dict[str, str] | None: - transfer_method = _string_value(file_mapping, "transfer_method") - if transfer_method == "remote_url": - url = _string_value(file_mapping, "url") or _string_value(file_mapping, "remote_url") - if url is None: - return None - return {"transfer_method": "remote_url", "url": url} - elif transfer_method in _REFERENCE_FILE_TRANSFER_METHODS: - if transfer_method is None: - return None - reference = _canonical_file_reference( - _string_value(file_mapping, "reference") - or _string_value(file_mapping, "upload_file_id") - or _string_value(file_mapping, "file_id") - or _string_value(file_mapping, "id") - ) - if reference is None: - return None - return {"transfer_method": transfer_method, "reference": reference} - else: - return None - - -def _canonical_file_reference(reference: str | None) -> str | None: - if reference is None: - return None - if reference.startswith("dify-file-ref:"): - return reference if is_canonical_file_reference(reference) else None - return build_file_reference(record_id=reference) - - -def _string_value(mapping: Mapping[str, object], key: str) -> str | None: - value = mapping.get(key) - return value if isinstance(value, str) and value else None - class AgentAppGenerator(MessageBasedAppGenerator): def generate( @@ -155,7 +91,7 @@ class AgentAppGenerator(MessageBasedAppGenerator): query = self._require_query(args) inputs = args["inputs"] - prompt_file_mappings = args.get("files") or [] + raw_files = args.get("files") or [] conversation = None conversation_id = args.get("conversation_id") @@ -193,19 +129,33 @@ class AgentAppGenerator(MessageBasedAppGenerator): conversation=conversation, ) model_conf = ModelConfigConverter.convert(app_config) + with self._bind_file_access_scope(tenant_id=app_model.tenant_id, user=user, invoke_from=invoke_from): + file_upload_config = ( + FileUploadConfigManager.convert(app_config.app_model_config_dict, is_vision=True) if raw_files else None + ) + file_objs = ( + file_factory.build_from_mappings( + mappings=raw_files, + tenant_id=app_model.tenant_id, + config=file_upload_config, + access_controller=self._file_access_controller, + ) + if raw_files and file_upload_config is not None + else [] + ) trace_manager = TraceQueueManager(app_model.id, user.id if isinstance(user, Account) else user.session_id) application_generate_entity = AgentAppGenerateEntity( task_id=str(uuid.uuid4()), app_config=app_config, model_conf=model_conf, + file_upload_config=file_upload_config, conversation_id=conversation.id if conversation else None, inputs=self._prepare_user_inputs( user_inputs=inputs, variables=app_config.variables, tenant_id=app_model.tenant_id ), query=query, - files=[], - prompt_file_mappings=prompt_file_mappings, + files=list(file_objs), parent_message_id=( args.get("parent_message_id") if invoke_from not in {InvokeFrom.SERVICE_API, InvokeFrom.OPENAPI} @@ -492,10 +442,6 @@ class AgentAppGenerator(MessageBasedAppGenerator): ) if handled: return - query = _append_prompt_file_mappings( - query=query, - prompt_file_mappings=application_generate_entity.prompt_file_mappings, - ) dify_context = DifyRunContext( tenant_id=app_config.tenant_id, @@ -514,6 +460,14 @@ class AgentAppGenerator(MessageBasedAppGenerator): ) runner = self._build_runner() + image_detail_config = ( + application_generate_entity.file_upload_config.image_config.detail + if ( + application_generate_entity.file_upload_config + and application_generate_entity.file_upload_config.image_config + ) + else None + ) runner.run( dify_context=dify_context, agent_id=application_generate_entity.agent_id, @@ -526,6 +480,8 @@ class AgentAppGenerator(MessageBasedAppGenerator): message_id=message.id, model_name=application_generate_entity.model_conf.model, queue_manager=queue_manager, + files=list(application_generate_entity.files), + image_detail_config=image_detail_config, session_scope_snapshot_id=application_generate_entity.agent_session_scope_config_version_id, build_draft_id=( application_generate_entity.agent_config_snapshot_id diff --git a/api/core/app/apps/agent_app/app_runner.py b/api/core/app/apps/agent_app/app_runner.py index 665af35a035..f155c07a333 100644 --- a/api/core/app/apps/agent_app/app_runner.py +++ b/api/core/app/apps/agent_app/app_runner.py @@ -55,8 +55,14 @@ from core.repositories.human_input_repository import HumanInputFormRepository, H from core.workflow.nodes.agent_v2.ask_human_hitl import AskHumanFormBuildError, create_ask_human_form from core.workflow.nodes.agent_v2.ask_human_resume import build_deferred_tool_results, resolve_ask_human_form from extensions.ext_database import db +from graphon.file import File from graphon.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta, LLMUsage -from graphon.model_runtime.entities.message_entities import AssistantPromptMessage, PromptMessage, UserPromptMessage +from graphon.model_runtime.entities.message_entities import ( + AssistantPromptMessage, + ImagePromptMessageContent, + PromptMessage, + UserPromptMessage, +) from graphon.model_runtime.errors.invoke import ( InvokeAuthorizationError, InvokeBadRequestError, @@ -643,6 +649,8 @@ class AgentAppRunner: message_id: str, model_name: str, queue_manager: AppQueueManager, + files: list[File] | None = None, + image_detail_config: ImagePromptMessageContent.DETAIL | None = None, session_scope_snapshot_id: str | None | _DefaultSessionScopeSnapshotId = _DEFAULT_SESSION_SCOPE_SNAPSHOT_ID, build_draft_id: str | None = None, ) -> None: @@ -669,6 +677,8 @@ class AgentAppRunner: backend_binding_ref=stored.backend_binding_ref, conversation_id=conversation_id, query=query, + files=tuple(files or ()), + image_detail_config=image_detail_config, idempotency_key=message_id, stored=stored, message_id=message_id, @@ -796,6 +806,8 @@ class AgentAppRunner: backend_binding_ref: str, conversation_id: str, query: str, + files: tuple[File, ...], + image_detail_config: ImagePromptMessageContent.DETAIL | None, idempotency_key: str, stored: StoredAgentAppSession, message_id: str | None, @@ -815,6 +827,8 @@ class AgentAppRunner: agent_soul=agent_soul, conversation_id=conversation_id, user_query=query, + files=files, + image_detail_config=image_detail_config, idempotency_key=idempotency_key, binding_id=binding_id, backend_binding_ref=backend_binding_ref, diff --git a/api/core/app/apps/agent_app/runtime_request_builder.py b/api/core/app/apps/agent_app/runtime_request_builder.py index 70c813d0fd5..5f05b0c99d6 100644 --- a/api/core/app/apps/agent_app/runtime_request_builder.py +++ b/api/core/app/apps/agent_app/runtime_request_builder.py @@ -19,6 +19,12 @@ from dify_agent.layers.execution_context import ( DifyExecutionContextLayerConfig, DifyExecutionContextUserFrom, ) +from dify_agent.layers.user_prompt import ( + DifyUserPromptDownloadConfig, + DifyUserPromptFileConfig, + DifyUserPromptFileType, + DifyUserPromptImageConfig, +) from dify_agent.protocol import CreateRunRequest, DeferredToolResultsPayload from clients.agent_backend import ( @@ -29,8 +35,9 @@ from clients.agent_backend import ( ) from configs import dify_config from core.app.entities.app_invoke_entities import DifyRunContext, InvokeFrom -from core.app.llm.model_access import resolve_model_context_window +from core.app.llm.model_access import resolve_model_context_window, resolve_model_supports_vision from core.plugin.provider_identity import normalize_plugin_daemon_provider_identity +from core.workflow.file_reference import build_file_reference, is_canonical_file_reference from core.workflow.nodes.agent_v2.dify_tools_builder import ( WorkflowAgentDifyToolLayersBuilder, WorkflowAgentDifyToolsBuilder, @@ -46,6 +53,8 @@ from core.workflow.nodes.agent_v2.runtime_request_builder import ( build_shell_layer_config, load_runtime_agent_skill_configs, ) +from graphon.file import File, FileTransferMethod, FileType, file_manager +from graphon.model_runtime.entities.message_entities import ImagePromptMessageContent from models.agent_config_entities import AgentSoulConfig, AgentSoulToolsConfig from models.provider_ids import ModelProviderID from services.agent.prompt_mentions import expand_prompt_mentions @@ -61,6 +70,9 @@ class AgentAppRuntimeRequestBuildError(ValueError): super().__init__(message) +type _ReferenceFileTransferMethod = Literal["local_file", "tool_file", "datasource_file"] + + @dataclass(frozen=True, slots=True) class AgentAppRuntimeBuildContext: dify_context: DifyRunContext @@ -72,6 +84,8 @@ class AgentAppRuntimeBuildContext: idempotency_key: str binding_id: str backend_binding_ref: str + files: tuple[File, ...] = () + image_detail_config: ImagePromptMessageContent.DETAIL | None = None agent_config_version_kind: Literal["snapshot", "draft", "build_draft"] = "snapshot" session_snapshot: CompositorSessionSnapshot | None = None # ENG-638: set when resuming a chat turn after a submitted ask_human form. @@ -150,6 +164,13 @@ class AgentAppRuntimeRequestBuilder: ModelProviderID(agent_soul.model.model_provider), agent_soul.model.plugin_id, ) + user_files = self._build_user_files( + files=context.files, + run_context=context.dify_context, + provider_name=agent_soul.model.model_provider, + model_name=agent_soul.model.model, + image_detail_config=context.image_detail_config, + ) request = self._request_builder.build_for_agent_app( AgentBackendAgentAppRunInput( @@ -180,6 +201,7 @@ class AgentAppRuntimeRequestBuilder: or None, agent_config_version_kind=context.agent_config_version_kind, user_prompt=context.user_query, + user_files=user_files, tools=tool_layers.plugin_tools, core_tools=tool_layers.core_tools, knowledge=knowledge_config, @@ -202,6 +224,27 @@ class AgentAppRuntimeRequestBuilder: binding_id=context.binding_id, ) + @staticmethod + def _build_user_files( + *, + files: tuple[File, ...], + run_context: DifyRunContext, + provider_name: str, + model_name: str, + image_detail_config: ImagePromptMessageContent.DETAIL | None, + ) -> list[DifyUserPromptFileConfig]: + supports_vision = any(file.type == FileType.IMAGE for file in files) and resolve_model_supports_vision( + run_context=run_context, + provider_name=provider_name, + model_name=model_name, + ) + return [ + _build_user_image(file, image_detail_config=image_detail_config) + if supports_vision and file.type == FileType.IMAGE + else _build_user_download(file) + for file in files + ] + @staticmethod def _validate_session_snapshot_layers(request: CreateRunRequest) -> None: """Reject stale snapshots before they reach the Agent backend. @@ -251,6 +294,57 @@ class AgentAppRuntimeRequestBuilder: } +def _build_user_image( + file: File, + *, + image_detail_config: ImagePromptMessageContent.DETAIL | None, +) -> DifyUserPromptImageConfig: + content = file_manager.to_prompt_message_content(file, image_detail_config=image_detail_config) + if not isinstance(content, ImagePromptMessageContent): + raise AgentAppRuntimeRequestBuildError( + "agent_user_file_unsupported", + f"Agent App cannot send file '{file.filename or 'image'}' as vision content.", + ) + detail = content.detail.value + return DifyUserPromptImageConfig( + filename=content.filename or file.filename or f"image.{content.format}", + mime_type=content.mime_type, + format=content.format, + url=content.url or None, + base64_data=content.base64_data or None, + detail=detail if detail in {"low", "high"} else None, + ) + + +def _build_user_download(file: File) -> DifyUserPromptDownloadConfig: + file_type = cast(DifyUserPromptFileType, file.type.value) + if file.transfer_method == FileTransferMethod.REMOTE_URL: + if file.remote_url is None: + raise AgentAppRuntimeRequestBuildError("agent_user_file_invalid", "Remote user file is missing its URL.") + return DifyUserPromptDownloadConfig(type=file_type, transfer_method="remote_url", url=file.remote_url) + if file.reference is None: + raise AgentAppRuntimeRequestBuildError("agent_user_file_invalid", "User file is missing its reference.") + reference = file.reference + if not reference.startswith("dify-file-ref:"): + reference = build_file_reference(record_id=reference) + elif not is_canonical_file_reference(reference): + raise AgentAppRuntimeRequestBuildError("agent_user_file_invalid", "User file reference is invalid.") + transfer_method: _ReferenceFileTransferMethod + match file.transfer_method: + case FileTransferMethod.LOCAL_FILE: + transfer_method = "local_file" + case FileTransferMethod.TOOL_FILE: + transfer_method = "tool_file" + case FileTransferMethod.DATASOURCE_FILE: + transfer_method = "datasource_file" + case _: + raise AgentAppRuntimeRequestBuildError( + "agent_user_file_invalid", + f"User file transfer method '{file.transfer_method.value}' is unsupported.", + ) + return DifyUserPromptDownloadConfig(type=file_type, transfer_method=transfer_method, reference=reference) + + __all__ = [ "AgentAppRuntimeBuildContext", "AgentAppRuntimeRequest", diff --git a/api/core/app/entities/app_invoke_entities.py b/api/core/app/entities/app_invoke_entities.py index 7f983135994..cb3f52d12a0 100644 --- a/api/core/app/entities/app_invoke_entities.py +++ b/api/core/app/entities/app_invoke_entities.py @@ -2,7 +2,7 @@ from collections.abc import Mapping, Sequence from enum import StrEnum from typing import TYPE_CHECKING, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, JsonValue, ValidationInfo, field_validator +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator from constants import UUID_NIL from core.app.app_config.entities import EasyUIBasedAppConfig, WorkflowUIBasedAppConfig @@ -286,16 +286,15 @@ class AgentAppGenerateEntity(ChatAppGenerateEntity): ``agent_session_scope_config_version_id`` identifies the draft or immutable config version whose Workspace Binding should be reused for this session. - ``prompt_file_mappings`` preserves the raw request ``files`` array for the - Agent backend prompt. These references are appended to the backend prompt - text while the stored chat message keeps the user's original query. + Uploaded files use the inherited ``files`` field. The Agent App runtime + sends supported images directly to vision models and preserves the sandbox + locator fallback for all other files. """ agent_id: str agent_config_snapshot_id: str agent_config_version_kind: Literal["snapshot", "draft", "build_draft"] = "snapshot" agent_session_scope_config_version_id: str | None = None - prompt_file_mappings: Sequence[JsonValue] = Field(default_factory=list) agent_llm_gateway_enabled: bool = False diff --git a/api/core/app/llm/model_access.py b/api/core/app/llm/model_access.py index 52fb9add70b..e793200ffb7 100644 --- a/api/core/app/llm/model_access.py +++ b/api/core/app/llm/model_access.py @@ -9,7 +9,7 @@ from core.errors.error import ProviderTokenNotInitError from core.model_manager import ModelInstance, ModelManager from core.plugin.impl.model_runtime_factory import create_plugin_provider_manager from core.provider_manager import ProviderManager -from graphon.model_runtime.entities.model_entities import ModelPropertyKey, ModelType +from graphon.model_runtime.entities.model_entities import ModelFeature, ModelPropertyKey, ModelType from graphon.nodes.llm.entities import ModelConfig from graphon.nodes.llm.exc import LLMModeRequiredError, ModelNotExistError from graphon.nodes.llm.protocols import CredentialsProvider @@ -149,6 +149,18 @@ def resolve_model_context_window( return context_window +def resolve_model_supports_vision( + *, + run_context: DifyRunContext, + provider_name: str, + model_name: str, +) -> bool: + """Return whether the credential-bound model advertises vision support.""" + + model_instance = DifyModelFactory(run_context=run_context).init_model_instance(provider_name, model_name) + return ModelFeature.VISION in (model_instance.get_model_schema().features or []) + + def _normalize_completion_params(completion_params: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: """ Split node-level completion params into provider parameters and stop sequences. diff --git a/api/core/ops/ops_trace_manager.py b/api/core/ops/ops_trace_manager.py index 3c109222f91..34679afc139 100644 --- a/api/core/ops/ops_trace_manager.py +++ b/api/core/ops/ops_trace_manager.py @@ -1212,7 +1212,7 @@ class TraceTask: tool_parameters = {} created_time = message_data.created_at end_time = message_data.updated_at - agent_thoughts = message_data.agent_thoughts + agent_thoughts = message_data.agent_thoughts_with_session(session=db.session()) for agent_thought in agent_thoughts: if tool_name in agent_thought.tools: created_time = agent_thought.created_at diff --git a/api/core/plugin/impl/base.py b/api/core/plugin/impl/base.py index e26a04e71ae..f8d8dbfc981 100644 --- a/api/core/plugin/impl/base.py +++ b/api/core/plugin/impl/base.py @@ -380,8 +380,8 @@ class BasePluginClient: if rep.code == -500: try: error = PluginDaemonError.model_validate(json.loads(rep.message)) - except Exception: - raise PluginDaemonInnerError(code=rep.code, message=rep.message) + except Exception as e: + raise PluginDaemonInnerError(code=rep.code, message=rep.message) from e logger.error("Error in stream response for plugin %s", rep.__dict__) self._handle_plugin_daemon_error(error.error_type, error.message) diff --git a/api/core/rbac/entities.py b/api/core/rbac/entities.py index 853b1703728..e35e12e01e5 100644 --- a/api/core/rbac/entities.py +++ b/api/core/rbac/entities.py @@ -5,11 +5,12 @@ class RBACResourceScope(StrEnum): """Resource scopes accepted by the ``rbac_permission_required`` decorator. ``WORKSPACE`` denotes a workspace-level check that carries no concrete - resource id; ``APP`` and ``DATASET`` are resource-scoped checks. + resource id; ``APP``, ``DATASET`` and ``AGENT`` are resource-scoped checks. """ APP = "app" DATASET = "dataset" + AGENT = "agent" WORKSPACE = "workspace" @@ -41,6 +42,19 @@ class RBACPermission(StrEnum): APP_DELETE = "app_delete" APP_ACCESS_CONFIG = "app_access_config" + AGENT_CREATE = "agent_create" + AGENT_PREVIEW = "agent_preview" + AGENT_EDIT = "agent_edit" + AGENT_TEST_AND_RUN = "agent_test_and_run" + AGENT_RELEASE_AND_VERSION = "agent_release_and_version" + AGENT_ACCESS_POINT_VIEW = "agent_access_point_view" + AGENT_ACCESS_POINT_MANAGE = "agent_access_point_manage" + AGENT_LOG_MANAGE = "agent_log_manage" + AGENT_MONITOR = "agent_monitor" + AGENT_ACCESS_CONFIG = "agent_access_config" + AGENT_IMPORT_EXPORT_DSL = "agent_import_export_dsl" + AGENT_DELETE = "agent_delete" + DATASET_PREVIEW = "dataset_preview" DATASET_READONLY = "dataset_readonly" DATASET_EDIT = "dataset_edit" @@ -61,7 +75,6 @@ class RBACPermission(StrEnum): WORKSPACE_ROLE_MANAGE = "workspace_role_manage" API_EXTENSION_MANAGE = "api_extension_manage" CUSTOMIZATION_MANAGE = "customization_manage" - AGENT_MANAGE = "agent_manage" SKILL_VIEW = "skill_view" SKILL_EDIT = "skill_edit" SKILL_PUBLISH = "skill_publish" @@ -83,3 +96,25 @@ class RBACPermission(StrEnum): TOOL_MANAGE = "tool_manage" MCP_MANAGE = "mcp_manage" + + @property + def scope(self) -> RBACResourceScope: + if self in _FUNCTION_SCOPED_RESOURCE_SCENES: + return RBACResourceScope.WORKSPACE + prefix = self.name.split("_", 1)[0] + return _SCENE_PREFIX_SCOPE.get(prefix, RBACResourceScope.WORKSPACE) + + +_SCENE_PREFIX_SCOPE: dict[str, RBACResourceScope] = { + "APP": RBACResourceScope.APP, + "DATASET": RBACResourceScope.DATASET, + "AGENT": RBACResourceScope.AGENT, +} + +_FUNCTION_SCOPED_RESOURCE_SCENES: frozenset[RBACPermission] = frozenset( + { + RBACPermission.APP_CREATE_AND_MANAGEMENT, + RBACPermission.DATASET_CREATE_AND_MANAGEMENT, + RBACPermission.AGENT_CREATE, + } +) diff --git a/api/core/tools/custom_tool/provider.py b/api/core/tools/custom_tool/provider.py index df48f63809d..41cd038cc5f 100644 --- a/api/core/tools/custom_tool/provider.py +++ b/api/core/tools/custom_tool/provider.py @@ -4,6 +4,7 @@ from typing import override from pydantic import Field from sqlalchemy import select +from sqlalchemy.orm import Session from core.entities.provider_entities import ProviderConfig, ProviderConfigType from core.tools.__base.tool_provider import ToolProviderController @@ -36,7 +37,9 @@ class ApiToolProviderController(ToolProviderController[ToolProviderEntity, ApiTo self.tools = [] @classmethod - def from_db(cls, db_provider: ApiToolProvider, auth_type: ApiProviderAuthType) -> ApiToolProviderController: + def from_db( + cls, db_provider: ApiToolProvider, auth_type: ApiProviderAuthType, *, session: Session + ) -> ApiToolProviderController: credentials_schema = [ ProviderConfig( name="auth_type", @@ -104,7 +107,7 @@ class ApiToolProviderController(ToolProviderController[ToolProviderEntity, ApiTo elif auth_type == ApiProviderAuthType.NONE: pass - user = db_provider.user + user = db_provider.user(session=session) user_name = user.name if user else "" return ApiToolProviderController( diff --git a/api/core/tools/signature.py b/api/core/tools/signature.py index fc5a7642ac5..f6954d67e5a 100644 --- a/api/core/tools/signature.py +++ b/api/core/tools/signature.py @@ -164,8 +164,13 @@ def verify_plugin_file_signature( if sign != recalculated_encoded_sign: return False + try: + signed_at = int(timestamp) + except ValueError: + return False + current_time = int(time.time()) - return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT + return current_time - signed_at <= dify_config.FILES_ACCESS_TIMEOUT def _plugin_upload_signature_payload( diff --git a/api/core/tools/tool_manager.py b/api/core/tools/tool_manager.py index fc02ecaf259..f3c61630a08 100644 --- a/api/core/tools/tool_manager.py +++ b/api/core/tools/tool_manager.py @@ -781,6 +781,7 @@ class ToolManager: db_provider=db_provider, decrypt_credentials=False, labels=provider_labels, + session=db.session(), ) result_providers[f"api_provider.{user_provider.name}"] = user_provider @@ -858,6 +859,7 @@ class ToolManager: controller = ApiToolProviderController.from_db( provider, auth_type, + session=db.session(), ) controller.load_bundled_tools(provider.tools) @@ -918,6 +920,7 @@ class ToolManager: controller = ApiToolProviderController.from_db( provider_obj, auth_type, + session=db.session(), ) # init tool configuration encrypter, _ = create_tool_provider_encrypter( diff --git a/api/core/workflow/nodes/agent_v2/agent_node.py b/api/core/workflow/nodes/agent_v2/agent_node.py index c822e5d3ab1..86c6f993221 100644 --- a/api/core/workflow/nodes/agent_v2/agent_node.py +++ b/api/core/workflow/nodes/agent_v2/agent_node.py @@ -178,6 +178,7 @@ class DifyAgentNode(Node[DifyAgentNodeData]): workflow_run_id=workflow_run_id, node_id=self._node_id, node_execution_id=self.execution_id, + conversation_id=conversation_id, ) bundle = self._binding_resolver.resolve( tenant_id=dify_ctx.tenant_id, @@ -223,6 +224,7 @@ class DifyAgentNode(Node[DifyAgentNodeData]): workflow_agent_binding_id=bundle.binding.id, agent_id=bundle.agent.id, agent_config_snapshot_id=bundle.snapshot.id, + conversation_id=conversation_id, ) node_job = WorkflowNodeJobConfig.model_validate(bundle.binding.node_job_config_dict) diff --git a/api/core/workflow/nodes/agent_v2/session_store.py b/api/core/workflow/nodes/agent_v2/session_store.py index 134ccc0a62a..7ea3450deb5 100644 --- a/api/core/workflow/nodes/agent_v2/session_store.py +++ b/api/core/workflow/nodes/agent_v2/session_store.py @@ -29,6 +29,41 @@ _CALLER_VISIBILITY_ATTEMPTS = 60 _CALLER_VISIBILITY_INTERVAL_SECONDS = 0.05 +def resolve_workflow_agent_workspace_owner_scope( + *, + tenant_id: str, + app_id: str, + conversation_id: str | None, + workflow_run_id: str | None, + node_id: str, + workflow_agent_binding_id: str, + node_execution_id: str | None = None, +) -> WorkspaceOwnerScope: + """Choose the Workspace owner for a workflow Agent participant. + + Chatflow runs carry ``conversation_id`` and should persist Agent memory across + turns the same way standalone Agent Apps do. Pure workflow runs keep the + per-run ``WORKFLOW_RUN`` scope. + """ + + owner_scope_key = f"{node_id}:{workflow_agent_binding_id}" + if conversation_id: + return WorkspaceOwnerScope( + tenant_id=tenant_id, + app_id=app_id, + owner_type=AgentWorkspaceOwnerType.CONVERSATION, + owner_id=conversation_id, + owner_scope_key=owner_scope_key, + ) + return WorkspaceOwnerScope( + tenant_id=tenant_id, + app_id=app_id, + owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN, + owner_id=workflow_run_id or node_execution_id or "", + owner_scope_key=owner_scope_key, + ) + + @dataclass(frozen=True, slots=True) class WorkflowAgentSessionScope: tenant_id: str @@ -40,15 +75,18 @@ class WorkflowAgentSessionScope: workflow_agent_binding_id: str agent_id: str agent_config_snapshot_id: str + conversation_id: str | None = None @property def workspace_owner(self) -> WorkspaceOwnerScope: - return WorkspaceOwnerScope( + return resolve_workflow_agent_workspace_owner_scope( tenant_id=self.tenant_id, app_id=self.app_id, - owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN, - owner_id=self.workflow_run_id or self.node_execution_id, - owner_scope_key=f"{self.node_id}:{self.workflow_agent_binding_id}", + conversation_id=self.conversation_id, + workflow_run_id=self.workflow_run_id, + node_id=self.node_id, + workflow_agent_binding_id=self.workflow_agent_binding_id, + node_execution_id=self.node_execution_id, ) @@ -75,6 +113,7 @@ class WorkflowAgentWorkspaceStore: workflow_run_id: str | None, node_id: str, node_execution_id: str, + conversation_id: str | None = None, ) -> WorkflowAgentSessionScope | None: """Return the generation pinned by an existing node execution participant.""" @@ -97,12 +136,14 @@ class WorkflowAgentWorkspaceStore: workflow_agent_binding_id = process_data.get("workflow_agent_binding_id") if not isinstance(workflow_agent_binding_id, str): raise AgentWorkspaceNotFoundError("Workflow node execution caller identity is missing") - owner_scope = WorkspaceOwnerScope( + owner_scope = resolve_workflow_agent_workspace_owner_scope( tenant_id=tenant_id, app_id=app_id, - owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN, - owner_id=workflow_run_id or node_execution_id, - owner_scope_key=f"{node_id}:{workflow_agent_binding_id}", + conversation_id=conversation_id, + workflow_run_id=workflow_run_id, + node_id=node_id, + workflow_agent_binding_id=workflow_agent_binding_id, + node_execution_id=node_execution_id, ) binding = AgentWorkspaceService.get_active_binding( session=session, @@ -122,6 +163,7 @@ class WorkflowAgentWorkspaceStore: workflow_agent_binding_id=workflow_agent_binding_id, agent_id=binding.agent_id, agent_config_snapshot_id=binding.agent_config_version_id, + conversation_id=conversation_id, ) def load_or_create_node_execution_session( @@ -140,13 +182,10 @@ class WorkflowAgentWorkspaceStore: binding_id = execution.agent_workspace_binding_id if binding_id is None: - binding = AgentWorkspaceService.create_binding( + binding = self._resolve_or_create_binding( session=session, - scope=scope.workspace_owner, - agent_id=scope.agent_id, - base_home_snapshot_id=home_snapshot_id, - agent_config_version_id=scope.agent_config_snapshot_id, - agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT, + scope=scope, + home_snapshot_id=home_snapshot_id, ) execution.agent_workspace_binding_id = binding.id execution.process_data = json.dumps( @@ -175,7 +214,7 @@ class WorkflowAgentWorkspaceStore: agent_config_version_id=scope.agent_config_snapshot_id, agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT, ) - return self._stored(scope, binding) + return self._stored(session, scope, binding) def save_active_snapshot( self, @@ -267,7 +306,44 @@ class WorkflowAgentWorkspaceStore: raise AgentWorkspaceNotFoundError("Workflow node execution caller is unavailable") @staticmethod - def _stored(scope: WorkflowAgentSessionScope, binding: AgentWorkspaceBinding) -> StoredWorkflowAgentSession: + def _resolve_or_create_binding( + *, + session: Session, + scope: WorkflowAgentSessionScope, + home_snapshot_id: str | None, + ) -> AgentWorkspaceBinding: + """Reuse a conversation-scoped participant or allocate a new one.""" + + if scope.conversation_id is not None: + existing_binding = AgentWorkspaceService.resolve_active_binding_for_scope( + session=session, + scope=scope.workspace_owner, + agent_id=scope.agent_id, + ) + if existing_binding is not None: + AgentWorkspaceService.validate_binding_generation( + existing_binding, + base_home_snapshot_id=home_snapshot_id, + agent_config_version_id=scope.agent_config_snapshot_id, + agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT, + ) + return existing_binding + + return AgentWorkspaceService.create_binding( + session=session, + scope=scope.workspace_owner, + agent_id=scope.agent_id, + base_home_snapshot_id=home_snapshot_id, + agent_config_version_id=scope.agent_config_snapshot_id, + agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT, + ) + + @staticmethod + def _stored( + session: Session, + scope: WorkflowAgentSessionScope, + binding: AgentWorkspaceBinding, + ) -> StoredWorkflowAgentSession: snapshot = ( CompositorSessionSnapshot.model_validate_json(binding.session_snapshot) if binding.session_snapshot @@ -284,4 +360,9 @@ class WorkflowAgentWorkspaceStore: ) -__all__ = ["StoredWorkflowAgentSession", "WorkflowAgentSessionScope", "WorkflowAgentWorkspaceStore"] +__all__ = [ + "StoredWorkflowAgentSession", + "WorkflowAgentSessionScope", + "WorkflowAgentWorkspaceStore", + "resolve_workflow_agent_workspace_owner_scope", +] diff --git a/api/events/event_handlers/clean_when_dataset_deleted.py b/api/events/event_handlers/clean_when_dataset_deleted.py index d6007662d8d..ce0cf66f8f1 100644 --- a/api/events/event_handlers/clean_when_dataset_deleted.py +++ b/api/events/event_handlers/clean_when_dataset_deleted.py @@ -1,4 +1,5 @@ from events.dataset_event import dataset_was_deleted +from extensions.ext_database import db from models import Dataset from tasks.clean_dataset_task import clean_dataset_task @@ -6,7 +7,8 @@ from tasks.clean_dataset_task import clean_dataset_task @dataset_was_deleted.connect def handle(sender: Dataset, **kwargs): dataset = sender - if not dataset.doc_form or not dataset.indexing_technique: + doc_form = dataset.get_doc_form(session=db.session()) + if not doc_form or not dataset.indexing_technique: return clean_dataset_task.delay( dataset.id, @@ -14,6 +16,6 @@ def handle(sender: Dataset, **kwargs): dataset.indexing_technique, dataset.index_struct, dataset.collection_binding_id, - dataset.doc_form, + doc_form, dataset.pipeline_id, ) diff --git a/api/events/event_handlers/update_provider_when_message_created.py b/api/events/event_handlers/update_provider_when_message_created.py index af60032d099..935e6a2306c 100644 --- a/api/events/event_handlers/update_provider_when_message_created.py +++ b/api/events/event_handlers/update_provider_when_message_created.py @@ -142,7 +142,7 @@ def handle(sender: Message, **kwargs): "created_by": get_credit_usage_created_by(app_mode), } credit_deduction_context: _CreditDeductionContext = { - "request_id": str(message.id) if message.id else None, + "request_id": message.id or None, "metadata": credit_deduction_metadata, } agent_gateway_metered = ( diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.py index b68354b194d..07aa6edc21e 100644 --- a/api/extensions/ext_application_services.py +++ b/api/extensions/ext_application_services.py @@ -47,15 +47,19 @@ from repositories.data_source_oauth_binding_repository import SQLAlchemyDataSour from repositories.explore_banner_query_repository import ExploreBannerQueryRepository from repositories.factory import DifyAPIRepositoryFactory from repositories.file_grant_repository import FileGrantRepository +from repositories.human_input_file_upload_repository import SQLAlchemyHumanInputFileUploadRepository from repositories.installation_state_repository import InstallationStateRepository +from repositories.message_file_preview_repository import MessageFilePreviewQueryRepository from repositories.oauth_access_token_repository import SQLAlchemyOAuthAccessTokenRepository from repositories.oauth_server_repository import RedisOAuthServerTokenRepository, SQLAlchemyOAuthServerRepository +from repositories.plugin_file_upload_repository import SQLAlchemyPluginFileUploadOwnerRepository from repositories.recommended_app_catalog_repository import DatabaseRecommendedAppCatalogRepository from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository from repositories.step_by_step_tour_repository import SQLAlchemyStepByStepTourStateRepository from repositories.tag_repository import TagRepository from repositories.trial_app_query_repository import TrialAppQueryRepository from repositories.trial_app_usage_repository import TrialAppUsageRepository +from repositories.upload_file_delivery_repository import UploadFileDeliveryQueryRepository from repositories.web_passport_repository import WebPassportRepository from repositories.webapp_access_query_repository import WebAppAccessQueryRepository from repositories.workflow_app_log_query_repository import WorkflowAppLogQueryRepository @@ -155,13 +159,17 @@ from services.feature_service_gateway import FeatureServiceGateway from services.file_grant_gateways import FileGrantFileGateway, FileGrantRemoteFileGateway, FileGrantTokenGateway from services.file_grant_service import FileGrantService from services.file_service import FileService +from services.human_input_file_upload_service import HumanInputFileUploadService from services.init_validation_service import InitValidationService from services.inner_mail_service import InnerMailService +from services.message_file_preview_service import MessageFilePreviewService from services.notification_gateway import BillingNotificationGateway from services.notification_service import NotificationService from services.notion_data_source_gateway import NotionDataSourceGateway from services.oauth_server_service import OAUTH_ACCESS_TOKEN_EXPIRES_IN, OAuthServerService from services.partner_tenant_binding_service import PartnerTenantBindingService +from services.plugin_file_upload_gateway import ToolFilePluginUploadGateway +from services.plugin_file_upload_service import PluginFileUploadService from services.recommended_app_catalog_gateway import ( BuiltinRecommendedAppCatalogGateway, RecommendedAppCatalogRouter, @@ -181,7 +189,9 @@ from services.setup_service import SetupService from services.step_by_step_tour_service import StepByStepTourService from services.system_feature_service import SystemFeatureService from services.tag_application_service import TagApplicationService +from services.tool_file_download_service import ToolFileDownloadService from services.trial_app_usage import TrialAppUsageRecorder +from services.upload_file_delivery_service import UploadFileDeliveryService from services.web_app_runtime_query_service import WebAppRuntimeQueryService from services.web_passport_gateways import ( DeploymentWebPassportAuthGateway, @@ -260,6 +270,11 @@ class ApplicationServices: feature_queries: FeatureQueryService file_grants: FileGrantService files: FileService + human_input_file_uploads: HumanInputFileUploadService + message_file_previews: MessageFilePreviewService + plugin_file_uploads: PluginFileUploadService + tool_file_downloads: ToolFileDownloadService + upload_file_delivery: UploadFileDeliveryService oauth_server: OAuthServerService init_validation: InitValidationService notifications: NotificationService @@ -423,6 +438,7 @@ def build_application_services( ) workspace_query_repository = WorkspaceQueryRepository(session_factory=database_client) file_service = FileService(session_factory=database_client) + remote_file_service = RemoteFileService(files=file_service) passwords = DefaultAccountPasswordHasher() invitation_tokens = RedisInvitationTokenStore(redis=redis) activation_accounts = SQLAlchemyAccountActivationRepository(session_factory=database_client) @@ -540,7 +556,7 @@ def build_application_services( passwords=passwords, tokens=RedisForgotPasswordTokenGateway( redis=redis, - expiry_seconds=int(dify_config.RESET_PASSWORD_TOKEN_EXPIRY_MINUTES * 60), + expiry_seconds=dify_config.RESET_PASSWORD_TOKEN_EXPIRY_MINUTES * 60, ), codes=SecureForgotPasswordCodeGenerator(), notifications=CeleryForgotPasswordNotificationGateway(), @@ -631,6 +647,7 @@ def build_application_services( file_service=file_service, workspace_features=feature_gateway.get_workspace_features, files_url=dify_config.FILES_URL, + deployment_edition=deployment_edition, ), explore_banner_queries=ExploreBannerQueryService( banners=ExploreBannerQueryRepository(session_factory=database_client), @@ -649,6 +666,27 @@ def build_application_services( ), file_grants=_build_file_grant_service(database_client=database_client), files=file_service, + human_input_file_uploads=HumanInputFileUploadService( + uploads=SQLAlchemyHumanInputFileUploadRepository(session_factory=database_client), + workflow_run_repository=DifyAPIRepositoryFactory.create_api_workflow_run_repository( + session_maker=database_client, + ), + files=file_service, + remote_files=remote_file_service, + ), + message_file_previews=MessageFilePreviewService( + files=MessageFilePreviewQueryRepository(session_factory=database_client), + storage=storage, + ), + plugin_file_uploads=PluginFileUploadService( + owners=SQLAlchemyPluginFileUploadOwnerRepository(session_factory=database_client), + files=ToolFilePluginUploadGateway(tool_files=ToolFileManager()), + ), + tool_file_downloads=ToolFileDownloadService(tool_files=ToolFileManager()), + upload_file_delivery=UploadFileDeliveryService( + files=UploadFileDeliveryQueryRepository(session_factory=database_client), + storage=storage, + ), oauth_server=_build_oauth_server_service(database_client=database_client, redis=redis), init_validation=InitValidationService( state=installation_state, @@ -672,9 +710,7 @@ def build_application_services( trial_apps=TrialAppQueryRepository(session_factory=database_client), trial_enabled=trial_app_enabled, ), - remote_files=RemoteFileService( - files=FileService(session_factory=database_client), - ), + remote_files=remote_file_service, trial_app_usage=TrialAppUsageRepository(session_factory=database_client), workflow_run_archives=WorkflowRunArchiveService( bundles=WorkflowRunArchiveBundleQueryRepository(session_factory=database_client), diff --git a/api/extensions/ext_commands.py b/api/extensions/ext_commands.py index 92c47f630f1..290ade6992b 100644 --- a/api/extensions/ext_commands.py +++ b/api/extensions/ext_commands.py @@ -27,6 +27,7 @@ def init_app(app: DifyApp): import_migration_data, install_plugins, install_rag_pipeline_plugins, + migrate_agent_permissions_to_rbac, migrate_data_for_plugin, migrate_dataset_permissions_to_rbac, migrate_member_roles_to_rbac, @@ -60,6 +61,7 @@ def init_app(app: DifyApp): migrate_data_for_plugin, migrate_dataset_permissions_to_rbac, migrate_member_roles_to_rbac, + migrate_agent_permissions_to_rbac, backfill_plugin_auto_upgrade, extract_plugins, extract_unique_plugins, diff --git a/api/fields/snippet_fields.py b/api/fields/snippet_fields.py index 77aba3fe76e..6c6d6469afb 100644 --- a/api/fields/snippet_fields.py +++ b/api/fields/snippet_fields.py @@ -1,12 +1,14 @@ +from collections.abc import Iterable from datetime import datetime from typing import Any from pydantic import Field, field_validator +from sqlalchemy.orm import Session from fields.base import ResponseModel from fields.member_fields import SimpleAccountResponse from libs.helper import to_timestamp -from models.snippet import SnippetType +from models.snippet import CustomizedSnippet, SnippetType class SnippetTagResponse(ResponseModel): @@ -72,3 +74,54 @@ class SnippetPaginationResponse(ResponseModel): limit: int total: int has_more: bool + + +def snippet_response(snippet: CustomizedSnippet, *, session: Session) -> SnippetResponse: + """Build the snippet detail response, resolving session-backed lookups at the request boundary.""" + return SnippetResponse.model_validate( + { + "id": snippet.id, + "name": snippet.name, + "description": snippet.description, + "type": snippet.type, + "version": snippet.version, + "use_count": snippet.use_count, + "is_published": snippet.is_published, + "icon_info": snippet.icon_info, + "graph": snippet.get_graph_dict(session=session), + "input_fields": snippet.input_fields_list, + "tags": snippet.get_tags(session=session), + "created_by": snippet.get_created_by_account(session=session), + "created_at": snippet.created_at, + "updated_by": snippet.get_updated_by_account(session=session), + "updated_at": snippet.updated_at, + } + ) + + +def snippet_list_item_response(snippet: CustomizedSnippet, *, session: Session) -> SnippetListItemResponse: + """Build one snippet list row, resolving session-backed lookups at the request boundary.""" + return SnippetListItemResponse.model_validate( + { + "id": snippet.id, + "name": snippet.name, + "description": snippet.description, + "type": snippet.type, + "version": snippet.version, + "use_count": snippet.use_count, + "is_published": snippet.is_published, + "icon_info": snippet.icon_info, + "tags": snippet.get_tags(session=session), + "created_by": snippet.created_by, + "author_name": snippet.get_author_name(session=session), + "created_at": snippet.created_at, + "updated_by": snippet.updated_by, + "updated_at": snippet.updated_at, + } + ) + + +def snippet_list_item_responses( + snippets: Iterable[CustomizedSnippet], *, session: Session +) -> list[SnippetListItemResponse]: + return [snippet_list_item_response(snippet, session=session) for snippet in snippets] diff --git a/api/models/dataset.py b/api/models/dataset.py index 327c9503420..87e6d3e5635 100644 --- a/api/models/dataset.py +++ b/api/models/dataset.py @@ -243,10 +243,6 @@ class Dataset(Base): } return self.retrieval_model or default_retrieval_model - @property - def created_by_account(self): - return self.get_created_by_account(session=db.session()) - def get_created_by_account(self, *, session: Session) -> Account | None: return session.get(Account, self.created_by) @@ -264,10 +260,6 @@ class Dataset(Base): .limit(1) ) - @property - def app_count(self) -> int: - return self.get_app_count(session=db.session()) - def get_app_count(self, *, session: Session) -> int: return ( session.scalar( @@ -278,17 +270,12 @@ class Dataset(Base): or 0 ) - @property - def document_count(self) -> int: - return self.get_document_count(session=db.session()) - def get_document_count(self, *, session: Session) -> int: return session.scalar(select(func.count(Document.id)).where(Document.dataset_id == self.id)) or 0 - @property - def available_document_count(self): + def get_available_document_count(self, *, session: Session) -> int: return ( - db.session.scalar( + session.scalar( select(func.count(Document.id)).where( Document.dataset_id == self.id, Document.indexing_status == "completed", @@ -312,10 +299,6 @@ class Dataset(Base): or 0 ) - @property - def word_count(self) -> int: - return self.get_word_count(session=db.session()) - def get_word_count(self, *, session: Session) -> int: return ( session.scalar( @@ -324,10 +307,6 @@ class Dataset(Base): or 0 ) - @property - def doc_form(self) -> str | None: - return self.get_doc_form(session=db.session()) - def get_doc_form(self, *, session: Session) -> str | None: if self.chunk_structure: return self.chunk_structure @@ -357,10 +336,6 @@ class Dataset(Base): return {**default_retrieval_model, **self.retrieval_model} - @property - def tags(self) -> Sequence[Tag]: - return self.get_tags(session=db.session()) - def get_tags(self, *, session: Session) -> Sequence[Tag]: tags = session.scalars( select(Tag) @@ -401,10 +376,6 @@ class Dataset(Base): "external_knowledge_api_endpoint": json.loads(external_knowledge_api.settings).get("endpoint", ""), } - @property - def is_published(self) -> bool: - return self.get_is_published(session=db.session()) - def get_is_published(self, *, session: Session) -> bool: if self.pipeline_id: pipeline = session.scalar(select(Pipeline).where(Pipeline.id == self.pipeline_id)) @@ -412,10 +383,6 @@ class Dataset(Base): return pipeline.is_published return False - @property - def doc_metadata(self) -> list[dict[str, str]]: - return self.get_doc_metadata(session=db.session()) - def get_doc_metadata(self, *, session: Session) -> list[dict[str, str]]: dataset_metadatas = session.scalars(select(DatasetMetadata).where(DatasetMetadata.dataset_id == self.id)).all() @@ -922,18 +889,10 @@ class DocumentSegment(TypeBase): stopped_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None) hit_count: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0) - @property - def dataset(self) -> Dataset | None: - return self.get_dataset(session=db.session()) - def get_dataset(self, *, session: Session) -> Dataset | None: """Load the owning dataset with the caller-owned database session.""" return session.get(Dataset, self.dataset_id) - @property - def document(self) -> Document | None: - return self.get_document(session=db.session()) - def get_document(self, *, session: Session) -> Document | None: """Load the owning document with the caller-owned database session.""" return session.get(Document, self.document_id) @@ -952,10 +911,6 @@ class DocumentSegment(TypeBase): ) ) - @property - def child_chunks(self): - return self.get_child_chunks(session=db.session(), include_full_doc=False) - def get_child_chunks(self, *, session: Session, include_full_doc: bool = True) -> Sequence["ChildChunk"]: """Load hierarchical child chunks with the caller-owned database session.""" document = session.get(Document, self.document_id) @@ -1042,10 +997,6 @@ class DocumentSegment(TypeBase): return text - @property - def attachments(self) -> list[AttachmentItem]: - return self.get_attachments(session=db.session()) - def get_attachments(self, *, session: Session) -> list[AttachmentItem]: """Load attachment metadata with the caller-owned database session.""" # Use JOIN to fetch attachments in a single query instead of two separate queries @@ -1195,10 +1146,6 @@ class DatasetQuery(TypeBase): DateTime, nullable=False, server_default=sa.func.current_timestamp(), init=False ) - @property - def queries(self) -> list[dict[str, Any]]: - return self.get_queries(session=db.session()) - def get_queries(self, *, session: Session) -> list[dict[str, Any]]: try: queries = json.loads(self.content) @@ -1467,7 +1414,7 @@ class ExternalKnowledgeApis(TypeBase): return None @property - def dataset_bindings(self) -> list[DatasetBindingItem]: + def dataset_bindings(self): return self.get_dataset_bindings(session=db.session()) def get_dataset_bindings(self, *, session: Session) -> list[DatasetBindingItem]: diff --git a/api/models/model.py b/api/models/model.py index a6324973865..b735268065f 100644 --- a/api/models/model.py +++ b/api/models/model.py @@ -15,7 +15,7 @@ import sqlalchemy as sa from flask import request from flask_login import UserMixin # type: ignore[import-untyped] from sqlalchemy import BigInteger, Float, Index, PrimaryKeyConstraint, String, exists, func, select, text -from sqlalchemy.orm import Mapped, Session, mapped_column, validates +from sqlalchemy.orm import Mapped, Session, mapped_column, scoped_session, validates from configs import dify_config from constants import DEFAULT_FILE_NUMBER_LIMITS @@ -57,6 +57,7 @@ from .types import EnumText, LongText, StringUUID if TYPE_CHECKING: from .agent import Agent + from .dataset import DatasetCollectionBinding from .workflow import Workflow @@ -508,7 +509,9 @@ class App(Base): agent = self.agent_app_binding_with_session(session=session) return agent.id if agent else None - def agent_app_binding_with_session(self, *, session: Session, include_archived: bool = False) -> Agent | None: + def agent_app_binding_with_session( + self, *, session: Session | scoped_session, include_archived: bool = False + ) -> Agent | None: """For an Agent App (mode=agent), the Agent bound to it. A roster Agent is bound through ``Agent.app_id``; a workflow-only Agent @@ -1042,9 +1045,8 @@ class InstalledApp(TypeBase): def app_with_session(self, *, session: Session) -> App | None: return session.scalar(select(App).where(App.id == self.app_id)) - @property - def tenant(self) -> Tenant | None: - return db.session.scalar(select(Tenant).where(Tenant.id == self.tenant_id)) + def tenant(self, session: Session) -> Tenant | None: + return session.scalar(select(Tenant).where(Tenant.id == self.tenant_id)) class TrialApp(TypeBase): @@ -1333,10 +1335,6 @@ class Conversation(Base): return model_config - @property - def summary_or_query(self): - return self.summary_or_query_with_session(session=db.session()) - def summary_or_query_with_session(self, *, session: Session) -> str: if self.summary: return self.summary @@ -1347,41 +1345,21 @@ class Conversation(Base): else: return "" - @property - def annotated(self) -> bool: - return self.annotated_with_session(session=db.session()) - def annotated_with_session(self, *, session: Session) -> bool: return ( session.scalar(select(func.count(MessageAnnotation.id)).where(MessageAnnotation.conversation_id == self.id)) or 0 ) > 0 - @property - def annotation(self) -> MessageAnnotation | None: - return self.annotation_with_session(session=db.session()) - def annotation_with_session(self, *, session: Session) -> MessageAnnotation | None: return session.scalar(select(MessageAnnotation).where(MessageAnnotation.conversation_id == self.id).limit(1)) - @property - def message_count(self) -> int: - return self.message_count_with_session(session=db.session()) - def message_count_with_session(self, *, session: Session) -> int: return session.scalar(select(func.count(Message.id)).where(Message.conversation_id == self.id)) or 0 - @property - def user_feedback_stats(self) -> dict[str, int]: - return self.user_feedback_stats_with_session(session=db.session()) - def user_feedback_stats_with_session(self, *, session: Session) -> dict[str, int]: return self._feedback_stats_with_session(session=session, from_source=FeedbackFromSource.USER) - @property - def admin_feedback_stats(self) -> dict[str, int]: - return self.admin_feedback_stats_with_session(session=db.session()) - def admin_feedback_stats_with_session(self, *, session: Session) -> dict[str, int]: return self._feedback_stats_with_session(session=session, from_source=FeedbackFromSource.ADMIN) @@ -1410,10 +1388,6 @@ class Conversation(Base): return {"like": like, "dislike": dislike} - @property - def status_count(self): - return self.status_count_with_session(session=db.session()) - def status_count_with_session(self, *, session: Session) -> dict[str, int] | None: from models.workflow import WorkflowRun @@ -1468,10 +1442,6 @@ class Conversation(Base): "paused": status_counts[WorkflowExecutionStatus.PAUSED], } - @property - def first_message(self) -> Message | None: - return self.first_message_with_session(session=db.session()) - def first_message_with_session(self, *, session: Session) -> Message | None: return session.scalar( select(Message).where(Message.conversation_id == self.id).order_by(Message.created_at.asc()) @@ -1482,10 +1452,6 @@ class Conversation(Base): with Session(db.engine, expire_on_commit=False) as session: return session.scalar(select(App).where(App.id == self.app_id)) - @property - def from_end_user_session_id(self) -> str | None: - return self.from_end_user_session_id_with_session(session=db.session()) - def from_end_user_session_id_with_session(self, *, session: Session) -> str | None: if self.from_end_user_id: end_user = session.scalar(select(EndUser).where(EndUser.id == self.from_end_user_id)) @@ -1494,10 +1460,6 @@ class Conversation(Base): return None - @property - def from_account_name(self) -> str | None: - return self.from_account_name_with_session(session=db.session()) - def from_account_name_with_session(self, *, session: Session) -> str | None: if self.from_account_id: account = session.scalar(select(Account).where(Account.id == self.from_account_id)) @@ -1740,10 +1702,6 @@ class Message(Base): return re_sign_file_url_answer - @property - def user_feedback(self) -> MessageFeedback | None: - return self.user_feedback_with_session(session=db.session()) - def user_feedback_with_session(self, *, session: Session) -> MessageFeedback | None: return session.scalar( select(MessageFeedback).where(MessageFeedback.message_id == self.id, MessageFeedback.from_source == "user") @@ -1757,24 +1715,12 @@ class Message(Base): select(MessageFeedback).where(MessageFeedback.message_id == self.id, MessageFeedback.from_source == "admin") ) - @property - def feedbacks(self) -> Sequence[MessageFeedback]: - return self.feedbacks_with_session(session=db.session()) - def feedbacks_with_session(self, *, session: Session) -> Sequence[MessageFeedback]: return session.scalars(select(MessageFeedback).where(MessageFeedback.message_id == self.id)).all() - @property - def annotation(self) -> MessageAnnotation | None: - return self.annotation_with_session(session=db.session()) - def annotation_with_session(self, *, session: Session) -> MessageAnnotation | None: return session.scalar(select(MessageAnnotation).where(MessageAnnotation.message_id == self.id)) - @property - def annotation_hit_history(self) -> MessageAnnotation | None: - return self.annotation_hit_history_with_session(session=db.session()) - def annotation_hit_history_with_session(self, *, session: Session) -> MessageAnnotation | None: annotation_history = session.scalar( select(AppAnnotationHitHistory).where(AppAnnotationHitHistory.message_id == self.id) @@ -1785,10 +1731,6 @@ class Message(Base): ) return None - @property - def app_model_config(self) -> AppModelConfig | None: - return self.app_model_config_with_session(session=db.session()) - def app_model_config_with_session(self, *, session: Session) -> AppModelConfig | None: conversation = session.scalar(select(Conversation).where(Conversation.id == self.conversation_id)) if conversation: @@ -1804,10 +1746,6 @@ class Message(Base): def message_metadata_dict(self) -> dict[str, Any]: return json.loads(self.message_metadata) if self.message_metadata else {} - @property - def agent_thoughts(self) -> Sequence[MessageAgentThought]: - return self.agent_thoughts_with_session(session=db.session()) - def agent_thoughts_with_session(self, *, session: Session) -> Sequence[MessageAgentThought]: return session.scalars( select(MessageAgentThought) @@ -1819,10 +1757,6 @@ class Message(Base): def retriever_resources(self) -> Any: return self.message_metadata_dict.get("retriever_resources") if self.message_metadata else [] - @property - def message_files(self) -> list[MessageFileInfo]: - return self.message_files_with_session(session=db.session()) - def message_files_with_session(self, *, session: Session) -> list[MessageFileInfo]: from factories import file_factory @@ -1993,10 +1927,6 @@ class MessageFeedback(TypeBase): init=False, ) - @property - def from_account(self) -> Account | None: - return self.from_account_with_session(session=db.session()) - def from_account_with_session(self, *, session: Session) -> Account | None: return session.scalar(select(Account).where(Account.id == self.from_account_id)) @@ -2082,17 +2012,9 @@ class MessageAnnotation(TypeBase): """Return a non-null question string, falling back to the answer content.""" return self.question or self.content - @property - def account(self) -> Account | None: - return self.account_with_session(session=db.session()) - def account_with_session(self, *, session: Session) -> Account | None: return session.scalar(select(Account).where(Account.id == self.account_id)) - @property - def annotation_create_account(self) -> Account | None: - return self.annotation_create_account_with_session(session=db.session()) - def annotation_create_account_with_session(self, *, session: Session) -> Account | None: return session.scalar(select(Account).where(Account.id == self.account_id)) @@ -2160,11 +2082,10 @@ class AppAnnotationSetting(TypeBase): init=False, ) - @property - def collection_binding_detail(self): + def collection_binding_detail(self, session: Session) -> DatasetCollectionBinding | None: from .dataset import DatasetCollectionBinding - return db.session.scalar( + return session.scalar( select(DatasetCollectionBinding).where(DatasetCollectionBinding.id == self.collection_binding_id) ) diff --git a/api/models/snippet.py b/api/models/snippet.py index 4a9320e51f6..57c51ea9e3f 100644 --- a/api/models/snippet.py +++ b/api/models/snippet.py @@ -1,17 +1,17 @@ import json +from collections.abc import Sequence from datetime import datetime from enum import StrEnum from typing import Any import sqlalchemy as sa from sqlalchemy import DateTime, String, func -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, Session, mapped_column from libs.uuid_utils import uuidv7 from .account import Account from .base import Base -from .engine import db from .model import Tag, TagBinding from .types import AdjustedJSON, LongText, StringUUID @@ -65,13 +65,12 @@ class CustomizedSnippet(Base): DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp() ) - @property - def graph_dict(self) -> dict[str, Any]: + def get_graph_dict(self, *, session: Session) -> dict[str, Any]: """Get graph from associated workflow.""" if self.workflow_id: from .workflow import Workflow - workflow = db.session.get(Workflow, self.workflow_id) + workflow = session.get(Workflow, self.workflow_id) if workflow: return json.loads(workflow.graph) if workflow.graph else {} return {} @@ -81,10 +80,9 @@ class CustomizedSnippet(Base): """Parse input_fields JSON to list.""" return json.loads(self.input_fields) if self.input_fields else [] - @property - def tags(self): + def get_tags(self, *, session: Session) -> Sequence[Tag]: """Get snippet tags.""" - tags = db.session.scalars( + tags = session.scalars( sa.select(Tag) .join(TagBinding, Tag.id == TagBinding.tag_id) .where( @@ -97,24 +95,21 @@ class CustomizedSnippet(Base): return tags or [] - @property - def created_by_account(self) -> Account | None: + def get_created_by_account(self, *, session: Session) -> Account | None: """Get the account that created this snippet.""" if self.created_by: - return db.session.get(Account, self.created_by) + return session.get(Account, self.created_by) return None - @property - def author_name(self) -> str | None: + def get_author_name(self, *, session: Session) -> str | None: """Get the creator account name.""" - account = self.created_by_account + account = self.get_created_by_account(session=session) return account.name if account else None - @property - def updated_by_account(self) -> Account | None: + def get_updated_by_account(self, *, session: Session) -> Account | None: """Get the account that last updated this snippet.""" if self.updated_by: - return db.session.get(Account, self.updated_by) + return session.get(Account, self.updated_by) return None @property diff --git a/api/models/tools.py b/api/models/tools.py index ceb54207a58..222d8d9c0eb 100644 --- a/api/models/tools.py +++ b/api/models/tools.py @@ -197,11 +197,10 @@ class ApiToolProvider(TypeBase): def credentials(self) -> dict[str, Any]: return dict[str, Any](json.loads(self.credentials_str)) - @property - def user(self) -> Account | None: + def user(self, session: Session) -> Account | None: if not self.user_id: return None - return db.session.scalar(select(Account).where(Account.id == self.user_id)) + return session.scalar(select(Account).where(Account.id == self.user_id)) def tenant(self, session: Session) -> Tenant | None: return session.scalar(select(Tenant).where(Tenant.id == self.tenant_id)) diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md index 2bf4c995c66..58c45079d6a 100644 --- a/api/openapi/markdown/console-openapi.md +++ b/api/openapi/markdown/console-openapi.md @@ -2172,7 +2172,7 @@ Update annotation settings for an app | Code | Description | | ---- | ----------- | -| 204 | Annotations deleted successfully | +| 200 | Success | ### [GET] /apps/{app_id}/annotations Get annotations for an app with pagination @@ -2294,7 +2294,7 @@ Export all annotations for an app with CSV injection protection | Code | Description | | ---- | ----------- | -| 204 | Annotation deleted successfully | +| 200 | Success | ### [POST] /apps/{app_id}/annotations/{annotation_id} Update or delete an annotation @@ -3324,9 +3324,9 @@ Create a new tracing configuration for an application #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [WorkflowTriggerResponse](#workflowtriggerresponse)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [GET] /apps/{app_id}/triggers **Get app triggers list** @@ -4713,7 +4713,7 @@ Full value for one declared output of a published run. | Code | Description | | ---- | ----------- | -| 204 | Workflow deleted successfully | +| 200 | Success | ### [PATCH] /apps/{app_id}/workflows/{workflow_id} **Update workflow attributes** @@ -4861,9 +4861,9 @@ Restore a published workflow version into the draft workflow #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [SimpleResultResponse](#simpleresultresponse)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [POST] /auth/plugin/datasource/{provider_id}/custom-client #### Parameters @@ -5047,16 +5047,16 @@ Get compliance document download link ### [GET] /data-source/integrates #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [DataSourceIntegrateListResponse](#datasourceintegratelistresponse)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [PATCH] /data-source/integrates #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [SimpleResultResponse](#simpleresultresponse)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [GET] /data-source/integrates/{binding_id}/{action} #### Parameters @@ -5068,9 +5068,9 @@ Get compliance document download link #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [DataSourceIntegrateListResponse](#datasourceintegratelistresponse)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [PATCH] /data-source/integrates/{binding_id}/{action} #### Parameters @@ -5082,9 +5082,9 @@ Get compliance document download link #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [SimpleResultResponse](#simpleresultresponse)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [GET] /datasets Get list of datasets @@ -6446,6 +6446,117 @@ Check if dataset is in use | ---- | ----------- | | 204 | API key deleted successfully | +### [POST] /dify-builder/agent/ping +#### Responses + +| Code | Description | +| ---- | ----------- | +| 200 | Success | + +### [POST] /dify-builder/sessions +#### Request Body + +| Required | Schema | +| -------- | ------ | +| Yes | **application/json**: [DifyBuilderCreateSessionPayload](#difybuildercreatesessionpayload)
| + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Dify Builder event stream | **text/event-stream**: [DifyBuilderStreamEventResponse](#difybuilderstreameventresponse)
| +| 400 | Invalid request | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| + +### [GET] /dify-builder/sessions/{session_id} +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| session_id | path | | Yes | string | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Dify Builder session state | **application/json**: [DifyBuilderSessionViewResponse](#difybuildersessionviewresponse)
| +| 404 | Session not found | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| + +### [POST] /dify-builder/sessions/{session_id}/actions +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| session_id | path | | Yes | string | + +#### Request Body + +| Required | Schema | +| -------- | ------ | +| Yes | **application/json**: [DifyBuilderSubmitActionPayload](#difybuildersubmitactionpayload)
| + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Dify Builder event stream | **text/event-stream**: [DifyBuilderStreamEventResponse](#difybuilderstreameventresponse)
| +| 400 | Invalid request | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| +| 404 | Session not found | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| +| 409 | Session conflict | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| + +### [GET] /dify-builder/sessions/{session_id}/conversation +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| after_seq | query | Load groups after this sequence | No | integer | +| before_seq | query | Load groups before this sequence | No | integer | +| limit | query | Number of conversation groups to return | No | integer,
**Default:** 20 | +| session_id | path | | Yes | string | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Dify Builder conversation page | **application/json**: [DifyBuilderConversationPageResponse](#difybuilderconversationpageresponse)
| +| 400 | Invalid request | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| +| 404 | Session not found | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| + +### [POST] /dify-builder/sessions/{session_id}/messages +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| session_id | path | | Yes | string | + +#### Request Body + +| Required | Schema | +| -------- | ------ | +| Yes | **application/json**: [DifyBuilderSubmitMessagePayload](#difybuildersubmitmessagepayload)
| + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Dify Builder event stream | **text/event-stream**: [DifyBuilderStreamEventResponse](#difybuilderstreameventresponse)
| +| 400 | Invalid request | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| +| 404 | Session not found | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| +| 409 | Session conflict | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| + +### [GET] /dify-builder/sessions/{session_id}/stream +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| session_id | path | | Yes | string | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Dify Builder reconnect event stream | **text/event-stream**: [DifyBuilderStreamEventResponse](#difybuilderstreameventresponse)
| +| 404 | Session not found | **application/json**: [DifyBuilderErrorResponse](#difybuildererrorresponse)
| + ### [POST] /email-code-login #### Request Body @@ -6552,7 +6663,9 @@ Check if dataset is in use | 404 | Recommended app not found | | ### [GET] /features -**Get feature configuration for current tenant** +**Get current workspace features** + +Get feature availability and limits for the current workspace #### Responses @@ -7869,17 +7982,11 @@ Update account-level Step-by-step Tour state | ---- | ---------- | ----------- | -------- | ------ | | pipeline_id | path | | Yes | string (uuid) | -#### Request Body - -| Required | Schema | -| -------- | ------ | -| Yes | **application/json**: [DraftWorkflowSyncPayload](#draftworkflowsyncpayload)
| - #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [RagPipelineWorkflowSyncResponse](#ragpipelineworkflowsyncresponse)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [POST] /rag/pipelines/{pipeline_id}/workflows/draft/datasource/nodes/{node_id}/run **Run rag pipeline datasource** @@ -8179,12 +8286,6 @@ Update account-level Step-by-step Tour state | pipeline_id | path | | Yes | string (uuid) | | variable_id | path | | Yes | string (uuid) | -#### Request Body - -| Required | Schema | -| -------- | ------ | -| Yes | **application/json**: [WorkflowDraftVariablePatchPayload](#workflowdraftvariablepatchpayload)
| - #### Responses | Code | Description | Schema | @@ -8359,12 +8460,6 @@ Update account-level Step-by-step Tour state | pipeline_id | path | | Yes | string (uuid) | | workflow_id | path | | Yes | string | -#### Request Body - -| Required | Schema | -| -------- | ------ | -| Yes | **application/json**: [WorkflowUpdatePayload](#workflowupdatepayload)
| - #### Responses | Code | Description | Schema | @@ -11159,16 +11254,16 @@ Returns permission flags that control workspace features like member invitations ### [GET] /workspaces/current/rbac/access-policies #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [_AccessPolicyList](#_accesspolicylist)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [POST] /workspaces/current/rbac/access-policies #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 201 | Policy created | **application/json**: [AccessPolicy](#accesspolicy)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [DELETE] /workspaces/current/rbac/access-policies/{policy_id} #### Parameters @@ -11179,9 +11274,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [AccessPolicy](#accesspolicy)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [GET] /workspaces/current/rbac/access-policies/{policy_id} #### Parameters @@ -11192,9 +11287,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [AccessPolicy](#accesspolicy)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [PUT] /workspaces/current/rbac/access-policies/{policy_id} #### Parameters @@ -11205,9 +11300,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [AccessPolicy](#accesspolicy)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [POST] /workspaces/current/rbac/access-policies/{policy_id}/copy #### Parameters @@ -11218,9 +11313,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 201 | Policy copied | **application/json**: [AccessPolicy](#accesspolicy)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [PUT] /workspaces/current/rbac/access-policy-bindings/{binding_id}/lock #### Parameters @@ -11231,9 +11326,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [AccessPolicyBindingState](#accesspolicybindingstate)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [PUT] /workspaces/current/rbac/access-policy-bindings/{binding_id}/unlock #### Parameters @@ -11244,9 +11339,153 @@ Returns permission flags that control workspace features like member invitations #### Responses +| Code | Description | +| ---- | ----------- | +| 200 | Success | + +### [DELETE] /workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/member-bindings +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| agent_id | path | | Yes | string (uuid) | +| policy_id | path | | Yes | string | + +#### Request Body + +| Required | Schema | +| -------- | ------ | +| Yes | **application/json**: [_DeleteMemberBindingsRequest](#_deletememberbindingsrequest)
| + +#### Responses + | Code | Description | Schema | | ---- | ----------- | ------ | -| 200 | Success | **application/json**: [AccessPolicyBindingState](#accesspolicybindingstate)
| +| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)
| + +### [GET] /workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/member-bindings +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| agent_id | path | | Yes | string (uuid) | +| policy_id | path | | Yes | string | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)
| + +### [GET] /workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/role-bindings +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| agent_id | path | | Yes | string (uuid) | +| policy_id | path | | Yes | string (uuid) | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [RoleBindingsResponse](#rolebindingsresponse)
| + +### [GET] /workspaces/current/rbac/agents/{agent_id}/access-policy +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| language | query | Localized policy label language | No | string,
**Available values:** "en", "ja", "zh" | +| agent_id | path | | Yes | string (uuid) | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [AgentAccessMatrix](#agentaccessmatrix)
| + +### [GET] /workspaces/current/rbac/agents/{agent_id}/user-access-policies +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| language | query | Localized policy label language | No | string,
**Available values:** "en", "ja", "zh" | +| limit | query | | No | integer | +| page | query | | No | integer | +| reverse | query | | No | boolean | +| agent_id | path | | Yes | string (uuid) | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [ResourceUserAccessPoliciesResponse](#resourceuseraccesspoliciesresponse)
| + +### [PUT] /workspaces/current/rbac/agents/{agent_id}/users/{target_account_id}/access-policies +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| agent_id | path | | Yes | string (uuid) | +| target_account_id | path | | Yes | string (uuid) | + +#### Request Body + +| Required | Schema | +| -------- | ------ | +| Yes | **application/json**: [ReplaceUserAccessPolicies](#replaceuseraccesspolicies)
| + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [ReplaceUserAccessPoliciesResponse](#replaceuseraccesspoliciesresponse)
| + +### [GET] /workspaces/current/rbac/agents/{agent_id}/whitelist +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| agent_id | path | | Yes | string (uuid) | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [ResourceWhitelist](#resourcewhitelist)
| + +### [PUT] /workspaces/current/rbac/agents/{agent_id}/whitelist +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| agent_id | path | | Yes | string (uuid) | + +#### Request Body + +| Required | Schema | +| -------- | ------ | +| Yes | **application/json**: [_ResourceAccessScopeRequest](#_resourceaccessscoperequest)
| + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [ResourceWhitelist](#resourcewhitelist)
| + +### [GET] /workspaces/current/rbac/agents/{agent_id}/whitelist_config +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| agent_id | path | | Yes | string (uuid) | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [ResourceWhitelistConfig](#resourcewhitelistconfig)
| ### [DELETE] /workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings #### Parameters @@ -11582,6 +11821,13 @@ Returns permission flags that control workspace features like member invitations | ---- | ----------- | ------ | | 200 | Success | **application/json**: [PermissionCatalogResponse](#permissioncatalogresponse)
| +### [GET] /workspaces/current/rbac/role-permissions/catalog/agent +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [PermissionCatalogResponse](#permissioncatalogresponse)
| + ### [GET] /workspaces/current/rbac/role-permissions/catalog/app #### Responses @@ -11599,16 +11845,16 @@ Returns permission flags that control workspace features like member invitations ### [GET] /workspaces/current/rbac/roles #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [_RBACRoleList](#_rbacrolelist)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [POST] /workspaces/current/rbac/roles #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 201 | Role created | **application/json**: [RBACRole](#rbacrole)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [DELETE] /workspaces/current/rbac/roles/{role_id} #### Parameters @@ -11619,9 +11865,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [RBACRole](#rbacrole)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [GET] /workspaces/current/rbac/roles/{role_id} #### Parameters @@ -11632,9 +11878,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [RBACRole](#rbacrole)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [PUT] /workspaces/current/rbac/roles/{role_id} #### Parameters @@ -11645,9 +11891,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 200 | Success | **application/json**: [RBACRole](#rbacrole)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [POST] /workspaces/current/rbac/roles/{role_id}/copy #### Parameters @@ -11658,9 +11904,9 @@ Returns permission flags that control workspace features like member invitations #### Responses -| Code | Description | Schema | -| ---- | ----------- | ------ | -| 201 | Role copied | **application/json**: [RBACRole](#rbacrole)
| +| Code | Description | +| ---- | ----------- | +| 200 | Success | ### [GET] /workspaces/current/rbac/roles/{role_id}/members #### Parameters @@ -11675,6 +11921,58 @@ Returns permission flags that control workspace features like member invitations | ---- | ----------- | ------ | | 200 | Success | **application/json**: [_MembersInRoleList](#_membersinrolelist)
| +### [PUT] /workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/bindings +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| policy_id | path | | Yes | string (uuid) | + +#### Request Body + +| Required | Schema | +| -------- | ------ | +| Yes | **application/json**: [_ReplaceBindingsRequest](#_replacebindingsrequest)
| + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [AccessMatrixItem](#accessmatrixitem)
| + +### [GET] /workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/member-bindings +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| policy_id | path | | Yes | string (uuid) | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [MemberBindingsResponse](#memberbindingsresponse)
| + +### [GET] /workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/role-bindings +#### Parameters + +| Name | Located in | Description | Required | Schema | +| ---- | ---------- | ----------- | -------- | ------ | +| policy_id | path | | Yes | string (uuid) | + +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [RoleBindingsResponse](#rolebindingsresponse)
| + +### [GET] /workspaces/current/rbac/workspace/agents/access-policy +#### Responses + +| Code | Description | Schema | +| ---- | ----------- | ------ | +| 200 | Success | **application/json**: [WorkspaceAccessMatrix](#workspaceaccessmatrix)
| + ### [PUT] /workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/bindings #### Parameters @@ -13307,6 +13605,28 @@ Model class for AI model. | roles | [ object ] | | No | | status | string | | Yes | +#### Action + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| canvas_event | string | | No | +| id | string | | Yes | +| kind | [ActionKind](#actionkind) | | Yes | +| label | string | | Yes | +| next_state | string | | No | + +#### ActionKind + +Action button styling / semantics (spec §2, §5). + +``automatic`` actions are not buttons — the client must not render +them; the server auto-advances. They exist in the stream only so the +FE can show "auto-continuing...". + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| ActionKind | string | Action button styling / semantics (spec §2, §5). ``automatic`` actions are not buttons — the client must not render them; the server auto-advances. They exist in the stream only so the FE can show "auto-continuing...". | | + #### ActivateCheckQuery | Name | Type | Description | Required | @@ -13401,6 +13721,13 @@ Model class for AI model. | chat_prompt_config | object | | No | | completion_prompt_config | object | | No | +#### AgentAccessMatrix + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| agent_id | string | | No | +| items | [ [AccessMatrixItem](#accessmatrixitem) ] | | No | + #### AgentApiAccessResponse | Name | Type | Description | Required | @@ -14580,6 +14907,20 @@ section may be empty, which is how callers express "no knowledge layer". | type | string | | No | | url | string | | No | +#### AgentMessageEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| answer | string | | Yes | +| at_version | integer | | Yes | +| id | string | | Yes | +| kind | string,
**Default:** agent_message | | No | +| operation_id | string | | Yes | +| revision | integer | | Yes | +| seq | integer | | Yes | +| session_id | string | | Yes | +| stage_id | string | | Yes | + #### AgentModelResponseFormatConfig | Name | Type | Description | Required | @@ -15735,6 +16076,14 @@ AppMCPServer Status Enum | use_icon_as_answer_icon | boolean | | No | | workflow | [WorkflowPartial](#workflowpartial) | | No | +#### AppRevision + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| conflicted | boolean | | Yes | +| current | string | | Yes | +| observed | string | | Yes | + #### AppSelectorScope | Name | Type | Description | Required | @@ -15813,6 +16162,18 @@ AppMCPServer Status Enum | required | boolean | | No | | type | string | | Yes | +#### AssistantTurnItem + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| card_state | string | | No | +| cards | [ string ] | | No | +| execution | [ExecutionProgress](#executionprogress) | | Yes | +| reasoning_text | string | | No | +| reply_text | string | | No | +| stage_id | string | | Yes | +| turn_id | string | | Yes | + #### AudioBinaryResponse | Name | Type | Description | Required | @@ -15926,7 +16287,6 @@ ExporleBanner status | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | -| enabled | boolean | Deprecated. Use system features deployment_edition to determine the product edition. | Yes | | subscription | [SubscriptionModel](#subscriptionmodel) | | Yes | #### BillingOperationFailedErrorResponse @@ -15981,6 +16341,21 @@ ExporleBanner status | login_page_logo | string | | Yes | | workspace_logo | string | | Yes | +#### BuildLearningCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| policy | string | | Yes | +| state | string | | Yes | + +#### BuilderErrorCode + +Stable HTTP error codes returned by the Builder console routes. + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| BuilderErrorCode | string | Stable HTTP error codes returned by the Builder console routes. | | + #### BuiltinCredentialListQuery | Name | Type | Description | Required | @@ -16034,6 +16409,47 @@ Button styles for user actions. | ---- | ---- | ----------- | -------- | | ButtonStyle | string | Button styles for user actions. | | +#### CanvasEdge + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| source | string | | Yes | +| target | string | | Yes | + +#### CanvasEvent + +Granular canvas-mutation signals (spec §6). + +Exactly 22 members, snake_cased from the mock's ``DifyBuilderCanvasEvent`` +union. Presentation of committed backend state: replaying these from a +snapshot must reconstruct the same canvas. + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| CanvasEvent | string | Granular canvas-mutation signals (spec §6). Exactly 22 members, snake_cased from the mock's ``DifyBuilderCanvasEvent`` union. Presentation of committed backend state: replaying these from a snapshot must reconstruct the same canvas. | | + +#### CanvasEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| edge | [CanvasEdge](#canvasedge) | | No | +| event | [CanvasEvent](#canvasevent) | | Yes | +| kind | string,
**Default:** canvas | | No | +| node_id | string | | No | +| operation_id | string | | Yes | +| revision | integer | | Yes | +| session_id | string | | Yes | +| stage_id | string | | Yes | + +#### ChallengeCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| body | string | | Yes | +| title | string | | Yes | +| tone | string,
**Default:** warning | | No | + #### ChangeEmailResetPayload | Name | Type | Description | Required | @@ -16058,6 +16474,22 @@ Button styles for user actions. | email | string | | Yes | | token | string | | Yes | +#### ChangeSetCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| changes | [ string ] | | Yes | +| count | integer | | Yes | +| nodes | [ [ChangedNode](#changednode) ] | | No | +| scope | string | | Yes | + +#### ChangedNode + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| node_id | string | | Yes | +| title | string | | No | + #### ChatConversationQuery | Name | Type | Description | Required | @@ -16124,6 +16556,22 @@ Button styles for user actions. | passed | boolean | | Yes | | reason | string | | No | +#### CheckpointCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| checkpoint_id | string | | Yes | +| created_at | string | | Yes | +| label | string | | Yes | + +#### CheckpointRef + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| checkpoint_id | string | | Yes | +| created_at | string | | Yes | +| label | string | | Yes | + #### ChildChunkBatchUpdatePayload | Name | Type | Description | Required | @@ -16374,6 +16822,14 @@ Enum class for configurate method of provider model. | ---- | ---- | ----------- | -------- | | ConfigurateMethod | string | Enum class for configurate method of provider model. | | +#### ConflictPolicyOption + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| id | string | | Yes | +| label | string | | Yes | +| recommended | boolean | | No | + #### ConsoleDatasetListQuery | Name | Type | Description | Required | @@ -17347,6 +17803,12 @@ Enum class for datasource provider | start_node_id | string | | Yes | | start_node_title | string | | Yes | +#### DecisionItem + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| text | string | | Yes | + #### DeclaredArrayItem Per-item shape for an ``array``-typed declared output. @@ -17483,6 +17945,415 @@ Enum representing the deployment edition of the platform. | ---- | ---- | ----------- | -------- | | DeploymentEdition | string | Enum representing the deployment edition of the platform. | | +#### DifyBuilderActiveInteractionResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| action_id | string | | Yes | +| card | [DifyBuilderUserConversationItemResponse](#difybuilderuserconversationitemresponse)
[DifyBuilderDecisionConversationItemResponse](#difybuilderdecisionconversationitemresponse)
[DifyBuilderNoticeConversationItemResponse](#difybuildernoticeconversationitemresponse)
[DifyBuilderRunContextConversationItemResponse](#difybuilderruncontextconversationitemresponse)
[DifyBuilderPreflightContextConversationItemResponse](#difybuilderpreflightcontextconversationitemresponse)
[DifyBuilderAssistantTurnConversationItemResponse](#difybuilderassistantturnconversationitemresponse)
[DifyBuilderPlanConversationItemResponse](#difybuilderplanconversationitemresponse)
[DifyBuilderFormConversationItemResponse](#difybuilderformconversationitemresponse)
[DifyBuilderChallengeConversationItemResponse](#difybuilderchallengeconversationitemresponse)
[DifyBuilderResourceSelectConversationItemResponse](#difybuilderresourceselectconversationitemresponse)
[DifyBuilderCheckpointConversationItemResponse](#difybuildercheckpointconversationitemresponse)
[DifyBuilderChangeSetConversationItemResponse](#difybuilderchangesetconversationitemresponse)
[DifyBuilderTestResultConversationItemResponse](#difybuildertestresultconversationitemresponse)
[DifyBuilderErrorConversationItemResponse](#difybuildererrorconversationitemresponse)
[DifyBuilderSummaryConversationItemResponse](#difybuildersummaryconversationitemresponse)
[DifyBuilderPublishConversationItemResponse](#difybuilderpublishconversationitemresponse)
[DifyBuilderBuildLearningConversationItemResponse](#difybuilderbuildlearningconversationitemresponse) | | Yes | +| valid_at_version | integer | | Yes | + +#### DifyBuilderAgentMessageEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [AgentMessageEventData](#agentmessageeventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderAssistantTurnConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [AssistantTurnItem](#assistantturnitem) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderBuildLearningConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [BuildLearningCard](#buildlearningcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderCanvasEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [CanvasEventData](#canvaseventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderChallengeConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [ChallengeCard](#challengecard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderChangeSetConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [ChangeSetCard](#changesetcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderChecklistErrorPayload + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| messages | [ string ] | | Yes | +| node_id | string | | Yes | +| node_type | string | | Yes | +| plugin_missing | boolean | | Yes | +| title | string | | Yes | +| unconnected | boolean | | Yes | + +#### DifyBuilderCheckpointConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [CheckpointCard](#checkpointcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderCommandStartedEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| actions | [ [Action](#action) ] | | No | +| active_interaction | [DifyBuilderActiveInteractionResponse](#difybuilderactiveinteractionresponse) | | No | +| app_id | string | | Yes | +| app_revision | [AppRevision](#apprevision) | | No | +| canvas_read_only | boolean | | Yes | +| checkpoint | [CheckpointRef](#checkpointref) | | No | +| conversation_last_seq | integer | | Yes | +| entry_mode | [EntryMode](#entrymode) | | No | +| interrupted | boolean | | Yes | +| kind | string,
**Default:** command_started | | No | +| model | [SessionModel](#sessionmodel) | | No | +| phase | [Phase](#phase) | | No | +| recovery | [RecoveryRef](#recoveryref) | | No | +| run_status | [RunStatus](#runstatus) | | Yes | +| session_id | string | | Yes | +| state | string | | Yes | +| version | integer | | Yes | + +#### DifyBuilderCommandStartedEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [DifyBuilderCommandStartedEventData](#difybuildercommandstartedeventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderCommitEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| items | [ [DifyBuilderUserConversationItemResponse](#difybuilderuserconversationitemresponse)
[DifyBuilderDecisionConversationItemResponse](#difybuilderdecisionconversationitemresponse)
[DifyBuilderNoticeConversationItemResponse](#difybuildernoticeconversationitemresponse)
[DifyBuilderRunContextConversationItemResponse](#difybuilderruncontextconversationitemresponse)
[DifyBuilderPreflightContextConversationItemResponse](#difybuilderpreflightcontextconversationitemresponse)
[DifyBuilderAssistantTurnConversationItemResponse](#difybuilderassistantturnconversationitemresponse)
[DifyBuilderPlanConversationItemResponse](#difybuilderplanconversationitemresponse)
[DifyBuilderFormConversationItemResponse](#difybuilderformconversationitemresponse)
[DifyBuilderChallengeConversationItemResponse](#difybuilderchallengeconversationitemresponse)
[DifyBuilderResourceSelectConversationItemResponse](#difybuilderresourceselectconversationitemresponse)
[DifyBuilderCheckpointConversationItemResponse](#difybuildercheckpointconversationitemresponse)
[DifyBuilderChangeSetConversationItemResponse](#difybuilderchangesetconversationitemresponse)
[DifyBuilderTestResultConversationItemResponse](#difybuildertestresultconversationitemresponse)
[DifyBuilderErrorConversationItemResponse](#difybuildererrorconversationitemresponse)
[DifyBuilderSummaryConversationItemResponse](#difybuildersummaryconversationitemresponse)
[DifyBuilderPublishConversationItemResponse](#difybuilderpublishconversationitemresponse)
[DifyBuilderBuildLearningConversationItemResponse](#difybuilderbuildlearningconversationitemresponse) ] | | Yes | +| kind | string,
**Default:** commit | | No | +| operation_id | string | | Yes | +| session_id | string | | Yes | +| settled | boolean | | Yes | +| stage_id | string | | Yes | +| state | string | | Yes | +| version | integer | | Yes | + +#### DifyBuilderCommitEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [DifyBuilderCommitEventData](#difybuildercommiteventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderConversationListQuery + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| after_seq | integer | Load groups after this sequence | No | +| before_seq | integer | Load groups before this sequence | No | +| limit | integer,
**Default:** 20 | Number of conversation groups to return | No | + +#### DifyBuilderConversationPageResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [ [DifyBuilderUserConversationItemResponse](#difybuilderuserconversationitemresponse)
[DifyBuilderDecisionConversationItemResponse](#difybuilderdecisionconversationitemresponse)
[DifyBuilderNoticeConversationItemResponse](#difybuildernoticeconversationitemresponse)
[DifyBuilderRunContextConversationItemResponse](#difybuilderruncontextconversationitemresponse)
[DifyBuilderPreflightContextConversationItemResponse](#difybuilderpreflightcontextconversationitemresponse)
[DifyBuilderAssistantTurnConversationItemResponse](#difybuilderassistantturnconversationitemresponse)
[DifyBuilderPlanConversationItemResponse](#difybuilderplanconversationitemresponse)
[DifyBuilderFormConversationItemResponse](#difybuilderformconversationitemresponse)
[DifyBuilderChallengeConversationItemResponse](#difybuilderchallengeconversationitemresponse)
[DifyBuilderResourceSelectConversationItemResponse](#difybuilderresourceselectconversationitemresponse)
[DifyBuilderCheckpointConversationItemResponse](#difybuildercheckpointconversationitemresponse)
[DifyBuilderChangeSetConversationItemResponse](#difybuilderchangesetconversationitemresponse)
[DifyBuilderTestResultConversationItemResponse](#difybuildertestresultconversationitemresponse)
[DifyBuilderErrorConversationItemResponse](#difybuildererrorconversationitemresponse)
[DifyBuilderSummaryConversationItemResponse](#difybuildersummaryconversationitemresponse)
[DifyBuilderPublishConversationItemResponse](#difybuilderpublishconversationitemresponse)
[DifyBuilderBuildLearningConversationItemResponse](#difybuilderbuildlearningconversationitemresponse) ] | | Yes | +| first_seq | integer | | Yes | +| has_more | boolean | | Yes | +| last_seq | integer | | Yes | + +#### DifyBuilderCreateBuildSessionPayload + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| app_id | string | | Yes | +| goal_text | string | | Yes | +| model_config | [SessionModel](#sessionmodel) | | No | +| scenario | string | | Yes | + +#### DifyBuilderCreateChecklistFixSessionPayload + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| app_id | string | | Yes | +| checklist_errors | [ [DifyBuilderChecklistErrorPayload](#difybuilderchecklisterrorpayload) ] | | Yes | +| failed_run_id | string | | No | +| model_config | [SessionModel](#sessionmodel) | | No | +| scenario | string | | Yes | + +#### DifyBuilderCreateEditSessionPayload + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| app_id | string | | Yes | +| goal_text | string | | Yes | +| model_config | [SessionModel](#sessionmodel) | | No | +| scenario | string | | Yes | + +#### DifyBuilderCreateFixSessionPayload + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| app_id | string | | Yes | +| failed_run_id | string | | Yes | +| model_config | [SessionModel](#sessionmodel) | | No | +| scenario | string | | Yes | + +#### DifyBuilderCreateSessionPayload + +Create a Build, Edit, failed-run Fix, or checklist Fix session. + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| DifyBuilderCreateSessionPayload | [DifyBuilderCreateBuildSessionPayload](#difybuildercreatebuildsessionpayload)
[DifyBuilderCreateEditSessionPayload](#difybuildercreateeditsessionpayload)
[DifyBuilderCreateFixSessionPayload](#difybuildercreatefixsessionpayload)
[DifyBuilderCreateChecklistFixSessionPayload](#difybuildercreatechecklistfixsessionpayload) | Create a Build, Edit, failed-run Fix, or checklist Fix session. | | + +#### DifyBuilderDecisionConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [DecisionItem](#decisionitem) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderErrorConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [ErrorCard](#errorcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderErrorEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [ErrorEventData](#erroreventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderErrorResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| code | [BuilderErrorCode](#buildererrorcode) | | Yes | +| message | string | | No | +| recoverable | boolean | | No | + +#### DifyBuilderFormConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [FormCard](#formcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderNodeEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [NodeEventData](#nodeeventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderNoticeConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [NoticeItem](#noticeitem) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderPlanConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [PlanCard](#plancard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderPreflightContextConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [PreflightContextCard](#preflightcontextcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderProgressEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [ProgressEventData](#progresseventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderPublishConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [PublishCard](#publishcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderReasoningEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [ReasoningEventData](#reasoningeventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderResourceSelectConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [ResourceSelectCard](#resourceselectcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderRunContextConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [RunContextCard](#runcontextcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderSessionViewResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| actions | [ [Action](#action) ] | | No | +| active_interaction | [DifyBuilderActiveInteractionResponse](#difybuilderactiveinteractionresponse) | | No | +| app_id | string | | Yes | +| app_revision | [AppRevision](#apprevision) | | No | +| canvas_read_only | boolean | | Yes | +| checkpoint | [CheckpointRef](#checkpointref) | | No | +| conversation_last_seq | integer | | Yes | +| entry_mode | [EntryMode](#entrymode) | | No | +| interrupted | boolean | | Yes | +| model | [SessionModel](#sessionmodel) | | No | +| phase | [Phase](#phase) | | No | +| recovery | [RecoveryRef](#recoveryref) | | No | +| run_status | [RunStatus](#runstatus) | | Yes | +| session_id | string | | Yes | +| state | string | | Yes | +| version | integer | | Yes | + +#### DifyBuilderStateEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| actions | [ [Action](#action) ] | | No | +| active_interaction | [DifyBuilderActiveInteractionResponse](#difybuilderactiveinteractionresponse) | | No | +| app_id | string | | Yes | +| app_revision | [AppRevision](#apprevision) | | No | +| canvas_read_only | boolean | | Yes | +| checkpoint | [CheckpointRef](#checkpointref) | | No | +| conversation_last_seq | integer | | Yes | +| entry_mode | [EntryMode](#entrymode) | | No | +| interrupted | boolean | | Yes | +| kind | string,
**Default:** state | | No | +| model | [SessionModel](#sessionmodel) | | No | +| phase | [Phase](#phase) | | No | +| recovery | [RecoveryRef](#recoveryref) | | No | +| run_status | [RunStatus](#runstatus) | | Yes | +| session_id | string | | Yes | +| state | string | | Yes | +| version | integer | | Yes | + +#### DifyBuilderStateEventResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| data | [DifyBuilderStateEventData](#difybuilderstateeventdata) | | Yes | +| event | string | | Yes | + +#### DifyBuilderStreamEventResponse + +One JSON object carried by an SSE ``data:`` frame. + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| DifyBuilderStreamEventResponse | [DifyBuilderCommandStartedEventResponse](#difybuildercommandstartedeventresponse)
[DifyBuilderNodeEventResponse](#difybuildernodeeventresponse)
[DifyBuilderCanvasEventResponse](#difybuildercanvaseventresponse)
[DifyBuilderAgentMessageEventResponse](#difybuilderagentmessageeventresponse)
[DifyBuilderReasoningEventResponse](#difybuilderreasoningeventresponse)
[DifyBuilderProgressEventResponse](#difybuilderprogresseventresponse)
[DifyBuilderCommitEventResponse](#difybuildercommiteventresponse)
[DifyBuilderStateEventResponse](#difybuilderstateeventresponse)
[DifyBuilderErrorEventResponse](#difybuildererroreventresponse) | One JSON object carried by an SSE ``data:`` frame. | | + +#### DifyBuilderSubmitActionPayload + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| action_id | string | | Yes | +| base_app_revision | string | | Yes | +| base_version | integer | | Yes | +| payload | object | | No | + +#### DifyBuilderSubmitMessagePayload + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| base_version | integer | | Yes | +| client_turn_id | string | | Yes | +| text | string | | Yes | + +#### DifyBuilderSummaryConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [SummaryCard](#summarycard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderTestResultConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [TestResultCard](#testresultcard) | | Yes | +| seq | integer | | Yes | + +#### DifyBuilderUserConversationItemResponse + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| kind | string | | Yes | +| payload | [UserItem](#useritem) | | Yes | +| seq | integer | | Yes | + #### DismissNotificationPayload | Name | Type | Description | Required | @@ -18005,6 +18876,12 @@ declaration of an endpoint group | name | string | | Yes | | settings | object | | Yes | +#### EntryMode + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| EntryMode | string | | | + #### EnvironmentVariableItemPayload | Name | Type | Description | Required | @@ -18044,6 +18921,15 @@ declaration of an endpoint group | environment_variables | [ [EnvironmentVariableItemPayload](#environmentvariableitempayload) ] | Environment variables for the draft workflow | Yes | | patch | boolean | Treat environment_variables as per-ID upserts instead of replacing the full collection | No | +#### ErrorCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| body | string | | Yes | +| node_id | string | | No | +| title | string | | Yes | +| tone | string,
**Default:** danger | | No | + #### ErrorDocsResponse | Name | Type | Description | Required | @@ -18051,6 +18937,16 @@ declaration of an endpoint group | data | [ [DocumentStatusResponse](#documentstatusresponse) ] | | Yes | | total | integer | | Yes | +#### ErrorEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| code | string | | No | +| error | string | | Yes | +| kind | string,
**Default:** error | | No | +| message | string | | No | +| recoverable | boolean | | No | + #### EventApiEntity | Name | Type | Description | Required | @@ -18118,12 +19014,29 @@ The type of the parameter | ---- | ---- | ----------- | -------- | | EventStreamResponse | string | | | +#### ExecutionActivity + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| id | string | | Yes | +| kind | string,
**Available values:** "node", "stage",
**Default:** stage | *Enum:* `"node"`, `"stage"` | No | +| label | string | | Yes | +| parent_id | string | | No | +| state | string,
**Available values:** "active", "done", "failed", "stopped" | *Enum:* `"active"`, `"done"`, `"failed"`, `"stopped"` | Yes | + #### ExecutionContentType | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | | ExecutionContentType | string | | | +#### ExecutionProgress + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| activities | [ [ExecutionActivity](#executionactivity) ] | | No | +| status | string,
**Available values:** "completed", "error", "running", "stopped" | *Enum:* `"completed"`, `"error"`, `"running"`, `"stopped"` | Yes | + #### ExploreAppMetaResponse Metadata consumed by the installed-app chat UI. @@ -18262,6 +19175,8 @@ Flask blueprint initialization. #### FeatureModel +Effective feature availability and limits for the current workspace. + | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | | annotation_quota_limit | [LimitationModel](#limitationmodel) | | Yes | @@ -18269,20 +19184,16 @@ Flask blueprint initialization. | apps | [LimitationModel](#limitationmodel) | | Yes | | billing | [BillingModel](#billingmodel) | | Yes | | can_replace_logo | boolean | | Yes | -| dataset_operator_enabled | boolean | | Yes | -| docs_processing | string,
**Default:** standard | | Yes | +| dify_builder_enabled | boolean | | Yes | | documents_upload_quota | [LimitationModel](#limitationmodel) | | Yes | | education | [EducationModel](#educationmodel) | | Yes | | enable_skill | boolean,
**Default:** true | | Yes | | human_input_email_delivery_enabled | boolean | | Yes | | is_allow_transfer_workspace | boolean,
**Default:** true | | Yes | | knowledge_pipeline | [KnowledgePipeline](#knowledgepipeline) | | Yes | -| knowledge_rate_limit | integer,
**Default:** 10 | | Yes | | members | [LimitationModel](#limitationmodel) | | Yes | | model_load_balancing_enabled | boolean | | Yes | -| next_credit_reset_date | integer | | Yes | | trigger_event | [Quota](#quota) | | Yes | -| vector_space | [LimitationModel](#limitationmodel) | | Yes | | webapp_copyright_enabled | boolean | | Yes | | workspace_members | [LicenseLimitationModel](#licenselimitationmodel) | | Yes | @@ -18445,6 +19356,35 @@ Enum class for fetch from. | email | string | | Yes | | language | string | | No | +#### FormCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| fields | [ [FormField](#formfield) ] | | No | +| frozen | boolean | | No | +| values | object | | No | +| variant | string | | Yes | + +#### FormField + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| allowed_file_extensions | [ string ] | | No | +| allowed_file_types | [ string ] | | No | +| allowed_file_upload_methods | [ string ] | | No | +| default | string
integer
number
boolean | | No | +| hint | string | | No | +| json_schema | string
object | | No | +| key | string | | Yes | +| label | string | | Yes | +| max_length | integer | | No | +| number_limits | integer | | No | +| options | [ string ] | | No | +| placeholder | string | | No | +| required | boolean | | No | +| type | string | | Yes | +| unit | string | | No | + #### FormInputConfig | Name | Type | Description | Required | @@ -19598,6 +20538,7 @@ Model with provider entity. | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | +| agent | [ResourcePermissionSnapshot](#resourcepermissionsnapshot) | | No | | app | [ResourcePermissionSnapshot](#resourcepermissionsnapshot) | | No | | dataset | [ResourcePermissionSnapshot](#resourcepermissionsnapshot) | | No | | workspace | [WorkspacePermissionSnapshot](#workspacepermissionsnapshot) | | No | @@ -19615,6 +20556,21 @@ Model with provider entity. | ---- | ---- | ----------- | -------- | | enabled | boolean | | No | +#### NodeEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| error | string | | Yes | +| kind | string,
**Default:** node | | No | +| node_id | string | | Yes | +| operation_id | string | | Yes | +| revision | integer | | Yes | +| session_id | string | | Yes | +| stage_id | string | | Yes | +| status | string | | Yes | +| title | string | | Yes | + #### NodeIdQuery | Name | Type | Description | Required | @@ -19673,6 +20629,13 @@ Coarse node-level status used by Inspector to pick a banner. | ---- | ---- | ----------- | -------- | | NodeStatus | string | Coarse node-level status used by Inspector to pick a banner. | | +#### NoticeItem + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| text | string | | Yes | +| tone | string,
**Default:** neutral | | No | + #### NotificationItemResponse | Name | Type | Description | Required | @@ -20370,6 +21333,14 @@ Shared permission levels for resources (datasets, credentials, etc.) | ---- | ---- | ----------- | -------- | | PermissionEnum | string | Shared permission levels for resources (datasets, credentials, etc.) | | +#### Phase + +Coarse UX phase shown in the panel header (spec §2). + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| Phase | string | Coarse UX phase shown in the panel header (spec §2). | | + #### PipelineTemplateDetailQuery | Name | Type | Description | Required | @@ -20434,6 +21405,15 @@ Shared permission levels for resources (datasets, credentials, etc.) | unit | string | | No | | variable | string | | Yes | +#### PlanCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| items | [ string ] | | No | +| subtitle | string | | No | +| title | string | | Yes | +| version_tag | string | | Yes | + #### PluginAutoUpgradeChangeResponse | Name | Type | Description | Required | @@ -20889,6 +21869,22 @@ Verification of the plugin. | enabled | boolean | Whether this preprocessing rule is enabled. | Yes | | id | string,
**Available values:** "remove_extra_spaces", "remove_stopwords", "remove_urls_emails" | Rule identifier.
*Enum:* `"remove_extra_spaces"`, `"remove_stopwords"`, `"remove_urls_emails"` | Yes | +#### PreflightContextCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| issue_count | integer | | Yes | +| issues | [ [PreflightIssue](#preflightissue) ] | | No | +| node_count | integer | | Yes | + +#### PreflightIssue + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| kind | string | | Yes | +| label | string | | Yes | +| node_id | string | | Yes | + #### PreviewDetail | Name | Type | Description | Required | @@ -20942,6 +21938,18 @@ Dataset Process Rule Mode | mode | [ProcessRuleMode](#processrulemode) | | Yes | | rules | [Rule](#rule) | | No | +#### ProgressEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| execution | [ExecutionProgress](#executionprogress) | | Yes | +| kind | string,
**Default:** progress | | No | +| operation_id | string | | Yes | +| revision | integer | | Yes | +| session_id | string | | Yes | +| stage_id | string | | Yes | + #### ProviderConfig Model class for common provider settings like credentials @@ -21118,6 +22126,13 @@ Model class for provider with models response. | status | [CustomConfigurationStatus](#customconfigurationstatus) | Provider status. `active` when credentials are configured and valid. | Yes | | tenant_id | string | | Yes | +#### PublishCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| badge | string,
**Default:** live | | No | +| version | string | | Yes | + #### PublishWorkflowPayload Payload for publishing snippet workflow. @@ -21151,8 +22166,8 @@ Payload for publishing snippet workflow. | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | -| limit | integer | | Yes | -| reset_date | integer,
**Default:** -1 | | Yes | +| limit | integer | Quota limit; -1 means unlimited and 0 means no quota | Yes | +| reset_date | integer,
**Default:** -1 | Next quota reset as a Unix timestamp in seconds; -1 means no reset | Yes | | usage | integer | | Yes | #### QuotaConfiguration @@ -21268,6 +22283,19 @@ Model class for provider quota configuration. | result | string | | Yes | | updated_at | integer | | Yes | +#### ReasoningEventData + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| at_version | integer | | Yes | +| delta | string | | Yes | +| kind | string,
**Default:** reasoning | | No | +| operation_id | string | | Yes | +| revision | integer | | Yes | +| session_id | string | | Yes | +| span_id | string | | Yes | +| stage_id | string | | Yes | + #### RecentAppListResponse | Name | Type | Description | Required | @@ -21342,6 +22370,15 @@ Model class for provider quota configuration. | ---- | ---- | ----------- | -------- | | language | string,
**Default:** en-US | Language code for recommended app localization | No | +#### RecoveryRef + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| can_continue | boolean | | Yes | +| can_restart | boolean | | Yes | +| message | string | | Yes | +| recovery_class | string | | Yes | + #### RedirectResponse | Name | Type | Description | Required | @@ -21417,6 +22454,16 @@ Model class for provider quota configuration. | reranking_model_name | string | Name of the reranking model. | No | | reranking_provider_name | string | Provider name of the reranking model. | No | +#### ResourceOption + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| id | string | | Yes | +| kind | string | | Yes | +| label | string | | Yes | +| meta | string | | Yes | +| readiness | string | | Yes | + #### ResourcePermissionKeys | Name | Type | Description | Required | @@ -21431,6 +22478,13 @@ Model class for provider quota configuration. | default_permission_keys | [ string ] | | No | | overrides | [ [ResourcePermissionKeys](#resourcepermissionkeys) ] | | No | +#### ResourceSelectCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| conflict_policy_options | [ [ConflictPolicyOption](#conflictpolicyoption) ] | | No | +| recommended | [ [ResourceOption](#resourceoption) ] | | No | + #### ResourceUserAccessPolicies | Name | Type | Description | Required | @@ -21567,6 +22621,28 @@ Model class for provider quota configuration. | instruction | string | Structured output generation instruction | Yes | | model_config | [ModelConfig](#modelconfig) | Model configuration | Yes | +#### RunContextCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| error_code | string | | Yes | +| message | string | | Yes | +| run_id | string | | Yes | +| title | string | | Yes | +| trace_ref | string | | No | + +#### RunStatus + +Widened run-status vocabulary (spec §2). + +``processing`` => ``canvas_read_only = true`` (WORKING). +``waiting_*``/``paused`` => editable (WAITING). +``complete``/``failed`` => terminal. + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| RunStatus | string | Widened run-status vocabulary (spec §2). ``processing`` => ``canvas_read_only = true`` (WORKING). ``waiting_*``/``paused`` => editable (WAITING). ``complete``/``failed`` => terminal. | | + #### SSOProtocol | Name | Type | Description | Required | @@ -21770,6 +22846,15 @@ Model class for provider quota configuration. | output_variable_name | string | | Yes | | type | string | | No | +#### SessionModel + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| completion_params | object | | No | +| mode | string | | No | +| name | string | | Yes | +| provider | string | | Yes | + #### SimpleAccount | Name | Type | Description | Required | @@ -22614,6 +23699,15 @@ The subscription constructor of the trigger provider | ---- | ---- | ----------- | -------- | | data | [ string ] | | Yes | +#### SummaryCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| items | [ string ] | | No | +| rows | [ [SummaryRow](#summaryrow) ] | | No | +| title | string | | No | +| variant | string | | Yes | + #### SummaryEntryResponse | Name | Type | Description | Required | @@ -22626,6 +23720,13 @@ The subscription constructor of the trigger provider | summary_preview | string | | No | | updated_at | integer | | No | +#### SummaryRow + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| label | string | | Yes | +| value | string | | Yes | + #### SummaryStatusResponse | Name | Type | Description | Required | @@ -22863,6 +23964,23 @@ Tag type | ---- | ---- | ----------- | -------- | | TenantPluginInstallPermission | string | | | +#### TestResultCard + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| run_ids | [ string ] | | No | +| stats | [ [TestStat](#teststat) ] | | No | +| subtitle | string | | Yes | +| title | string | | Yes | +| tone | string | | Yes | + +#### TestStat + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| label | string | | Yes | +| value | string | | Yes | + #### TextContentResponse | Name | Type | Description | Required | @@ -23629,6 +24747,13 @@ User action configuration. | id | string | | Yes | | title | string | | Yes | +#### UserItem + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| text | string | | Yes | +| turn_id | string | | Yes | + #### UserSatisfactionRateStatisticItem | Name | Type | Description | Required | diff --git a/api/openapi/markdown/service-openapi.md b/api/openapi/markdown/service-openapi.md index a4b57a96b56..679d04605e9 100644 --- a/api/openapi/markdown/service-openapi.md +++ b/api/openapi/markdown/service-openapi.md @@ -181,7 +181,6 @@ Retrieves the status of an asynchronous annotation reply configuration job start | 400 | `invalid_param` : The specified job does not exist. | | | 401 | Unauthorized - invalid API token | | | 403 | Forbidden - token scope, app, dataset, or workspace access denied | | -| 404 | Job not found | | ### [GET] /apps/annotations **List Annotations** @@ -560,7 +559,6 @@ Send a request to the text generation application. | 400 | - `app_unavailable` : App unavailable or misconfigured. - `provider_not_initialize` : No valid model provider credentials found. - `provider_quota_exceeded` : Model provider quota exhausted. - `model_currently_not_support` : Current model unavailable. - `completion_request_error` : Text generation failed. | | | 401 | Unauthorized - invalid API token | | | 403 | Forbidden - token scope, app, dataset, or workspace access denied | | -| 404 | Conversation not found | | | 429 | `too_many_requests` : Too many concurrent requests for this app. | | | 500 | `internal_server_error` : Internal server error. | | @@ -798,7 +796,7 @@ Create a new empty knowledge base. After creation, use [Create Document by Text] ### [DELETE] /datasets/{dataset_id} **Delete Knowledge Base** -Permanently delete a knowledge base and all its documents. The knowledge base must not be in use by any application. +Permanently delete a knowledge base and all its documents. #### Parameters @@ -814,7 +812,6 @@ Permanently delete a knowledge base and all its documents. The knowledge base mu | 401 | Unauthorized - invalid API token | | 403 | Forbidden - dataset API access or workspace access denied | | 404 | `not_found` : Dataset not found. | -| 409 | `dataset_in_use` : The knowledge base is being used by some apps. Please remove it from the apps before deleting. | ### [GET] /datasets/{dataset_id} **Get Knowledge Base** @@ -1370,7 +1367,6 @@ Permanently delete a document and all its chunks from the knowledge base. | Code | Description | | ---- | ----------- | | 204 | Success. | -| 400 | `document_indexing` : Cannot delete document during indexing. | | 401 | Unauthorized - invalid API token | | 403 | `archived_document_immutable` : The archived document is not editable. | | 404 | `not_found` : Document Not Exists. | @@ -1386,7 +1382,7 @@ Retrieve detailed information about a specific document, including its indexing | ---- | ---------- | ----------- | -------- | ------ | | dataset_id | path | Knowledge base ID. | Yes | string (uuid) | | document_id | path | Document ID. | Yes | string (uuid) | -| metadata | query | `all` returns all fields including metadata. `only` returns only `id`, `doc_type`, and `doc_metadata`. `without` returns all fields except `doc_metadata`. | No | string,
**Available values:** "all", "only", "without",
**Default:** all | +| metadata | query | `all` returns all fields including metadata. `only` returns only `id`, `doc_type`, and `doc_metadata`. `without` returns all fields except `doc_type` and `doc_metadata`. | No | string,
**Available values:** "all", "only", "without",
**Default:** all | #### Responses @@ -2093,9 +2089,9 @@ Retrieve basic information about this application, including name, description, | Code | Description | Schema | | ---- | ----------- | ------ | | 200 | Basic information of the application. | **application/json**: [AppInfoResponse](#appinforesponse)
| +| 400 | `app_unavailable` : App unavailable or misconfigured. | | | 401 | Unauthorized - invalid API token | | | 403 | Forbidden - token scope, app, dataset, or workspace access denied | | -| 404 | Application not found | | ### [GET] /meta **Get App Meta** @@ -2107,9 +2103,9 @@ Retrieve metadata about this application, including tool icons and other configu | Code | Description | Schema | | ---- | ----------- | ------ | | 200 | Successfully retrieved application meta information. | **application/json**: [AppMetaResponse](#appmetaresponse)
| +| 400 | `app_unavailable` : App unavailable or misconfigured. | | | 401 | Unauthorized - invalid API token | | | 403 | Forbidden - token scope, app, dataset, or workspace access denied | | -| 404 | Application not found | | ### [GET] /parameters **Get App Parameters** @@ -2124,7 +2120,6 @@ Retrieve the application's input form configuration, including feature switches, | 400 | `app_unavailable` : App unavailable or misconfigured. | | | 401 | Unauthorized - invalid API token | | | 403 | Forbidden - token scope, app, dataset, or workspace access denied | | -| 404 | Application not found | | ### [GET] /site **Get App WebApp Settings** @@ -2212,8 +2207,7 @@ Execute a workflow. Cannot be executed without a published workflow. | 400 | - `not_workflow_app` : App mode does not match the API route. - `provider_not_initialize` : No valid model provider credentials found. - `provider_quota_exceeded` : Model provider quota exhausted. - `model_currently_not_support` : Current model unavailable. - `completion_request_error` : Workflow execution request failed. - `invalid_param` : Invalid parameter value. | | | 401 | Unauthorized - invalid API token | | | 403 | - `forbidden` : Token scope, app, or workspace access denied. - `trigger_workflow_service_mode_unavailable` : Trigger-entry workflows cannot be invoked through Web App, Service API, OpenAPI, or MCP. | | -| 404 | Workflow not found | | -| 429 | - `too_many_requests` : Too many concurrent requests for this app. - `rate_limit_error` : The upstream model provider rate limit was exceeded. | | +| 429 | - `too_many_requests` : Too many concurrent requests for this app. - `rate_limit_error` : The upstream model provider rate limit or the Dify Cloud workflow execution quota was exceeded. | | | 500 | `internal_server_error` : Internal server error. | | ### [GET] /workflows/run/{workflow_run_id} @@ -2289,7 +2283,7 @@ Execute a specific workflow version identified by its ID. Useful for running a p | 401 | Unauthorized - invalid API token | | | 403 | - `forbidden` : Token scope, app, or workspace access denied. - `workflow_version_execution_not_allowed` : Workflow version execution is unavailable on the current plan. Upgrade to a paid plan. - `trigger_workflow_service_mode_unavailable` : The selected workflow version uses a trigger entry and cannot be invoked through Web App, Service API, OpenAPI, or MCP. | | | 404 | `not_found` : Workflow not found. | | -| 429 | - `too_many_requests` : Too many concurrent requests for this app. - `rate_limit_error` : The upstream model provider rate limit was exceeded. | | +| 429 | - `too_many_requests` : Too many concurrent requests for this app. - `rate_limit_error` : The upstream model provider rate limit or the Dify Cloud workflow execution quota was exceeded. | | | 500 | `internal_server_error` : Internal server error. | | --- @@ -2600,7 +2594,7 @@ Public pause reason emitted by a blocking Chatflow execution. | inputs | object | Values for app-defined variables. Refer to the `user_input_form` field in the [Get App Parameters](/api-reference/applications/get-app-parameters) response to discover expected variable names and types. | Yes | | query | string | User input or question content. | Yes | | response_mode | string,
**Available values:** "blocking", "streaming" | Response mode. `streaming` uses Server-Sent Events; `blocking` returns after completion. New Agent app mode supports streaming only. When omitted, non-Agent apps run in blocking mode and new Agent apps stream. | No | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | Yes | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | Yes | | workflow_id | string | Published workflow version ID to execute for advanced chat. If omitted, the app's current published workflow is used. | No | #### ChildChunkCreatePayload @@ -2682,7 +2676,7 @@ Public pause reason emitted by a blocking Chatflow execution. | inputs | object | Values for app-defined variables. Refer to the `user_input_form` field in the [Get App Parameters](/api-reference/applications/get-app-parameters) response to discover expected variable names and types. | Yes | | query | string | User input or prompt content. | No | | response_mode | string,
**Available values:** "blocking", "streaming" | Response mode. `streaming` uses Server-Sent Events; `blocking` returns after completion. When omitted, the request runs in blocking mode. | No | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | Yes | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | Yes | #### Condition @@ -2723,7 +2717,7 @@ Condition detail | ---- | ---- | ----------- | -------- | | auto_generate | boolean | Automatically generate the conversation name. When `true`, the `name` field is ignored. | No | | name | string | Conversation name. Required when `auto_generate` is `false`. | No | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | No | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | No | #### ConversationVariableInfiniteScrollPaginationResponse @@ -2755,7 +2749,7 @@ Condition detail | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | No | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | No | | value | | The new value for the variable. Must match the variable's expected type. | Yes | #### ConversationVariablesQuery @@ -2833,7 +2827,6 @@ Enum class for custom configuration status. | maintainer | string | | No | | name | string | | Yes | | permission | string | | Yes | -| permission_keys | [ string ] | | No | | pipeline_id | string | | Yes | | provider | string | | Yes | | retrieval_model_dict | [DatasetRetrievalModelResponse](#datasetretrievalmodelresponse) | Retrieval configuration for the knowledge base. | Yes | @@ -2876,7 +2869,6 @@ Enum class for custom configuration status. | name | string | | Yes | | partial_member_list | [ string ] | | No | | permission | string | | Yes | -| permission_keys | [ string ] | | No | | pipeline_id | string | | Yes | | provider | string | | Yes | | retrieval_model_dict | [DatasetRetrievalModelResponse](#datasetretrievalmodelresponse) | Retrieval configuration for the knowledge base. | Yes | @@ -3158,7 +3150,7 @@ Request payload for bulk downloading documents as a zip archive. | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | -| metadata | string,
**Available values:** "all", "only", "without",
**Default:** all | `all` returns all fields including metadata. `only` returns only `id`, `doc_type`, and `doc_metadata`. `without` returns all fields except `doc_metadata`.
*Enum:* `"all"`, `"only"`, `"without"` | No | +| metadata | string,
**Available values:** "all", "only", "without",
**Default:** all | `all` returns all fields including metadata. `only` returns only `id`, `doc_type`, and `doc_metadata`. `without` returns all fields except `doc_type` and `doc_metadata`.
*Enum:* `"all"`, `"only"`, `"without"` | No | #### DocumentListQuery @@ -3546,7 +3538,7 @@ Enum class for fetch from. | ---- | ---- | ----------- | -------- | | action | string | ID of the action button the recipient selected. Must match one of the `id` values from the form's `user_actions` list. | Yes | | inputs | object | Submitted human input values keyed by output variable name. Use a string for paragraph or select input values, a file mapping for file inputs, and a list of file mappings for file-list inputs. Local file mappings use `transfer_method=local_file` with `upload_file_id`; remote file mappings use `transfer_method=remote_url` with `url` or `remote_url`. | Yes | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | Yes | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | Yes | #### HumanInputFormSubmitResponse @@ -3622,7 +3614,7 @@ Model class for i18n object. | ---- | ---- | ----------- | -------- | | content | string | Optional text feedback providing additional detail. | No | | rating | string,
**Available values:** "dislike", "like" | Feedback rating. Set to `null` to revoke previously submitted feedback. | No | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | Yes | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | Yes | #### MessageFile @@ -3753,7 +3745,7 @@ Enum class for model type. | Name | Type | Description | Required | | ---- | ---- | ----------- | -------- | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | No | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | No | #### ParagraphInputConfig @@ -4253,7 +4245,7 @@ Accepts either the legacy tag_id payload or the normalized tag_ids payload. | message_id | string | Message ID. Takes priority over `text` when both are provided. | No | | streaming | boolean | Reserved for compatibility; TTS response streaming is determined by the provider output. | No | | text | string | Speech content to convert. | No | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | No | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | No | | voice | string | Voice to use for text-to-speech. Available voices depend on the TTS provider configured for this app. Omit to use the app's configured voice when available; that value is exposed by [Get App Parameters](/api-reference/applications/get-app-parameters) as `text_to_speech.voice`. | No | #### ToolIcon @@ -4461,7 +4453,7 @@ Public pause reason emitted by a blocking Workflow execution. | files | [ object
object
object
object ] | File list for workflow system file inputs. Available when file upload is enabled for the workflow. To attach a local file, first upload it via [Upload File](/api-reference/files/upload-file) and use the returned `id` as `upload_file_id` with `transfer_method: local_file`. | No | | inputs | object | Key-value pairs for workflow input variables. Values for file-type variables should be arrays of file objects with `type`, `transfer_method`, and either `url` or `upload_file_id`. Refer to the `user_input_form` field in the [Get App Parameters](/api-reference/applications/get-app-parameters) response to discover the variable names and types expected by your app. | Yes | | response_mode | string,
**Available values:** "blocking", "streaming" | Response mode. Use `blocking` for synchronous responses or `streaming` for Server-Sent Events. When omitted, the request runs in blocking mode. | No | -| user | string | User identifier, unique within the application. This identifier scopes data access; resources created with one `user` value are only visible when queried with the same `user` value. | Yes | +| user | string | End-user identifier, defined by your app and unique within it. Identifies the end user for this request. See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules. | Yes | #### WorkflowRunResponse diff --git a/api/providers/trace/README.md b/api/providers/trace/README.md index a7ffa5ed260..0f280c6ee84 100644 --- a/api/providers/trace/README.md +++ b/api/providers/trace/README.md @@ -32,8 +32,7 @@ List these key names in your `OpsTraceProviderConfigMap` entry so encrypt/decryp Subclass `BaseTraceInstance` and implement: ```python -def trace(self, trace_info: BaseTraceInfo) -> None: - ... +def trace(self, trace_info: BaseTraceInfo) -> None: ... ``` Dispatch on the concrete type with `isinstance` (see `trace_langfuse` or `trace_langsmith` for full patterns). Payload types are defined in `core/ops/entities/trace_entity.py`, including: diff --git a/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py b/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py index dc7e7edd4a8..9d1cc8ff132 100644 --- a/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py +++ b/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py @@ -202,6 +202,11 @@ class TencentVector(BaseVector): if metadatas is None: continue metadata = metadatas[i] or {} + if metadata.get("is_summary") is True: + # Tencent VectorDB JSON fields do not support boolean values. + # Use an integer only for the summary marker so other metadata + # and other vector backends keep their existing types. + metadata = {**metadata, "is_summary": 1} doc = document.Document( id=metadata.get("doc_id"), vector=embeddings[i], diff --git a/api/providers/vdb/vdb-tencent/tests/unit_tests/test_tencent_vector.py b/api/providers/vdb/vdb-tencent/tests/unit_tests/test_tencent_vector.py index 7ad76e1960f..41db20db61a 100644 --- a/api/providers/vdb/vdb-tencent/tests/unit_tests/test_tencent_vector.py +++ b/api/providers/vdb/vdb-tencent/tests/unit_tests/test_tencent_vector.py @@ -281,6 +281,23 @@ def test_create_add_delete_and_search_behaviour(tencent_module): vector._client.drop_collection.assert_called_once() +def test_add_texts_converts_only_true_summary_marker(tencent_module): + vector = tencent_module.TencentVector("collection_1", _config(tencent_module)) + summary_metadata = {"doc_id": "summary", "is_summary": True, "published": False} + regular_metadata = {"doc_id": "regular", "published": False} + docs = [ + Document(page_content="summary", metadata=summary_metadata), + Document(page_content="regular", metadata=regular_metadata), + ] + + vector.add_texts(docs, [[0.1], [0.2]]) + + upserted = vector._client.upsert.call_args.kwargs["documents"] + assert upserted[0].metadata == {"doc_id": "summary", "is_summary": 1, "published": False} + assert upserted[1].metadata == regular_metadata + assert summary_metadata["is_summary"] is True + + def test_tencent_factory_existing_and_generated_collection(tencent_module, monkeypatch: pytest.MonkeyPatch): factory = tencent_module.TencentVectorFactory() dataset_with_index = Dataset( diff --git a/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py b/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py index 00824831eb3..ca6081ff89e 100644 --- a/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py +++ b/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py @@ -278,18 +278,38 @@ class WeaviateVector(BaseVector): logger.warning("Could not add property %s: %s", prop.name, e) @override - def _get_uuids(self, documents: list[Document]) -> list[str]: + def _get_uuids(self, texts: list[Document]) -> list[str]: """ - Generates deterministic UUIDs for documents based on their content. + Generate canonical Weaviate object ids for each document. - Uses UUID5 with URL namespace to ensure consistent IDs for identical content. + Issue #41714: insert and the cleanup path + (``batch_clean_document_task`` → ``index_processor.clean`` → + ``vector.delete_by_ids``) must agree on the object id, otherwise + ``delete_by_id`` silently no-ops and the cleanup task reports + success while the objects stay behind as orphans. + + Use the same source the rest of the VDB stack uses + (``VectorBase._get_uuids``): the ``doc_id`` stored in each + document's metadata. ``doc_id`` is the segment's + ``index_node_id`` that ``delete_by_ids`` already passes in. + + Preserve the parent caller's positional alignment: a missing + ``doc_id`` is replaced with a freshly generated ``uuid4`` rather + than dropping the slot, so the parallel ``objs`` list in + ``add_texts`` keeps matching the input documents one-for-one. """ - URL_NAMESPACE = _uuid.UUID("6ba7b811-9dad-11d1-80b4-00c04fd430c8") - - uuids = [] - for doc in documents: - uuid_val = _uuid.uuid5(URL_NAMESPACE, doc.page_content) - uuids.append(str(uuid_val)) + uuids: list[str] = [] + for doc in texts: + doc_id = (doc.metadata or {}).get("doc_id") + if isinstance(doc_id, str) and doc_id: + uuids.append(doc_id) + else: + # Fallback only when the caller didn't supply a doc_id. + # Random uuid4 keeps the object uniquely addressable; the + # cleanup path can't find it without doc_id, but that's + # only acceptable for tests / fixtures that don't exercise + # cleanup. + uuids.append(str(_uuid.uuid4())) return uuids @@ -380,17 +400,40 @@ class WeaviateVector(BaseVector): Deletes objects by their UUID identifiers. Silently ignores 404 errors for non-existent IDs. + + Issue #41714: cleanup task (and any other caller) passes + ``index_node_id`` (a UUID) here. New objects inserted after this + fix use the segment's ``index_node_id`` as their Weaviate UUID, so + the call lands cleanly. **Pre-existing** objects written by the + old UUID5 path still don't match — fall through to a + backward-compatible ``doc_id``-metadata filter so they are + cleaned up too, and a legacy object whose Weaviate UUID differs + from its ``doc_id`` is still reaped. """ if not self._client.collections.exists(self._collection_name): return col = self._client.collections.use(self._collection_name) + # 1. Best-effort direct delete by UUID for the fresh-write path. + # 404s mean the object was never written (or was written under + # a different UUID), which is expected for legacy rows. for uid in ids: try: col.data.delete_by_id(uid) except UnexpectedStatusCodeError as e: - if getattr(e, "status_code", None) != 404: + if e.status_code != 404: + raise + + # 2. Backward-compatible catch-up: the legacy UUID5 path (or any + # other source) wrote rows whose Weaviate UUID no longer + # matches ``index_node_id``. Reap them by the ``doc_id`` + # metadata so a delete pass never leaves orphans behind. + if ids: + try: + col.data.delete_many(where=Filter.by_property("doc_id").contains_any(ids)) + except UnexpectedStatusCodeError as e: + if e.status_code != 404: raise @override diff --git a/api/providers/vdb/vdb-weaviate/tests/unit_tests/test_doc_id_cleanup_41714.py b/api/providers/vdb/vdb-weaviate/tests/unit_tests/test_doc_id_cleanup_41714.py new file mode 100644 index 00000000000..dfc43d58b88 --- /dev/null +++ b/api/providers/vdb/vdb-weaviate/tests/unit_tests/test_doc_id_cleanup_41714.py @@ -0,0 +1,208 @@ +"""Regression tests for issue #41714. + +The pre-fix code generated Weaviate object ids via +``uuid5(URL_NAMESPACE, page_content)`` (UUID v5 from content). The +cleanup path (``batch_clean_document_task`` -> ``index_processor.clean`` +-> ``vector.delete_by_ids``) passes the segment's ``index_node_id`` +(random UUID v4 from the database), so the two never agreed and +``delete_by_id`` silently no-op'd on every cleanup pass. + +The fix: + +1. ``_get_uuids`` now uses the segment's ``doc_id`` (== ``index_node_id``) + from each document's metadata. New objects line up with the + cleanup path one-for-one. +2. Documents without a ``doc_id`` keep a stable slot via a freshly + generated ``uuid4`` so the parallel ``objs`` list in ``add_texts`` + never goes out of alignment with the input documents. +3. ``delete_by_ids`` keeps the best-effort direct-UUID delete (the + fresh-write path), then falls through to a ``doc_id``-metadata + ``contains_any`` filter so the legacy UUID5 objects are reaped + too -- backwards-compatible with the rows already in production. +""" + +from unittest.mock import MagicMock, patch + +from dify_vdb_weaviate import weaviate_vector as weaviate_vector_module +from dify_vdb_weaviate.weaviate_vector import WeaviateVector + +from core.rag.models.document import Document + + +class _FakeUnexpectedStatusCodeError(Exception): + """Stand-in for ``weaviate.exceptions.UnexpectedStatusCodeError``. + + The real class has a read-only ``status_code`` property; the + production code only reads ``.status_code`` off the exception, so + a plain attribute is enough. We patch the module-level reference + in the production module so the ``except`` clause catches ours. + """ + + def __init__(self, status_code: int) -> None: + super().__init__(f"status={status_code}") + self.status_code = status_code + + +def _make_vector() -> tuple[WeaviateVector, MagicMock]: + """Build a ``WeaviateVector`` without invoking ``__init__`` so we + never reach ``_init_client`` (which would try to connect). + + Only ``_client`` and ``_collection_name`` are touched by the + production code paths exercised here (``_get_uuids`` and + ``delete_by_ids``), so the rest of the instance dict is left bare. + + Returns the ``WeaviateVector`` together with its mocked client so + tests can reach ``client.collections.use(...).data`` (the same + path the production code walks) without pyrefly tripping over + chained ``.return_value`` access through the dynamic ``_client`` + instance attribute. + """ + # pyrefly cannot resolve chained ``.return_value`` access through + # dynamically-attached attributes (it infers ``v._client`` as the + # missing-on-class attribute and falls through to the stdlib + # ``collections`` module), so keep the mocked client in a local + # variable whose type pyrefly can see. + client: MagicMock = MagicMock() + client.collections.exists.return_value = True + client.collections.use.return_value = client.data + + v = WeaviateVector.__new__(WeaviateVector) + v._collection_name = "Test_Collection" + v._client = client + return v, client + + +def _collection(client: MagicMock) -> MagicMock: + """Resolve ``client.collections.use().data`` as a typed MagicMock. + + Centralised so the same ``client.data`` instance is reused -- the + production code reaches the Weaviate collection's ``data`` object + via ``v._client.collections.use(name).data``; we mirror that path + so ``delete_by_id`` / ``delete_many`` side effects wired on the + returned mock are observed by the production calls. + """ + col: MagicMock = client.collections.use.return_value + return col.data + + +class TestGetUuidsUsesDocId: + """_get_uuids must return one id per input document, positionally aligned.""" + + def test_doc_id_passes_through(self) -> None: + v, _client = _make_vector() + docs = [Document(page_content="x", metadata={"doc_id": "doc-aaa-1"})] + + uuids = v._get_uuids(docs) + + assert uuids == ["doc-aaa-1"] + + def test_missing_doc_id_falls_back_to_fresh_uuid4(self) -> None: + """A document without ``doc_id`` still needs a slot in the + returned list so the parallel ``objs`` list in ``add_texts`` + never goes out of alignment with the input documents. + """ + v, _client = _make_vector() + docs = [ + Document(page_content="x", metadata={"doc_id": "doc-aaa-1"}), + Document(page_content="y", metadata={}), + Document(page_content="z", metadata={"doc_id": "doc-ccc-3"}), + ] + + uuids = v._get_uuids(docs) + + assert uuids[0] == "doc-aaa-1" + assert uuids[2] == "doc-ccc-3" + # The middle slot is filled, not dropped. + assert len(uuids) == 3 + assert uuids[1] != "" + # And the fallback is a valid UUID4. + import uuid as _uuid + + parsed = _uuid.UUID(uuids[1]) + assert parsed.version == 4 + + def test_all_doc_ids_present(self) -> None: + v, _client = _make_vector() + docs = [ + Document(page_content="x", metadata={"doc_id": "a"}), + Document(page_content="y", metadata={"doc_id": "b"}), + Document(page_content="z", metadata={"doc_id": "c"}), + ] + + assert v._get_uuids(docs) == ["a", "b", "c"] + + +class TestDeleteByIdsBackwardCompatible: + """#41714 backwards-compatibility: legacy UUID5 objects whose Weaviate + UUID no longer matches ``index_node_id`` are reaped via the + ``doc_id``-metadata filter.""" + + def test_legacy_object_with_matching_doc_id_is_reaped(self) -> None: + """A legacy object whose ``doc_id`` matches the supplied + ``index_node_id`` must be reaped even though its Weaviate UUID + no longer matches. + """ + v, client = _make_vector() + col = _collection(client) + col.delete_by_id.side_effect = _FakeUnexpectedStatusCodeError(404) + + with patch.object(weaviate_vector_module, "UnexpectedStatusCodeError", _FakeUnexpectedStatusCodeError): + v.delete_by_ids(["doc-aaa-1"]) + + # Best-effort direct delete ran for each id. + assert col.delete_by_id.call_count == 1 + # And the metadata catch-up filter ran with the same ids. + col.delete_many.assert_called_once() + kwargs = col.delete_many.call_args.kwargs + where = kwargs["where"] + # Filter.by_property("doc_id").contains_any(["doc-aaa-1"]) + assert "doc_id" in str(where) + assert "doc-aaa-1" in str(where) + + def test_fresh_object_is_reaped_by_direct_delete(self) -> None: + """A fresh object whose Weaviate UUID equals the supplied + ``index_node_id`` is reaped by the direct delete, and the + metadata-filter pass is a redundant no-op (no rows match). + """ + v, client = _make_vector() + col = _collection(client) + + v.delete_by_ids(["doc-aaa-1"]) + + col.delete_by_id.assert_called_once_with("doc-aaa-1") + # The metadata filter always runs, but it's a no-op when the row + # is already gone (Weaviate's ``delete_many`` returns an empty + # result set against the cleared UUID). + col.delete_many.assert_called_once() + where = col.delete_many.call_args.kwargs["where"] + assert "doc_id" in str(where) + assert "doc-aaa-1" in str(where) + + def test_non_404_error_propagates(self) -> None: + """A non-404 (e.g. 500) error on direct delete must propagate, + not be swallowed as if it were a 404. + """ + import pytest + + v, client = _make_vector() + col = _collection(client) + col.delete_by_id.side_effect = _FakeUnexpectedStatusCodeError(500) + + with ( + patch.object(weaviate_vector_module, "UnexpectedStatusCodeError", _FakeUnexpectedStatusCodeError), + pytest.raises(_FakeUnexpectedStatusCodeError), + ): + v.delete_by_ids(["doc-aaa-1"]) + + def test_delete_many_404_is_swallowed(self) -> None: + """The metadata-filter 404 (column doesn't exist) is also + swallowed -- the schema may not have been migrated yet. + """ + v, client = _make_vector() + col = _collection(client) + col.delete_by_id.side_effect = _FakeUnexpectedStatusCodeError(404) + col.delete_many.side_effect = _FakeUnexpectedStatusCodeError(404) + + # Neither path raises. + with patch.object(weaviate_vector_module, "UnexpectedStatusCodeError", _FakeUnexpectedStatusCodeError): + v.delete_by_ids(["doc-aaa-1"]) diff --git a/api/pyproject.toml b/api/pyproject.toml index de89fdd5676..76d67eb2523 100644 --- a/api/pyproject.toml +++ b/api/pyproject.toml @@ -123,63 +123,63 @@ override-dependencies = [ # Required for development and running tests ############################################################ dev = [ - "coverage>=7.13.4", - "dotenv-linter>=0.7.0", - "faker>=40.15.0", + "coverage>=7.16.0", + "dotenv-linter>=0.9.0", + "faker>=40.38.0", "lxml-stubs>=0.5.1", - "ruff>=0.15.12", - "pytest>=9.0.3", - "pytest-benchmark>=5.2.3", + "ruff>=0.16.6", + "pytest>=9.1.1", + "pytest-benchmark>=5.3.0", "pytest-cov>=7.1.0", - "pytest-env>=1.6.0", + "pytest-env>=1.7.0", "pytest-mock>=3.15.1", "testcontainers>=4.14.2", - "types-aiofiles>=25.1.0", + "types-aiofiles>=25.1.0.20260518", "types-beautifulsoup4>=4.12.0", - "types-cachetools>=7.0.0.20260503", - "types-colorama>=0.4.15", - "types-defusedxml>=0.7.0", - "types-deprecated>=1.3.1", - "types-docutils>=0.22.3", - "types-flask-cors>=6.0.0", - "types-flask-migrate>=4.1.0", - "types-gevent>=26.4.0", - "types-greenlet>=3.5.0.20260428", - "types-html5lib>=1.1.11", - "types-markdown>=3.10.2", - "types-oauthlib>=3.3.0", - "types-objgraph>=3.6.0", - "types-olefile>=0.47.0", - "types-openpyxl>=3.1.5", - "types-pexpect>=4.9.0", - "types-protobuf>=7.34.1.20260503", - "types-psutil>=7.2.2", - "types-psycopg2>=2.9.21.20260422", - "types-pygments>=2.20.0", - "types-pymysql>=1.1.0", - "types-python-dateutil>=2.9.0", - "types-pywin32>=311.0.0", - "types-pyyaml>=6.0.12", - "types-regex>=2026.4.4", - "types-shapely>=2.1.0", - "types-simplejson>=3.20.0.20260408", - "types-six>=1.17.0.20260408", - "types-tensorflow>=2.18.0.20260408", - "types-tqdm>=4.67.3.20260408", + "types-cachetools>=7.0.0.20260713", + "types-colorama>=0.4.15.20260508", + "types-defusedxml>=0.7.0.20260504", + "types-deprecated>=1.3.1.20260728", + "types-docutils>=0.23.0.20260827", + "types-flask-cors>=6.0.3.20260712", + "types-flask-migrate>=4.1.0.20260508", + "types-gevent>=26.8.0.20260811", + "types-greenlet>=3.5.0.20260518", + "types-html5lib>=1.1.11.20260518", + "types-markdown>=3.10.2.20260712", + "types-oauthlib>=3.3.0.20260724", + "types-objgraph>=3.6.0.20260508", + "types-olefile>=0.47.0.20260508", + "types-openpyxl>=3.1.5.20260827", + "types-pexpect>=4.9.0.20260518", + "types-protobuf>=7.35.1.20260827", + "types-psutil>=7.2.2.20260827", + "types-psycopg2>=2.9.21.20260724", + "types-pygments>=2.21.0.20260819", + "types-pymysql>=1.2.0.20260807", + "types-python-dateutil>=2.9.0.20260807", + "types-pywin32>=312.0.0.20260827", + "types-pyyaml>=6.0.12.20260815", + "types-regex>=2026.9.3.20260903", + "types-shapely>=2.1.0.20260728", + "types-simplejson>=4.1.0.20260724", + "types-six>=1.17.0.20260724", + "types-tensorflow>=2.18.0.20260827", + "types-tqdm>=4.70.0.20260827", "types-ujson>=5.10.0", - "boto3-stubs>=1.43.10", - "types-jmespath>=1.1.0.20260408", - "hypothesis>=6.152.4", + "boto3-stubs>=1.43.88", + "types-jmespath>=1.1.0.20260724", + "hypothesis>=6.167.1", "types_pyOpenSSL>=24.1.0", - "types_cffi>=2.0.0.20260429", - "types_setuptools>=82.0.0.20260408", - "pandas-stubs>=3.0.0", - "scipy-stubs>=1.17.1.4", - "types-python-http-client>=3.3.7.20260408", - "import-linter>=2.3", + "types_cffi>=2.1.0.20260827", + "types_setuptools>=84.0.0.20260812", + "pandas-stubs>=3.0.5.260730", + "scipy-stubs>=1.18.1.0", + "types-python-http-client>=3.3.7.20260518", + "import-linter>=2.14", "types-redis>=4.6.0.20241004", "celery-types>=0.23.0", - "mypy>=1.20.2", + "mypy>=2.3.1", # "locust>=2.40.4", # Temporarily removed due to compatibility issues. Uncomment when resolved. "pytest-timeout>=2.4.0", "pytest-xdist>=3.8.0", diff --git a/api/repositories/human_input_file_upload_repository.py b/api/repositories/human_input_file_upload_repository.py new file mode 100644 index 00000000000..7406a5337b3 --- /dev/null +++ b/api/repositories/human_input_file_upload_repository.py @@ -0,0 +1,166 @@ +"""SQLAlchemy persistence adapter for human-input file uploads.""" + +from typing import override + +from sqlalchemy import select +from sqlalchemy.orm import Session, sessionmaker + +from models.account import Account, Tenant +from models.enums import CreatorUserRole +from models.human_input import ( + HumanInputForm, + HumanInputFormRecipient, + HumanInputFormUploadFile, + HumanInputFormUploadToken, +) +from models.model import App, EndUser +from services.human_input_file_upload_service import ( + HumanInputFileUploadRepository, + HumanInputUploadFormRecord, + HumanInputUploadGrantRecord, +) + + +class SQLAlchemyHumanInputFileUploadRepository(HumanInputFileUploadRepository): + def __init__(self, *, session_factory: sessionmaker[Session]) -> None: + self._session_factory = session_factory + + @override + def get_form_by_recipient_token(self, form_token: str) -> HumanInputUploadFormRecord | None: + stmt = ( + select(HumanInputFormRecipient, HumanInputForm) + .join(HumanInputForm, HumanInputForm.id == HumanInputFormRecipient.form_id) + .where(HumanInputFormRecipient.access_token == form_token) + .limit(1) + ) + with self._session_factory() as session: + row = session.execute(stmt).one_or_none() + if row is None: + return None + recipient, form = row + return self._to_form_record(form=form, recipient_id=recipient.id) + + @override + def create_upload_token(self, *, form: HumanInputUploadFormRecord, upload_token: str) -> None: + with self._session_factory.begin() as session: + session.add( + HumanInputFormUploadToken( + tenant_id=form.tenant_id, + app_id=form.app_id, + form_id=form.form_id, + recipient_id=form.recipient_id, + token=upload_token, + ) + ) + + @override + def get_upload_grant(self, upload_token: str) -> HumanInputUploadGrantRecord | None: + stmt = ( + select(HumanInputFormUploadToken, HumanInputForm) + .join(HumanInputForm, HumanInputForm.id == HumanInputFormUploadToken.form_id) + .where(HumanInputFormUploadToken.token == upload_token) + .limit(1) + ) + with self._session_factory() as session: + row = session.execute(stmt).one_or_none() + if row is None: + return None + token, form = row + return HumanInputUploadGrantRecord( + upload_token_id=token.id, + form=self._to_form_record(form=form, recipient_id=token.recipient_id), + ) + + @override + def get_upload_owner( + self, + *, + owner_id: str, + owner_role: CreatorUserRole, + tenant_id: str, + app_id: str, + ) -> Account | EndUser | None: + with self._session_factory() as session: + if owner_role == CreatorUserRole.END_USER: + return session.scalar( + select(EndUser) + .where( + EndUser.id == owner_id, + EndUser.tenant_id == tenant_id, + EndUser.app_id == app_id, + ) + .limit(1) + ) + + if owner_role != CreatorUserRole.ACCOUNT: + return None + + account = session.scalar(select(Account).where(Account.id == owner_id).limit(1)) + tenant = session.scalar(select(Tenant).where(Tenant.id == tenant_id).limit(1)) + if account is None or tenant is None: + return None + + account.set_current_tenant_with_session(tenant, session=session) + if account.current_tenant_id != tenant_id: + return None + return account + + @override + def get_delivery_test_upload_owner(self, *, tenant_id: str, app_id: str) -> Account | None: + with self._session_factory() as session: + app = session.scalar( + select(App) + .where( + App.id == app_id, + App.tenant_id == tenant_id, + ) + .limit(1) + ) + if app is None or app.created_by is None: + return None + + account = session.scalar(select(Account).where(Account.id == app.created_by).limit(1)) + tenant = session.scalar(select(Tenant).where(Tenant.id == tenant_id).limit(1)) + if account is None or tenant is None: + return None + + account.set_current_tenant_with_session(tenant, session=session) + if account.current_tenant_id != tenant_id: + return None + return account + + @override + def add_file( + self, + *, + tenant_id: str, + app_id: str, + form_id: str, + upload_token_id: str, + file_id: str, + ) -> None: + with self._session_factory.begin() as session: + session.add( + HumanInputFormUploadFile( + tenant_id=tenant_id, + app_id=app_id, + form_id=form_id, + upload_file_id=file_id, + upload_token_id=upload_token_id, + ) + ) + + @staticmethod + def _to_form_record(*, form: HumanInputForm, recipient_id: str) -> HumanInputUploadFormRecord: + return HumanInputUploadFormRecord( + form_id=form.id, + recipient_id=recipient_id, + tenant_id=form.tenant_id, + app_id=form.app_id, + workflow_run_id=form.workflow_run_id, + form_kind=form.form_kind, + status=form.status, + submitted_at=form.submitted_at, + expiration_time=form.expiration_time, + created_at=form.created_at, + ) diff --git a/api/repositories/message_file_preview_repository.py b/api/repositories/message_file_preview_repository.py new file mode 100644 index 00000000000..ad0aa68e219 --- /dev/null +++ b/api/repositories/message_file_preview_repository.py @@ -0,0 +1,66 @@ +"""SQLAlchemy query adapter for app-scoped message file previews.""" + +from typing import override + +from sqlalchemy import case, select +from sqlalchemy.orm import Session, sessionmaker + +from models.model import Message, MessageFile, UploadFile +from services.message_file_preview_service import ( + MessageFilePreviewAccessDeniedError, + MessageFilePreviewNotFoundError, + MessageFilePreviewQuery, + MessageFilePreviewRecord, +) + + +class MessageFilePreviewQueryRepository(MessageFilePreviewQuery): + def __init__(self, *, session_factory: sessionmaker[Session]) -> None: + self._session_factory = session_factory + + @override + def get_for_app( + self, + *, + file_id: str, + app_id: str, + tenant_id: str, + ) -> MessageFilePreviewRecord: + stmt = ( + select( + Message.app_id.label("message_app_id"), + UploadFile.tenant_id.label("file_tenant_id"), + UploadFile.key.label("file_key"), + UploadFile.name.label("file_name"), + UploadFile.size.label("file_size"), + UploadFile.extension.label("file_extension"), + UploadFile.mime_type.label("file_mime_type"), + ) + .select_from(MessageFile) + .outerjoin(Message, Message.id == MessageFile.message_id) + .outerjoin(UploadFile, UploadFile.id == MessageFile.upload_file_id) + .where(MessageFile.upload_file_id == file_id) + # One upload may be linked to multiple messages; prefer a reference owned by this app. + .order_by(case((Message.app_id == app_id, 0), else_=1), MessageFile.id) + .limit(1) + ) + + with self._session_factory() as session: + row = session.execute(stmt).one_or_none() + + if row is None: + raise MessageFilePreviewNotFoundError + if row.message_app_id != app_id: + raise MessageFilePreviewAccessDeniedError + if row.file_key is None: + raise MessageFilePreviewNotFoundError + if row.file_tenant_id != tenant_id: + raise MessageFilePreviewAccessDeniedError + + return MessageFilePreviewRecord( + key=row.file_key, + name=row.file_name, + size=row.file_size, + extension=row.file_extension, + mime_type=row.file_mime_type, + ) diff --git a/api/repositories/oauth_access_token_repository.py b/api/repositories/oauth_access_token_repository.py index 87ba4704093..d47c315cfd8 100644 --- a/api/repositories/oauth_access_token_repository.py +++ b/api/repositories/oauth_access_token_repository.py @@ -44,7 +44,7 @@ class SQLAlchemyOAuthAccessTokenRepository(AccountSessionRepository): .offset(offset) .limit(limit) ).all() - return int(total), tuple(self._to_snapshot(row) for row in rows) + return total, tuple(self._to_snapshot(row) for row in rows) @override def revoke( @@ -79,7 +79,7 @@ class SQLAlchemyOAuthAccessTokenRepository(AccountSessionRepository): @staticmethod def _to_snapshot(row: OAuthAccessToken) -> AccountSessionSnapshot: return AccountSessionSnapshot( - id=str(row.id), + id=row.id, prefix=row.prefix, client_id=row.client_id, device_label=row.device_label, diff --git a/api/repositories/plugin_file_upload_repository.py b/api/repositories/plugin_file_upload_repository.py new file mode 100644 index 00000000000..2b39aa8af89 --- /dev/null +++ b/api/repositories/plugin_file_upload_repository.py @@ -0,0 +1,45 @@ +"""Persistence queries for signed plugin file upload owners.""" + +from typing import override + +from sqlalchemy import select +from sqlalchemy.orm import Session, sessionmaker + +from models.account import TenantAccountJoin +from models.model import EndUser +from services.plugin_file_upload_service import PluginFileUploadOwnerQuery, PluginUploadUserFrom + + +class SQLAlchemyPluginFileUploadOwnerRepository(PluginFileUploadOwnerQuery): + def __init__(self, *, session_factory: sessionmaker[Session]) -> None: + self._session_factory = session_factory + + @override + def owner_exists( + self, + *, + tenant_id: str, + user_id: str, + user_from: PluginUploadUserFrom, + ) -> bool: + if user_from == "account": + statement = ( + select(TenantAccountJoin.id) + .where( + TenantAccountJoin.tenant_id == tenant_id, + TenantAccountJoin.account_id == user_id, + ) + .limit(1) + ) + else: + statement = ( + select(EndUser.id) + .where( + EndUser.tenant_id == tenant_id, + EndUser.id == user_id, + ) + .limit(1) + ) + + with self._session_factory() as session: + return session.scalar(statement) is not None diff --git a/api/repositories/upload_file_delivery_repository.py b/api/repositories/upload_file_delivery_repository.py new file mode 100644 index 00000000000..13a2a3518e9 --- /dev/null +++ b/api/repositories/upload_file_delivery_repository.py @@ -0,0 +1,78 @@ +"""SQLAlchemy query adapter for public UploadFile delivery endpoints.""" + +import json +from typing import cast, override + +from sqlalchemy import Row, Select, select +from sqlalchemy.orm import Session, sessionmaker + +from models.account import Tenant, TenantCustomConfigDict +from models.model import UploadFile +from services.upload_file_delivery_service import ( + UploadFileDeliveryNotFoundError, + UploadFileDeliveryQuery, + UploadFileDeliveryRecord, +) + + +class UploadFileDeliveryQueryRepository(UploadFileDeliveryQuery): + def __init__(self, *, session_factory: sessionmaker[Session]) -> None: + self._session_factory = session_factory + + @override + def get_by_id(self, *, file_id: str) -> UploadFileDeliveryRecord | None: + with self._session_factory() as session: + row = session.execute(self._file_query().where(UploadFile.id == file_id).limit(1)).one_or_none() + + return self._to_record(row) + + @override + def get_workspace_logo(self, *, workspace_id: str) -> UploadFileDeliveryRecord | None: + with self._session_factory() as session: + workspace_row = session.execute( + select(Tenant.custom_config).where(Tenant.id == workspace_id).limit(1) + ).one_or_none() + if workspace_row is None: + raise UploadFileDeliveryNotFoundError + + custom_config = ( + cast(TenantCustomConfigDict, json.loads(workspace_row.custom_config)) + if workspace_row.custom_config + else {} + ) + logo_file_id = custom_config.get("replace_webapp_logo") + if not logo_file_id: + raise UploadFileDeliveryNotFoundError("webapp logo is not found") + + file_row = session.execute( + self._file_query() + .where( + UploadFile.id == logo_file_id, + UploadFile.tenant_id == workspace_id, + ) + .limit(1) + ).one_or_none() + + return self._to_record(file_row) + + @staticmethod + def _file_query() -> Select[tuple[str, str, int, str, str | None]]: + return select( + UploadFile.key, + UploadFile.name, + UploadFile.size, + UploadFile.extension, + UploadFile.mime_type, + ) + + @staticmethod + def _to_record(row: Row[tuple[str, str, int, str, str | None]] | None) -> UploadFileDeliveryRecord | None: + if row is None: + return None + return UploadFileDeliveryRecord( + key=row.key, + name=row.name, + size=row.size, + extension=row.extension, + mime_type=row.mime_type, + ) diff --git a/api/repositories/webapp_access_query_repository.py b/api/repositories/webapp_access_query_repository.py index 94e2a31b6a9..cb29ce2603e 100644 --- a/api/repositories/webapp_access_query_repository.py +++ b/api/repositories/webapp_access_query_repository.py @@ -19,6 +19,6 @@ class WebAppAccessQueryRepository(WebAppAccessQuery): try: with self._session_factory() as session: app_id = session.scalar(select(Site.app_id).where(Site.code == app_code).limit(1)) - return str(app_id) if app_id is not None else None + return app_id if app_id is not None else None except (DBAPIError, TimeoutError) as e: raise WebAppAccessUnavailableError from e diff --git a/api/services/account_adapters.py b/api/services/account_adapters.py index 36bbff56052..2dd2689e7a4 100644 --- a/api/services/account_adapters.py +++ b/api/services/account_adapters.py @@ -151,8 +151,8 @@ class RBACWorkspaceMemberAccessSync(WorkspaceMemberAccessSync): from tasks.initialize_created_app_rbac_access_task import sync_joined_workspace_member_rbac_access_task sync_joined_workspace_member_rbac_access_task.delay( - str(workspace_id), - str(account_id), + workspace_id, + account_id, operator_account_id=None, ) @@ -221,8 +221,8 @@ class TokenManagerChangeEmailTokenGateway(ChangeEmailTokenGateway): return None token_kwargs = { "account_id": token_data.account_id, - "email": str(token_data.email), - "old_email": str(token_data.old_email), + "email": token_data.email, + "old_email": token_data.old_email, "code": token_data.code, } if isinstance(token_data, ChangeEmailOldEmailToken): diff --git a/api/services/account_login_adapters.py b/api/services/account_login_adapters.py index 65c8fac4513..412380d4922 100644 --- a/api/services/account_login_adapters.py +++ b/api/services/account_login_adapters.py @@ -447,7 +447,7 @@ class SQLAlchemyConsoleAuthProvisioningGateway(AccountProvisioningGateway, Works ).data for role in roles: if role.is_builtin and role.category == "global_system_default" and role.role_tag == "owner": - return str(role.id) + return role.id raise ValueError(f"Builtin RBAC owner role not found in tenant {tenant_id}") diff --git a/api/services/account_service.py b/api/services/account_service.py index e33af75e385..81ee3aeb037 100644 --- a/api/services/account_service.py +++ b/api/services/account_service.py @@ -1680,12 +1680,6 @@ class TenantService: target_member_join.role = new_tenant_role session.commit() - @staticmethod - def get_custom_config(tenant_id: str): - tenant = db.get_or_404(Tenant, tenant_id) - - return tenant.custom_config_dict - @staticmethod def is_owner(account: Account, tenant: Tenant, *, session: Session) -> bool: return TenantService.get_user_role(account, tenant, session=session) == TenantAccountRole.OWNER diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.py index a45ab42bf28..e781feb169e 100644 --- a/api/services/agent/roster_service.py +++ b/api/services/agent/roster_service.py @@ -44,6 +44,7 @@ from services.agent.workspace_service import AgentWorkspaceNotFoundError, AgentW from services.app_service import AppService, CreateAppParams from services.enterprise.enterprise_service import EnterpriseService from services.entities.agent_entities import RosterAgentCreatePayload, RosterAgentUpdatePayload +from services.rbac_agent_access_service import initialize_agent_rbac_access from services.system_feature_service import SystemFeatureService from tasks.collect_agent_resources_task import enqueue_agent_resource_collection @@ -314,11 +315,13 @@ class AgentRosterService: source=source, ) self._session.commit() - return agent except IntegrityError as exc: self._session.rollback() raise AgentNameConflictError() from exc + initialize_agent_rbac_access(tenant_id=tenant_id, agent_id=agent.id, creator_account_id=account_id) + return agent + def _create_roster_agent_in_transaction( self, *, diff --git a/api/services/agent/workspace_service.py b/api/services/agent/workspace_service.py index a3ffeea0064..fee8348b66f 100644 --- a/api/services/agent/workspace_service.py +++ b/api/services/agent/workspace_service.py @@ -104,6 +104,39 @@ class AgentWorkspaceService: ) ) + @classmethod + def resolve_active_binding_for_scope( + cls, + *, + session: Session, + scope: WorkspaceOwnerScope, + agent_id: str, + ) -> AgentWorkspaceBinding | None: + """Return the ACTIVE participant for a stable Workspace owner scope.""" + + return session.scalar( + select(AgentWorkspaceBinding) + .join( + AgentWorkspace, + (AgentWorkspace.tenant_id == AgentWorkspaceBinding.tenant_id) + & (AgentWorkspace.id == AgentWorkspaceBinding.workspace_id), + ) + .where( + AgentWorkspaceBinding.tenant_id == scope.tenant_id, + AgentWorkspaceBinding.app_id == scope.app_id, + AgentWorkspaceBinding.agent_id == agent_id, + AgentWorkspaceBinding.status == AgentWorkingResourceStatus.ACTIVE, + AgentWorkspace.tenant_id == scope.tenant_id, + AgentWorkspace.app_id == scope.app_id, + AgentWorkspace.owner_type == scope.owner_type, + AgentWorkspace.owner_id == scope.owner_id, + AgentWorkspace.owner_scope_key == scope.owner_scope_key, + AgentWorkspace.status == AgentWorkingResourceStatus.ACTIVE, + ) + .order_by(AgentWorkspaceBinding.created_at.desc()) + .limit(1) + ) + @classmethod def create_binding( cls, @@ -297,6 +330,37 @@ class AgentWorkspaceService: retired.append(workspace_id) return retired + @classmethod + def retire_all_for_conversation( + cls, + *, + session: Session, + tenant_id: str, + app_id: str, + conversation_id: str, + ) -> list[str]: + """Retire all ACTIVE conversation-owned Workspaces for one Chatflow conversation.""" + + workspaces = session.scalars( + select(AgentWorkspace).where( + AgentWorkspace.tenant_id == tenant_id, + AgentWorkspace.app_id == app_id, + AgentWorkspace.owner_type == AgentWorkspaceOwnerType.CONVERSATION, + AgentWorkspace.owner_id == conversation_id, + AgentWorkspace.status == AgentWorkingResourceStatus.ACTIVE, + ) + ).all() + retired: list[str] = [] + for workspace in workspaces: + workspace_id = cls.retire_workspace( + session=session, + tenant_id=tenant_id, + workspace_id=workspace.id, + ) + if workspace_id is not None: + retired.append(workspace_id) + return retired + @classmethod def collect_retired_binding(cls, *, tenant_id: str, binding_id: str) -> None: with session_factory.create_session() as session: diff --git a/api/services/agent_app_sandbox_service.py b/api/services/agent_app_sandbox_service.py index f9b0149abf1..02deb6f0023 100644 --- a/api/services/agent_app_sandbox_service.py +++ b/api/services/agent_app_sandbox_service.py @@ -25,6 +25,7 @@ from clients.agent_backend.factory import create_agent_backend_client from configs import dify_config from core.db.session_factory import session_factory from core.tools.signature import bind_file_uri +from core.workflow.nodes.agent_v2.session_store import resolve_workflow_agent_workspace_owner_scope from models.agent import ( Agent, AgentConfigDraft, @@ -32,7 +33,7 @@ from models.agent import ( AgentWorkspaceBinding, AgentWorkspaceOwnerType, ) -from models.model import App, AppMode, Conversation +from models.model import App, AppMode, Conversation, Message from models.workflow import WorkflowNodeExecutionModel from services.agent.roster_service import AgentRosterService from services.agent.workspace_service import AgentWorkspaceService, WorkspaceOwnerScope @@ -406,16 +407,26 @@ class WorkflowAgentSandboxService: "this Workflow Agent node execution has no active Workspace Binding", status_code=404, ) + conversation_id = session.scalar( + select(Message.conversation_id) + .where( + Message.app_id == app_id, + Message.workflow_run_id == workflow_run_id, + ) + .limit(1) + ) binding = AgentWorkspaceService.get_active_binding( session=session, tenant_id=tenant_id, binding_id=execution.agent_workspace_binding_id, - expected_owner_scope=WorkspaceOwnerScope( + expected_owner_scope=resolve_workflow_agent_workspace_owner_scope( tenant_id=tenant_id, app_id=app_id, - owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN, - owner_id=workflow_run_id, - owner_scope_key=f"{node_id}:{workflow_agent_binding_id}", + conversation_id=conversation_id, + workflow_run_id=workflow_run_id, + node_id=node_id, + workflow_agent_binding_id=workflow_agent_binding_id, + node_execution_id=node_execution_id, ), ) if binding is None: diff --git a/api/services/annotation_service.py b/api/services/annotation_service.py index ac0de983eb9..317ada53d89 100644 --- a/api/services/annotation_service.py +++ b/api/services/annotation_service.py @@ -9,6 +9,7 @@ from werkzeug.datastructures import FileStorage from werkzeug.exceptions import NotFound from core.helper.csv_sanitizer import CSVSanitizer +from enums import DeploymentEdition from extensions.ext_redis import redis_client from libs.datetime_utils import naive_utc_now from libs.login import current_account_with_tenant @@ -532,10 +533,10 @@ class AppAnnotationService: ) # Check annotation quota limit - features = FeatureService.get_features(current_tenant_id, exclude_vector_space=True) - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: + features = FeatureService.get_features(current_tenant_id, exclude_vector_space=True) annotation_quota_limit = features.annotation_quota_limit - if annotation_quota_limit.limit < len(result) + annotation_quota_limit.size: + if 0 < annotation_quota_limit.limit < len(result) + annotation_quota_limit.size: raise ValueError("The number of annotations exceeds the limit of your subscription.") # async job job_id = str(uuid.uuid4()) diff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.py index a67ae313813..de501b83ca2 100644 --- a/api/services/app_dsl_service.py +++ b/api/services/app_dsl_service.py @@ -44,6 +44,7 @@ from graphon.nodes.question_classifier.entities import QuestionClassifierNodeDat from graphon.nodes.tool.entities import ToolNodeData from libs.datetime_utils import naive_utc_now from models import Account, App, AppMode +from models.agent import AgentScope from models.model import AppModelConfig, AppModelConfigDict, IconType, load_annotation_reply_config from models.workflow import Workflow from services.agent.dsl_service import AgentDslService, AgentPackage @@ -243,8 +244,11 @@ class AppDslService: # If major version mismatch, store import info in Redis if status == ImportStatus.PENDING: + tenant_id = account.current_tenant_id + if tenant_id is None: + raise ValueError("Current tenant is not set") pending_data = PendingData( - tenant_id=account.current_tenant_id, + tenant_id=tenant_id, account_id=account.id, import_mode=import_mode, yaml_content=content, @@ -456,20 +460,27 @@ class AppDslService: raise NoPermissionError("You do not have permission to overwrite this app") return app - @staticmethod - def _ensure_agent_manage_permission(account: Account) -> None: - """Importing an Agent DSL creates a roster Agent, which requires ``agent.manage``.""" + def _ensure_agent_import_permission(self, account: Account, *, app: App | None) -> None: if not dify_config.RBAC_ENABLED: return if account.current_tenant_id is None: raise ValueError("Current tenant is not set") + binding = ( + app.agent_app_binding_with_session(session=self._session, include_archived=True) + if app is not None + else None + ) + if binding is not None and binding.scope == AgentScope.WORKFLOW_ONLY: + raise NoPermissionError("Agent DSL import permission is required to import an Agent App") allowed = RBACService.CheckAccess.check( account.current_tenant_id, account.id, - scene=RBACPermission.AGENT_MANAGE, + scene=RBACPermission.AGENT_IMPORT_EXPORT_DSL, + resource_type=RBACResourceScope.AGENT if binding is not None else None, + resource_id=str(binding.id) if binding is not None else None, ) if not allowed: - raise NoPermissionError("Agent management permission is required to import an Agent App") + raise NoPermissionError("Agent DSL import permission is required to import an Agent App") def _create_or_update_app( self, @@ -492,7 +503,7 @@ class AppDslService: raise ValueError("loss app mode") app_mode = AppMode(app_mode) if app_mode == AppMode.AGENT: - self._ensure_agent_manage_permission(account) + self._ensure_agent_import_permission(account, app=app) # Set icon type icon_type_value = icon_type or app_data.get("icon_type") diff --git a/api/services/app_service.py b/api/services/app_service.py index 30797c97ede..e90e962cf2b 100644 --- a/api/services/app_service.py +++ b/api/services/app_service.py @@ -1,6 +1,6 @@ import json import logging -from collections.abc import Sequence +from collections.abc import Callable, Sequence from dataclasses import dataclass from datetime import datetime from typing import Any, Literal, NotRequired, TypedDict, cast, override @@ -50,6 +50,7 @@ from services.billing_service import BillingService from services.enterprise import rbac_service as enterprise_rbac_service from services.enterprise.enterprise_service import EnterpriseService from services.openapi.visibility import apply_openapi_gate, is_openapi_visible +from services.rbac_agent_access_service import initialize_agent_rbac_access from services.system_feature_service import SystemFeatureService from services.tag_service import TagService from tasks.collect_agent_resources_task import enqueue_agent_resource_collection @@ -74,6 +75,38 @@ RECENT_APP_MODES: tuple[RecentAppMode, ...] = ( ) +@dataclass(frozen=True) +class _CreatedApp: + tenant_id: str + creator_account_id: str + app_id: str + backing_agent_id: str | None + + +def _initialize_created_app_access(created: _CreatedApp) -> None: + enterprise_rbac_service.try_sync_creator_access_policy_member_bindings( + created.tenant_id, + created.creator_account_id, + enterprise_rbac_service.RBACResourceType.APP, + created.app_id, + ) + + +def _initialize_created_agent_access(created: _CreatedApp) -> None: + if created.backing_agent_id is None: + raise ValueError(f"agent app {created.app_id} was created without a backing agent") + initialize_agent_rbac_access( + tenant_id=created.tenant_id, + agent_id=created.backing_agent_id, + creator_account_id=created.creator_account_id, + ) + + +_CREATED_APP_ACCESS_INITIALIZERS: dict[AppMode, Callable[[_CreatedApp], None]] = { + AppMode.AGENT: _initialize_created_agent_access, +} + + class AppListBaseParams(BaseModel): page: int = Field(default=1, ge=1) limit: int = Field(default=20, ge=1, le=100) @@ -670,12 +703,13 @@ class AppService: # Created in the same transaction so the App and its backing Agent persist # atomically; the Agent Soul (model/prompt/tools) is configured afterward # in the Composer. + backing_agent: Agent | None = None if app_mode == AppMode.AGENT: from services.agent.roster_service import AgentRosterService icon_type = AgentIconType(params.icon_type) if params.icon_type else None try: - AgentRosterService(session).create_backing_agent_for_app( + backing_agent = AgentRosterService(session).create_backing_agent_for_app( tenant_id=tenant_id, account_id=account.id, app_id=app.id, @@ -696,11 +730,14 @@ class AppService: session.commit() app_was_created.send(app, account=account, session=session) session.commit() - enterprise_rbac_service.try_sync_creator_access_policy_member_bindings( - tenant_id, - account.id, - enterprise_rbac_service.RBACResourceType.APP, - app.id, + initialize_access = _CREATED_APP_ACCESS_INITIALIZERS.get(app_mode, _initialize_created_app_access) + initialize_access( + _CreatedApp( + tenant_id=tenant_id, + creator_account_id=account.id, + app_id=app.id, + backing_agent_id=backing_agent.id if backing_agent else None, + ) ) if SystemFeatureService.is_webapp_auth_enabled(): diff --git a/api/services/billing_service.py b/api/services/billing_service.py index f89547f4558..c16f5b5142c 100644 --- a/api/services/billing_service.py +++ b/api/services/billing_service.py @@ -147,15 +147,6 @@ class _VectorSpaceQuota(TypedDict): usage_unknown: NotRequired[bool] -class _KnowledgeRateLimit(TypedDict): - # NOTE (hj24): - # 1. Return for sandbox users but is null for other plans, it's defined but never used. - # 2. Keep it for compatibility for now, can be deprecated in future versions. - size: NotRequired[int] - # NOTE END - limit: int - - class _BillingSubscription(TypedDict): plan: str interval: str @@ -173,15 +164,12 @@ class BillingInfo(TypedDict): 3. To preserve compatibility, always keep non-strict mode here and avoid strict mode """ - enabled: bool subscription: _BillingSubscription members: _BillingQuota apps: _BillingQuota vector_space: NotRequired[_VectorSpaceQuota] - knowledge_rate_limit: _KnowledgeRateLimit documents_upload_quota: _BillingQuota annotation_quota_limit: _BillingQuota - docs_processing: str can_replace_logo: bool model_load_balancing_enabled: bool knowledge_pipeline_publish_enabled: bool diff --git a/api/services/conversation_service.py b/api/services/conversation_service.py index 68e8d3c3e2c..de73a7cf32f 100644 --- a/api/services/conversation_service.py +++ b/api/services/conversation_service.py @@ -201,7 +201,6 @@ class ConversationService: """ conversation = cls.get_conversation(app_model, conversation_id, user, session=session) binding_id = conversation.agent_workspace_binding_id - retired_binding_id: str | None = None if binding_id is not None: owner_scope = WorkspaceOwnerScope( tenant_id=app_model.tenant_id, @@ -224,23 +223,21 @@ class ConversationService: app_model.name, conversation_id, ) - if binding_id is not None: - retired_binding_id = AgentWorkspaceService.retire_binding( - session=session, - tenant_id=app_model.tenant_id, - binding_id=binding_id, - ) - if retired_binding_id is None: - raise AgentWorkspaceNotFoundError("Conversation participant Binding is unavailable") + retired_workspace_ids = AgentWorkspaceService.retire_all_for_conversation( + session=session, + tenant_id=app_model.tenant_id, + app_id=app_model.id, + conversation_id=conversation.id, + ) conversation.is_deleted = True session.commit() except Exception: session.rollback() raise - if retired_binding_id is not None: + if retired_workspace_ids: enqueue_agent_resource_collection( tenant_id=app_model.tenant_id, - binding_ids=(retired_binding_id,), + workspace_ids=retired_workspace_ids, ) try: delete_conversation_related_data.delay(conversation.id) diff --git a/api/services/dataset_service.py b/api/services/dataset_service.py index 37296e4b1ec..8b3464bf5ae 100644 --- a/api/services/dataset_service.py +++ b/api/services/dataset_service.py @@ -23,7 +23,7 @@ from core.model_manager import ModelManager from core.rag.index_processor.constant.built_in_field import BuiltInField from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType from core.rag.retrieval.retrieval_methods import RetrievalMethod -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from events.dataset_event import dataset_was_deleted from events.document_event import document_was_deleted from extensions.ext_redis import redis_client @@ -1455,8 +1455,11 @@ class DatasetService: @staticmethod def get_dataset_auto_disable_logs(dataset_ref: DatasetRef, session: Session) -> AutoDisableLogsDict: + if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD: + return {"document_ids": [], "count": 0} + features = FeatureService.get_features(dataset_ref.tenant_id, exclude_vector_space=True) - if not features.billing.enabled or features.billing.subscription.plan == CloudPlan.SANDBOX: + if features.billing.subscription.plan == CloudPlan.SANDBOX: return { "document_ids": [], "count": 0, @@ -2208,9 +2211,8 @@ class DocumentService: assert isinstance(current_user, Account) assert current_user.current_tenant_id is not None - features = FeatureService.get_features(current_user.current_tenant_id, exclude_vector_space=True) - - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: + features = FeatureService.get_features(current_user.current_tenant_id, exclude_vector_space=True) if not knowledge_config.original_document_id: count = 0 if knowledge_config.data_source: @@ -2339,6 +2341,23 @@ class DocumentService: if not knowledge_config.data_source.info_list.file_info_list: raise ValueError("File source info is required") upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids + # Issue #41735: under MySQL's default + # ``REPEATABLE READ`` isolation, the SELECT snapshot + # for this transaction is pinned by the first + # read done earlier in ``save_document_with_dataset_id`` + # (e.g. ``check_doc_form``). The caller has just + # committed the upload in a different session + # (``FileService.upload_text`` / + # ``FileService.upload_file``), so the rows exist + # but are invisible to *this* session until its + # snapshot is refreshed. End the current transaction + # so the next SELECT starts with a fresh snapshot. + # The pending changes on ``dataset`` are also + # flushed, which is what we want — they must be + # persisted by this point anyway. PostgreSQL's + # default ``READ COMMITTED`` rebuilds the read view + # per statement so it isn't affected. + session.commit() files = list( session.scalars( select(UploadFile).where( @@ -2520,7 +2539,7 @@ class DocumentService: # # check document limit # features = FeatureService.get_features(current_user.current_tenant_id) - # if features.billing.enabled: + # if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: # if not knowledge_config.original_document_id: # count = 0 # if knowledge_config.data_source: @@ -2797,7 +2816,7 @@ class DocumentService: @staticmethod def check_document_creation_limits(count: int, features: FeatureModel): """Validate billing-backed document creation limits before document rows are created.""" - if not features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD: return if features.billing.subscription.plan == CloudPlan.SANDBOX and count > 1: @@ -3014,9 +3033,8 @@ class DocumentService: assert current_user.current_tenant_id is not None assert knowledge_config.data_source - features = FeatureService.get_features(current_user.current_tenant_id, exclude_vector_space=True) - - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: + features = FeatureService.get_features(current_user.current_tenant_id, exclude_vector_space=True) count = 0 if knowledge_config.data_source.info_list.data_source_type == "upload_file": upload_file_list = ( diff --git a/api/services/dify_builder/wiring.py b/api/services/dify_builder/wiring.py index 41f6e27ef6c..77936b32e94 100644 --- a/api/services/dify_builder/wiring.py +++ b/api/services/dify_builder/wiring.py @@ -14,7 +14,7 @@ from sqlalchemy.orm import sessionmaker from werkzeug.exceptions import Forbidden from configs import dify_config -from controllers.common.wraps import RBACPermission, RBACResourceScope, enforce_rbac_access +from controllers.common.rbac import PlainApp, RBACCheck, RBACPermission, enforce_rbac_checks from core.dify_builder.errors import BadRequestError, BusyError, ConflictError, NotFoundError from core.dify_builder.models import Action, Actor from extensions.ext_database import db @@ -72,11 +72,10 @@ def _authorize_app(actor: Actor, app_id: str, access: AppAccess) -> None: elif access == AppAccess.RELEASE: scenes.append(RBACPermission.APP_RELEASE_AND_VERSION) for scene in scenes: - enforce_rbac_access( + enforce_rbac_checks( tenant_id=actor.tenant_id, account_id=actor.account_id, - resource_type=RBACResourceScope.APP, - scene=scene, + checks=[RBACCheck(scene, PlainApp())], path_args={"app_id": str(trusted_app_id)}, ) diff --git a/api/services/document_indexing_proxy/base.py b/api/services/document_indexing_proxy/base.py index 91835c8abb2..b38d6e64a6a 100644 --- a/api/services/document_indexing_proxy/base.py +++ b/api/services/document_indexing_proxy/base.py @@ -4,7 +4,8 @@ from collections.abc import Callable from functools import cached_property from typing import Any, ClassVar -from enums import CloudPlan +from configs import dify_config +from enums import CloudPlan, DeploymentEdition from services.feature_service import FeatureService logger = logging.getLogger(__name__) @@ -88,14 +89,10 @@ class DocumentTaskProxyBase(ABC): - Paid plans → priority queue + tenant isolation - Self-hosted → priority queue, no isolation """ - logger.info( - "dispatch args: %s - %s - %s", - self._tenant_id, - self.features.billing.enabled, - self.features.billing.subscription.plan, - ) - # dispatch to different indexing queue with tenant isolation when billing enabled - if self.features.billing.enabled: + logger.info("Dispatching tenant %s in %s", self._tenant_id, dify_config.DEPLOYMENT_EDITION) + + # Cloud queues isolate tenants and prioritize paid plans. + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: if self.features.billing.subscription.plan == CloudPlan.SANDBOX: # dispatch to normal pipeline queue with tenant self sub queue for sandbox plan self._send_to_default_tenant_queue() diff --git a/api/services/enterprise/rbac_service.py b/api/services/enterprise/rbac_service.py index b511bfbb103..0edeb9485af 100644 --- a/api/services/enterprise/rbac_service.py +++ b/api/services/enterprise/rbac_service.py @@ -2,6 +2,7 @@ from __future__ import annotations import logging from collections.abc import Sequence +from dataclasses import dataclass from enum import StrEnum from typing import Any, TypeVar @@ -53,11 +54,27 @@ class MembersInRole(_RBACModel): account_name: str = "" +@dataclass(frozen=True) +class _ResourceAccessRoute: + segment: str + id_param: str + + class RBACResourceType(StrEnum): """Resource types understood by access policies.""" APP = "app" DATASET = "dataset" + AGENT = "agent" + + @property + def route(self) -> _ResourceAccessRoute: + routes = { + RBACResourceType.APP: _ResourceAccessRoute("apps", "app_id"), + RBACResourceType.DATASET: _ResourceAccessRoute("datasets", "dataset_id"), + RBACResourceType.AGENT: _ResourceAccessRoute("agents", "agent_id"), + } + return routes[self] class RBACRoleType(StrEnum): @@ -211,6 +228,11 @@ class DatasetAccessMatrix(_RBACModel): items: list[AccessMatrixItem] = Field(default_factory=list) +class AgentAccessMatrix(_RBACModel): + agent_id: str = Field(default="", validation_alias=AliasChoices("agent_id", "resource_id")) + items: list[AccessMatrixItem] = Field(default_factory=list) + + class WorkspaceAccessMatrix(_RBACModel): items: list[AccessMatrixItem] = Field(default_factory=list) pagination: Pagination | None = None @@ -281,6 +303,24 @@ class _LegacyResourceWhitelistConfig(_RBACModel): return value +class LegacyAgentRoleMigration(_RBACModel): + role_id: str + role_name: str = "" + added_keys: list[str] = Field(default_factory=list) + removed_keys: list[str] = Field(default_factory=list) + bound_policies: list[str] = Field(default_factory=list) + skipped: str = "" + + +class LegacyAgentMigrationReport(_RBACModel): + roles: list[LegacyAgentRoleMigration] = Field(default_factory=list) + role_templates: list[LegacyAgentRoleMigration] = Field(default_factory=list) + + +class ConfiguredAgentIDs(_RBACModel): + configured_agent_ids: list[str] = Field(default_factory=list) + + class ResourceWhitelistResources(_RBACModel): unrestricted: bool = False resource_ids: list[str] = Field(default_factory=list) @@ -339,6 +379,12 @@ class AppendDatasetWhitelistMembersBatchItem(_RBACModel): policy_id: str +class AppendAgentWhitelistMembersBatchItem(_RBACModel): + agent_id: str + account_ids: list[str] = Field(default_factory=list) + policy_id: str + + class MemberRolesResponse(_RBACModel): account_id: str roles: list[RBACRole] = Field(default_factory=list) @@ -369,6 +415,14 @@ class MyPermissionsResponse(_RBACModel): workspace: WorkspacePermissionSnapshot = Field(default_factory=WorkspacePermissionSnapshot) app: ResourcePermissionSnapshot = Field(default_factory=ResourcePermissionSnapshot) dataset: ResourcePermissionSnapshot = Field(default_factory=ResourcePermissionSnapshot) + agent: ResourcePermissionSnapshot = Field(default_factory=ResourcePermissionSnapshot) + + def resource_snapshot(self, resource_type: RBACResourceType) -> ResourcePermissionSnapshot: + return { + RBACResourceType.APP: self.app, + RBACResourceType.DATASET: self.dataset, + RBACResourceType.AGENT: self.agent, + }[resource_type] # Fallback permission snapshots for legacy Dify tenant roles when external RBAC is disabled. @@ -404,7 +458,9 @@ _LEGACY_WORKSPACE_OWNER_KEYS: list[str] = [ "snippets.management", "tool.manage", "mcp.manage", - "agent.manage", + "agent.create", + "agent.acl.preview", + "agent.acl.access_point_view", ] _LEGACY_WORKSPACE_ADMIN_KEYS: list[str] = [ @@ -436,7 +492,9 @@ _LEGACY_WORKSPACE_ADMIN_KEYS: list[str] = [ "snippets.management", "tool.manage", "mcp.manage", - "agent.manage", + "agent.create", + "agent.acl.preview", + "agent.acl.access_point_view", ] _LEGACY_WORKSPACE_EDITOR_KEYS: list[str] = [ @@ -455,7 +513,9 @@ _LEGACY_WORKSPACE_EDITOR_KEYS: list[str] = [ "dataset.external.connect", "snippets.create_and_modify", "tool.manage", - "agent.manage", + "agent.create", + "agent.acl.preview", + "agent.acl.access_point_view", ] _LEGACY_WORKSPACE_NORMAL_KEYS: list[str] = [ @@ -464,7 +524,8 @@ _LEGACY_WORKSPACE_NORMAL_KEYS: list[str] = [ "plugin.install", "credential.use", "app_library.access", - "agent.manage", + "agent.acl.preview", + "agent.acl.access_point_view", ] _LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS: list[str] = [ @@ -472,7 +533,8 @@ _LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS: list[str] = [ "plugin.install", "dataset.create_and_management", "dataset.external.connect", - "agent.manage", + "agent.acl.preview", + "agent.acl.access_point_view", ] _LEGACY_APP_OWNER_KEYS: list[str] = [ @@ -589,30 +651,54 @@ _LEGACY_DATASET_DATASET_OPERATOR_KEYS: list[str] = [ "dataset.acl.pipeline_release", ] +_LEGACY_AGENT_FULL_ACCESS_KEYS: list[str] = [ + "agent.acl.preview", + "agent.acl.edit", + "agent.acl.test_and_run", + "agent.acl.release_and_version", + "agent.acl.access_point_view", + "agent.acl.access_point_manage", + "agent.acl.log_manage", + "agent.acl.monitor", + "agent.acl.access_config", + "agent.acl.import_export_dsl", + "agent.acl.delete", +] + +_LEGACY_AGENT_PREVIEW_KEYS: list[str] = [ + "agent.acl.preview", + "agent.acl.access_point_view", +] + _LEGACY_MY_PERMISSIONS: dict[TenantAccountRole, dict[str, list[str]]] = { TenantAccountRole.OWNER: { "workspace": _LEGACY_WORKSPACE_OWNER_KEYS, "app": _LEGACY_APP_OWNER_KEYS, "dataset": _LEGACY_DATASET_OWNER_KEYS, + "agent": _LEGACY_AGENT_FULL_ACCESS_KEYS, }, TenantAccountRole.ADMIN: { "workspace": _LEGACY_WORKSPACE_ADMIN_KEYS, "app": _LEGACY_APP_ADMIN_KEYS, "dataset": _LEGACY_DATASET_ADMIN_KEYS, + "agent": _LEGACY_AGENT_FULL_ACCESS_KEYS, }, TenantAccountRole.EDITOR: { "workspace": _LEGACY_WORKSPACE_EDITOR_KEYS, "app": _LEGACY_APP_EDITOR_KEYS, "dataset": _LEGACY_DATASET_EDITOR_KEYS, + "agent": _LEGACY_AGENT_FULL_ACCESS_KEYS, }, TenantAccountRole.NORMAL: { "workspace": _LEGACY_WORKSPACE_NORMAL_KEYS, "app": _LEGACY_APP_NORMAL_KEYS, + "agent": _LEGACY_AGENT_PREVIEW_KEYS, }, TenantAccountRole.DATASET_OPERATOR: { "workspace": _LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS, "app": _LEGACY_APP_DATASET_OPERATOR_KEYS, "dataset": _LEGACY_DATASET_DATASET_OPERATOR_KEYS, + "agent": _LEGACY_AGENT_PREVIEW_KEYS, }, } @@ -625,6 +711,7 @@ def _legacy_role_permission_keys(role: TenantAccountRole) -> list[str]: *permissions.get("workspace", []), *permissions.get("app", []), *permissions.get("dataset", []), + *permissions.get("agent", []), ] ) ) @@ -681,6 +768,7 @@ def _legacy_my_permissions(tenant_id: str, account_id: str | None, *, session: S workspace=WorkspacePermissionSnapshot(permission_keys=list(permissions.get("workspace", []))), app=ResourcePermissionSnapshot(default_permission_keys=list(permissions.get("app", []))), dataset=ResourcePermissionSnapshot(default_permission_keys=list(permissions.get("dataset", []))), + agent=ResourcePermissionSnapshot(default_permission_keys=list(permissions.get("agent", []))), ) @@ -693,10 +781,7 @@ def _legacy_resource_permission_keys_batch( session: Session, ) -> dict[str, list[str]]: snapshot = _legacy_my_permissions(tenant_id, account_id, session=session) - if resource_type == RBACResourceType.APP: - permission_keys = snapshot.app.default_permission_keys - else: - permission_keys = snapshot.dataset.default_permission_keys + permission_keys = snapshot.resource_snapshot(resource_type).default_permission_keys return {str(resource_id): list(permission_keys) for resource_id in resource_ids} @@ -830,13 +915,8 @@ def _inner_call( def _resource_id_params(resource_type: RBACResourceType | str, resource_id: str) -> dict[str, str]: - resource_type_value = resource_type.value if isinstance(resource_type, RBACResourceType) else str(resource_type) - resource_id = resource_id.strip() - if resource_type_value == RBACResourceType.APP.value: - return {"resource_type": resource_type_value, "app_id": resource_id} - if resource_type_value == RBACResourceType.DATASET.value: - return {"resource_type": resource_type_value, "dataset_id": resource_id} - raise ValueError(f"unsupported resource_type: {resource_type_value}") + resolved = resource_type if isinstance(resource_type, RBACResourceType) else RBACResourceType(resource_type) + return {"resource_type": resolved.value, resolved.route.id_param: resource_id.strip()} def try_sync_creator_access_policy_member_bindings( @@ -866,6 +946,333 @@ def try_sync_creator_access_policy_member_bindings( ) +class _ResourceAccessClient[MatrixT: _RBACModel]: + def __init__( + self, + route: _ResourceAccessRoute, + matrix_model: type[MatrixT], + *, + replace_user_policies_exclude_unset: bool = False, + ) -> None: + self._route = route + self._matrix_model = matrix_model + self._replace_user_policies_exclude_unset = replace_user_policies_exclude_unset + + def _path(self, suffix: str) -> str: + return f"{_INNER_PREFIX}/{self._route.segment}/{suffix}" + + def _params(self, resource_id: str, policy_id: str | None = None) -> dict[str, object]: + params: dict[str, object] = {self._route.id_param: resource_id} + if policy_id is not None: + params["policy_id"] = policy_id + return params + + def whitelist_resources(self, tenant_id: str, account_id: str | None) -> ResourceWhitelistResources: + data = _inner_call( + "GET", + self._path("whitelist/resources"), + tenant_id=tenant_id, + account_id=account_id, + ) + return ResourceWhitelistResources.model_validate(data or {}) + + def user_access_policies( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + *, + options: ListOption | None = None, + ) -> ResourceUserAccessPoliciesResponse: + params = (options or ListOption()).to_params({self._route.id_param: resource_id}) + data = _inner_call( + "GET", + self._path("user-access-policies"), + tenant_id=tenant_id, + account_id=account_id, + params=params, + ) + return ResourceUserAccessPoliciesResponse.model_validate(data or {}) + + def replace_user_access_policies( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + target_account_id: str | None, + payload: ReplaceUserAccessPolicies, + ) -> ReplaceUserAccessPoliciesResponse: + params = self._params(resource_id) + params["account_id"] = target_account_id + data = _inner_call( + "PUT", + self._path("user-access-policies"), + tenant_id=tenant_id, + account_id=account_id, + params=params, + json=payload.model_dump(mode="json", exclude_unset=self._replace_user_policies_exclude_unset), + ) + return ReplaceUserAccessPoliciesResponse.model_validate(data or {}) + + def whitelist(self, tenant_id: str, account_id: str | None, resource_id: str) -> ResourceWhitelist: + data = _inner_call( + "GET", + self._path("whitelist"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id), + ) + return ResourceWhitelist.model_validate(data or {}) + + def whitelist_config(self, tenant_id: str, account_id: str | None, resource_id: str) -> ResourceWhitelistConfig: + data = _inner_call( + "GET", + self._path("whitelist"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id), + ) + return ResourceWhitelistConfig.model_validate(data or {}) + + def legacy_whitelist_config( + self, tenant_id: str, account_id: str | None, resource_id: str + ) -> _LegacyResourceWhitelistConfig: + data = _inner_call( + "GET", + self._path("whitelist"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id), + ) + return _LegacyResourceWhitelistConfig.model_validate(data or {}) + + def replace_whitelist( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + payload: ReplaceMemberBindings, + ) -> ResourceWhitelist: + data = _inner_call( + "PUT", + self._path("whitelist"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id), + json=payload.model_dump(mode="json"), + ) + return ResourceWhitelist.model_validate(data or {}) + + def append_whitelist_members_batch( + self, + tenant_id: str, + account_id: str | None, + data: Sequence[_RBACModel], + ) -> None: + _inner_call( + "POST", + self._path("whitelist/members/batch"), + tenant_id=tenant_id, + account_id=account_id, + json={"data": [item.model_dump(mode="json") for item in data]}, + ) + + def matrix(self, tenant_id: str, account_id: str | None, resource_id: str) -> MatrixT: + data = _inner_call( + "GET", + self._path("access-policy"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id), + ) + return self._matrix_model.model_validate(data or {}) + + def list_role_bindings( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + policy_id: str, + ) -> RoleBindingsResponse: + data = _inner_call( + "GET", + self._path("access-policy/role-bindings"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id, policy_id), + ) + return RoleBindingsResponse.model_validate(data or {}) + + def replace_role_bindings( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + policy_id: str, + payload: ReplaceRoleBindings, + ) -> RoleBindingsResponse: + data = _inner_call( + "PUT", + self._path("access-policy/role-bindings"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id, policy_id), + json=payload.model_dump(mode="json"), + ) + return RoleBindingsResponse.model_validate(data or {}) + + def list_member_bindings( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + policy_id: str, + ) -> MemberBindingsResponse: + data = _inner_call( + "GET", + self._path("access-policy/member-bindings"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id, policy_id), + ) + return MemberBindingsResponse.model_validate(data or {}) + + def delete_member_bindings( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + policy_id: str, + payload: DeleteMemberBindings, + ) -> None: + _inner_call( + "DELETE", + self._path("access-policy/member-bindings"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id, policy_id), + json=payload.model_dump(mode="json"), + ) + + def replace_bindings( + self, + tenant_id: str, + account_id: str | None, + resource_id: str, + policy_id: str, + payload: ReplaceBindings, + ) -> AccessMatrixItem: + data = _inner_call( + "PUT", + self._path("access-policy/bindings"), + tenant_id=tenant_id, + account_id=account_id, + params=self._params(resource_id, policy_id), + json=payload.model_dump(mode="json"), + ) + return AccessMatrixItem.model_validate(data or {}) + + +class _WorkspaceAccessClient: + def __init__(self, route: _ResourceAccessRoute) -> None: + self._route = route + + def _path(self, suffix: str) -> str: + return f"{_INNER_PREFIX}/workspace/{self._route.segment}/{suffix}" + + def matrix( + self, + tenant_id: str, + account_id: str | None = None, + *, + options: ListOption | None = None, + ) -> WorkspaceAccessMatrix: + data = _inner_call( + "GET", + self._path("access-policy"), + tenant_id=tenant_id, + account_id=account_id, + params=(options or ListOption()).to_params() or None, + ) + return WorkspaceAccessMatrix.model_validate(data or {}) + + def list_role_bindings(self, tenant_id: str, account_id: str | None, policy_id: str) -> RoleBindingsResponse: + data = _inner_call( + "GET", + self._path("access-policy/role-bindings"), + tenant_id=tenant_id, + account_id=account_id, + params={"policy_id": policy_id}, + ) + return RoleBindingsResponse.model_validate(data or {}) + + def replace_role_bindings( + self, + tenant_id: str, + account_id: str | None, + policy_id: str, + payload: ReplaceRoleBindings, + ) -> RoleBindingsResponse: + data = _inner_call( + "PUT", + self._path("access-policy/role-bindings"), + tenant_id=tenant_id, + account_id=account_id, + params={"policy_id": policy_id}, + json=payload.model_dump(mode="json"), + ) + return RoleBindingsResponse.model_validate(data or {}) + + def list_member_bindings(self, tenant_id: str, account_id: str | None, policy_id: str) -> MemberBindingsResponse: + data = _inner_call( + "GET", + self._path("access-policy/member-bindings"), + tenant_id=tenant_id, + account_id=account_id, + params={"policy_id": policy_id}, + ) + return MemberBindingsResponse.model_validate(data or {}) + + def replace_bindings( + self, + tenant_id: str, + account_id: str | None, + policy_id: str, + payload: ReplaceBindings, + ) -> AccessMatrixItem: + data = _inner_call( + "PUT", + self._path("access-policy/bindings"), + tenant_id=tenant_id, + account_id=account_id, + params={"policy_id": policy_id}, + json=payload.model_dump(mode="json"), + ) + return AccessMatrixItem.model_validate(data or {}) + + +_APP_ACCESS = _ResourceAccessClient(RBACResourceType.APP.route, AppAccessMatrix) +_DATASET_ACCESS = _ResourceAccessClient( + RBACResourceType.DATASET.route, DatasetAccessMatrix, replace_user_policies_exclude_unset=True +) +_AGENT_ACCESS = _ResourceAccessClient(RBACResourceType.AGENT.route, AgentAccessMatrix) +_WORKSPACE_APP_ACCESS = _WorkspaceAccessClient(RBACResourceType.APP.route) +_WORKSPACE_DATASET_ACCESS = _WorkspaceAccessClient(RBACResourceType.DATASET.route) +_WORKSPACE_AGENT_ACCESS = _WorkspaceAccessClient(RBACResourceType.AGENT.route) + + +def _resource_permission_catalog( + resource_type: RBACResourceType, tenant_id: str, account_id: str | None +) -> PermissionCatalogResponse: + data = _inner_call( + "GET", + f"{_INNER_PREFIX}/role-permissions/catalog/{resource_type.value}", + tenant_id=tenant_id, + account_id=account_id, + ) + return PermissionCatalogResponse.model_validate(data or {}) + + class RBACService: """Single entry point grouping every inner RBAC call by feature area. @@ -890,23 +1297,15 @@ class RBACService: @staticmethod def app(tenant_id: str, account_id: str | None = None) -> PermissionCatalogResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/role-permissions/catalog/app", - tenant_id=tenant_id, - account_id=account_id, - ) - return PermissionCatalogResponse.model_validate(data or {}) + return _resource_permission_catalog(RBACResourceType.APP, tenant_id, account_id) @staticmethod def dataset(tenant_id: str, account_id: str | None = None) -> PermissionCatalogResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/role-permissions/catalog/dataset", - tenant_id=tenant_id, - account_id=account_id, - ) - return PermissionCatalogResponse.model_validate(data or {}) + return _resource_permission_catalog(RBACResourceType.DATASET, tenant_id, account_id) + + @staticmethod + def agent(tenant_id: str, account_id: str | None = None) -> PermissionCatalogResponse: + return _resource_permission_catalog(RBACResourceType.AGENT, tenant_id, account_id) # ------------------------------------------------------------------ # Role CRUD (Settings > Permissions). @@ -1200,13 +1599,7 @@ class RBACService: class AppAccess: @staticmethod def whitelist_resources(tenant_id: str, account_id: str | None) -> ResourceWhitelistResources: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/whitelist/resources", - tenant_id=tenant_id, - account_id=account_id, - ) - return ResourceWhitelistResources.model_validate(data or {}) + return _APP_ACCESS.whitelist_resources(tenant_id, account_id) @staticmethod def user_access_policies( @@ -1216,15 +1609,7 @@ class RBACService: *, options: ListOption | None = None, ) -> ResourceUserAccessPoliciesResponse: - params = (options or ListOption()).to_params({"app_id": app_id}) - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/user-access-policies", - tenant_id=tenant_id, - account_id=account_id, - params=params, - ) - return ResourceUserAccessPoliciesResponse.model_validate(data or {}) + return _APP_ACCESS.user_access_policies(tenant_id, account_id, app_id, options=options) @staticmethod def replace_user_access_policies( @@ -1234,51 +1619,21 @@ class RBACService: target_account_id: str | None, payload: ReplaceUserAccessPolicies, ) -> ReplaceUserAccessPoliciesResponse: - request_data = payload.model_dump(mode="json") - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/apps/user-access-policies", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id, "account_id": target_account_id}, - json=request_data, - ) - return ReplaceUserAccessPoliciesResponse.model_validate(data or {}) + return _APP_ACCESS.replace_user_access_policies(tenant_id, account_id, app_id, target_account_id, payload) @staticmethod def whitelist(tenant_id: str, account_id: str | None, app_id: str) -> ResourceWhitelist: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id}, - ) - return ResourceWhitelist.model_validate(data or {}) + return _APP_ACCESS.whitelist(tenant_id, account_id, app_id) @staticmethod def whitelist_config(tenant_id: str, account_id: str | None, app_id: str) -> ResourceWhitelistConfig: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id}, - ) - return ResourceWhitelistConfig.model_validate(data or {}) + return _APP_ACCESS.whitelist_config(tenant_id, account_id, app_id) @staticmethod def legacy_whitelist_config( tenant_id: str, account_id: str | None, app_id: str ) -> _LegacyResourceWhitelistConfig: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id}, - ) - return _LegacyResourceWhitelistConfig.model_validate(data or {}) + return _APP_ACCESS.legacy_whitelist_config(tenant_id, account_id, app_id) @staticmethod def replace_whitelist( @@ -1287,15 +1642,7 @@ class RBACService: app_id: str, payload: ReplaceMemberBindings, ) -> ResourceWhitelist: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/apps/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id}, - json=payload.model_dump(mode="json"), - ) - return ResourceWhitelist.model_validate(data or {}) + return _APP_ACCESS.replace_whitelist(tenant_id, account_id, app_id, payload) @staticmethod def append_whitelist_members_batch( @@ -1303,24 +1650,11 @@ class RBACService: account_id: str | None, data: Sequence[AppendAppWhitelistMembersBatchItem], ) -> None: - _inner_call( - "POST", - f"{_INNER_PREFIX}/apps/whitelist/members/batch", - tenant_id=tenant_id, - account_id=account_id, - json={"data": [item.model_dump(mode="json") for item in data]}, - ) + _APP_ACCESS.append_whitelist_members_batch(tenant_id, account_id, data) @staticmethod def matrix(tenant_id: str, account_id: str | None, app_id: str) -> AppAccessMatrix: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/access-policy", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id}, - ) - return AppAccessMatrix.model_validate(data or {}) + return _APP_ACCESS.matrix(tenant_id, account_id, app_id) @staticmethod def list_role_bindings( @@ -1329,14 +1663,7 @@ class RBACService: app_id: str, policy_id: str, ) -> RoleBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id, "policy_id": policy_id}, - ) - return RoleBindingsResponse.model_validate(data or {}) + return _APP_ACCESS.list_role_bindings(tenant_id, account_id, app_id, policy_id) @staticmethod def replace_role_bindings( @@ -1346,15 +1673,7 @@ class RBACService: policy_id: str, payload: ReplaceRoleBindings, ) -> RoleBindingsResponse: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/apps/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id, "policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) - return RoleBindingsResponse.model_validate(data or {}) + return _APP_ACCESS.replace_role_bindings(tenant_id, account_id, app_id, policy_id, payload) @staticmethod def list_member_bindings( @@ -1363,14 +1682,7 @@ class RBACService: app_id: str, policy_id: str, ) -> MemberBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/apps/access-policy/member-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id, "policy_id": policy_id}, - ) - return MemberBindingsResponse.model_validate(data or {}) + return _APP_ACCESS.list_member_bindings(tenant_id, account_id, app_id, policy_id) @staticmethod def delete_member_bindings( @@ -1380,14 +1692,7 @@ class RBACService: policy_id: str, payload: DeleteMemberBindings, ) -> None: - _inner_call( - "DELETE", - f"{_INNER_PREFIX}/apps/access-policy/member-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id, "policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) + _APP_ACCESS.delete_member_bindings(tenant_id, account_id, app_id, policy_id, payload) @staticmethod def replace_bindings( @@ -1397,15 +1702,7 @@ class RBACService: policy_id: str, payload: ReplaceBindings, ) -> AccessMatrixItem: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/apps/access-policy/bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"app_id": app_id, "policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) - return AccessMatrixItem.model_validate(data or {}) + return _APP_ACCESS.replace_bindings(tenant_id, account_id, app_id, policy_id, payload) # ------------------------------------------------------------------ # Per-dataset access (screenshot 1: Knowledge Base Access Config). @@ -1413,13 +1710,7 @@ class RBACService: class DatasetAccess: @staticmethod def whitelist_resources(tenant_id: str, account_id: str | None) -> ResourceWhitelistResources: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/whitelist/resources", - tenant_id=tenant_id, - account_id=account_id, - ) - return ResourceWhitelistResources.model_validate(data or {}) + return _DATASET_ACCESS.whitelist_resources(tenant_id, account_id) @staticmethod def user_access_policies( @@ -1429,15 +1720,7 @@ class RBACService: *, options: ListOption | None = None, ) -> ResourceUserAccessPoliciesResponse: - params = (options or ListOption()).to_params({"dataset_id": dataset_id}) - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/user-access-policies", - tenant_id=tenant_id, - account_id=account_id, - params=params, - ) - return ResourceUserAccessPoliciesResponse.model_validate(data or {}) + return _DATASET_ACCESS.user_access_policies(tenant_id, account_id, dataset_id, options=options) @staticmethod def replace_user_access_policies( @@ -1447,50 +1730,23 @@ class RBACService: target_account_id: str | None, payload: ReplaceUserAccessPolicies, ) -> ReplaceUserAccessPoliciesResponse: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/datasets/user-access-policies", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id, "account_id": target_account_id}, - json=payload.model_dump(mode="json", exclude_unset=True), + return _DATASET_ACCESS.replace_user_access_policies( + tenant_id, account_id, dataset_id, target_account_id, payload ) - return ReplaceUserAccessPoliciesResponse.model_validate(data or {}) @staticmethod def whitelist(tenant_id: str, account_id: str | None, dataset_id: str) -> ResourceWhitelist: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id}, - ) - return ResourceWhitelist.model_validate(data or {}) + return _DATASET_ACCESS.whitelist(tenant_id, account_id, dataset_id) @staticmethod def whitelist_config(tenant_id: str, account_id: str | None, dataset_id: str) -> ResourceWhitelistConfig: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id}, - ) - return ResourceWhitelistConfig.model_validate(data or {}) + return _DATASET_ACCESS.whitelist_config(tenant_id, account_id, dataset_id) @staticmethod def legacy_whitelist_config( tenant_id: str, account_id: str | None, dataset_id: str ) -> _LegacyResourceWhitelistConfig: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id}, - ) - return _LegacyResourceWhitelistConfig.model_validate(data or {}) + return _DATASET_ACCESS.legacy_whitelist_config(tenant_id, account_id, dataset_id) @staticmethod def replace_whitelist( @@ -1499,15 +1755,7 @@ class RBACService: dataset_id: str, payload: ReplaceMemberBindings, ) -> ResourceWhitelist: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/datasets/whitelist", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id}, - json=payload.model_dump(mode="json"), - ) - return ResourceWhitelist.model_validate(data or {}) + return _DATASET_ACCESS.replace_whitelist(tenant_id, account_id, dataset_id, payload) @staticmethod def append_whitelist_members_batch( @@ -1515,24 +1763,11 @@ class RBACService: account_id: str | None, data: Sequence[AppendDatasetWhitelistMembersBatchItem], ) -> None: - _inner_call( - "POST", - f"{_INNER_PREFIX}/datasets/whitelist/members/batch", - tenant_id=tenant_id, - account_id=account_id, - json={"data": [item.model_dump(mode="json") for item in data]}, - ) + _DATASET_ACCESS.append_whitelist_members_batch(tenant_id, account_id, data) @staticmethod def matrix(tenant_id: str, account_id: str | None, dataset_id: str) -> DatasetAccessMatrix: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/access-policy", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id}, - ) - return DatasetAccessMatrix.model_validate(data or {}) + return _DATASET_ACCESS.matrix(tenant_id, account_id, dataset_id) @staticmethod def list_role_bindings( @@ -1541,14 +1776,7 @@ class RBACService: dataset_id: str, policy_id: str, ) -> RoleBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id, "policy_id": policy_id}, - ) - return RoleBindingsResponse.model_validate(data or {}) + return _DATASET_ACCESS.list_role_bindings(tenant_id, account_id, dataset_id, policy_id) @staticmethod def replace_role_bindings( @@ -1558,15 +1786,7 @@ class RBACService: policy_id: str, payload: ReplaceRoleBindings, ) -> RoleBindingsResponse: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/datasets/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id, "policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) - return RoleBindingsResponse.model_validate(data or {}) + return _DATASET_ACCESS.replace_role_bindings(tenant_id, account_id, dataset_id, policy_id, payload) @staticmethod def list_member_bindings( @@ -1575,14 +1795,7 @@ class RBACService: dataset_id: str, policy_id: str, ) -> MemberBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/datasets/access-policy/member-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id, "policy_id": policy_id}, - ) - return MemberBindingsResponse.model_validate(data or {}) + return _DATASET_ACCESS.list_member_bindings(tenant_id, account_id, dataset_id, policy_id) @staticmethod def delete_member_bindings( @@ -1592,14 +1805,7 @@ class RBACService: policy_id: str, payload: DeleteMemberBindings, ) -> None: - _inner_call( - "DELETE", - f"{_INNER_PREFIX}/datasets/access-policy/member-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id, "policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) + _DATASET_ACCESS.delete_member_bindings(tenant_id, account_id, dataset_id, policy_id, payload) @staticmethod def replace_bindings( @@ -1609,15 +1815,117 @@ class RBACService: policy_id: str, payload: ReplaceBindings, ) -> AccessMatrixItem: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/datasets/access-policy/bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"dataset_id": dataset_id, "policy_id": policy_id}, - json=payload.model_dump(mode="json"), + return _DATASET_ACCESS.replace_bindings(tenant_id, account_id, dataset_id, policy_id, payload) + + class AgentAccess: + @staticmethod + def whitelist_resources(tenant_id: str, account_id: str | None) -> ResourceWhitelistResources: + return _AGENT_ACCESS.whitelist_resources(tenant_id, account_id) + + @staticmethod + def user_access_policies( + tenant_id: str, + account_id: str | None, + agent_id: str, + *, + options: ListOption | None = None, + ) -> ResourceUserAccessPoliciesResponse: + return _AGENT_ACCESS.user_access_policies(tenant_id, account_id, agent_id, options=options) + + @staticmethod + def replace_user_access_policies( + tenant_id: str, + account_id: str | None, + agent_id: str, + target_account_id: str | None, + payload: ReplaceUserAccessPolicies, + ) -> ReplaceUserAccessPoliciesResponse: + return _AGENT_ACCESS.replace_user_access_policies( + tenant_id, account_id, agent_id, target_account_id, payload ) - return AccessMatrixItem.model_validate(data or {}) + + @staticmethod + def whitelist(tenant_id: str, account_id: str | None, agent_id: str) -> ResourceWhitelist: + return _AGENT_ACCESS.whitelist(tenant_id, account_id, agent_id) + + @staticmethod + def whitelist_config(tenant_id: str, account_id: str | None, agent_id: str) -> ResourceWhitelistConfig: + return _AGENT_ACCESS.whitelist_config(tenant_id, account_id, agent_id) + + @staticmethod + def legacy_whitelist_config( + tenant_id: str, account_id: str | None, agent_id: str + ) -> _LegacyResourceWhitelistConfig: + return _AGENT_ACCESS.legacy_whitelist_config(tenant_id, account_id, agent_id) + + @staticmethod + def replace_whitelist( + tenant_id: str, + account_id: str | None, + agent_id: str, + payload: ReplaceMemberBindings, + ) -> ResourceWhitelist: + return _AGENT_ACCESS.replace_whitelist(tenant_id, account_id, agent_id, payload) + + @staticmethod + def append_whitelist_members_batch( + tenant_id: str, + account_id: str | None, + data: Sequence[AppendAgentWhitelistMembersBatchItem], + ) -> None: + _AGENT_ACCESS.append_whitelist_members_batch(tenant_id, account_id, data) + + @staticmethod + def matrix(tenant_id: str, account_id: str | None, agent_id: str) -> AgentAccessMatrix: + return _AGENT_ACCESS.matrix(tenant_id, account_id, agent_id) + + @staticmethod + def list_role_bindings( + tenant_id: str, + account_id: str | None, + agent_id: str, + policy_id: str, + ) -> RoleBindingsResponse: + return _AGENT_ACCESS.list_role_bindings(tenant_id, account_id, agent_id, policy_id) + + @staticmethod + def replace_role_bindings( + tenant_id: str, + account_id: str | None, + agent_id: str, + policy_id: str, + payload: ReplaceRoleBindings, + ) -> RoleBindingsResponse: + return _AGENT_ACCESS.replace_role_bindings(tenant_id, account_id, agent_id, policy_id, payload) + + @staticmethod + def list_member_bindings( + tenant_id: str, + account_id: str | None, + agent_id: str, + policy_id: str, + ) -> MemberBindingsResponse: + return _AGENT_ACCESS.list_member_bindings(tenant_id, account_id, agent_id, policy_id) + + @staticmethod + def delete_member_bindings( + tenant_id: str, + account_id: str | None, + agent_id: str, + policy_id: str, + payload: DeleteMemberBindings, + ) -> None: + _AGENT_ACCESS.delete_member_bindings(tenant_id, account_id, agent_id, policy_id, payload) + + @staticmethod + def replace_bindings( + tenant_id: str, + account_id: str | None, + agent_id: str, + policy_id: str, + payload: ReplaceBindings, + ) -> AccessMatrixItem: + return _AGENT_ACCESS.replace_bindings(tenant_id, account_id, agent_id, policy_id, payload) # ------------------------------------------------------------------ # Workspace-level access (screenshot 2: Settings > Access Rules). @@ -1630,14 +1938,7 @@ class RBACService: *, options: ListOption | None = None, ) -> WorkspaceAccessMatrix: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/workspace/apps/access-policy", - tenant_id=tenant_id, - account_id=account_id, - params=(options or ListOption()).to_params() or None, - ) - return WorkspaceAccessMatrix.model_validate(data or {}) + return _WORKSPACE_APP_ACCESS.matrix(tenant_id, account_id, options=options) @staticmethod def dataset_matrix( @@ -1646,14 +1947,16 @@ class RBACService: *, options: ListOption | None = None, ) -> WorkspaceAccessMatrix: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/workspace/datasets/access-policy", - tenant_id=tenant_id, - account_id=account_id, - params=(options or ListOption()).to_params() or None, - ) - return WorkspaceAccessMatrix.model_validate(data or {}) + return _WORKSPACE_DATASET_ACCESS.matrix(tenant_id, account_id, options=options) + + @staticmethod + def agent_matrix( + tenant_id: str, + account_id: str | None = None, + *, + options: ListOption | None = None, + ) -> WorkspaceAccessMatrix: + return _WORKSPACE_AGENT_ACCESS.matrix(tenant_id, account_id, options=options) @staticmethod def list_app_role_bindings( @@ -1661,14 +1964,7 @@ class RBACService: account_id: str | None, policy_id: str, ) -> RoleBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/workspace/apps/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - ) - return RoleBindingsResponse.model_validate(data or {}) + return _WORKSPACE_APP_ACCESS.list_role_bindings(tenant_id, account_id, policy_id) @staticmethod def replace_app_role_bindings( @@ -1677,15 +1973,7 @@ class RBACService: policy_id: str, payload: ReplaceRoleBindings, ) -> RoleBindingsResponse: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/workspace/apps/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) - return RoleBindingsResponse.model_validate(data or {}) + return _WORKSPACE_APP_ACCESS.replace_role_bindings(tenant_id, account_id, policy_id, payload) @staticmethod def list_app_member_bindings( @@ -1693,14 +1981,7 @@ class RBACService: account_id: str | None, policy_id: str, ) -> MemberBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/workspace/apps/access-policy/member-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - ) - return MemberBindingsResponse.model_validate(data or {}) + return _WORKSPACE_APP_ACCESS.list_member_bindings(tenant_id, account_id, policy_id) @staticmethod def replace_app_bindings( @@ -1709,15 +1990,7 @@ class RBACService: policy_id: str, payload: ReplaceBindings, ) -> AccessMatrixItem: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/workspace/apps/access-policy/bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) - return AccessMatrixItem.model_validate(data or {}) + return _WORKSPACE_APP_ACCESS.replace_bindings(tenant_id, account_id, policy_id, payload) @staticmethod def list_dataset_role_bindings( @@ -1725,14 +1998,7 @@ class RBACService: account_id: str | None, policy_id: str, ) -> RoleBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/workspace/datasets/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - ) - return RoleBindingsResponse.model_validate(data or {}) + return _WORKSPACE_DATASET_ACCESS.list_role_bindings(tenant_id, account_id, policy_id) @staticmethod def replace_dataset_role_bindings( @@ -1741,15 +2007,7 @@ class RBACService: policy_id: str, payload: ReplaceRoleBindings, ) -> RoleBindingsResponse: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/workspace/datasets/access-policy/role-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) - return RoleBindingsResponse.model_validate(data or {}) + return _WORKSPACE_DATASET_ACCESS.replace_role_bindings(tenant_id, account_id, policy_id, payload) @staticmethod def list_dataset_member_bindings( @@ -1757,14 +2015,7 @@ class RBACService: account_id: str | None, policy_id: str, ) -> MemberBindingsResponse: - data = _inner_call( - "GET", - f"{_INNER_PREFIX}/workspace/datasets/access-policy/member-bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - ) - return MemberBindingsResponse.model_validate(data or {}) + return _WORKSPACE_DATASET_ACCESS.list_member_bindings(tenant_id, account_id, policy_id) @staticmethod def replace_dataset_bindings( @@ -1773,15 +2024,41 @@ class RBACService: policy_id: str, payload: ReplaceBindings, ) -> AccessMatrixItem: - data = _inner_call( - "PUT", - f"{_INNER_PREFIX}/workspace/datasets/access-policy/bindings", - tenant_id=tenant_id, - account_id=account_id, - params={"policy_id": policy_id}, - json=payload.model_dump(mode="json"), - ) - return AccessMatrixItem.model_validate(data or {}) + return _WORKSPACE_DATASET_ACCESS.replace_bindings(tenant_id, account_id, policy_id, payload) + + @staticmethod + def list_agent_role_bindings( + tenant_id: str, + account_id: str | None, + policy_id: str, + ) -> RoleBindingsResponse: + return _WORKSPACE_AGENT_ACCESS.list_role_bindings(tenant_id, account_id, policy_id) + + @staticmethod + def replace_agent_role_bindings( + tenant_id: str, + account_id: str | None, + policy_id: str, + payload: ReplaceRoleBindings, + ) -> RoleBindingsResponse: + return _WORKSPACE_AGENT_ACCESS.replace_role_bindings(tenant_id, account_id, policy_id, payload) + + @staticmethod + def list_agent_member_bindings( + tenant_id: str, + account_id: str | None, + policy_id: str, + ) -> MemberBindingsResponse: + return _WORKSPACE_AGENT_ACCESS.list_member_bindings(tenant_id, account_id, policy_id) + + @staticmethod + def replace_agent_bindings( + tenant_id: str, + account_id: str | None, + policy_id: str, + payload: ReplaceBindings, + ) -> AccessMatrixItem: + return _WORKSPACE_AGENT_ACCESS.replace_bindings(tenant_id, account_id, policy_id, payload) class MemberRoles: @staticmethod @@ -1888,6 +2165,27 @@ class RBACService: ) return data + class Migrations: + @staticmethod + def migrate_agent_manage_roles(tenant_id: str, *, apply: bool) -> LegacyAgentMigrationReport: + data = _inner_call( + "POST", + f"{_INNER_PREFIX}/migrations/agent-manage-roles", + tenant_id=tenant_id, + json={"apply": apply}, + ) + return LegacyAgentMigrationReport.model_validate(data or {}) + + @staticmethod + def list_configured_agent_ids(tenant_id: str, agent_ids: list[str]) -> list[str]: + data = _inner_call( + "POST", + f"{_INNER_PREFIX}/migrations/agent-access-state", + tenant_id=tenant_id, + json={"agent_ids": agent_ids}, + ) + return ConfiguredAgentIDs.model_validate(data or {}).configured_agent_ids + class CheckAccess: """Call the ``/inner/api/rbac/check-access`` endpoint.""" @@ -1979,6 +2277,7 @@ class RBACService: *, app_id: str | None = None, dataset_id: str | None = None, + agent_id: str | None = None, session: Session, ) -> MyPermissionsResponse: if not dify_config.RBAC_ENABLED: @@ -1994,6 +2293,7 @@ class RBACService: for k, v in { "app_id": app_id, "dataset_id": dataset_id, + "agent_id": agent_id, }.items() if v is not None } diff --git a/api/services/entities/dsl_entities.py b/api/services/entities/dsl_entities.py index 2bff3fcac24..67bada2207e 100644 --- a/api/services/entities/dsl_entities.py +++ b/api/services/entities/dsl_entities.py @@ -1,7 +1,7 @@ from enum import StrEnum from typing import Any -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field from core.plugin.entities.plugin import PluginDependency @@ -19,15 +19,13 @@ class ImportStatus(StrEnum): class PendingImportOwner(BaseModel): - tenant_id: str | None = None - account_id: str | None = None + model_config = ConfigDict(hide_input_in_errors=True) + + tenant_id: str + account_id: str def is_accessible_by(self, *, tenant_id: str | None, account_id: str) -> bool: - if tenant_id is None: - return False - owner = (self.tenant_id, self.account_id) - # Ownerless payloads come from older pods and expire after 10 minutes; #40106 removes this bridge. - return owner in ((None, None), (tenant_id, account_id)) + return tenant_id is not None and (self.tenant_id, self.account_id) == (tenant_id, account_id) class DslImportWarning(BaseModel): diff --git a/api/services/entities/feature_entities.py b/api/services/entities/feature_entities.py index 2992ca5f918..5f03507305a 100644 --- a/api/services/entities/feature_entities.py +++ b/api/services/entities/feature_entities.py @@ -17,13 +17,6 @@ class SubscriptionModel(FeatureResponseModel): class BillingModel(FeatureResponseModel): - # Deprecated compatibility field. Deployment edition is the only source of truth for product edition. - # TODO: Remove after clients migrate to `SystemFeatureModel.deployment_edition`. - enabled: bool = Field( - default=False, - deprecated=True, - description="Deprecated. Use system features deployment_edition to determine the product edition.", - ) subscription: SubscriptionModel = SubscriptionModel() @@ -73,8 +66,10 @@ class LicenseLimitationModel(FeatureResponseModel): class Quota(FeatureResponseModel): usage: int = 0 - limit: int = 0 - reset_date: int = -1 + limit: int = Field(default=0, description="Quota limit; -1 means unlimited and 0 means no quota") + reset_date: int = Field( + default=-1, description="Next quota reset as a Unix timestamp in seconds; -1 means no reset" + ) class LicenseStatus(StrEnum): @@ -149,22 +144,23 @@ class PluginInstallationPermissionModel(FeatureResponseModel): class FeatureModel(FeatureResponseModel): + """Effective feature availability and limits for the current workspace.""" + billing: BillingModel = BillingModel() education: EducationModel = EducationModel() enable_skill: bool = True members: LimitationModel = LimitationModel(size=0, limit=1) apps: LimitationModel = LimitationModel(size=0, limit=10) - vector_space: LimitationModel | None = LimitationModel(size=0, limit=5) - knowledge_rate_limit: int = 10 + # Indexing tasks still consume this internally; Console queries vector usage separately. + vector_space: LimitationModel | None = Field(default=LimitationModel(size=0, limit=5), exclude=True) annotation_quota_limit: LimitationModel = LimitationModel(size=0, limit=10) documents_upload_quota: LimitationModel = LimitationModel(size=0, limit=50) - docs_processing: str = "standard" can_replace_logo: bool = False model_load_balancing_enabled: bool = False - dataset_operator_enabled: bool = False webapp_copyright_enabled: bool = False dify_builder_enabled: bool = False - skill_learning_policy: str = "ask" + # Dify Builder execution consumes this internally; it is not part of the Console response contract. + skill_learning_policy: str = Field(default="ask", exclude=True) workspace_members: LicenseLimitationModel = LicenseLimitationModel(enabled=False, size=0, limit=0) is_allow_transfer_workspace: bool = True trigger_event: Quota = Quota(usage=0, limit=3000, reset_date=0) @@ -172,7 +168,8 @@ class FeatureModel(FeatureResponseModel): # Controls whether email delivery is allowed for HumanInput nodes. human_input_email_delivery_enabled: bool = False knowledge_pipeline: KnowledgePipeline = KnowledgePipeline() - next_credit_reset_date: int = 0 + # Workspace and model-provider credit responses own the public reset-date contract. + next_credit_reset_date: int = Field(default=0, exclude=True) class KnowledgeRateLimitModel(FeatureResponseModel): diff --git a/api/services/feature_service.py b/api/services/feature_service.py index 00e3cc969ac..35e3010cbab 100644 --- a/api/services/feature_service.py +++ b/api/services/feature_service.py @@ -12,8 +12,6 @@ class FeatureService: return CloudPlan.SANDBOX billing_info = BillingService.get_info(tenant_id, exclude_vector_space=True) - if not billing_info["enabled"]: - return CloudPlan.SANDBOX return CloudPlan(billing_info["subscription"]["plan"]) @classmethod @@ -86,7 +84,7 @@ class FeatureService: return True if not tenant_id: return False - return features.billing.enabled and features.billing.subscription.plan.is_paid + return features.billing.subscription.plan.is_paid @classmethod def _fulfill_trial_models_from_env(cls, quota_types: tuple[str, ...] | None = None) -> list[str]: @@ -114,7 +112,6 @@ class FeatureService: def _fulfill_params_from_env(cls, features: feature_entities.FeatureModel): features.can_replace_logo = dify_config.CAN_REPLACE_LOGO features.model_load_balancing_enabled = dify_config.MODEL_LB_ENABLED - features.dataset_operator_enabled = dify_config.DATASET_OPERATOR_ENABLED features.education.enabled = dify_config.EDUCATION_ENABLED features.enable_skill = dify_config.ENABLE_SKILL features.dify_builder_enabled = dify_config.DIFY_BUILDER_ENABLED @@ -142,7 +139,6 @@ class FeatureService: features_usage_info = BillingService.get_quota_info(tenant_id) - features.billing.enabled = billing_info["enabled"] features.billing.subscription.plan = CloudPlan(billing_info["subscription"]["plan"]) features.billing.subscription.interval = billing_info["subscription"]["interval"] features.education.activated = billing_info["subscription"].get("education", False) @@ -182,22 +178,12 @@ class FeatureService: features.annotation_quota_limit.size = billing_info["annotation_quota_limit"]["size"] features.annotation_quota_limit.limit = billing_info["annotation_quota_limit"]["limit"] - if "docs_processing" in billing_info: - features.docs_processing = billing_info["docs_processing"] - if "can_replace_logo" in billing_info: features.can_replace_logo = billing_info["can_replace_logo"] if "model_load_balancing_enabled" in billing_info: features.model_load_balancing_enabled = billing_info["model_load_balancing_enabled"] - if "knowledge_rate_limit" in billing_info: - # NOTE (hj24): - # 1. knowledge_rate_limit size is nullable, currently it's defined but never used, only limit is used. - # 2. So be careful if later we decide to use [size], we cannot assume it is always present. - features.knowledge_rate_limit = billing_info["knowledge_rate_limit"]["limit"] - # NOTE END - if "knowledge_pipeline_publish_enabled" in billing_info: features.knowledge_pipeline.publish_enabled = billing_info["knowledge_pipeline_publish_enabled"] diff --git a/api/services/file_service.py b/api/services/file_service.py index 9c387720002..9fe68ab75b3 100644 --- a/api/services/file_service.py +++ b/api/services/file_service.py @@ -252,58 +252,6 @@ class FileService: text = ExtractProcessor.load_from_upload_file(upload_file, return_text=True) return text[0:PREVIEW_WORDS_LIMIT] if text else "" - def get_image_preview(self, file_id: str, timestamp: str, nonce: str, sign: str): - result = file_helpers.verify_image_signature( - upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign - ) - if not result: - raise NotFound("File not found or signature is invalid") - with self._session_maker(expire_on_commit=False) as session: - upload_file = session.scalar(select(UploadFile).where(UploadFile.id == file_id).limit(1)) - - if not upload_file: - raise NotFound("File not found or signature is invalid") - - # extract text from file - extension = upload_file.extension - if extension.lower() not in IMAGE_EXTENSIONS: - raise UnsupportedFileTypeError() - - generator = storage.load(upload_file.key, stream=True) - - return generator, upload_file.mime_type - - def get_file_generator_by_file_id(self, file_id: str, timestamp: str, nonce: str, sign: str): - result = file_helpers.verify_file_signature(upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign) - if not result: - raise NotFound("File not found or signature is invalid") - - with self._session_maker(expire_on_commit=False) as session: - upload_file = session.scalar(select(UploadFile).where(UploadFile.id == file_id).limit(1)) - - if not upload_file: - raise NotFound("File not found or signature is invalid") - - generator = storage.load(upload_file.key, stream=True) - - return generator, upload_file - - def get_public_image_preview(self, file_id: str): - with self._session_maker(expire_on_commit=False) as session: - upload_file = session.scalar(select(UploadFile).where(UploadFile.id == file_id).limit(1)) - - if not upload_file: - raise NotFound("File not found or signature is invalid") - - # extract text from file - extension = upload_file.extension - if extension.lower() not in IMAGE_EXTENSIONS: - raise UnsupportedFileTypeError() - - generator = storage.load(upload_file.key) - - return generator, upload_file.mime_type - def get_file_content(self, file_id: str) -> str: with self._session_maker(expire_on_commit=False) as session: upload_file: UploadFile | None = session.scalar(select(UploadFile).where(UploadFile.id == file_id).limit(1)) diff --git a/api/services/human_input_file_upload_service.py b/api/services/human_input_file_upload_service.py index 00b4230870c..538b5f128a6 100644 --- a/api/services/human_input_file_upload_service.py +++ b/api/services/human_input_file_upload_service.py @@ -3,24 +3,18 @@ from __future__ import annotations import secrets from dataclasses import dataclass from datetime import datetime, timedelta - -from sqlalchemy import Engine, select -from sqlalchemy.orm import Session, selectinload, sessionmaker +from typing import Protocol from configs import dify_config from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus from libs.datetime_utils import ensure_naive_utc, naive_utc_now -from models.account import Account, Tenant +from models.account import Account from models.enums import CreatorUserRole -from models.human_input import ( - HumanInputForm, - HumanInputFormRecipient, - HumanInputFormUploadFile, - HumanInputFormUploadToken, -) -from models.model import App, EndUser +from models.model import EndUser, UploadFile from repositories.api_workflow_run_repository import APIWorkflowRunRepository +from services.file_service import FileService from services.human_input_service import FormExpiredError, FormNotFoundError, FormSubmittedError +from services.remote_file_service import RemoteFileService, RemoteFileUploadResult HITL_UPLOAD_TOKEN_PREFIX = "hitl_upload_" _TOKEN_RANDOM_BYTES = 32 @@ -33,6 +27,26 @@ class HumanInputUploadToken: expires_at: datetime +@dataclass(frozen=True) +class HumanInputUploadFormRecord: + form_id: str + recipient_id: str + tenant_id: str + app_id: str + workflow_run_id: str | None + form_kind: HumanInputFormKind + status: HumanInputFormStatus + submitted_at: datetime | None + expiration_time: datetime + created_at: datetime + + +@dataclass(frozen=True) +class HumanInputUploadGrantRecord: + upload_token_id: str + form: HumanInputUploadFormRecord + + @dataclass(frozen=True) class HumanInputUploadContext: tenant_id: str @@ -47,6 +61,35 @@ class InvalidUploadTokenError(Exception): pass +class HumanInputFileUploadRepository(Protocol): + def get_form_by_recipient_token(self, form_token: str) -> HumanInputUploadFormRecord | None: ... + + def create_upload_token(self, *, form: HumanInputUploadFormRecord, upload_token: str) -> None: ... + + def get_upload_grant(self, upload_token: str) -> HumanInputUploadGrantRecord | None: ... + + def get_upload_owner( + self, + *, + owner_id: str, + owner_role: CreatorUserRole, + tenant_id: str, + app_id: str, + ) -> Account | EndUser | None: ... + + def get_delivery_test_upload_owner(self, *, tenant_id: str, app_id: str) -> Account | None: ... + + def add_file( + self, + *, + tenant_id: str, + app_id: str, + form_id: str, + upload_token_id: str, + file_id: str, + ) -> None: ... + + class HumanInputFileUploadService: """Coordinates HITL upload tokens, workflow-run owners, and form-file links. @@ -56,92 +99,96 @@ class HumanInputFileUploadService: uploads are scoped to the app creator account inside the form tenant. """ - _session_maker: sessionmaker[Session] + _uploads: HumanInputFileUploadRepository _workflow_run_repository: APIWorkflowRunRepository + _files: FileService + _remote_files: RemoteFileService def __init__( self, - session_factory: sessionmaker[Session] | Engine, + *, + uploads: HumanInputFileUploadRepository, workflow_run_repository: APIWorkflowRunRepository, + files: FileService, + remote_files: RemoteFileService, ) -> None: - if isinstance(session_factory, Engine): - session_factory = sessionmaker(bind=session_factory) - self._session_maker = session_factory + self._uploads = uploads self._workflow_run_repository = workflow_run_repository + self._files = files + self._remote_files = remote_files def issue_upload_token(self, form_token: str) -> HumanInputUploadToken: """Create an upload token for an active human input recipient token.""" - with self._session_maker() as session, session.begin(): - recipient_model = session.scalar( - select(HumanInputFormRecipient) - .options(selectinload(HumanInputFormRecipient.form)) - .where(HumanInputFormRecipient.access_token == form_token) - .limit(1) - ) - if recipient_model is None or recipient_model.form is None: - raise FormNotFoundError() + form = self._uploads.get_form_by_recipient_token(form_token) + if form is None: + raise FormNotFoundError() - form = recipient_model.form - self._ensure_form_model_active(form) - upload_token = self._generate_unique_upload_token() - token_model = HumanInputFormUploadToken( - tenant_id=form.tenant_id, - app_id=form.app_id, - form_id=form.id, - recipient_id=recipient_model.id, - token=upload_token, - ) - session.add(token_model) - # Snapshot the expiry before commit so callers do not depend on the - # session factory's expire_on_commit policy. - token = HumanInputUploadToken(upload_token=upload_token, expires_at=form.expiration_time) - - return token + self._ensure_form_active(form) + upload_token = self._generate_unique_upload_token() + self._uploads.create_upload_token(form=form, upload_token=upload_token) + return HumanInputUploadToken(upload_token=upload_token, expires_at=form.expiration_time) def validate_upload_token(self, upload_token: str) -> HumanInputUploadContext: """Resolve an upload token and ensure the bound form is still active.""" - query = ( - select(HumanInputFormUploadToken) - .options(selectinload(HumanInputFormUploadToken.form)) - .where(HumanInputFormUploadToken.token == upload_token) - .limit(1) + grant = self._uploads.get_upload_grant(upload_token) + if grant is None: + raise InvalidUploadTokenError() + + form = grant.form + self._ensure_form_active(form) + owner = self._resolve_upload_owner(form=form) + return HumanInputUploadContext( + tenant_id=form.tenant_id, + app_id=form.app_id, + form_id=form.form_id, + recipient_id=form.recipient_id, + upload_token_id=grant.upload_token_id, + owner=owner, ) - with self._session_maker(expire_on_commit=False) as session: - token_model = session.scalars(query).first() - if token_model is None: - raise InvalidUploadTokenError() - - form_model = token_model.form - if form_model is None: - raise InvalidUploadTokenError() - self._ensure_form_model_active(form_model) - - owner = self._resolve_upload_owner(session=session, form_model=form_model) - - return HumanInputUploadContext( - tenant_id=token_model.tenant_id, - app_id=token_model.app_id, - form_id=token_model.form_id, - recipient_id=token_model.recipient_id, - upload_token_id=token_model.id, - owner=owner, - ) def record_upload_file(self, *, context: HumanInputUploadContext, file_id: str) -> None: """Record that a file was uploaded through a specific form upload token.""" - with self._session_maker() as session, session.begin(): - session.add( - HumanInputFormUploadFile( - tenant_id=context.tenant_id, - app_id=context.app_id, - form_id=context.form_id, - upload_file_id=file_id, - upload_token_id=context.upload_token_id, - ) - ) + self._uploads.add_file( + tenant_id=context.tenant_id, + app_id=context.app_id, + form_id=context.form_id, + upload_token_id=context.upload_token_id, + file_id=file_id, + ) + + def upload_local_file( + self, + *, + context: HumanInputUploadContext, + filename: str, + content: bytes, + mimetype: str, + ) -> UploadFile: + upload_file = self._files.upload_file( + filename=filename, + content=content, + mimetype=mimetype, + user=context.owner, + source=None, + ) + self.record_upload_file(context=context, file_id=upload_file.id) + return upload_file + + def upload_remote_file( + self, + *, + context: HumanInputUploadContext, + url: str, + ) -> RemoteFileUploadResult: + upload_file = self._remote_files.upload_from_url( + url=url, + user=context.owner, + ) + self.record_upload_file(context=context, file_id=upload_file.id) + return upload_file def _generate_unique_upload_token(self) -> str: return f"{HITL_UPLOAD_TOKEN_PREFIX}{secrets.token_urlsafe(_TOKEN_RANDOM_BYTES)}" @@ -149,96 +196,54 @@ class HumanInputFileUploadService: def _resolve_upload_owner( self, *, - session: Session, - form_model: HumanInputForm, + form: HumanInputUploadFormRecord, ) -> Account | EndUser: - if form_model.workflow_run_id is None: - if form_model.form_kind == HumanInputFormKind.DELIVERY_TEST: - return self._resolve_delivery_test_upload_owner(session=session, form_model=form_model) + if form.workflow_run_id is None: + if form.form_kind == HumanInputFormKind.DELIVERY_TEST: + owner = self._uploads.get_delivery_test_upload_owner( + tenant_id=form.tenant_id, + app_id=form.app_id, + ) + if owner is not None: + return owner raise InvalidUploadTokenError() workflow_run = self._workflow_run_repository.get_workflow_run_by_id( - tenant_id=form_model.tenant_id, - app_id=form_model.app_id, - run_id=form_model.workflow_run_id, + tenant_id=form.tenant_id, + app_id=form.app_id, + run_id=form.workflow_run_id, ) if workflow_run is None: raise InvalidUploadTokenError() - if workflow_run.created_by_role == CreatorUserRole.END_USER: - end_user = session.scalar( - select(EndUser) - .where( - EndUser.id == workflow_run.created_by, - EndUser.tenant_id == workflow_run.tenant_id, - EndUser.app_id == workflow_run.app_id, - ) - .limit(1) - ) - if end_user is None: - raise InvalidUploadTokenError() - return end_user - - if workflow_run.created_by_role != CreatorUserRole.ACCOUNT: + owner_role = workflow_run.created_by_role + if owner_role not in {CreatorUserRole.ACCOUNT, CreatorUserRole.END_USER}: raise InvalidUploadTokenError() - account = session.scalar(select(Account).where(Account.id == workflow_run.created_by).limit(1)) - if account is None: - raise InvalidUploadTokenError() - - tenant = session.scalar(select(Tenant).where(Tenant.id == workflow_run.tenant_id).limit(1)) - if tenant is None: - raise InvalidUploadTokenError() - - # HITL upload runs outside the normal account auth flow, so hydrate the - # account tenant context explicitly before delegating to FileService. - account.set_current_tenant_with_session(tenant, session=session) - return account - - def _resolve_delivery_test_upload_owner( - self, - *, - session: Session, - form_model: HumanInputForm, - ) -> Account: - app = session.scalar( - select(App) - .where( - App.id == form_model.app_id, - App.tenant_id == form_model.tenant_id, - ) - .limit(1) + owner = self._uploads.get_upload_owner( + owner_id=workflow_run.created_by, + owner_role=owner_role, + tenant_id=workflow_run.tenant_id, + app_id=workflow_run.app_id, ) - if app is None or app.created_by is None: + if owner is None: raise InvalidUploadTokenError() - - account = session.scalar(select(Account).where(Account.id == app.created_by).limit(1)) - if account is None: - raise InvalidUploadTokenError() - - tenant = session.scalar(select(Tenant).where(Tenant.id == form_model.tenant_id).limit(1)) - if tenant is None: - raise InvalidUploadTokenError() - - account.set_current_tenant_with_session(tenant, session=session) - if account.current_tenant_id != form_model.tenant_id: - raise InvalidUploadTokenError() - return account + return owner @staticmethod - def _ensure_form_model_active(form: HumanInputForm) -> None: + def _ensure_form_active(form: HumanInputUploadFormRecord) -> None: if form.submitted_at is not None or form.status == HumanInputFormStatus.SUBMITTED: - raise FormSubmittedError(form.id) + raise FormSubmittedError(form.form_id) if form.status in {HumanInputFormStatus.TIMEOUT, HumanInputFormStatus.EXPIRED}: - raise FormExpiredError(form.id) + raise FormExpiredError(form.form_id) now = naive_utc_now() if ensure_naive_utc(form.expiration_time) <= now: - raise FormExpiredError(form.id) + raise FormExpiredError(form.form_id) global_timeout_seconds = dify_config.HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS if global_timeout_seconds <= 0 or form.workflow_run_id is None: return global_deadline = ensure_naive_utc(form.created_at) + timedelta(seconds=global_timeout_seconds) if global_deadline <= now: - raise FormExpiredError(form.id) + raise FormExpiredError(form.form_id) diff --git a/api/services/message_file_preview_service.py b/api/services/message_file_preview_service.py new file mode 100644 index 00000000000..ebebc0f312d --- /dev/null +++ b/api/services/message_file_preview_service.py @@ -0,0 +1,73 @@ +"""Application service for previewing files attached to app messages.""" + +from collections.abc import Iterator +from typing import NamedTuple, Protocol + + +class MessageFilePreviewNotFoundError(Exception): + """Raised when a requested file is not attached to a message.""" + + +class MessageFilePreviewAccessDeniedError(Exception): + """Raised when a requested file is outside the authenticated app scope.""" + + +class MessageFilePreviewRecord(NamedTuple): + key: str + name: str + size: int + extension: str + mime_type: str | None + + +class MessageFilePreviewQuery(Protocol): + def get_for_app( + self, + *, + file_id: str, + app_id: str, + tenant_id: str, + ) -> MessageFilePreviewRecord: + """Return preview metadata after enforcing the file ownership chain. + + The upload must be referenced by a MessageFile, its Message must belong + to app_id, and the UploadFile must exist under tenant_id. + """ + ... + + +class FileStreamStorage(Protocol): + def load_stream(self, filename: str) -> Iterator[bytes]: ... + + +class MessageFilePreview(NamedTuple): + content: Iterator[bytes] + file: MessageFilePreviewRecord + + +class MessageFilePreviewService: + def __init__( + self, + *, + files: MessageFilePreviewQuery, + storage: FileStreamStorage, + ) -> None: + self._files = files + self._storage = storage + + def get_preview( + self, + *, + file_id: str, + app_id: str, + tenant_id: str, + ) -> MessageFilePreview: + file = self._files.get_for_app( + file_id=file_id, + app_id=app_id, + tenant_id=tenant_id, + ) + return MessageFilePreview( + content=self._storage.load_stream(file.key), + file=file, + ) diff --git a/api/services/plugin_file_upload_gateway.py b/api/services/plugin_file_upload_gateway.py new file mode 100644 index 00000000000..4cfa13747aa --- /dev/null +++ b/api/services/plugin_file_upload_gateway.py @@ -0,0 +1,54 @@ +"""ToolFile adapter for signed plugin uploads.""" + +from typing import override + +from core.tools.signature import sign_tool_file +from core.tools.tool_file_manager import ToolFileManager, resolve_extension +from core.workflow.file_reference import build_file_reference +from services.plugin_file_upload_service import PluginFileUploadFiles, PluginFileUploadResult + + +class ToolFilePluginUploadGateway(PluginFileUploadFiles): + def __init__(self, *, tool_files: ToolFileManager) -> None: + self._tool_files = tool_files + + @override + def store( + self, + *, + user_id: str, + tenant_id: str, + conversation_id: str | None, + content: bytes, + mimetype: str, + filename: str, + ) -> PluginFileUploadResult: + tool_file = self._tool_files.create_file_by_raw( + user_id=user_id, + tenant_id=tenant_id, + conversation_id=conversation_id, + file_binary=content, + mimetype=mimetype, + filename=filename, + ) + extension = resolve_extension(filename=tool_file.name, mimetype=tool_file.mimetype) + + return PluginFileUploadResult( + id=tool_file.id, + reference=build_file_reference(record_id=tool_file.id), + name=tool_file.name, + size=tool_file.size, + extension=extension, + mime_type=mimetype, + preview_url=sign_tool_file( + tool_file_id=tool_file.id, + extension=extension, + for_external=True, + ), + source_url=tool_file.original_url, + original_url=tool_file.original_url, + user_id=tool_file.user_id, + tenant_id=tool_file.tenant_id, + conversation_id=tool_file.conversation_id, + file_key=tool_file.file_key, + ) diff --git a/api/services/plugin_file_upload_service.py b/api/services/plugin_file_upload_service.py new file mode 100644 index 00000000000..67470f737e4 --- /dev/null +++ b/api/services/plugin_file_upload_service.py @@ -0,0 +1,116 @@ +"""Application service for signed plugin file uploads.""" + +from dataclasses import dataclass +from typing import IO, Literal, Protocol + +from core.tools.signature import verify_plugin_file_signature +from services.errors.file import FileTooLargeError + +PluginUploadUserFrom = Literal["account", "end-user"] | None + + +class PluginFileUploadAccessDeniedError(PermissionError): + pass + + +@dataclass(frozen=True, slots=True) +class PluginFileUploadResult: + id: str + reference: str + name: str + size: int + extension: str + mime_type: str + preview_url: str + source_url: str | None + original_url: str | None + user_id: str + tenant_id: str + conversation_id: str | None + file_key: str + + +class PluginFileUploadOwnerQuery(Protocol): + def owner_exists( + self, + *, + tenant_id: str, + user_id: str, + user_from: PluginUploadUserFrom, + ) -> bool: ... + + +class PluginFileUploadFiles(Protocol): + def store( + self, + *, + user_id: str, + tenant_id: str, + conversation_id: str | None, + content: bytes, + mimetype: str, + filename: str, + ) -> PluginFileUploadResult: ... + + +class PluginFileUploadService: + def __init__( + self, + *, + owners: PluginFileUploadOwnerQuery, + files: PluginFileUploadFiles, + ) -> None: + self._owners = owners + self._files = files + + def upload( + self, + *, + stream: IO[bytes], + filename: str, + mimetype: str, + tenant_id: str, + user_id: str, + user_from: PluginUploadUserFrom, + conversation_id: str | None, + timestamp: str, + nonce: str, + sign: str, + max_size: int | None, + ) -> PluginFileUploadResult: + if not verify_plugin_file_signature( + filename=filename, + mimetype=mimetype, + tenant_id=tenant_id, + user_id=user_id, + user_from=user_from, + conversation_id=conversation_id, + timestamp=timestamp, + nonce=nonce, + sign=sign, + max_size=max_size, + ): + raise PluginFileUploadAccessDeniedError + + if not self._owners.owner_exists( + tenant_id=tenant_id, + user_id=user_id, + user_from=user_from, + ): + raise PluginFileUploadAccessDeniedError + + if max_size is None: + content = stream.read() + else: + content = stream.read(max_size + 1) + if len(content) > max_size: + raise FileTooLargeError("File size exceeds the signed upload limit.") + + return self._files.store( + user_id=user_id, + tenant_id=tenant_id, + conversation_id=conversation_id, + content=content, + mimetype=mimetype, + filename=filename, + ) diff --git a/api/services/rag_pipeline/rag_pipeline_dsl_service.py b/api/services/rag_pipeline/rag_pipeline_dsl_service.py index 6977c28b7a6..6ee64efc9d5 100644 --- a/api/services/rag_pipeline/rag_pipeline_dsl_service.py +++ b/api/services/rag_pipeline/rag_pipeline_dsl_service.py @@ -221,8 +221,11 @@ class RagPipelineDslService: # If major version mismatch, store import info in Redis if status == ImportStatus.PENDING: + tenant_id = account.current_tenant_id + if tenant_id is None: + raise ValueError("Current tenant is not set") pending_data = RagPipelinePendingData( - tenant_id=account.current_tenant_id, + tenant_id=tenant_id, account_id=account.id, import_mode=import_mode, yaml_content=content, diff --git a/api/services/rag_pipeline/rag_pipeline_task_proxy.py b/api/services/rag_pipeline/rag_pipeline_task_proxy.py index 4c466e37d0b..ab3b7338c08 100644 --- a/api/services/rag_pipeline/rag_pipeline_task_proxy.py +++ b/api/services/rag_pipeline/rag_pipeline_task_proxy.py @@ -3,9 +3,10 @@ import logging from collections.abc import Callable, Sequence from functools import cached_property +from configs import dify_config from core.app.entities.rag_pipeline_invoke_entities import RagPipelineInvokeEntity from core.rag.pipeline.queue import TenantIsolatedTaskQueue -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from extensions.ext_database import db from services.feature_service import FeatureService from services.file_service import FileService @@ -79,15 +80,10 @@ class RagPipelineTaskProxy: if not upload_file_id: raise ValueError("upload_file_id is empty") - logger.info( - "dispatch args: %s - %s - %s", - self._dataset_tenant_id, - self.features.billing.enabled, - self.features.billing.subscription.plan, - ) + logger.info("Dispatching tenant %s in %s", self._dataset_tenant_id, dify_config.DEPLOYMENT_EDITION) - # dispatch to different pipeline queue with tenant isolation when billing enabled - if self.features.billing.enabled: + # Cloud queues isolate tenants and prioritize paid plans. + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: if self.features.billing.subscription.plan == CloudPlan.SANDBOX: # dispatch to normal pipeline queue with tenant isolation for sandbox plan self._send_to_default_tenant_queue(upload_file_id) diff --git a/api/services/rbac_agent_access_service.py b/api/services/rbac_agent_access_service.py new file mode 100644 index 00000000000..4540c587c53 --- /dev/null +++ b/api/services/rbac_agent_access_service.py @@ -0,0 +1,35 @@ +import logging + +from configs import dify_config +from services.enterprise import rbac_service as enterprise_rbac_service +from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task + +logger = logging.getLogger(__name__) + + +def initialize_agent_rbac_access(*, tenant_id: str, agent_id: str, creator_account_id: str) -> None: + if not dify_config.RBAC_ENABLED: + return + + try: + initialize_created_app_rbac_access_task.delay(tenant_id, creator_account_id, agent_id=agent_id) + enterprise_rbac_service.RBACService.AccessPolicies.sync_creator_access_policy_member_bindings( + tenant_id, + creator_account_id, + resource_type=enterprise_rbac_service.RBACResourceType.AGENT, + resource_id=agent_id, + ) + enterprise_rbac_service.RBACService.AgentAccess.replace_whitelist( + tenant_id, + creator_account_id, + agent_id, + enterprise_rbac_service.ReplaceMemberBindings(automatic_include_workspace_members=True), + ) + except Exception: + logger.warning( + "Failed to initialize RBAC access for agent: tenant_id=%s agent_id=%s account_id=%s", + tenant_id, + agent_id, + creator_account_id, + exc_info=True, + ) diff --git a/api/services/rbac_resource_service.py b/api/services/rbac_resource_service.py new file mode 100644 index 00000000000..7acc54abedb --- /dev/null +++ b/api/services/rbac_resource_service.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import select + +from extensions.ext_database import db +from models.dataset import Dataset +from models.model import App + +if TYPE_CHECKING: + from models.agent import Agent + + +class RBACResourceService: + @staticmethod + def get_app_agent_binding(tenant_id: str, app_id: str) -> Agent | None: + app_model = db.session.scalar(select(App).where(App.id == app_id, App.tenant_id == tenant_id)) + if app_model is None: + return None + return app_model.agent_app_binding_with_session(session=db.session, include_archived=True) + + @staticmethod + def get_app_maintainer(tenant_id: str, app_id: str) -> str | None: + return db.session.scalar( + select(App.maintainer).where(App.id == app_id, App.tenant_id == tenant_id, App.status == "normal") + ) + + @staticmethod + def get_dataset_maintainer(tenant_id: str, dataset_id: str) -> str | None: + return db.session.scalar( + select(Dataset.maintainer).where(Dataset.id == dataset_id, Dataset.tenant_id == tenant_id) + ) + + @staticmethod + def get_dataset_id_by_pipeline(tenant_id: str, pipeline_id: str) -> str | None: + dataset_id = db.session.scalar( + select(Dataset.id).where(Dataset.pipeline_id == pipeline_id, Dataset.tenant_id == tenant_id) + ) + return None if dataset_id is None else str(dataset_id) diff --git a/api/services/skill_management_service.py b/api/services/skill_management_service.py index 4d4c4299b79..8616b388e9c 100644 --- a/api/services/skill_management_service.py +++ b/api/services/skill_management_service.py @@ -3623,7 +3623,7 @@ class SkillManagementService: except yaml.YAMLError as exc: line = None if isinstance(exc, MarkedYAMLError) and exc.problem_mark is not None: - line = int(exc.problem_mark.line) + 2 + line = exc.problem_mark.line + 2 raise SkillManagementServiceError( "invalid_skill_md", f"SKILL.md frontmatter YAML is invalid: {exc}", diff --git a/api/services/snippet_dsl_service.py b/api/services/snippet_dsl_service.py index 78361700ad4..a6e03021d55 100644 --- a/api/services/snippet_dsl_service.py +++ b/api/services/snippet_dsl_service.py @@ -235,8 +235,11 @@ class SnippetDslService: # If major version mismatch, store import info in Redis if status == ImportStatus.PENDING: + tenant_id = account.current_tenant_id + if tenant_id is None: + raise ValueError("Current tenant is not set") pending_data = SnippetPendingData( - tenant_id=account.current_tenant_id, + tenant_id=tenant_id, account_id=account.id, import_mode=import_mode, yaml_content=content, diff --git a/api/services/summary_index_service.py b/api/services/summary_index_service.py index 9d820d14659..2f5d832c0e1 100644 --- a/api/services/summary_index_service.py +++ b/api/services/summary_index_service.py @@ -517,8 +517,16 @@ class SummaryIndexService: summary_record_id, original_session is not None, ) - # Always create a new session for error handling to avoid issues with closed sessions - # Even if original_session was provided, we create a new one for safety + if original_session is not None: + # Keep the error update in the caller-owned transaction. Opening another + # session here can deadlock when the caller has already flushed this row. + summary_record.status = SummaryStatus.ERROR + summary_record.error = f"Vectorization failed: {str(e)}" + summary_record.updated_at = datetime.now(UTC).replace(tzinfo=None) + original_session.add(summary_record) + raise + + # Standalone callers still need this method to persist the error itself. with session_factory.create_session() as error_session: # Try to find the record by id first # Note: Using assignment only (no type annotation) to avoid redeclaration error diff --git a/api/services/tool_file_download_service.py b/api/services/tool_file_download_service.py new file mode 100644 index 00000000000..bfee566abde --- /dev/null +++ b/api/services/tool_file_download_service.py @@ -0,0 +1,61 @@ +"""Application service for signed ToolFile downloads.""" + +from collections.abc import Iterator +from typing import NamedTuple, Protocol + +from core.tools.signature import verify_tool_file_signature +from graphon.file import File + + +class ToolFileDownloadAccessDeniedError(PermissionError): + pass + + +class ToolFileDownloadNotFoundError(LookupError): + pass + + +class ToolFileDownloadSource(Protocol): + def get_file_generator_by_tool_file_id( + self, + tool_file_id: str, + ) -> tuple[Iterator[bytes] | None, File | None]: ... + + +class ToolFileDownload(NamedTuple): + content: Iterator[bytes] + mime_type: str | None + filename: str | None + size: int + + +class ToolFileDownloadService: + def __init__(self, *, tool_files: ToolFileDownloadSource) -> None: + self._tool_files = tool_files + + def get_signed_file( + self, + *, + file_id: str, + timestamp: str, + nonce: str, + sign: str, + ) -> ToolFileDownload: + if not verify_tool_file_signature( + file_id=file_id, + timestamp=timestamp, + nonce=nonce, + sign=sign, + ): + raise ToolFileDownloadAccessDeniedError + + content, file = self._tool_files.get_file_generator_by_tool_file_id(tool_file_id=file_id) + if content is None or file is None: + raise ToolFileDownloadNotFoundError + + return ToolFileDownload( + content=content, + mime_type=file.mime_type, + filename=file.filename, + size=file.size, + ) diff --git a/api/services/tools/api_tools_manage_service.py b/api/services/tools/api_tools_manage_service.py index c7a35884fa3..5e2baf09ab1 100644 --- a/api/services/tools/api_tools_manage_service.py +++ b/api/services/tools/api_tools_manage_service.py @@ -201,7 +201,7 @@ class ApiToolManageService: auth_type = ApiProviderAuthType.value_of(credentials["auth_type"]) # create provider entity - provider_controller = ApiToolProviderController.from_db(api_tool_provider, auth_type) + provider_controller = ApiToolProviderController.from_db(api_tool_provider, auth_type, session=db.session()) # load tools into provider entity provider_controller.load_bundled_tools(tool_bundles) @@ -352,7 +352,7 @@ class ApiToolManageService: auth_type = ApiProviderAuthType.value_of(credentials["auth_type"]) # create provider entity - provider_controller = ApiToolProviderController.from_db(provider, auth_type) + provider_controller = ApiToolProviderController.from_db(provider, auth_type, session=db.session()) # load tools into provider entity provider_controller.load_bundled_tools(tool_bundles) @@ -494,7 +494,7 @@ class ApiToolManageService: auth_type = ApiProviderAuthType.value_of(credentials["auth_type"]) # create provider entity - provider_controller = ApiToolProviderController.from_db(provider, auth_type) + provider_controller = ApiToolProviderController.from_db(provider, auth_type, session=db.session()) # load tools into provider entity provider_controller.load_bundled_tools(tool_bundles) @@ -549,7 +549,7 @@ class ApiToolManageService: provider_controller = ToolTransformService.api_provider_to_controller(db_provider=provider) labels = ToolLabelManager.get_tool_labels(provider_controller) user_provider = ToolTransformService.api_provider_to_user_provider( - provider_controller, db_provider=provider, decrypt_credentials=True + provider_controller, db_provider=provider, decrypt_credentials=True, session=db.session() ) user_provider.labels = labels diff --git a/api/services/tools/tools_transform_service.py b/api/services/tools/tools_transform_service.py index b62a31f8fc2..29be9eb9563 100644 --- a/api/services/tools/tools_transform_service.py +++ b/api/services/tools/tools_transform_service.py @@ -3,6 +3,7 @@ from collections.abc import Mapping from typing import Any from pydantic import TypeAdapter, ValidationError +from sqlalchemy.orm import Session from yarl import URL from configs import dify_config @@ -27,6 +28,7 @@ from core.tools.plugin_tool.provider import PluginToolProviderController from core.tools.utils.encryption import create_provider_encrypter, create_tool_provider_encrypter from core.tools.workflow_as_tool.provider import WorkflowToolProviderController from core.tools.workflow_as_tool.tool import WorkflowTool +from extensions.ext_database import db from models.tools import ApiToolProvider, BuiltinToolProvider, MCPToolProvider, WorkflowToolProvider logger = logging.getLogger(__name__) @@ -202,6 +204,7 @@ class ToolTransformService: controller = ApiToolProviderController.from_db( db_provider=db_provider, auth_type=auth_type, + session=db.session(), ) return controller @@ -305,15 +308,17 @@ class ToolTransformService: db_provider: ApiToolProvider, decrypt_credentials: bool = True, labels: list[str] | None = None, + *, + session: Session, ) -> ToolProviderApiEntity: """ convert provider controller to user provider """ username = "Anonymous" - if db_provider.user is None: + user = db_provider.user(session=session) + if user is None: raise ValueError(f"user is None for api provider {db_provider.id}") try: - user = db_provider.user if not user: raise ValueError("user not found") diff --git a/api/services/upload_file_delivery_service.py b/api/services/upload_file_delivery_service.py new file mode 100644 index 00000000000..3ae6742c2fe --- /dev/null +++ b/api/services/upload_file_delivery_service.py @@ -0,0 +1,115 @@ +"""Application service for delivering uploaded files through public file endpoints.""" + +from collections.abc import Iterator +from typing import NamedTuple, Protocol + +from constants import IMAGE_EXTENSIONS +from graphon.file import helpers as file_helpers +from services.errors.file import UnsupportedFileTypeError + + +class UploadFileDeliveryNotFoundError(LookupError): + pass + + +class UploadFileDeliveryRecord(NamedTuple): + key: str + name: str + size: int + extension: str + mime_type: str | None + + +class UploadFileDeliveryQuery(Protocol): + def get_by_id(self, *, file_id: str) -> UploadFileDeliveryRecord | None: ... + + def get_workspace_logo(self, *, workspace_id: str) -> UploadFileDeliveryRecord | None: ... + + +class UploadFileStorage(Protocol): + def load_stream(self, filename: str) -> Iterator[bytes]: ... + + def load_once(self, filename: str) -> bytes: ... + + +class UploadFileDelivery(NamedTuple): + content: bytes | Iterator[bytes] + file: UploadFileDeliveryRecord + + +class UploadFileDeliveryService: + def __init__( + self, + *, + files: UploadFileDeliveryQuery, + storage: UploadFileStorage, + ) -> None: + self._files = files + self._storage = storage + + def get_signed_image_preview( + self, + *, + file_id: str, + timestamp: str, + nonce: str, + sign: str, + ) -> UploadFileDelivery: + if not file_helpers.verify_image_signature( + upload_file_id=file_id, + timestamp=timestamp, + nonce=nonce, + sign=sign, + ): + raise UploadFileDeliveryNotFoundError("File not found or signature is invalid") + + file = self._get_file(file_id=file_id) + self._ensure_image(file=file) + return UploadFileDelivery( + content=self._storage.load_stream(file.key), + file=file, + ) + + def get_signed_file_preview( + self, + *, + file_id: str, + timestamp: str, + nonce: str, + sign: str, + ) -> UploadFileDelivery: + if not file_helpers.verify_file_signature( + upload_file_id=file_id, + timestamp=timestamp, + nonce=nonce, + sign=sign, + ): + raise UploadFileDeliveryNotFoundError("File not found or signature is invalid") + + file = self._get_file(file_id=file_id) + return UploadFileDelivery( + content=self._storage.load_stream(file.key), + file=file, + ) + + def get_workspace_webapp_logo(self, *, workspace_id: str) -> UploadFileDelivery: + file = self._files.get_workspace_logo(workspace_id=workspace_id) + if file is None: + raise UploadFileDeliveryNotFoundError("File not found or signature is invalid") + + self._ensure_image(file=file) + return UploadFileDelivery( + content=self._storage.load_once(file.key), + file=file, + ) + + def _get_file(self, *, file_id: str) -> UploadFileDeliveryRecord: + file = self._files.get_by_id(file_id=file_id) + if file is None: + raise UploadFileDeliveryNotFoundError("File not found or signature is invalid") + return file + + @staticmethod + def _ensure_image(*, file: UploadFileDeliveryRecord) -> None: + if file.extension.lower() not in IMAGE_EXTENSIONS: + raise UnsupportedFileTypeError() diff --git a/api/services/vector_space_admission_service.py b/api/services/vector_space_admission_service.py index 8d3da92bb1c..98d3a8aef5f 100644 --- a/api/services/vector_space_admission_service.py +++ b/api/services/vector_space_admission_service.py @@ -395,15 +395,13 @@ class VectorSpaceAdmissionService: ) from error plan = None - if billing_info["enabled"]: - try: - plan = CloudPlan(billing_info["subscription"]["plan"]) - except ValueError: - logger.warning( - "Skipping TiDB vector-space admission for unknown plan tenant_id=%s plan=%s", - tenant_id, - billing_info["subscription"]["plan"], - ) + try: + plan = CloudPlan(billing_info["subscription"]["plan"]) + except ValueError: + logger.warning( + "Skipping TiDB vector-space admission for unknown plan tenant_id=%s", + tenant_id, + ) self._plan_by_tenant[tenant_id] = plan return plan diff --git a/api/services/web_app_runtime_query_service.py b/api/services/web_app_runtime_query_service.py index 559b0685d85..5b64c946be5 100644 --- a/api/services/web_app_runtime_query_service.py +++ b/api/services/web_app_runtime_query_service.py @@ -4,6 +4,7 @@ import json from collections.abc import Callable, Mapping from typing import NamedTuple, Protocol, cast +from enums import DeploymentEdition from services.app_definition_query_service import AppSiteConfiguration from services.entities.feature_entities import FeatureModel from services.file_service import FileService @@ -50,11 +51,13 @@ class WebAppRuntimeQueryService: file_service: FileService, workspace_features: Callable[[str], FeatureModel], files_url: str, + deployment_edition: DeploymentEdition, ) -> None: self._runtime = runtime self._file_service = file_service self._workspace_features = workspace_features self._files_url = files_url + self._deployment_edition = deployment_edition def get_bootstrap(self, app_id: str) -> WebAppBootstrap: record = self._runtime.get_runtime_record(app_id) @@ -70,7 +73,7 @@ class WebAppRuntimeQueryService: site = cast(dict[str, str | bool | None], record.site._asdict()) site["icon_url"] = site_icon_url - if features.billing.enabled and not features.webapp_copyright_enabled: + if self._deployment_edition == DeploymentEdition.CLOUD and not features.webapp_copyright_enabled: site["copyright"] = None site["input_placeholder"] = None diff --git a/api/services/workspace_service.py b/api/services/workspace_service.py index 855dcdd1131..9cfd620867a 100644 --- a/api/services/workspace_service.py +++ b/api/services/workspace_service.py @@ -73,7 +73,7 @@ class WorkspaceService: if effective_pool is None: return EffectiveCreditPool( - plan=subscription_plan if billing_info["enabled"] else None, + plan=subscription_plan, next_credit_reset_date=billing_info.get("next_credit_reset_date"), ) @@ -87,7 +87,7 @@ class WorkspaceService: exhausted_at = None return EffectiveCreditPool( - plan=subscription_plan if billing_info["enabled"] else None, + plan=subscription_plan, pool_type=effective_pool_type, quota_limit=effective_pool.quota_limit, quota_used=effective_pool.quota_used, @@ -137,7 +137,9 @@ class WorkspaceService: tenant_info["role"] = tenant_account_join.role feature = FeatureService.get_features(tenant.id, exclude_vector_space=True) - tenant_info["plan"] = feature.billing.subscription.plan if feature.billing.enabled else None + tenant_info["plan"] = ( + feature.billing.subscription.plan if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD else None + ) can_replace_logo = feature.can_replace_logo if can_replace_logo and TenantService.has_roles( diff --git a/api/tasks/annotation/batch_import_annotations_task.py b/api/tasks/annotation/batch_import_annotations_task.py index 68f086df8a2..12af1a13df8 100644 --- a/api/tasks/annotation/batch_import_annotations_task.py +++ b/api/tasks/annotation/batch_import_annotations_task.py @@ -31,7 +31,7 @@ def batch_import_annotations_task(job_id: str, content_list: list[dict], app_id: """ logger.info(click.style(f"Start batch import annotation: {job_id}", fg="green")) start_at = time.perf_counter() - indexing_cache_key = f"app_annotation_batch_import_{str(job_id)}" + indexing_cache_key = f"app_annotation_batch_import_{job_id}" active_jobs_key = f"annotation_import_active:{tenant_id}" with session_factory.create_session() as session: @@ -94,7 +94,7 @@ def batch_import_annotations_task(job_id: str, content_list: list[dict], app_id: except Exception as e: session.rollback() redis_client.setex(indexing_cache_key, 600, "error") - indexing_error_msg_key = f"app_annotation_batch_import_error_msg_{str(job_id)}" + indexing_error_msg_key = f"app_annotation_batch_import_error_msg_{job_id}" redis_client.setex(indexing_error_msg_key, 600, str(e)) logger.exception("Build index for batch import annotations failed") finally: diff --git a/api/tasks/annotation/disable_annotation_reply_task.py b/api/tasks/annotation/disable_annotation_reply_task.py index 31ffd72a575..50199c50a18 100644 --- a/api/tasks/annotation/disable_annotation_reply_task.py +++ b/api/tasks/annotation/disable_annotation_reply_task.py @@ -40,8 +40,8 @@ def disable_annotation_reply_task(job_id: str, app_id: str, tenant_id: str): logger.info(click.style(f"App annotation setting not found: {app_id}", fg="red")) return - disable_app_annotation_key = f"disable_app_annotation_{str(app_id)}" - disable_app_annotation_job_key = f"disable_app_annotation_job_{str(job_id)}" + disable_app_annotation_key = f"disable_app_annotation_{app_id}" + disable_app_annotation_job_key = f"disable_app_annotation_job_{job_id}" try: dataset = Dataset( @@ -73,7 +73,7 @@ def disable_annotation_reply_task(job_id: str, app_id: str, tenant_id: str): except Exception as e: logger.exception("Annotation batch deleted index failed") redis_client.setex(disable_app_annotation_job_key, 600, "error") - disable_app_annotation_error_key = f"disable_app_annotation_error_{str(job_id)}" + disable_app_annotation_error_key = f"disable_app_annotation_error_{job_id}" redis_client.setex(disable_app_annotation_error_key, 600, str(e)) finally: redis_client.delete(disable_app_annotation_key) diff --git a/api/tasks/annotation/enable_annotation_reply_task.py b/api/tasks/annotation/enable_annotation_reply_task.py index 69aff9bbd11..1247cdf32b7 100644 --- a/api/tasks/annotation/enable_annotation_reply_task.py +++ b/api/tasks/annotation/enable_annotation_reply_task.py @@ -45,8 +45,8 @@ def enable_annotation_reply_task( return annotations = session.scalars(select(MessageAnnotation).where(MessageAnnotation.app_id == app_id)).all() - enable_app_annotation_key = f"enable_app_annotation_{str(app_id)}" - enable_app_annotation_job_key = f"enable_app_annotation_job_{str(job_id)}" + enable_app_annotation_key = f"enable_app_annotation_{app_id}" + enable_app_annotation_job_key = f"enable_app_annotation_job_{job_id}" try: documents = [] @@ -131,7 +131,7 @@ def enable_annotation_reply_task( except Exception as e: logger.exception("Annotation batch created index failed") redis_client.setex(enable_app_annotation_job_key, 600, "error") - enable_app_annotation_error_key = f"enable_app_annotation_error_{str(job_id)}" + enable_app_annotation_error_key = f"enable_app_annotation_error_{job_id}" redis_client.setex(enable_app_annotation_error_key, 600, str(e)) session.rollback() finally: diff --git a/api/tasks/document_indexing_task.py b/api/tasks/document_indexing_task.py index 2ad17d31577..7d41c542bba 100644 --- a/api/tasks/document_indexing_task.py +++ b/api/tasks/document_indexing_task.py @@ -13,7 +13,7 @@ from core.entities.document_task import DocumentTask from core.indexing_runner import DocumentIsPausedError, IndexingRunner from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType from core.rag.pipeline.queue import TenantIsolatedTaskQueue -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from libs.datetime_utils import naive_utc_now from models.dataset import Dataset, Document from models.enums import IndexingStatus @@ -62,9 +62,9 @@ def _document_indexing(dataset_id: str, document_ids: Sequence[str]): logger.info(click.style(f"Dataset is not found: {dataset_id}", fg="yellow")) return # check document limit - features = FeatureService.get_features(dataset.tenant_id) - try: - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: + features = FeatureService.get_features(dataset.tenant_id) + try: vector_space = features.vector_space assert vector_space is not None count = len(document_ids) @@ -78,18 +78,18 @@ def _document_indexing(dataset_id: str, document_ids: Sequence[str]): "Your total number of documents plus the number of uploads have over the limit of " "your subscription." ) - except Exception as e: - for document_id in document_ids: - document = session.scalar( - select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1) - ) - if document: - document.indexing_status = IndexingStatus.ERROR - document.error = str(e) - document.stopped_at = naive_utc_now() - session.add(document) - session.commit() - return + except Exception as e: + for document_id in document_ids: + document = session.scalar( + select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1) + ) + if document: + document.indexing_status = IndexingStatus.ERROR + document.error = str(e) + document.stopped_at = naive_utc_now() + session.add(document) + session.commit() + return # Phase 1: Persist parsing status before slow extraction and vector operations. with session_factory.create_session() as session, session.begin(): diff --git a/api/tasks/duplicate_document_indexing_task.py b/api/tasks/duplicate_document_indexing_task.py index d062794df33..c083dbdbbad 100644 --- a/api/tasks/duplicate_document_indexing_task.py +++ b/api/tasks/duplicate_document_indexing_task.py @@ -12,7 +12,7 @@ from core.entities.document_task import DocumentTask from core.indexing_runner import DocumentIsPausedError, IndexingRunner from core.rag.index_processor.index_processor_factory import IndexProcessorFactory from core.rag.pipeline.queue import TenantIsolatedTaskQueue -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from libs.datetime_utils import naive_utc_now from models.dataset import Dataset, Document, DocumentSegment from models.enums import IndexingStatus @@ -88,9 +88,9 @@ def _duplicate_document_indexing_task(dataset_id: str, document_ids: Sequence[st return # check document limit - features = FeatureService.get_features(dataset.tenant_id) - try: - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: + features = FeatureService.get_features(dataset.tenant_id) + try: vector_space = features.vector_space assert vector_space is not None count = len(document_ids) @@ -106,20 +106,20 @@ def _duplicate_document_indexing_task(dataset_id: str, document_ids: Sequence[st "Your total number of documents plus the number of uploads have exceeded the limit of " "your subscription." ) - except Exception as e: - documents = list( - session.scalars( - select(Document).where(Document.id.in_(document_ids), Document.dataset_id == dataset_id) - ).all() - ) - for document in documents: - if document is not None: - document.indexing_status = IndexingStatus.ERROR - document.error = str(e) - document.stopped_at = naive_utc_now() - session.add(document) - session.commit() - return + except Exception as e: + documents = list( + session.scalars( + select(Document).where(Document.id.in_(document_ids), Document.dataset_id == dataset_id) + ).all() + ) + for document in documents: + if document is not None: + document.indexing_status = IndexingStatus.ERROR + document.error = str(e) + document.stopped_at = naive_utc_now() + session.add(document) + session.commit() + return documents = list( session.scalars( diff --git a/api/tasks/initialize_created_app_rbac_access_task.py b/api/tasks/initialize_created_app_rbac_access_task.py index ad69f2374ac..1c3c87a483b 100644 --- a/api/tasks/initialize_created_app_rbac_access_task.py +++ b/api/tasks/initialize_created_app_rbac_access_task.py @@ -1,14 +1,15 @@ """Initialize default RBAC access for existing workspace members after app creation.""" import logging -from collections.abc import Iterator +from collections.abc import Callable, Iterator, Sequence +from dataclasses import dataclass from celery import shared_task from sqlalchemy import select from configs import dify_config from extensions.ext_database import db -from models import App, Dataset, TenantAccountJoin, TenantAccountRole +from models import Agent, App, Dataset, TenantAccountJoin, TenantAccountRole from services.account_service import TenantService from services.enterprise import rbac_service as enterprise_rbac_service @@ -30,43 +31,122 @@ def _owner_account_id(tenant_id: str) -> str | None: ) +@dataclass(frozen=True) +class _WhitelistResourceKind[ItemT]: + resource_type: enterprise_rbac_service.RBACResourceType + model: type[App] | type[Dataset] | type[Agent] + build_item: Callable[[str, str], ItemT] + append_members: Callable[[str, str | None, Sequence[ItemT]], None] + replace_user_access_policies: Callable[ + [str, str, str, enterprise_rbac_service.ReplaceUserAccessPolicies], + enterprise_rbac_service.ReplaceUserAccessPoliciesResponse, + ] + + def iter_id_batches(self, tenant_id: str, batch_size: int) -> Iterator[list[str]]: + last_id: str | None = None + while True: + stmt = ( + select(self.model.id) + .where(self.model.tenant_id == tenant_id) + .order_by(self.model.id.asc()) + .limit(batch_size) + ) + if last_id: + stmt = stmt.where(self.model.id > last_id) + ids = [str(resource_id) for resource_id in db.session().scalars(stmt).all()] + if not ids: + return + yield ids + last_id = ids[-1] + + def append_member(self, tenant_id: str, actor_account_id: str, resource_ids: list[str], member_account_id: str): + self.append_members( + tenant_id, + actor_account_id, + [self.build_item(resource_id, member_account_id) for resource_id in resource_ids], + ) + + +_WHITELIST_RESOURCE_KINDS = ( + _WhitelistResourceKind( + resource_type=enterprise_rbac_service.RBACResourceType.APP, + model=App, + build_item=lambda app_id, member: enterprise_rbac_service.AppendAppWhitelistMembersBatchItem( + app_id=app_id, account_ids=[member], policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID + ), + append_members=lambda tenant_id, account_id, data: ( + enterprise_rbac_service.RBACService.AppAccess.append_whitelist_members_batch( + tenant_id=tenant_id, account_id=account_id, data=data + ) + ), + replace_user_access_policies=lambda tenant_id, account_id, resource_id, payload: ( + enterprise_rbac_service.RBACService.AppAccess.replace_user_access_policies( + tenant_id=tenant_id, + account_id=account_id, + app_id=resource_id, + target_account_id=None, + payload=payload, + ) + ), + ), + _WhitelistResourceKind( + resource_type=enterprise_rbac_service.RBACResourceType.DATASET, + model=Dataset, + build_item=lambda dataset_id, member: enterprise_rbac_service.AppendDatasetWhitelistMembersBatchItem( + dataset_id=dataset_id, account_ids=[member], policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID + ), + append_members=lambda tenant_id, account_id, data: ( + enterprise_rbac_service.RBACService.DatasetAccess.append_whitelist_members_batch( + tenant_id=tenant_id, account_id=account_id, data=data + ) + ), + replace_user_access_policies=lambda tenant_id, account_id, resource_id, payload: ( + enterprise_rbac_service.RBACService.DatasetAccess.replace_user_access_policies( + tenant_id=tenant_id, + account_id=account_id, + dataset_id=resource_id, + target_account_id=None, + payload=payload, + ) + ), + ), + _WhitelistResourceKind( + resource_type=enterprise_rbac_service.RBACResourceType.AGENT, + model=Agent, + build_item=lambda agent_id, member: enterprise_rbac_service.AppendAgentWhitelistMembersBatchItem( + agent_id=agent_id, account_ids=[member], policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID + ), + append_members=lambda tenant_id, account_id, data: ( + enterprise_rbac_service.RBACService.AgentAccess.append_whitelist_members_batch( + tenant_id=tenant_id, account_id=account_id, data=data + ) + ), + replace_user_access_policies=lambda tenant_id, account_id, resource_id, payload: ( + enterprise_rbac_service.RBACService.AgentAccess.replace_user_access_policies( + tenant_id=tenant_id, + account_id=account_id, + agent_id=resource_id, + target_account_id=None, + payload=payload, + ) + ), + ), +) +_WHITELIST_RESOURCE_KIND_BY_TYPE = {kind.resource_type: kind for kind in _WHITELIST_RESOURCE_KINDS} + + def _iter_resource_config_batches( tenant_id: str, batch_size: int, ) -> Iterator[list[enterprise_rbac_service.ResourceWhitelistConfigResource]]: - last_app_id: str | None = None - while True: - stmt = select(App.id).where(App.tenant_id == tenant_id).order_by(App.id.asc()).limit(batch_size) - if last_app_id: - stmt = stmt.where(App.id > last_app_id) - app_ids = [str(app_id) for app_id in db.session().scalars(stmt).all()] - if not app_ids: - break - yield [ - enterprise_rbac_service.ResourceWhitelistConfigResource( - resource_type=enterprise_rbac_service.RBACResourceType.APP, - resource_id=app_id, - ) - for app_id in app_ids - ] - last_app_id = app_ids[-1] - - last_dataset_id: str | None = None - while True: - stmt = select(Dataset.id).where(Dataset.tenant_id == tenant_id).order_by(Dataset.id.asc()).limit(batch_size) - if last_dataset_id: - stmt = stmt.where(Dataset.id > last_dataset_id) - dataset_ids = [str(dataset_id) for dataset_id in db.session().scalars(stmt).all()] - if not dataset_ids: - break - yield [ - enterprise_rbac_service.ResourceWhitelistConfigResource( - resource_type=enterprise_rbac_service.RBACResourceType.DATASET, - resource_id=dataset_id, - ) - for dataset_id in dataset_ids - ] - last_dataset_id = dataset_ids[-1] + for kind in _WHITELIST_RESOURCE_KINDS: + for ids in kind.iter_id_batches(tenant_id, batch_size): + yield [ + enterprise_rbac_service.ResourceWhitelistConfigResource( + resource_type=kind.resource_type, resource_id=resource_id + ) + for resource_id in ids + ] def _chunks[T](items: list[T], chunk_size: int) -> Iterator[list[T]]: @@ -74,52 +154,64 @@ def _chunks[T](items: list[T], chunk_size: int) -> Iterator[list[T]]: yield items[index : index + chunk_size] +def _resolve_target_resource( + resource_ids: dict[enterprise_rbac_service.RBACResourceType, str | None], +) -> tuple[_WhitelistResourceKind, str]: + provided = [(resource_type, rid) for resource_type, rid in resource_ids.items() if rid is not None] + if len(provided) != 1: + given = ", ".join(sorted(resource_type.value for resource_type, _ in provided)) or "none" + raise ValueError(f"exactly one of app_id, dataset_id, agent_id must be given, got: {given}") + resource_type, resource_id = provided[0] + return _WHITELIST_RESOURCE_KIND_BY_TYPE[resource_type], resource_id + + @shared_task(queue=APP_RBAC_QUEUE, bind=True, max_retries=3, default_retry_delay=60) def initialize_created_app_rbac_access_task( - self, tenant_id: str, account_id: str, app_id: str | None = None, dataset_id: str | None = None + self, + tenant_id: str, + account_id: str, + app_id: str | None = None, + dataset_id: str | None = None, + agent_id: str | None = None, ) -> None: - """Grant the default app policy to current workspace members. + """Grant the default policy on one app, dataset or agent to current workspace members. - App scope is persisted synchronously before this task is queued. Replacing + The resource scope is persisted synchronously before this task is queued. Replacing member policies is idempotent, so retrying the whole synchronization is safe when the enterprise RBAC service is temporarily unavailable. """ if not dify_config.RBAC_ENABLED: return + kind, resource_id = _resolve_target_resource( + { + enterprise_rbac_service.RBACResourceType.APP: app_id, + enterprise_rbac_service.RBACResourceType.DATASET: dataset_id, + enterprise_rbac_service.RBACResourceType.AGENT: agent_id, + } + ) + try: for account_ids in TenantService.iter_member_account_id_batches( tenant_id, APP_RBAC_ACCOUNT_POLICY_BATCH_SIZE, session=db.session(), ): - if app_id is not None: - enterprise_rbac_service.RBACService.AppAccess.replace_user_access_policies( - tenant_id=tenant_id, - account_id=account_id, - app_id=app_id, - target_account_id=None, - payload=enterprise_rbac_service.ReplaceUserAccessPolicies( - access_policy_ids=[APP_RBAC_DEFAULT_ACCESS_POLICY_ID], - account_ids=account_ids, - ), - ) - elif dataset_id is not None: - enterprise_rbac_service.RBACService.DatasetAccess.replace_user_access_policies( - tenant_id=tenant_id, - account_id=account_id, - dataset_id=dataset_id, - target_account_id=None, - payload=enterprise_rbac_service.ReplaceUserAccessPolicies( - access_policy_ids=[APP_RBAC_DEFAULT_ACCESS_POLICY_ID], - account_ids=account_ids, - ), - ) + kind.replace_user_access_policies( + tenant_id, + account_id, + resource_id, + enterprise_rbac_service.ReplaceUserAccessPolicies( + access_policy_ids=[APP_RBAC_DEFAULT_ACCESS_POLICY_ID], + account_ids=account_ids, + ), + ) except Exception as exc: logger.exception( - "Failed to initialize app RBAC access; retrying: tenant_id=%s app_id=%s attempt=%s", + "Failed to initialize RBAC access; retrying: tenant_id=%s resource_type=%s resource_id=%s attempt=%s", tenant_id, - app_id, + kind.resource_type.value, + resource_id, self.request.retries + 1, ) raise self.retry(exc=exc) @@ -146,8 +238,9 @@ def sync_joined_workspace_member_rbac_access_task( ) return - app_ids: list[str] = [] - dataset_ids: list[str] = [] + auto_included: dict[enterprise_rbac_service.RBACResourceType, list[str]] = { + kind.resource_type: [] for kind in _WHITELIST_RESOURCE_KINDS + } for resources in _iter_resource_config_batches(tenant_id, APP_RBAC_RESOURCE_CONFIG_BATCH_SIZE): configs = enterprise_rbac_service.RBACService.ResourceWhitelistConfigs.batch_get( tenant_id=tenant_id, @@ -157,38 +250,14 @@ def sync_joined_workspace_member_rbac_access_task( for config in configs.data: if not config.automatic_include_workspace_members: continue - if config.resource_type == enterprise_rbac_service.RBACResourceType.APP: - app_ids.append(config.resource_id) - elif config.resource_type == enterprise_rbac_service.RBACResourceType.DATASET: - dataset_ids.append(config.resource_id) + ids = auto_included.get(config.resource_type) + if ids is not None: + ids.append(config.resource_id) - for app_id_batch in _chunks(app_ids, APP_RBAC_MEMBER_APPEND_BATCH_SIZE): - enterprise_rbac_service.RBACService.AppAccess.append_whitelist_members_batch( - tenant_id=tenant_id, - account_id=actor_account_id, - data=[ - enterprise_rbac_service.AppendAppWhitelistMembersBatchItem( - app_id=app_id, - account_ids=[member_account_id], - policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID, - ) - for app_id in app_id_batch - ], - ) - - for dataset_id_batch in _chunks(dataset_ids, APP_RBAC_MEMBER_APPEND_BATCH_SIZE): - enterprise_rbac_service.RBACService.DatasetAccess.append_whitelist_members_batch( - tenant_id=tenant_id, - account_id=actor_account_id, - data=[ - enterprise_rbac_service.AppendDatasetWhitelistMembersBatchItem( - dataset_id=dataset_id, - account_ids=[member_account_id], - policy_id=APP_RBAC_DEFAULT_ACCESS_POLICY_ID, - ) - for dataset_id in dataset_id_batch - ], - ) + for resource_type, resource_ids in auto_included.items(): + kind = _WHITELIST_RESOURCE_KIND_BY_TYPE[resource_type] + for id_batch in _chunks(resource_ids, APP_RBAC_MEMBER_APPEND_BATCH_SIZE): + kind.append_member(tenant_id, actor_account_id, id_batch, member_account_id) except Exception as exc: logger.exception( "Failed to sync joined member RBAC access; retrying: tenant_id=%s member=%s attempt=%s", diff --git a/api/tasks/retry_document_indexing_task.py b/api/tasks/retry_document_indexing_task.py index dcf74737544..08e0aaea5ab 100644 --- a/api/tasks/retry_document_indexing_task.py +++ b/api/tasks/retry_document_indexing_task.py @@ -5,9 +5,11 @@ import click from celery import shared_task from sqlalchemy import delete, select +from configs import dify_config from core.db.session_factory import session_factory from core.indexing_runner import IndexingRunner from core.rag.index_processor.index_processor_factory import IndexProcessorFactory +from enums import DeploymentEdition from extensions.ext_redis import redis_client from libs.datetime_utils import naive_utc_now from models import Account, Tenant @@ -48,9 +50,9 @@ def retry_document_indexing_task(dataset_id: str, document_ids: list[str], user_ for document_id in document_ids: retry_indexing_cache_key = f"document_{document_id}_is_retried" # check document limit - features = FeatureService.get_features(tenant.id) - try: - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: + features = FeatureService.get_features(tenant.id) + try: vector_space = features.vector_space assert vector_space is not None if 0 < vector_space.limit <= vector_space.size: @@ -58,18 +60,20 @@ def retry_document_indexing_task(dataset_id: str, document_ids: list[str], user_ "Your total number of documents plus the number of uploads have over the limit of " "your subscription." ) - except Exception as e: - document = session.scalar( - select(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).limit(1) - ) - if document: - document.indexing_status = IndexingStatus.ERROR - document.error = str(e) - document.stopped_at = naive_utc_now() - session.add(document) - session.commit() - redis_client.delete(retry_indexing_cache_key) - return + except Exception as e: + document = session.scalar( + select(Document) + .where(Document.id == document_id, Document.dataset_id == dataset_id) + .limit(1) + ) + if document: + document.indexing_status = IndexingStatus.ERROR + document.error = str(e) + document.stopped_at = naive_utc_now() + session.add(document) + session.commit() + redis_client.delete(retry_indexing_cache_key) + return logger.info(click.style(f"Start retry document: {document_id}", fg="green")) document = session.scalar( diff --git a/api/tasks/sync_website_document_indexing_task.py b/api/tasks/sync_website_document_indexing_task.py index 6cd6d40459a..cceafa9623c 100644 --- a/api/tasks/sync_website_document_indexing_task.py +++ b/api/tasks/sync_website_document_indexing_task.py @@ -5,9 +5,11 @@ import click from celery import shared_task from sqlalchemy import delete, select +from configs import dify_config from core.db.session_factory import session_factory from core.indexing_runner import IndexingRunner from core.rag.index_processor.index_processor_factory import IndexProcessorFactory +from enums import DeploymentEdition from extensions.ext_redis import redis_client from libs.datetime_utils import naive_utc_now from models.dataset import Dataset, DocumentSegment @@ -45,9 +47,9 @@ def sync_website_document_indexing_task(dataset_id: str, document_id: str): sync_indexing_cache_key = f"document_{document_id}_is_sync" # check document limit - features = FeatureService.get_features(dataset.tenant_id) - try: - if features.billing.enabled: + if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD: + features = FeatureService.get_features(dataset.tenant_id) + try: vector_space = features.vector_space assert vector_space is not None if 0 < vector_space.limit <= vector_space.size: @@ -55,14 +57,14 @@ def sync_website_document_indexing_task(dataset_id: str, document_id: str): "Your total number of documents plus the number of uploads have over the limit of " "your subscription." ) - except Exception as e: - document.indexing_status = IndexingStatus.ERROR - document.error = str(e) - document.stopped_at = naive_utc_now() - session.add(document) - session.commit() - redis_client.delete(sync_indexing_cache_key) - return + except Exception as e: + document.indexing_status = IndexingStatus.ERROR + document.error = str(e) + document.stopped_at = naive_utc_now() + session.add(document) + session.commit() + redis_client.delete(sync_indexing_cache_key) + return logger.info(click.style(f"Start sync website document: {document_id}", fg="green")) try: diff --git a/api/tests/test_containers_integration_tests/controllers/console/test_apikey.py b/api/tests/test_containers_integration_tests/controllers/console/test_apikey.py index b71d2c647b3..e4d378d5260 100644 --- a/api/tests/test_containers_integration_tests/controllers/console/test_apikey.py +++ b/api/tests/test_containers_integration_tests/controllers/console/test_apikey.py @@ -219,12 +219,11 @@ class TestDatasetApiKeyListResource: """ def _bound_dataset_ids(self, session: Session, api_token_id: str) -> set[str]: - return { - str(dataset_id) - for dataset_id in session.scalars( + return set( + session.scalars( select(DatasetApiTokenBinding.dataset_id).where(DatasetApiTokenBinding.api_token_id == api_token_id) ).all() - } + ) def test_create_unbound_key( self, @@ -402,10 +401,9 @@ class TestDatasetDeleteCascadesToScopedKeys: assert resp.status_code == 204 # The key survives, still scoped to the remaining dataset only. assert db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == api_key_id)) is not None - remaining = { - str(ds_id) - for ds_id in db_session_with_containers.scalars( + remaining = set( + db_session_with_containers.scalars( select(DatasetApiTokenBinding.dataset_id).where(DatasetApiTokenBinding.api_token_id == api_key_id) ).all() - } + ) assert remaining == {other_id} diff --git a/api/tests/test_containers_integration_tests/models/test_conversation_status_count.py b/api/tests/test_containers_integration_tests/models/test_conversation_status_count.py index 9ad43df5402..96d672d5e4e 100644 --- a/api/tests/test_containers_integration_tests/models/test_conversation_status_count.py +++ b/api/tests/test_containers_integration_tests/models/test_conversation_status_count.py @@ -1,5 +1,5 @@ """ -Integration tests for Conversation.status_count and Site.generate_code model properties. +Integration tests for Conversation.status_count_with_session and Site.generate_code. Migrated from unit_tests/models/test_app_models.py TestConversationStatusCount and test_site_generate_code, replacing db.session.scalars mocks with real PostgreSQL queries. @@ -18,7 +18,7 @@ from models.workflow import Workflow, WorkflowRun, WorkflowRunTriggeredFrom, Wor class TestConversationStatusCount: - """Integration tests for Conversation.status_count property.""" + """Integration tests for Conversation.status_count_with_session.""" @pytest.fixture(autouse=True) def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None, None, None]: @@ -130,7 +130,7 @@ class TestConversationStatusCount: app = self._create_app(db_session_with_containers, tenant_id, created_by) conversation = self._create_conversation(db_session_with_containers, app) - result = conversation.status_count + result = conversation.status_count_with_session(session=db_session_with_containers) assert result is None @@ -145,7 +145,7 @@ class TestConversationStatusCount: conversation = self._create_conversation(db_session_with_containers, app) self._create_message(db_session_with_containers, app, conversation, workflow_run_id=None) - result = conversation.status_count + result = conversation.status_count_with_session(session=db_session_with_containers) assert result is None @@ -162,7 +162,7 @@ class TestConversationStatusCount: ) self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id) - result = conversation.status_count + result = conversation.status_count_with_session(session=db_session_with_containers) assert result is not None assert result["success"] == 1 @@ -183,7 +183,7 @@ class TestConversationStatusCount: ) self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id) - result = conversation.status_count + result = conversation.status_count_with_session(session=db_session_with_containers) assert result is not None assert result["success"] == 0 @@ -204,7 +204,7 @@ class TestConversationStatusCount: ) self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id) - result = conversation.status_count + result = conversation.status_count_with_session(session=db_session_with_containers) assert result is not None assert result["success"] == 0 @@ -230,7 +230,7 @@ class TestConversationStatusCount: run = self._create_workflow_run(db_session_with_containers, app, workflow, status, created_by) self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id) - result = conversation.status_count + result = conversation.status_count_with_session(session=db_session_with_containers) assert result is not None assert result["success"] == 1 @@ -255,7 +255,7 @@ class TestConversationStatusCount: # Message references that run but is in a conversation under app self._create_message(db_session_with_containers, app, conversation, workflow_run_id=other_run.id) - result = conversation.status_count + result = conversation.status_count_with_session(session=db_session_with_containers) # The run should be excluded because app_id filter doesn't match assert result is not None diff --git a/api/tests/test_containers_integration_tests/models/test_dataset_models.py b/api/tests/test_containers_integration_tests/models/test_dataset_models.py index d817894b1de..0f25a543c9c 100644 --- a/api/tests/test_containers_integration_tests/models/test_dataset_models.py +++ b/api/tests/test_containers_integration_tests/models/test_dataset_models.py @@ -132,7 +132,7 @@ class TestDatasetDocumentProperties: db_session_with_containers.add(doc) db_session_with_containers.flush() - assert dataset.word_count == 5000 + assert dataset.get_word_count(session=db_session_with_containers) == 5000 def test_dataset_available_segment_count(self, db_session_with_containers: Session) -> None: """Test Dataset.available_segment_count counts completed and enabled segments.""" @@ -322,7 +322,7 @@ class TestDocumentSegmentNavigationProperties: db_session_with_containers.flush() # Act - related_dataset = segment.dataset + related_dataset = segment.get_dataset(session=db_session_with_containers) # Assert assert related_dataset is not None @@ -369,7 +369,7 @@ class TestDocumentSegmentNavigationProperties: db_session_with_containers.flush() # Act - related_document = segment.document + related_document = segment.get_document(session=db_session_with_containers) # Assert assert related_document is not None diff --git a/api/tests/test_containers_integration_tests/services/test_account_service.py b/api/tests/test_containers_integration_tests/services/test_account_service.py index f7953f8dbf9..9bd696f4394 100644 --- a/api/tests/test_containers_integration_tests/services/test_account_service.py +++ b/api/tests/test_containers_integration_tests/services/test_account_service.py @@ -1701,34 +1701,6 @@ class TestTenantService: assert dataset_operators[0].email == operator_email assert dataset_operators[0].role == "dataset_operator" - def test_get_custom_config_success(self, db_session_with_containers: Session, mock_external_service_dependencies): - """ - Test getting custom config successfully. - """ - fake = Faker() - tenant_name = fake.company() - theme = fake.random_element(elements=("dark", "light")) - language = fake.random_element(elements=("zh-CN", "en-US")) - # Setup mocks - mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True - - # Create tenant with custom config - tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers) - - # Set custom config - custom_config = {"theme": theme, "language": language, "feature_flags": {"beta": True}} - tenant.custom_config_dict = custom_config - - db_session_with_containers.commit() - - # Get custom config - retrieved_config = TenantService.get_custom_config(tenant.id) - - assert retrieved_config == custom_config - assert retrieved_config["theme"] == theme - assert retrieved_config["language"] == language - assert retrieved_config["feature_flags"]["beta"] is True - class TestRegisterService: """Integration tests for RegisterService using testcontainers.""" diff --git a/api/tests/test_containers_integration_tests/services/test_annotation_service.py b/api/tests/test_containers_integration_tests/services/test_annotation_service.py index f9e66d91e78..d5ba5b20d68 100644 --- a/api/tests/test_containers_integration_tests/services/test_annotation_service.py +++ b/api/tests/test_containers_integration_tests/services/test_annotation_service.py @@ -5,6 +5,7 @@ from faker import Faker from sqlalchemy.orm import Session from werkzeug.exceptions import NotFound +from enums import DeploymentEdition from models import Account from models.enums import ConversationFromSource, InvokeFrom from models.model import MessageAnnotation @@ -12,6 +13,7 @@ from services.annotation_service import AppAnnotationService from services.app_ref_service import AnnotationRef, AppRef from services.app_service import AppService, CreateAppParams from tests.test_containers_integration_tests.helpers import generate_valid_password +from tests.unit_tests.config_override import config_overrides_context class TestAnnotationService: @@ -32,7 +34,6 @@ class TestAnnotationService: patch("services.annotation_service.current_account_with_tenant") as mock_current_account_with_tenant, ): # Setup default mock returns - mock_account_feature_service.get_features.return_value.billing.enabled = False mock_add_task.delay.return_value = None mock_update_task.delay.return_value = None mock_delete_task.delay.return_value = None @@ -879,6 +880,7 @@ class TestAnnotationService: assert retrieved_annotation.content == annotation_args["answer"] assert retrieved_annotation.account_id == account.id + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_batch_import_app_annotations_success( self, db_session_with_containers: Session, mock_external_service_dependencies ): @@ -900,8 +902,6 @@ class TestAnnotationService: stream=BytesIO(csv_content.encode("utf-8")), filename="annotations.csv", content_type="text/csv" ) - mock_external_service_dependencies["feature_service"].get_features.return_value.billing.enabled = False - # Mock pandas to return expected DataFrame import pandas as pd @@ -958,6 +958,7 @@ class TestAnnotationService: assert "error_msg" in result assert "empty" in result["error_msg"].lower() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_batch_import_app_annotations_quota_exceeded( self, db_session_with_containers: Session, mock_external_service_dependencies ): @@ -989,7 +990,6 @@ class TestAnnotationService: mock_pd.read_csv.return_value = mock_df # Mock FeatureService to return billing enabled with quota exceeded - mock_external_service_dependencies["feature_service"].get_features.return_value.billing.enabled = True mock_external_service_dependencies[ "feature_service" ].get_features.return_value.annotation_quota_limit.limit = 1 diff --git a/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.py b/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.py index ba0a3c2707a..1312911df1a 100644 --- a/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.py +++ b/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.py @@ -20,9 +20,6 @@ class TestAPIBasedExtensionService: patch("services.account_service.SystemFeatureService") as mock_account_feature_service, patch("services.api_based_extension_service.APIBasedExtensionRequestor") as mock_requestor, ): - # Setup default mock returns - mock_account_feature_service.get_features.return_value.billing.enabled = False - # Mock successful ping response mock_requestor_instance = mock_requestor.return_value mock_requestor_instance.request.return_value = {"result": "pong"} diff --git a/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py b/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py index eea8ab9c2a8..05ea4111378 100644 --- a/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py +++ b/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py @@ -600,6 +600,8 @@ class TestAppDslService: redis_key = f"{IMPORT_INFO_REDIS_KEY_PREFIX}{import_id}" pending = PendingData( + tenant_id=_DEFAULT_TENANT_ID, + account_id=_DEFAULT_ACCOUNT_ID, import_mode=ImportMode.YAML_CONTENT, yaml_content=_workflow_yaml(), name="name", @@ -609,11 +611,7 @@ class TestAppDslService: icon_background="#fff", app_id=None, ) - redis_client.setex( - redis_key, - IMPORT_INFO_REDIS_EXPIRY, - pending.model_dump_json(exclude={"tenant_id", "account_id"}), - ) + redis_client.setex(redis_key, IMPORT_INFO_REDIS_EXPIRY, pending.model_dump_json()) created_app = SimpleNamespace( id=str(uuid4()), diff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_delete_dataset.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_delete_dataset.py index 1c5ec6835bd..7881cc00733 100644 --- a/api/tests/test_containers_integration_tests/services/test_dataset_service_delete_dataset.py +++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_delete_dataset.py @@ -83,7 +83,7 @@ class DatasetDeleteIntegrationDataFactory: created_by: str, doc_form: str = IndexStructureType.PARAGRAPH_INDEX, ) -> Document: - """Persist a document so dataset.doc_form resolves through the real document path.""" + """Persist a document so dataset.get_doc_form resolves through the real document path.""" document = Document( tenant_id=tenant_id, dataset_id=dataset_id, @@ -142,7 +142,7 @@ class TestDatasetServiceDeleteDataset: dataset.indexing_technique, dataset.index_struct, dataset.collection_binding_id, - dataset.doc_form, + dataset.get_doc_form(session=db_session_with_containers), dataset.pipeline_id, ) diff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py index f9a176c1f57..bf53483f8b3 100644 --- a/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py +++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py @@ -624,7 +624,12 @@ def test_delete_documents_ignores_empty_input(db_session_with_containers: Sessio dataset_ref = DatasetRefService.create_dataset_ref(dataset) with patch("services.dataset_service.batch_clean_document_task.delay") as delay: - DocumentService.delete_documents(dataset_ref, [], dataset.doc_form, session=db_session_with_containers) + DocumentService.delete_documents( + dataset_ref, + [], + dataset.get_doc_form(session=db_session_with_containers), + session=db_session_with_containers, + ) delay.assert_not_called() @@ -662,7 +667,7 @@ def test_delete_documents_deletes_rows_and_dispatches_cleanup_task(db_session_wi DocumentService.delete_documents( dataset_ref, [document_a.id, document_b.id], - dataset.doc_form, + dataset.get_doc_form(session=db_session_with_containers), session=db_session_with_containers, ) diff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py index 58a129a15e4..e0dd574a175 100644 --- a/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py +++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py @@ -10,6 +10,7 @@ from flask import Flask from sqlalchemy.orm import Session from core.rag.index_processor.constant.index_type import IndexTechniqueType +from enums import DeploymentEdition from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole from models.dataset import ( AppDatasetJoin, @@ -23,6 +24,7 @@ from models.enums import DataSourceType from services.dataset_ref_service import DatasetRef, DatasetRefService from services.dataset_service import DatasetCollectionBindingService, DatasetPermissionService, DatasetService from services.errors.account import NoPermissionError +from tests.unit_tests.config_override import config_overrides_context class DatasetPermissionIntegrationFactory: @@ -406,13 +408,10 @@ class TestDatasetServicePermissionsAndLifecycle: assert dataset.updated_by == owner.id assert dataset.updated_at == now - def test_get_dataset_auto_disable_logs_returns_empty_when_billing_is_disabled( - self, db_session_with_containers: Session - ): + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) + def test_get_dataset_auto_disable_logs_returns_empty_outside_cloud(self, db_session_with_containers: Session): owner, tenant = DatasetPermissionIntegrationFactory.create_account_with_tenant(db_session_with_containers) - features = SimpleNamespace( - billing=SimpleNamespace(enabled=False, subscription=SimpleNamespace(plan="professional")) - ) + features = SimpleNamespace(billing=SimpleNamespace(subscription=SimpleNamespace(plan="professional"))) dataset_ref = DatasetRef(tenant_id=tenant.id, dataset_id=str(uuid4())) with patch("services.dataset_service.FeatureService.get_features", return_value=features): @@ -420,6 +419,7 @@ class TestDatasetServicePermissionsAndLifecycle: assert result == {"document_ids": [], "count": 0} + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_get_dataset_auto_disable_logs_returns_recent_document_ids(self, db_session_with_containers: Session): owner, tenant = DatasetPermissionIntegrationFactory.create_account_with_tenant(db_session_with_containers) dataset = DatasetPermissionIntegrationFactory.create_dataset( @@ -439,9 +439,7 @@ class TestDatasetServicePermissionsAndLifecycle: dataset_id=dataset.id, document_id=str(uuid4()), ) - features = SimpleNamespace( - billing=SimpleNamespace(enabled=True, subscription=SimpleNamespace(plan="professional")) - ) + features = SimpleNamespace(billing=SimpleNamespace(subscription=SimpleNamespace(plan="professional"))) dataset_ref = DatasetRefService.create_dataset_ref(dataset) with patch("services.dataset_service.FeatureService.get_features", return_value=features): diff --git a/api/tests/test_containers_integration_tests/services/test_feature_service.py b/api/tests/test_containers_integration_tests/services/test_feature_service.py index 99c8dd9b322..0ea4ac3a058 100644 --- a/api/tests/test_containers_integration_tests/services/test_feature_service.py +++ b/api/tests/test_containers_integration_tests/services/test_feature_service.py @@ -30,17 +30,14 @@ class TestFeatureService: ): # Setup default mock returns for BillingService mock_billing_service.get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "monthly", "education": True}, "members": {"size": 5, "limit": 10}, "apps": {"size": 3, "limit": 20}, "vector_space": {"size": 2, "limit": 10}, "documents_upload_quota": {"size": 15, "limit": 100}, "annotation_quota_limit": {"size": 8, "limit": 50}, - "docs_processing": "enhanced", "can_replace_logo": True, "model_load_balancing_enabled": True, - "knowledge_rate_limit": {"limit": 100}, } mock_billing_service.get_knowledge_rate_limit.return_value = { @@ -107,7 +104,6 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = True - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = True # Act: Execute the method under test @@ -118,7 +114,6 @@ class TestFeatureService: assert isinstance(result, FeatureModel) # Verify billing features - assert result.billing.enabled is True assert result.billing.subscription.plan == CloudPlan.PROFESSIONAL assert result.billing.subscription.interval == "monthly" assert result.education.activated is True @@ -144,10 +139,8 @@ class TestFeatureService: assert result.annotation_quota_limit.limit == 50 # Verify other features - assert result.docs_processing == "enhanced" assert result.can_replace_logo is True assert result.model_load_balancing_enabled is True - assert result.knowledge_rate_limit == 100 # Enterprise workspace features are not loaded in Cloud. assert result.workspace_members.enabled is False @@ -179,22 +172,18 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = False mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = False mock_config.EDUCATION_ENABLED = False # Set mock return value inside the patch context mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.SANDBOX, "interval": "monthly", "education": False}, "members": {"size": 1, "limit": 3}, "apps": {"size": 1, "limit": 5}, "vector_space": {"size": 1, "limit": 2}, "documents_upload_quota": {"size": 5, "limit": 20}, "annotation_quota_limit": {"size": 2, "limit": 10}, - "docs_processing": "standard", "can_replace_logo": False, "model_load_balancing_enabled": False, - "knowledge_rate_limit": {"limit": 10}, } # Act: Execute the method under test @@ -221,8 +210,6 @@ class TestFeatureService: assert result.is_allow_transfer_workspace is False assert result.can_replace_logo is False assert result.model_load_balancing_enabled is False - assert result.docs_processing == "standard" - assert result.knowledge_rate_limit == 10 # Verify mock interactions mock_external_service_dependencies["billing_service"].get_info.assert_called_once_with(tenant_id) @@ -498,7 +485,6 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = True - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = True tenant_id = self._create_test_tenant_id() @@ -510,13 +496,9 @@ class TestFeatureService: assert result is not None assert isinstance(result, FeatureModel) - # Verify billing is disabled - assert result.billing.enabled is False - # Verify environment-based features assert result.can_replace_logo is True assert result.model_load_balancing_enabled is True - assert result.dataset_operator_enabled is True assert result.education.enabled is True # Verify default limitations @@ -530,8 +512,6 @@ class TestFeatureService: assert result.documents_upload_quota.limit == 50 assert result.annotation_quota_limit.size == 0 assert result.annotation_quota_limit.limit == 10 - assert result.knowledge_rate_limit == 10 - assert result.docs_processing == "standard" # Verify no enterprise features assert result.workspace_members.enabled is False @@ -586,7 +566,6 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISE mock_config.CAN_REPLACE_LOGO = False mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = False mock_config.EDUCATION_ENABLED = False tenant_id = self._create_test_tenant_id() @@ -598,9 +577,6 @@ class TestFeatureService: assert result is not None assert isinstance(result, FeatureModel) - # Cloud billing is not loaded in the Enterprise edition. - assert result.billing.enabled is False - # Verify enterprise features assert result.webapp_copyright_enabled is True @@ -612,7 +588,6 @@ class TestFeatureService: # Verify environment-based features assert result.can_replace_logo is False assert result.model_load_balancing_enabled is False - assert result.dataset_operator_enabled is False assert result.education.enabled is False # Verify default limitations @@ -700,7 +675,6 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False # Act: Execute the method under test @@ -710,13 +684,9 @@ class TestFeatureService: assert result is not None assert isinstance(result, FeatureModel) - # Billing data is not loaded without a tenant ID. - assert result.billing.enabled is False - # Verify environment-based features assert result.can_replace_logo is True assert result.model_load_balancing_enabled is False - assert result.dataset_operator_enabled is True assert result.education.enabled is False # Verify default limitations @@ -749,11 +719,9 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "yearly"}, # Missing members, apps, vector_space, etc. } @@ -766,7 +734,6 @@ class TestFeatureService: assert isinstance(result, FeatureModel) # Verify billing features - assert result.billing.enabled is True assert result.billing.subscription.plan == CloudPlan.PROFESSIONAL assert result.billing.subscription.interval == "yearly" @@ -781,8 +748,6 @@ class TestFeatureService: assert result.documents_upload_quota.limit == 50 assert result.annotation_quota_limit.size == 0 assert result.annotation_quota_limit.limit == 10 - assert result.knowledge_rate_limit == 10 - assert result.docs_processing == "standard" # Verify paid plan behavior. assert result.webapp_copyright_enabled is True @@ -810,11 +775,9 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "monthly"}, "vector_space": {"size": 0, "limit": 0}, "apps": {"size": 5, "limit": 10}, @@ -846,8 +809,6 @@ class TestFeatureService: assert result.documents_upload_quota.limit == 50 assert result.annotation_quota_limit.size == 0 assert result.annotation_quota_limit.limit == 10 - assert result.knowledge_rate_limit == 10 - assert result.docs_processing == "standard" # Verify mock interactions mock_external_service_dependencies["billing_service"].get_info.assert_called_once_with(tenant_id) @@ -927,11 +888,9 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "yearly"}, "members": {"size": 10, "limit": 10}, "vector_space": {"size": 3, "limit": 5}, @@ -963,8 +922,6 @@ class TestFeatureService: assert result.documents_upload_quota.limit == 50 assert result.annotation_quota_limit.size == 0 assert result.annotation_quota_limit.limit == 10 - assert result.knowledge_rate_limit == 10 - assert result.docs_processing == "standard" # Verify mock interactions mock_external_service_dependencies["billing_service"].get_info.assert_called_once_with(tenant_id) @@ -1247,11 +1204,9 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.TEAM, "interval": "yearly"}, "members": {"size": 0, "limit": 0}, "apps": {"size": 0, "limit": -1}, @@ -1355,7 +1310,6 @@ class TestFeatureService: # Arrange: Setup edge case education mock tenant_id = self._create_test_tenant_id() mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "semester", "education": True}, "members": {"size": 100, "limit": 200}, "apps": {"size": 50, "limit": 100}, @@ -1486,63 +1440,6 @@ class TestFeatureService: # Verify mock interactions mock_external_service_dependencies["enterprise_service"].get_info.assert_called_once() - def test_get_features_edge_case_docs_processing( - self, db_session_with_containers: Session, mock_external_service_dependencies - ): - """ - Test feature retrieval with edge case document processing configuration. - - This test verifies: - - Proper handling of different document processing modes - - Correct integration with billing service - - Proper fallback to default values - - Return value correctness and structure - """ - # Arrange: Setup edge case docs processing mock with proper config - tenant_id = self._create_test_tenant_id() - - with patch("services.feature_service.dify_config") as mock_config: - mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD - mock_config.CAN_REPLACE_LOGO = True - mock_config.MODEL_LB_ENABLED = True - mock_config.DATASET_OPERATOR_ENABLED = True - mock_config.EDUCATION_ENABLED = False - - mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, - "subscription": {"plan": CloudPlan.TEAM, "interval": "monthly"}, - "docs_processing": "advanced", - "can_replace_logo": True, - "model_load_balancing_enabled": True, - } - - # Act: Execute the method under test - result = FeatureService.get_features(tenant_id) - - # Assert: Verify the expected outcomes - assert result is not None - assert isinstance(result, FeatureModel) - - # Verify docs processing configuration - assert result.docs_processing == "advanced" - assert result.can_replace_logo is True - assert result.model_load_balancing_enabled is True - - # Verify paid plan behavior. - assert result.webapp_copyright_enabled is True - assert result.is_allow_transfer_workspace is True - - # Verify default limitations (no specific billing info) - assert result.members.size == 0 - assert result.members.limit == 1 - assert result.apps.size == 0 - assert result.apps.limit == 10 - assert result.vector_space.size == 0 - assert result.vector_space.limit == 5 - - # Verify mock interactions - mock_external_service_dependencies["billing_service"].get_info.assert_called_once_with(tenant_id) - def test_get_system_features_edge_case_branding( self, db_session_with_containers: Session, mock_external_service_dependencies ): @@ -1623,14 +1520,11 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.TEAM, "interval": "yearly"}, "annotation_quota_limit": {"size": 999, "limit": 1000}, - "knowledge_rate_limit": {"limit": 500}, } # Act: Execute the method under test @@ -1644,9 +1538,6 @@ class TestFeatureService: assert result.annotation_quota_limit.size == 999 assert result.annotation_quota_limit.limit == 1000 - # Verify knowledge rate limit - assert result.knowledge_rate_limit == 500 - # Verify paid plan behavior. assert result.webapp_copyright_enabled is True assert result.is_allow_transfer_workspace is True @@ -1660,7 +1551,6 @@ class TestFeatureService: assert result.vector_space.limit == 5 assert result.documents_upload_quota.size == 0 assert result.documents_upload_quota.limit == 50 - assert result.docs_processing == "standard" # Verify mock interactions mock_external_service_dependencies["billing_service"].get_info.assert_called_once_with(tenant_id) @@ -1684,17 +1574,14 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "monthly"}, "documents_upload_quota": { "size": 0, # Edge case: zero current size "limit": 0, # Edge case: zero limit }, - "knowledge_rate_limit": {"limit": 100}, } # Act: Execute the method under test @@ -1708,9 +1595,6 @@ class TestFeatureService: assert result.documents_upload_quota.size == 0 assert result.documents_upload_quota.limit == 0 - # Verify knowledge rate limit - assert result.knowledge_rate_limit == 100 - # Verify paid plan behavior. assert result.webapp_copyright_enabled is True assert result.is_allow_transfer_workspace is True @@ -1724,7 +1608,6 @@ class TestFeatureService: assert result.vector_space.limit == 5 assert result.annotation_quota_limit.size == 0 assert result.annotation_quota_limit.limit == 10 # Default value when not provided - assert result.docs_processing == "standard" # Verify mock interactions mock_external_service_dependencies["billing_service"].get_info.assert_called_once_with(tenant_id) @@ -1799,17 +1682,14 @@ class TestFeatureService: mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_config.CAN_REPLACE_LOGO = True mock_config.MODEL_LB_ENABLED = False - mock_config.DATASET_OPERATOR_ENABLED = True mock_config.EDUCATION_ENABLED = False mock_external_service_dependencies["billing_service"].get_info.return_value = { - "enabled": True, "subscription": { "plan": CloudPlan.PROFESSIONAL, "interval": "monthly", "education": False, # Education explicitly disabled }, - "knowledge_rate_limit": {"limit": 100}, } # Act: Execute the method under test @@ -1822,9 +1702,6 @@ class TestFeatureService: # Verify education configuration assert result.education.activated is False - # Verify knowledge rate limit - assert result.knowledge_rate_limit == 100 - # Verify paid plan behavior. assert result.webapp_copyright_enabled is True assert result.is_allow_transfer_workspace is True @@ -1840,7 +1717,6 @@ class TestFeatureService: assert result.documents_upload_quota.limit == 50 assert result.annotation_quota_limit.size == 0 assert result.annotation_quota_limit.limit == 10 # Default value when not provided - assert result.docs_processing == "standard" # Verify mock interactions mock_external_service_dependencies["billing_service"].get_info.assert_called_once_with(tenant_id) diff --git a/api/tests/test_containers_integration_tests/services/test_file_service.py b/api/tests/test_containers_integration_tests/services/test_file_service.py index deb0d9d7d08..63d09e2fbaa 100644 --- a/api/tests/test_containers_integration_tests/services/test_file_service.py +++ b/api/tests/test_containers_integration_tests/services/test_file_service.py @@ -38,8 +38,6 @@ class TestFileService: mock_storage.save.return_value = None mock_storage.load.return_value = BytesIO(b"mock file content") mock_file_helpers.get_signed_file_url.return_value = "https://example.com/signed-url" - mock_file_helpers.verify_image_signature.return_value = True - mock_file_helpers.verify_file_signature.return_value = True mock_extract_processor.load_from_upload_file.return_value = "extracted text content" yield { @@ -577,248 +575,6 @@ class TestFileService: assert len(result) == 3000 # PREVIEW_WORDS_LIMIT assert result == "x" * 3000 - # Test get_image_preview method - def test_get_image_preview_success( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test successful image preview generation. - """ - fake = Faker() - account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies) - upload_file = self._create_test_upload_file( - db_session_with_containers, mock_external_service_dependencies, account - ) - - # Update file to have image extension - upload_file.extension = "jpg" - - db_session_with_containers.commit() - - timestamp = "1234567890" - nonce = "test_nonce" - sign = "test_signature" - - generator, mime_type = FileService(engine).get_image_preview( - file_id=upload_file.id, - timestamp=timestamp, - nonce=nonce, - sign=sign, - ) - - assert generator is not None - assert mime_type == upload_file.mime_type - mock_external_service_dependencies["file_helpers"].verify_image_signature.assert_called_once() - - def test_get_image_preview_invalid_signature( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test image preview with invalid signature. - """ - fake = Faker() - account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies) - upload_file = self._create_test_upload_file( - db_session_with_containers, mock_external_service_dependencies, account - ) - - # Mock invalid signature - mock_external_service_dependencies["file_helpers"].verify_image_signature.return_value = False - - timestamp = "1234567890" - nonce = "test_nonce" - sign = "invalid_signature" - - with pytest.raises(NotFound, match="File not found or signature is invalid"): - FileService(engine).get_image_preview( - file_id=upload_file.id, - timestamp=timestamp, - nonce=nonce, - sign=sign, - ) - - def test_get_image_preview_file_not_found( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test image preview with non-existent file. - """ - fake = Faker() - non_existent_id = str(fake.uuid4()) - - timestamp = "1234567890" - nonce = "test_nonce" - sign = "test_signature" - - with pytest.raises(NotFound, match="File not found or signature is invalid"): - FileService(engine).get_image_preview( - file_id=non_existent_id, - timestamp=timestamp, - nonce=nonce, - sign=sign, - ) - - def test_get_image_preview_unsupported_file_type( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test image preview with non-image file type. - """ - fake = Faker() - account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies) - upload_file = self._create_test_upload_file( - db_session_with_containers, mock_external_service_dependencies, account - ) - - # Update file to have non-image extension - upload_file.extension = "pdf" - - db_session_with_containers.commit() - - timestamp = "1234567890" - nonce = "test_nonce" - sign = "test_signature" - - with pytest.raises(UnsupportedFileTypeError): - FileService(engine).get_image_preview( - file_id=upload_file.id, - timestamp=timestamp, - nonce=nonce, - sign=sign, - ) - - # Test get_file_generator_by_file_id method - def test_get_file_generator_by_file_id_success( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test successful file generator retrieval. - """ - fake = Faker() - account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies) - upload_file = self._create_test_upload_file( - db_session_with_containers, mock_external_service_dependencies, account - ) - - timestamp = "1234567890" - nonce = "test_nonce" - sign = "test_signature" - - generator, file_obj = FileService(engine).get_file_generator_by_file_id( - file_id=upload_file.id, - timestamp=timestamp, - nonce=nonce, - sign=sign, - ) - - assert generator is not None - assert file_obj.id == upload_file.id - mock_external_service_dependencies["file_helpers"].verify_file_signature.assert_called_once() - - def test_get_file_generator_by_file_id_invalid_signature( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test file generator retrieval with invalid signature. - """ - fake = Faker() - account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies) - upload_file = self._create_test_upload_file( - db_session_with_containers, mock_external_service_dependencies, account - ) - - # Mock invalid signature - mock_external_service_dependencies["file_helpers"].verify_file_signature.return_value = False - - timestamp = "1234567890" - nonce = "test_nonce" - sign = "invalid_signature" - - with pytest.raises(NotFound, match="File not found or signature is invalid"): - FileService(engine).get_file_generator_by_file_id( - file_id=upload_file.id, - timestamp=timestamp, - nonce=nonce, - sign=sign, - ) - - def test_get_file_generator_by_file_id_file_not_found( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test file generator retrieval with non-existent file. - """ - fake = Faker() - non_existent_id = str(fake.uuid4()) - - timestamp = "1234567890" - nonce = "test_nonce" - sign = "test_signature" - - with pytest.raises(NotFound, match="File not found or signature is invalid"): - FileService(engine).get_file_generator_by_file_id( - file_id=non_existent_id, - timestamp=timestamp, - nonce=nonce, - sign=sign, - ) - - # Test get_public_image_preview method - def test_get_public_image_preview_success( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test successful public image preview generation. - """ - fake = Faker() - account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies) - upload_file = self._create_test_upload_file( - db_session_with_containers, mock_external_service_dependencies, account - ) - - # Update file to have image extension - upload_file.extension = "jpg" - - db_session_with_containers.commit() - - generator, mime_type = FileService(engine).get_public_image_preview(file_id=upload_file.id) - - assert generator is not None - assert mime_type == upload_file.mime_type - mock_external_service_dependencies["storage"].load.assert_called_once() - - def test_get_public_image_preview_file_not_found( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test public image preview with non-existent file. - """ - fake = Faker() - non_existent_id = str(fake.uuid4()) - - with pytest.raises(NotFound, match="File not found or signature is invalid"): - FileService(engine).get_public_image_preview(file_id=non_existent_id) - - def test_get_public_image_preview_unsupported_file_type( - self, db_session_with_containers: Session, engine, mock_external_service_dependencies - ): - """ - Test public image preview with non-image file type. - """ - fake = Faker() - account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies) - upload_file = self._create_test_upload_file( - db_session_with_containers, mock_external_service_dependencies, account - ) - - # Update file to have non-image extension - upload_file.extension = "pdf" - - db_session_with_containers.commit() - - with pytest.raises(UnsupportedFileTypeError): - FileService(engine).get_public_image_preview(file_id=upload_file.id) - # Test edge cases and boundary conditions def test_upload_file_empty_content( self, db_session_with_containers: Session, engine, mock_external_service_dependencies diff --git a/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py b/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py index 84a0226ba17..3ce7d9e1b93 100644 --- a/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py +++ b/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py @@ -1,7 +1,7 @@ import json import uuid from io import BytesIO -from unittest.mock import MagicMock +from unittest.mock import MagicMock, call import httpx import pytest @@ -9,7 +9,7 @@ from flask.testing import FlaskClient from sqlalchemy import select from sqlalchemy.orm import Session -import controllers.web.human_input_file_upload as human_input_file_upload_module +import services.remote_file_service as remote_file_service_module from core.workflow.human_input_adapter import ( EmailDeliveryConfig, EmailDeliveryMethod, @@ -257,10 +257,8 @@ def test_human_input_delivery_test_form_accepts_remote_file_upload( }, content=remote_content, ) - head_mock = MagicMock(return_value=head_response) - get_mock = MagicMock(return_value=get_response) - monkeypatch.setattr(human_input_file_upload_module.ssrf_proxy, "head", head_mock) - monkeypatch.setattr(human_input_file_upload_module.ssrf_proxy, "get", get_mock) + request_mock = MagicMock(side_effect=[head_response, get_response]) + monkeypatch.setattr(remote_file_service_module.remote_fetcher, "make_request", request_mock) upload_response = test_client_with_containers.post( "/api/human-input-forms/files", @@ -272,8 +270,10 @@ def test_human_input_delivery_test_form_accepts_remote_file_upload( assert upload_response.status_code == 201, upload_response.get_data(as_text=True) upload_file_id = upload_response.get_json()["id"] assert upload_response.get_json()["url"] - head_mock.assert_called_once_with(url=remote_url) - get_mock.assert_called_once_with(remote_url) + assert request_mock.call_args_list == [ + call("HEAD", url=remote_url), + call("GET", url=remote_url), + ] db_session_with_containers.expire_all() upload_file = db_session_with_containers.get(UploadFile, upload_file_id) diff --git a/api/tests/test_containers_integration_tests/services/test_human_input_file_upload_service.py b/api/tests/test_containers_integration_tests/services/test_human_input_file_upload_service.py index d88d43fad0b..b6f0da19105 100644 --- a/api/tests/test_containers_integration_tests/services/test_human_input_file_upload_service.py +++ b/api/tests/test_containers_integration_tests/services/test_human_input_file_upload_service.py @@ -16,6 +16,7 @@ from models.human_input import ( HumanInputFormUploadToken, StandaloneWebAppRecipientPayload, ) +from repositories.human_input_file_upload_repository import SQLAlchemyHumanInputFileUploadRepository from services.human_input_file_upload_service import HITL_UPLOAD_TOKEN_PREFIX, HumanInputFileUploadService @@ -61,8 +62,10 @@ def test_issue_upload_token_returns_expiration_with_default_session_expiry( monkeypatch.setattr(service_module.secrets, "token_urlsafe", lambda _bytes: "random-value") service = HumanInputFileUploadService( - session_factory=sessionmaker(bind=db.engine), + uploads=SQLAlchemyHumanInputFileUploadRepository(session_factory=sessionmaker(bind=db.engine)), workflow_run_repository=MagicMock(), + files=MagicMock(), + remote_files=MagicMock(), ) token = service.issue_upload_token("form-token-1") diff --git a/api/tests/test_containers_integration_tests/services/test_message_service.py b/api/tests/test_containers_integration_tests/services/test_message_service.py index 62d03690ee9..8c935876fe2 100644 --- a/api/tests/test_containers_integration_tests/services/test_message_service.py +++ b/api/tests/test_containers_integration_tests/services/test_message_service.py @@ -33,7 +33,6 @@ class TestMessageService: patch("services.message_service.TokenBufferMemory") as mock_token_buffer_memory, ): # Setup default mock returns - mock_account_feature_service.get_features.return_value.billing.enabled = False # Mock ModelManager mock_model_instance = mock_model_manager.return_value.get_default_model_instance.return_value diff --git a/api/tests/test_containers_integration_tests/services/test_workspace_service.py b/api/tests/test_containers_integration_tests/services/test_workspace_service.py index d6edcd25f85..e8a14c68acf 100644 --- a/api/tests/test_containers_integration_tests/services/test_workspace_service.py +++ b/api/tests/test_containers_integration_tests/services/test_workspace_service.py @@ -27,9 +27,9 @@ class TestWorkspaceService: # Setup default mock returns feature = mock_feature_service.get_features.return_value feature.can_replace_logo = True - feature.billing.enabled = True feature.billing.subscription.plan = "professional" mock_tenant_service.has_roles.return_value = True + mock_dify_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD mock_dify_config.FILES_URL = "https://example.com/files" yield { @@ -611,7 +611,6 @@ class TestWorkspaceService: mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY feature = mock_external_service_dependencies["feature_service"].get_features.return_value feature.can_replace_logo = False - feature.billing.enabled = False mock_external_service_dependencies["tenant_service"].has_roles.return_value = False with patch("services.workspace_service.current_user", account): diff --git a/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.py b/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.py index 4193223f311..770a145c6cb 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.py @@ -255,7 +255,10 @@ class TestBatchCleanDocumentTask: # Execute the task batch_clean_document_task( - document_ids=[document_id], dataset_id=dataset.id, doc_form=dataset.doc_form, file_ids=[file_id] + document_ids=[document_id], + dataset_id=dataset.id, + doc_form=dataset.get_doc_form(session=db_session_with_containers), + file_ids=[file_id], ) # Verify that the task completed successfully @@ -311,7 +314,10 @@ class TestBatchCleanDocumentTask: # Execute the task batch_clean_document_task( - document_ids=[document_id], dataset_id=dataset.id, doc_form=dataset.doc_form, file_ids=[] + document_ids=[document_id], + dataset_id=dataset.id, + doc_form=dataset.get_doc_form(session=db_session_with_containers), + file_ids=[], ) # Verify database cleanup @@ -351,7 +357,10 @@ class TestBatchCleanDocumentTask: # Execute the task batch_clean_document_task( - document_ids=[document_id], dataset_id=dataset.id, doc_form=dataset.doc_form, file_ids=[file_id] + document_ids=[document_id], + dataset_id=dataset.id, + doc_form=dataset.get_doc_form(session=db_session_with_containers), + file_ids=[file_id], ) # Verify that the task completed successfully @@ -446,7 +455,10 @@ class TestBatchCleanDocumentTask: # Execute the task batch_clean_document_task( - document_ids=[document_id], dataset_id=dataset.id, doc_form=dataset.doc_form, file_ids=[file_id] + document_ids=[document_id], + dataset_id=dataset.id, + doc_form=dataset.get_doc_form(session=db_session_with_containers), + file_ids=[file_id], ) # Verify that the task completed successfully despite storage failure @@ -504,7 +516,10 @@ class TestBatchCleanDocumentTask: # Execute the task with multiple documents batch_clean_document_task( - document_ids=document_ids, dataset_id=dataset.id, doc_form=dataset.doc_form, file_ids=file_ids + document_ids=document_ids, + dataset_id=dataset.id, + doc_form=dataset.get_doc_form(session=db_session_with_containers), + file_ids=file_ids, ) # Verify that the task completed successfully for all documents @@ -641,7 +656,10 @@ class TestBatchCleanDocumentTask: # Execute the task with large batch batch_clean_document_task( - document_ids=document_ids, dataset_id=dataset.id, doc_form=dataset.doc_form, file_ids=file_ids + document_ids=document_ids, + dataset_id=dataset.id, + doc_form=dataset.get_doc_form(session=db_session_with_containers), + file_ids=file_ids, ) end_time = time.perf_counter() @@ -734,7 +752,10 @@ class TestBatchCleanDocumentTask: # Execute the task batch_clean_document_task( - document_ids=[document_id], dataset_id=dataset.id, doc_form=dataset.doc_form, file_ids=[file_id] + document_ids=[document_id], + dataset_id=dataset.id, + doc_form=dataset.get_doc_form(session=db_session_with_containers), + file_ids=[file_id], ) # Verify that the task completed successfully diff --git a/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.py b/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.py index a31552a09ea..e801597e434 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.py @@ -295,7 +295,7 @@ class TestCleanDatasetTask: indexing_technique=dataset.indexing_technique, index_struct=dataset.index_struct, collection_binding_id=dataset.collection_binding_id, - doc_form=dataset.doc_form, + doc_form=dataset.get_doc_form(session=db_session_with_containers), ) # Verify results @@ -419,7 +419,7 @@ class TestCleanDatasetTask: indexing_technique=dataset.indexing_technique, index_struct=dataset.index_struct, collection_binding_id=dataset.collection_binding_id, - doc_form=dataset.doc_form, + doc_form=dataset.get_doc_form(session=db_session_with_containers), ) # Verify results @@ -552,7 +552,7 @@ class TestCleanDatasetTask: indexing_technique=dataset.indexing_technique, index_struct=dataset.index_struct, collection_binding_id=dataset.collection_binding_id, - doc_form=dataset.doc_form, + doc_form=dataset.get_doc_form(session=db_session_with_containers), ) # Verify results - even with vector cleanup failure, documents and segments should be deleted @@ -638,7 +638,7 @@ class TestCleanDatasetTask: indexing_technique=dataset.indexing_technique, index_struct=dataset.index_struct, collection_binding_id=dataset.collection_binding_id, - doc_form=dataset.doc_form, + doc_form=dataset.get_doc_form(session=db_session_with_containers), ) # Verify results @@ -751,7 +751,7 @@ class TestCleanDatasetTask: indexing_technique=dataset.indexing_technique, index_struct=dataset.index_struct, collection_binding_id=dataset.collection_binding_id, - doc_form=dataset.doc_form, + doc_form=dataset.get_doc_form(session=db_session_with_containers), ) end_time = time.time() @@ -845,7 +845,7 @@ class TestCleanDatasetTask: indexing_technique=dataset.indexing_technique, index_struct=dataset.index_struct, collection_binding_id=dataset.collection_binding_id, - doc_form=dataset.doc_form, + doc_form=dataset.get_doc_form(session=db_session_with_containers), ) # Verify results @@ -999,7 +999,7 @@ class TestCleanDatasetTask: indexing_technique=dataset.indexing_technique, index_struct=dataset.index_struct, collection_binding_id=dataset.collection_binding_id, - doc_form=dataset.doc_form, + doc_form=dataset.get_doc_form(session=db_session_with_containers), ) # Verify results diff --git a/api/tests/test_containers_integration_tests/tasks/test_create_segment_to_index_task.py b/api/tests/test_containers_integration_tests/tasks/test_create_segment_to_index_task.py index a8d295e6a90..0410fb5ebeb 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_create_segment_to_index_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_create_segment_to_index_task.py @@ -226,7 +226,9 @@ class TestCreateSegmentToIndexTask: assert segment.error is None # Verify index processor was called - mock_external_service_dependencies["index_processor_factory"].assert_called_once_with(dataset.doc_form) + mock_external_service_dependencies["index_processor_factory"].assert_called_once_with( + dataset.get_doc_form(session=db_session_with_containers) + ) mock_external_service_dependencies["index_processor"].load.assert_called_once() # Verify Redis cache cleanup @@ -552,7 +554,9 @@ class TestCreateSegmentToIndexTask: assert segment.completed_at is not None # Verify index processor was called - mock_external_service_dependencies["index_processor_factory"].assert_called_once_with(dataset.doc_form) + mock_external_service_dependencies["index_processor_factory"].assert_called_once_with( + dataset.get_doc_form(session=db_session_with_containers) + ) mock_external_service_dependencies["index_processor"].load.assert_called_once() def test_create_segment_to_index_different_doc_forms( @@ -983,7 +987,9 @@ class TestCreateSegmentToIndexTask: assert segment.completed_at is not None # Verify index processor was called - mock_external_service_dependencies["index_processor_factory"].assert_called_once_with(dataset.doc_form) + mock_external_service_dependencies["index_processor_factory"].assert_called_once_with( + dataset.get_doc_form(session=db_session_with_containers) + ) mock_external_service_dependencies["index_processor"].load.assert_called_once() def test_create_segment_to_index_tenant_isolation( @@ -1057,7 +1063,9 @@ class TestCreateSegmentToIndexTask: assert segment.completed_at is not None # Verify index processor was called - mock_external_service_dependencies["index_processor_factory"].assert_called_once_with(dataset.doc_form) + mock_external_service_dependencies["index_processor_factory"].assert_called_once_with( + dataset.get_doc_form(session=db_session_with_containers) + ) mock_external_service_dependencies["index_processor"].load.assert_called_once() def test_create_segment_to_index_comprehensive_integration( diff --git a/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.py b/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.py index 0c36794cb8c..b0700ea9709 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.py @@ -11,7 +11,7 @@ from sqlalchemy.orm import Session from core.indexing_runner import DocumentIsPausedError from core.rag.index_processor.constant.index_type import IndexTechniqueType -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from models import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus from models.dataset import Dataset, Document from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus @@ -22,6 +22,7 @@ from tasks.document_indexing_task import ( normal_document_indexing_task, priority_document_indexing_task, ) +from tests.unit_tests.config_override import config_overrides_context class _TrackedSessionContext: @@ -89,7 +90,6 @@ def patched_external_dependencies(): ): mock_runner_instance = mock_indexing_runner.return_value mock_features = MagicMock() - mock_features.billing.enabled = False mock_features.billing.subscription.plan = CloudPlan.PROFESSIONAL mock_features.vector_space.limit = 100 mock_features.vector_space.size = 0 @@ -249,6 +249,7 @@ class TestDatasetIndexingTaskIntegration: assert len(run_args) == len(document_ids) self._assert_documents_parsing(db_session_with_containers, document_ids) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_batch_processing_with_limit_check( self, db_session_with_containers: Session, patched_external_dependencies ): @@ -260,7 +261,6 @@ class TestDatasetIndexingTaskIntegration: dataset, documents = self._create_test_dataset_and_documents(db_session_with_containers, document_count=3) document_ids = [doc.id for doc in documents] features = patched_external_dependencies["features"] - features.billing.enabled = True features.billing.subscription.plan = CloudPlan.PROFESSIONAL features.vector_space.limit = 100 features.vector_space.size = 50 @@ -273,6 +273,7 @@ class TestDatasetIndexingTaskIntegration: patched_external_dependencies["indexing_runner_instance"].run.assert_not_called() self._assert_documents_error_contains(db_session_with_containers, document_ids, "batch upload limit") + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_batch_processing_sandbox_plan_single_document_only( self, db_session_with_containers: Session, patched_external_dependencies ): @@ -281,7 +282,6 @@ class TestDatasetIndexingTaskIntegration: dataset, documents = self._create_test_dataset_and_documents(db_session_with_containers, document_count=2) document_ids = [doc.id for doc in documents] features = patched_external_dependencies["features"] - features.billing.enabled = True features.billing.subscription.plan = CloudPlan.SANDBOX # Act @@ -375,6 +375,7 @@ class TestDatasetIndexingTaskIntegration: task_dispatch_spy.apply_async.assert_not_called() delete_key_spy.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_validation_failure_sets_error_status_when_vector_space_at_limit( self, db_session_with_containers: Session, patched_external_dependencies ): @@ -383,7 +384,6 @@ class TestDatasetIndexingTaskIntegration: dataset, documents = self._create_test_dataset_and_documents(db_session_with_containers, document_count=3) document_ids = [doc.id for doc in documents] features = patched_external_dependencies["features"] - features.billing.enabled = True features.billing.subscription.plan = CloudPlan.PROFESSIONAL features.vector_space.limit = 100 features.vector_space.size = 100 @@ -590,6 +590,7 @@ class TestDatasetIndexingTaskIntegration: call_kwargs = task_dispatch_spy.apply_async.call_args_list[index].kwargs.get("kwargs", {}) assert call_kwargs.get("document_ids") == expected_task["document_ids"] + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_billing_disabled_skips_limit_checks( self, db_session_with_containers: Session, patched_external_dependencies ): @@ -601,7 +602,6 @@ class TestDatasetIndexingTaskIntegration: document_ids=large_document_ids, ) features = patched_external_dependencies["features"] - features.billing.enabled = False # Act _document_indexing(dataset.id, large_document_ids) @@ -688,6 +688,7 @@ class TestDatasetIndexingTaskIntegration: # Assert self._assert_documents_parsing(db_session_with_containers, [special_document_id]) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_zero_vector_space_limit_allows_unlimited( self, db_session_with_containers: Session, patched_external_dependencies ): @@ -696,7 +697,6 @@ class TestDatasetIndexingTaskIntegration: dataset, documents = self._create_test_dataset_and_documents(db_session_with_containers, document_count=3) document_ids = [doc.id for doc in documents] features = patched_external_dependencies["features"] - features.billing.enabled = True features.billing.subscription.plan = CloudPlan.PROFESSIONAL features.vector_space.limit = 0 features.vector_space.size = 1000 @@ -708,6 +708,7 @@ class TestDatasetIndexingTaskIntegration: patched_external_dependencies["indexing_runner_instance"].run.assert_called_once() self._assert_documents_parsing(db_session_with_containers, document_ids) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_negative_vector_space_values_handled_gracefully( self, db_session_with_containers: Session, patched_external_dependencies ): @@ -716,7 +717,6 @@ class TestDatasetIndexingTaskIntegration: dataset, documents = self._create_test_dataset_and_documents(db_session_with_containers, document_count=3) document_ids = [doc.id for doc in documents] features = patched_external_dependencies["features"] - features.billing.enabled = True features.billing.subscription.plan = CloudPlan.PROFESSIONAL features.vector_space.limit = -1 features.vector_space.size = 100 @@ -728,6 +728,7 @@ class TestDatasetIndexingTaskIntegration: patched_external_dependencies["indexing_runner_instance"].run.assert_called_once() self._assert_documents_parsing(db_session_with_containers, document_ids) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_large_document_batch_processing(self, db_session_with_containers: Session, patched_external_dependencies): """Process a batch exactly at configured upload limit. @@ -741,7 +742,6 @@ class TestDatasetIndexingTaskIntegration: document_ids=document_ids, ) features = patched_external_dependencies["features"] - features.billing.enabled = True features.billing.subscription.plan = CloudPlan.PROFESSIONAL features.vector_space.limit = 10000 features.vector_space.size = 0 diff --git a/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.py b/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.py index bb45e2be34a..85b3993b1fd 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.py @@ -7,7 +7,7 @@ from sqlalchemy.orm import Session from core.entities.document_task import DocumentTask from core.rag.index_processor.constant.index_type import IndexTechniqueType -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from models import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus from models.dataset import Dataset, Document from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus @@ -18,6 +18,7 @@ from tasks.document_indexing_task import ( normal_document_indexing_task, # New normal task priority_document_indexing_task, # New priority task ) +from tests.unit_tests.config_override import config_overrides_context class TestDocumentIndexingTasks: @@ -41,7 +42,6 @@ class TestDocumentIndexingTasks: # Setup mock indexing runner mock_runner_instance = mock_indexing_runner.return_value # Setup mock feature service mock_features = MagicMock() - mock_features.billing.enabled = False mock_feature_service.get_features.return_value = mock_features yield { @@ -147,7 +147,9 @@ class TestDocumentIndexingTasks: return dataset, documents def _create_test_dataset_with_billing_features( - self, db_session_with_containers: Session, mock_external_service_dependencies, billing_enabled=True + self, + db_session_with_containers: Session, + mock_external_service_dependencies, ): """ Helper method to create a test dataset with billing features configured. @@ -155,7 +157,6 @@ class TestDocumentIndexingTasks: Args: db_session_with_containers: Database session from testcontainers infrastructure mock_external_service_dependencies: Mock dependencies - billing_enabled: Whether billing is enabled Returns: tuple: (dataset, documents) - Created dataset and document instances @@ -224,11 +225,9 @@ class TestDocumentIndexingTasks: db_session_with_containers.commit() # Configure billing features - mock_external_service_dependencies["features"].billing.enabled = billing_enabled - if billing_enabled: - mock_external_service_dependencies["features"].billing.subscription.plan = CloudPlan.SANDBOX - mock_external_service_dependencies["features"].vector_space.limit = 100 - mock_external_service_dependencies["features"].vector_space.size = 50 + mock_external_service_dependencies["features"].billing.subscription.plan = CloudPlan.SANDBOX + mock_external_service_dependencies["features"].vector_space.limit = 100 + mock_external_service_dependencies["features"].vector_space.size = 50 # Refresh dataset to ensure it's properly loaded db_session_with_containers.refresh(dataset) @@ -467,6 +466,7 @@ class TestDocumentIndexingTasks: processed_documents = self._runner_documents_arg(mock_external_service_dependencies) assert len(processed_documents) == 4 + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_document_indexing_task_billing_sandbox_plan_batch_limit( self, db_session_with_containers: Session, mock_external_service_dependencies ): @@ -481,7 +481,8 @@ class TestDocumentIndexingTasks: """ # Arrange: Create test data with billing enabled dataset, documents = self._create_test_dataset_with_billing_features( - db_session_with_containers, mock_external_service_dependencies, billing_enabled=True + db_session_with_containers, + mock_external_service_dependencies, ) # Configure sandbox plan with batch limit @@ -529,21 +530,23 @@ class TestDocumentIndexingTasks: # Verify no indexing runner was called mock_external_service_dependencies["indexing_runner"].assert_not_called() - def test_document_indexing_task_billing_disabled_success( + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) + def test_document_indexing_task_community_success( self, db_session_with_containers: Session, mock_external_service_dependencies ): """ - Test successful processing when billing is disabled. + Test successful processing outside Cloud. This test verifies: - - Processing continues normally when billing is disabled + - Processing continues normally outside Cloud - No billing validation occurs - Documents are processed successfully - IndexingRunner is called correctly """ # Arrange: Create test data with billing disabled dataset, documents = self._create_test_dataset_with_billing_features( - db_session_with_containers, mock_external_service_dependencies, billing_enabled=False + db_session_with_containers, + mock_external_service_dependencies, ) document_ids = [doc.id for doc in documents] diff --git a/api/tests/test_containers_integration_tests/tasks/test_duplicate_document_indexing_task.py b/api/tests/test_containers_integration_tests/tasks/test_duplicate_document_indexing_task.py index d5393435bfa..1dacc2bba10 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_duplicate_document_indexing_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_duplicate_document_indexing_task.py @@ -7,7 +7,7 @@ from sqlalchemy.orm import Session from core.indexing_runner import DocumentIsPausedError from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from models import Account, Tenant, TenantAccountJoin, TenantAccountRole from models.dataset import Dataset, Document, DocumentSegment from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus, SegmentStatus @@ -18,6 +18,7 @@ from tasks.duplicate_document_indexing_task import ( normal_duplicate_document_indexing_task, # New normal task priority_duplicate_document_indexing_task, # New priority task ) +from tests.unit_tests.config_override import config_overrides_context class TestDuplicateDocumentIndexingTasks: @@ -45,7 +46,6 @@ class TestDuplicateDocumentIndexingTasks: # Setup mock indexing runner mock_runner_instance = mock_indexing_runner.return_value # Setup mock feature service mock_features = MagicMock() - mock_features.billing.enabled = False mock_feature_service.get_features.return_value = mock_features # Setup mock index processor factory @@ -214,7 +214,9 @@ class TestDuplicateDocumentIndexingTasks: return dataset, documents, segments def _create_test_dataset_with_billing_features( - self, db_session_with_containers: Session, mock_external_service_dependencies, billing_enabled=True + self, + db_session_with_containers: Session, + mock_external_service_dependencies, ): """ Helper method to create a test dataset with billing features configured. @@ -222,7 +224,6 @@ class TestDuplicateDocumentIndexingTasks: Args: db_session_with_containers: Database session from testcontainers infrastructure mock_external_service_dependencies: Mock dependencies - billing_enabled: Whether billing is enabled Returns: tuple: (dataset, documents) - Created dataset and document instances @@ -292,11 +293,9 @@ class TestDuplicateDocumentIndexingTasks: db_session_with_containers.commit() # Configure billing features - mock_external_service_dependencies["features"].billing.enabled = billing_enabled - if billing_enabled: - mock_external_service_dependencies["features"].billing.subscription.plan = CloudPlan.SANDBOX - mock_external_service_dependencies["features"].vector_space.limit = 100 - mock_external_service_dependencies["features"].vector_space.size = 50 + mock_external_service_dependencies["features"].billing.subscription.plan = CloudPlan.SANDBOX + mock_external_service_dependencies["features"].vector_space.limit = 100 + mock_external_service_dependencies["features"].vector_space.size = 50 # Refresh dataset to ensure it's properly loaded db_session_with_containers.refresh(dataset) @@ -517,7 +516,8 @@ class TestDuplicateDocumentIndexingTasks: """ # Arrange: Create test data with billing enabled dataset, documents = self._create_test_dataset_with_billing_features( - db_session_with_containers, mock_external_service_dependencies, billing_enabled=True + db_session_with_containers, + mock_external_service_dependencies, ) # Configure sandbox plan with batch limit @@ -580,7 +580,8 @@ class TestDuplicateDocumentIndexingTasks: """ # Arrange: Create test data with billing enabled dataset, documents = self._create_test_dataset_with_billing_features( - db_session_with_containers, mock_external_service_dependencies, billing_enabled=True + db_session_with_containers, + mock_external_service_dependencies, ) # Configure TEAM plan with vector space limit exceeded @@ -818,7 +819,8 @@ class TestDuplicateDocumentIndexingTasks: db_session_with_containers, mock_external_service_dependencies ) - def test_duplicate_document_indexing_with_billing_enabled_sandbox_plan( + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) + def test_duplicate_document_indexing_with_cloud_sandbox_plan( self, db_session_with_containers: Session, mock_external_service_dependencies ): """Test duplicate document indexing with billing enabled and sandbox plan.""" @@ -826,6 +828,7 @@ class TestDuplicateDocumentIndexingTasks: db_session_with_containers, mock_external_service_dependencies ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_duplicate_document_indexing_with_billing_limit_exceeded( self, db_session_with_containers: Session, mock_external_service_dependencies ): diff --git a/api/tests/unit_tests/.ruff.toml b/api/tests/unit_tests/.ruff.toml index 32c17b823bd..09056d4e952 100644 --- a/api/tests/unit_tests/.ruff.toml +++ b/api/tests/unit_tests/.ruff.toml @@ -61,9 +61,7 @@ extend-select = ["ANN401", "ARG"] "controllers/console/workspace/test_tool_providers.py" = ["ARG001", "ARG005"] "controllers/console/workspace/test_trigger_providers.py" = ["ARG001"] "controllers/console/workspace/test_workspace.py" = ["ARG005"] -"controllers/files/test_image_preview.py" = ["ARG005"] "controllers/files/test_tool_files.py" = ["ARG002", "ARG005"] -"controllers/files/test_upload.py" = ["ARG002", "ARG005"] "controllers/inner_api/plugin/test_plugin.py" = ["ARG002"] "controllers/inner_api/plugin/test_plugin_wraps.py" = ["ARG001", "ARG002", "ARG003", "TID251"] "controllers/inner_api/test_runtime_credentials.py" = ["ARG001"] diff --git a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py b/api/tests/unit_tests/clients/agent_backend/test_request_builder.py index 978b522d509..29771083de6 100644 --- a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py +++ b/api/tests/unit_tests/clients/agent_backend/test_request_builder.py @@ -20,6 +20,11 @@ from dify_agent.layers.execution_context import DIFY_EXECUTION_CONTEXT_LAYER_TYP from dify_agent.layers.knowledge import DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID, DifyKnowledgeBaseLayerConfig from dify_agent.layers.output import DIFY_OUTPUT_LAYER_TYPE_ID from dify_agent.layers.shell import DIFY_SHELL_LAYER_TYPE_ID, DifyShellEnvVarConfig, DifyShellLayerConfig +from dify_agent.layers.user_prompt import ( + DIFY_USER_PROMPT_LAYER_TYPE_ID, + DifyUserPromptDownloadConfig, + DifyUserPromptImageConfig, +) from dify_agent.protocol import ( DIFY_AGENT_HISTORY_LAYER_ID, DIFY_AGENT_MODEL_LAYER_ID, @@ -367,6 +372,64 @@ def test_agent_app_request_builder_omits_shell_layer_by_default(): assert DIFY_SHELL_LAYER_ID not in {layer.name for layer in request.composition.layers} +def test_agent_app_request_builder_emits_multimodal_user_prompt_layer(): + run_input = _agent_app_input() + run_input.user_files = [ + DifyUserPromptDownloadConfig( + type="document", transfer_method="remote_url", url="https://example.com/brief.pdf" + ), + DifyUserPromptImageConfig( + filename="earth.png", + mime_type="image/png", + format="png", + url="https://files.example.com/earth.png?sign=secret", + detail="high", + ), + ] + + request = AgentBackendRunRequestBuilder().build_for_agent_app(run_input) + layer = next(layer for layer in request.composition.layers if layer.name == "agent_app_user_prompt") + + assert layer.type == DIFY_USER_PROMPT_LAYER_TYPE_ID + assert layer.config.text == "List files." + assert layer.config.files == run_input.user_files + restored_request = CreateRunRequest.model_validate_json(request.model_dump_json()) + restored_layer = next( + layer for layer in restored_request.composition.layers if layer.name == "agent_app_user_prompt" + ) + assert restored_layer.config == layer.config.model_dump(mode="json") + assert "locators" not in restored_layer.config + + +def test_agent_backend_log_redacts_multimodal_file_transport(): + run_input = _agent_app_input() + run_input.metadata = {"source_url": "https://example.com/docs"} + run_input.user_files = [ + DifyUserPromptImageConfig( + filename="earth.png", + mime_type="image/png", + format="png", + url="https://files.example.com/earth.png?sign=secret", + ), + DifyUserPromptImageConfig( + filename="inline.png", + mime_type="image/png", + format="png", + base64_data="aW1hZ2UtYnl0ZXM=", + ), + ] + + redacted = cast( + dict[str, Any], + redact_for_agent_backend_log(AgentBackendRunRequestBuilder().build_for_agent_app(run_input)), + ) + layer = next(item for item in redacted["composition"]["layers"] if item["name"] == "agent_app_user_prompt") + + assert layer["config"]["files"][0]["url"] == "[REDACTED]" + assert layer["config"]["files"][1]["base64_data"] == "[REDACTED]" + assert redacted["metadata"]["source_url"] == "https://example.com/docs" + + def test_agent_app_request_builder_keeps_build_draft_prompt_when_agent_soul_prompt_is_blank(): run_input = _agent_app_input().model_copy( update={"agent_soul_prompt": " ", "agent_config_version_kind": "build_draft"} diff --git a/api/tests/unit_tests/commands/test_generate_swagger_specs.py b/api/tests/unit_tests/commands/test_generate_swagger_specs.py index 6f1907a8261..35139e8e49b 100644 --- a/api/tests/unit_tests/commands/test_generate_swagger_specs.py +++ b/api/tests/unit_tests/commands/test_generate_swagger_specs.py @@ -195,6 +195,19 @@ def test_generate_specs_writes_openapi_with_resolvable_references_and_null_defau assert "default" in conversation_id assert conversation_id["default"] is None + schemas = service_payload["components"]["schemas"] + document_detail = schemas["DocumentDetailResponse"] + validator = Draft202012Validator(service_payload) + for schema in (document_detail, *schemas["DocumentTextUpdate"]["anyOf"]): + for property_schema in schema["properties"].values(): + if "default" in property_schema: + validator.evolve(schema=property_schema).validate(property_schema["default"]) + + assert document_detail["required"] == ["id"] + assert document_detail["properties"]["enabled"]["type"] == "boolean" + assert "default" not in document_detail["properties"]["enabled"] + assert document_detail["properties"]["tokens"]["default"] is None + def test_generate_specs_writes_unique_operation_ids(tmp_path: Path): module = _load_generate_swagger_specs_module() diff --git a/api/tests/unit_tests/commands/test_rbac_agent_migration.py b/api/tests/unit_tests/commands/test_rbac_agent_migration.py new file mode 100644 index 00000000000..7a324e33034 --- /dev/null +++ b/api/tests/unit_tests/commands/test_rbac_agent_migration.py @@ -0,0 +1,193 @@ +import json +from collections.abc import Iterator +from contextlib import ExitStack +from dataclasses import dataclass, field +from unittest.mock import MagicMock, patch + +import pytest +from click.testing import CliRunner, Result + +from commands.rbac import migrate_agent_permissions_to_rbac +from services.enterprise.rbac_service import ( + LegacyAgentMigrationReport, + LegacyAgentRoleMigration, + _LegacyResourceWhitelistConfig, +) + +MODULE = "commands.rbac" + + +def _events(output: str) -> list[dict[str, object]]: + return [json.loads(line) for line in output.splitlines() if line.startswith("{")] + + +@pytest.fixture(autouse=True) +def _no_agents() -> Iterator[None]: + with patch(f"{MODULE}._iter_agent_row_batches", return_value=iter(())): + yield + + +def _roles() -> list[LegacyAgentRoleMigration]: + return [ + LegacyAgentRoleMigration( + role_id="r1", + role_name="ops", + added_keys=["agent.create"], + removed_keys=["agent.manage"], + bound_policies=["agent.full_access"], + ), + LegacyAgentRoleMigration(role_id="r2", role_name="stuck", skipped="policy row missing"), + ] + + +def test_apply_flag_writes_and_reports_applied() -> None: + with ( + patch(f"{MODULE}._iter_tenant_ids", return_value=iter(["t1", "t2"])), + patch( + f"{MODULE}.RBACService.Migrations.migrate_agent_manage_roles", + return_value=LegacyAgentMigrationReport(roles=_roles()[:1]), + ) as migrate, + ): + result = CliRunner().invoke(migrate_agent_permissions_to_rbac, ["--apply"]) + + assert result.exit_code == 0, result.output + assert migrate.call_count == 2 + assert all(call.kwargs == {"apply": True} for call in migrate.call_args_list) + events = _events(result.output) + assert [e["event"] for e in events] == ["agent_manage_role_migration_applied"] * 2 + assert {e["tenant_id"] for e in events} == {"t1", "t2"} + assert "changed" in result.output + + +def _whitelist_config( + scope: str | None = "all", + account_ids: list[str] | None = None, +) -> _LegacyResourceWhitelistConfig: + return _LegacyResourceWhitelistConfig(rbac_whitelist_scope=scope, account_ids=account_ids or []) + + +@dataclass +class _AgentPhaseMocks: + agent_whitelist_config: MagicMock + app_whitelist_config: MagicMock + replace_whitelist: MagicMock + replace_user_access_policies: MagicMock + sync_creator_bindings: MagicMock + owner_account_id: MagicMock + member_batches: MagicMock + write_order: MagicMock + + +@dataclass +class _AgentPhaseSetup: + agents: list[tuple[str, str | None, str | None]] + configured_agent_ids: list[str] = field(default_factory=list) + agent_configs: list[_LegacyResourceWhitelistConfig] | None = None + app_config: _LegacyResourceWhitelistConfig = field(default_factory=_whitelist_config) + workspace_members: list[str] = field(default_factory=lambda: ["m1", "m2", "m3"]) + owner_account_id: str = "owner-1" + + +def _run_agent_phase(args: list[str], setup: _AgentPhaseSetup) -> tuple[Result, _AgentPhaseMocks]: + def _member_batches(_tenant_id: str, batch_size: int) -> Iterator[list[str]]: + for start in range(0, len(setup.workspace_members), batch_size): + yield setup.workspace_members[start : start + batch_size] + + with ExitStack() as stack: + stack.enter_context(patch(f"{MODULE}._iter_tenant_ids", return_value=iter(["t1"]))) + stack.enter_context( + patch( + f"{MODULE}.RBACService.Migrations.migrate_agent_manage_roles", + return_value=LegacyAgentMigrationReport(), + ) + ) + stack.enter_context(patch(f"{MODULE}._iter_agent_row_batches", return_value=iter([setup.agents]))) + stack.enter_context( + patch( + f"{MODULE}.RBACService.Migrations.list_configured_agent_ids", + return_value=setup.configured_agent_ids, + ) + ) + agent_whitelist_config = stack.enter_context(patch(f"{MODULE}.RBACService.AgentAccess.legacy_whitelist_config")) + if setup.agent_configs is None: + agent_whitelist_config.return_value = _whitelist_config() + else: + agent_whitelist_config.side_effect = setup.agent_configs + mocks = _AgentPhaseMocks( + agent_whitelist_config=agent_whitelist_config, + app_whitelist_config=stack.enter_context( + patch(f"{MODULE}.RBACService.AppAccess.legacy_whitelist_config", return_value=setup.app_config) + ), + replace_whitelist=stack.enter_context(patch(f"{MODULE}.RBACService.AgentAccess.replace_whitelist")), + replace_user_access_policies=stack.enter_context( + patch(f"{MODULE}.RBACService.AgentAccess.replace_user_access_policies") + ), + sync_creator_bindings=stack.enter_context( + patch(f"{MODULE}.RBACService.AccessPolicies.sync_creator_access_policy_member_bindings") + ), + owner_account_id=stack.enter_context( + patch(f"{MODULE}._owner_account_id", return_value=setup.owner_account_id) + ), + member_batches=stack.enter_context( + patch(f"{MODULE}._workspace_member_account_id_batches", side_effect=_member_batches) + ), + write_order=MagicMock(), + ) + mocks.write_order.attach_mock(mocks.replace_user_access_policies, "seed_members") + mocks.write_order.attach_mock(mocks.sync_creator_bindings, "sync_creator") + mocks.write_order.attach_mock(mocks.replace_whitelist, "replace_whitelist") + result = CliRunner().invoke(migrate_agent_permissions_to_rbac, args) + return result, mocks + + +def _write_order(mocks: _AgentPhaseMocks) -> list[str]: + return [name for name, _, _ in mocks.write_order.mock_calls] + + +def test_agent_bootstrap_apply_writes_whitelist_member_batches_and_creator_sync() -> None: + result, mocks = _run_agent_phase( + ["--apply", "--member-batch-size", "2"], + _AgentPhaseSetup(agents=[("ag1", "c1", None)], workspace_members=["m1", "m2", "m3"]), + ) + + assert result.exit_code == 0, result.output + assert [e["event"] for e in _events(result.output)] == ["agent_access_bootstrap_applied"] + assert _events(result.output)[0]["dry_run"] is False + + mocks.replace_whitelist.assert_called_once() + assert mocks.replace_whitelist.call_args.kwargs["agent_id"] == "ag1" + assert mocks.replace_whitelist.call_args.kwargs["account_id"] == "c1" + assert mocks.replace_whitelist.call_args.kwargs["payload"].automatic_include_workspace_members is True + + mocks.member_batches.assert_called_once_with("t1", 2) + assert mocks.replace_user_access_policies.call_count == 2 + calls = mocks.replace_user_access_policies.call_args_list + assert [call.kwargs["payload"].account_ids for call in calls] == [["m1", "m2"], ["m3"]] + assert all(call.kwargs["payload"].access_policy_ids == ["default"] for call in calls) + assert all(call.kwargs["target_account_id"] is None for call in calls) + + mocks.sync_creator_bindings.assert_called_once() + assert mocks.sync_creator_bindings.call_args.kwargs["resource_id"] == "ag1" + assert mocks.sync_creator_bindings.call_args.kwargs["account_id"] == "c1" + assert "1 agent(s) changed, 0 already initialised" in result.output + + assert _write_order(mocks) == ["seed_members", "seed_members", "sync_creator", "replace_whitelist"] + + +def test_agent_bootstrap_is_idempotent_on_a_second_apply() -> None: + result, mocks = _run_agent_phase( + ["--apply"], + _AgentPhaseSetup( + agents=[("ag1", "c1", None), ("ag2", "c2", None)], + configured_agent_ids=["ag1", "ag2"], + ), + ) + + assert result.exit_code == 0, result.output + events = _events(result.output) + assert [e["event"] for e in events] == ["agent_access_bootstrap_skipped"] * 2 + assert {e["reason"] for e in events} == {"already_initialized"} + mocks.replace_whitelist.assert_not_called() + mocks.sync_creator_bindings.assert_not_called() + mocks.replace_user_access_policies.assert_not_called() + assert "0 agent(s) changed, 2 already initialised" in result.output 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 f39a8e8a3c9..17397b0076b 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 @@ -2141,14 +2141,24 @@ def test_agent_chat_message_routes_resolve_app_from_agent_id( monkeypatch.setattr(message_controller, "_get_message_suggested_questions", get_message_suggested_questions) monkeypatch.setattr(message_controller, "_get_message_detail", get_message_detail) assert unwrap(AgentChatMessageListApi.get)( - AgentChatMessageListApi(), unbound_session, "tenant-1", current_user, agent_id + AgentChatMessageListApi(), + message_controller.ChatMessagesQuery(conversation_id="00000000-0000-0000-0000-000000000010"), + unbound_session, + "tenant-1", + current_user, + agent_id, ) == {"data": []} list_call = cast(dict[str, object], captured["list"]) assert list_call["session"] is unbound_session assert list_call["app_model"] is app_model with app.test_request_context(json={"message_id": message_id, "rating": "like"}): assert unwrap(AgentMessageFeedbackApi.post)( - AgentMessageFeedbackApi(), unbound_session, "tenant-1", current_user, agent_id + AgentMessageFeedbackApi(), + message_controller.MessageFeedbackPayload(message_id=message_id, rating="like"), + unbound_session, + "tenant-1", + current_user, + agent_id, ) == {"result": "success"} feedback_call = cast(dict[str, object], captured["feedback"]) assert feedback_call["session"] is unbound_session @@ -2221,7 +2231,13 @@ def test_list_chat_messages_supports_first_id_pagination( f"/console/api/agent/agent-1/chat-messages?conversation_id={conversation_id}&first_id={first_message_id}&limit=1" ): result = message_controller._list_chat_messages( - session=sqlite_session, app_model=_app_detail_obj(id=app_id, mode=AppMode.CHAT) + args=message_controller.ChatMessagesQuery( + conversation_id=conversation_id, + first_id=first_message_id, + limit=1, + ), + session=sqlite_session, + app_model=_app_detail_obj(id=app_id, mode=AppMode.CHAT), ) assert result == {"data": [older_message_id], "limit": 1, "has_more": True} @@ -2263,7 +2279,10 @@ def test_list_agent_chat_messages_uses_current_user_conversation( monkeypatch.setattr(message_controller, "MessageInfiniteScrollPaginationResponse", FakeMessagePaginationResponse) with app.test_request_context(f"/console/api/agent/agent-1/chat-messages?conversation_id={conversation_id}"): result = message_controller._list_chat_messages( - session=sqlite_session, app_model=app_model, current_user=current_user + args=message_controller.ChatMessagesQuery(conversation_id=conversation_id), + session=sqlite_session, + app_model=app_model, + current_user=current_user, ) assert result == {"data": [message_id], "limit": 20, "has_more": False} assert captured.pop("session") is sqlite_session @@ -2282,6 +2301,7 @@ def test_list_agent_chat_messages_rejects_foreign_conversation( with app.test_request_context(f"/console/api/agent/agent-1/chat-messages?conversation_id={conversation_id}"): with pytest.raises(NotFound): message_controller._list_chat_messages( + args=message_controller.ChatMessagesQuery(conversation_id=conversation_id), session=unbound_session, app_model=_app_detail_obj(id="app-1", mode=AppMode.AGENT), current_user=_account(), @@ -2303,6 +2323,7 @@ def test_update_message_feedback_rejects_empty_rating_without_existing_feedback( with app.test_request_context(json={"message_id": message_id, "rating": None}): with pytest.raises(ValueError, match="rating cannot be None"): message_controller._update_message_feedback( + args=message_controller.MessageFeedbackPayload(message_id=message_id, rating=None), session=sqlite_session, current_user=_account(), app_model=_app_detail_obj(id=app_id), diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py index ae0f807a715..0ce728baef9 100644 --- a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py +++ b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py @@ -1,6 +1,6 @@ from __future__ import annotations -from inspect import getclosurevars, unwrap +from inspect import unwrap from types import FunctionType, SimpleNamespace import pytest @@ -11,6 +11,7 @@ from controllers.console import agent_app_sandbox as module from models.account import Account from models.model import App, AppMode, IconType from services.agent_app_sandbox_service import AgentSandboxDownload, AgentSandboxInfo, AgentSandboxInspectorError +from tests.unit_tests.controllers.rbac_introspection import rbac_checks class _AgentAppService: @@ -155,12 +156,10 @@ def _account() -> Account: ], ) def test_sandbox_resources_require_app_view_layout(method: FunctionType) -> None: - rbac_wrapper = unwrap(method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname) - config = getclosurevars(rbac_wrapper).nonlocals + [check] = rbac_checks(method) - assert config["resource_type"] == module.RBACResourceScope.APP - assert config["scene"] == module.RBACPermission.APP_VIEW_LAYOUT - assert config["resource_required"] is True + assert isinstance(check.locator, module.PlainApp) + assert check.scene == module.RBACPermission.APP_VIEW_LAYOUT def test_handle_maps_sandbox_and_agent_backend_errors() -> None: diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_manage_guard.py b/api/tests/unit_tests/controllers/console/app/test_agent_manage_guard.py deleted file mode 100644 index 707b11a3f97..00000000000 --- a/api/tests/unit_tests/controllers/console/app/test_agent_manage_guard.py +++ /dev/null @@ -1,186 +0,0 @@ -from unittest.mock import patch - -import pytest -from sqlalchemy.orm import Session, scoped_session, sessionmaker -from werkzeug.exceptions import Forbidden - -from controllers.console.app.error import AppNotFoundError -from controllers.console.app.wraps import agent_manage_required_for_agent_app -from core.rbac import RBACPermission, RBACResourceScope -from models import Account -from models.agent import Agent, AgentScope, AgentSource, AgentStatus -from models.model import App, AppMode -from tests.unit_tests.config_override import config_overrides_context - -TENANT_ID = "tenant-1" - - -def _guarded_view(): - calls: list[dict[str, object]] = [] - - @agent_manage_required_for_agent_app - def view(*args, **kwargs): - calls.append(kwargs) - return "ok" - - return view, calls - - -def _persist_app( - session: Session, - *, - scope: AgentScope | None = None, - status: AgentStatus = AgentStatus.ACTIVE, -) -> App: - app_model = App( - id="app-1", - tenant_id=TENANT_ID, - name="Managed App", - mode=AppMode.AGENT if scope is not None else AppMode.CHAT, - enable_site=True, - enable_api=False, - ) - session.add(app_model) - if scope is not None: - agent = Agent( - tenant_id=TENANT_ID, - name=f"{scope.value} agent", - scope=scope, - source=AgentSource.AGENT_APP if scope == AgentScope.ROSTER else AgentSource.WORKFLOW, - status=status, - app_id=app_model.id if scope == AgentScope.ROSTER else None, - backing_app_id=app_model.id if scope == AgentScope.WORKFLOW_ONLY else None, - ) - session.add(agent) - session.commit() - return app_model - - -def _patch_guard(account: Account, rbac_enabled: bool): - return ( - patch("controllers.console.app.wraps.current_account_with_tenant", return_value=(account, TENANT_ID)), - config_overrides_context(RBAC_ENABLED=rbac_enabled), - ) - - -class TestAgentManageRequiredForAgentApp: - @pytest.fixture(autouse=True) - def _bind_database( - self, - sqlite_session: Session, - sqlite_session_factory: sessionmaker[Session], - ): - self.sqlite_session = sqlite_session - self.account = Account(name="Guard User", email="guard@example.com") - self.account.id = "account-1" - session_proxy = scoped_session(sqlite_session_factory) - with patch("controllers.console.app.wraps.db.session", session_proxy): - yield - session_proxy.remove() - - def test_non_agent_app_passes_through_without_workspace_check(self): - view, calls = _guarded_view() - _persist_app(self.sqlite_session) - patches = _patch_guard(self.account, rbac_enabled=True) - - with patches[0], patches[1], patch("controllers.console.app.wraps.enforce_rbac_access") as gate: - assert view(app_id="app-1") == "ok" - - gate.assert_not_called() - assert calls == [{"app_id": "app-1"}] - - def test_roster_agent_app_requires_agent_manage_when_rbac_enabled(self): - view, _ = _guarded_view() - _persist_app(self.sqlite_session, scope=AgentScope.ROSTER) - patches = _patch_guard(self.account, rbac_enabled=True) - - with patches[0], patches[1], patch("controllers.console.app.wraps.enforce_rbac_access") as gate: - assert view(app_id="app-1") == "ok" - - gate.assert_called_once_with( - tenant_id=TENANT_ID, - account_id=self.account.id, - resource_type=RBACResourceScope.WORKSPACE, - scene=RBACPermission.AGENT_MANAGE, - resource_required=False, - ) - - def test_roster_agent_app_denied_without_agent_manage(self): - view, calls = _guarded_view() - _persist_app(self.sqlite_session, scope=AgentScope.ROSTER) - patches = _patch_guard(self.account, rbac_enabled=True) - - with ( - patches[0], - patches[1], - patch("controllers.console.app.wraps.enforce_rbac_access", side_effect=Forbidden()), - ): - with pytest.raises(Forbidden): - view(app_id="app-1") - - assert calls == [] - - def test_roster_agent_app_skips_workspace_check_when_rbac_disabled(self): - view, _ = _guarded_view() - _persist_app(self.sqlite_session, scope=AgentScope.ROSTER) - patches = _patch_guard(self.account, rbac_enabled=False) - - with patches[0], patches[1], patch("controllers.console.app.wraps.enforce_rbac_access") as gate: - assert view(app_id="app-1") == "ok" - - gate.assert_not_called() - - def test_hidden_backing_app_is_rejected_even_without_rbac(self): - """A workflow-only backing App is not part of the general app management plane.""" - view, calls = _guarded_view() - _persist_app(self.sqlite_session, scope=AgentScope.WORKFLOW_ONLY) - patches = _patch_guard(self.account, rbac_enabled=False) - - with patches[0], patches[1]: - with pytest.raises(AppNotFoundError): - view(app_id="app-1") - - assert calls == [] - - def test_hidden_backing_app_is_rejected_before_workspace_check(self): - view, calls = _guarded_view() - _persist_app(self.sqlite_session, scope=AgentScope.WORKFLOW_ONLY) - patches = _patch_guard(self.account, rbac_enabled=True) - - with patches[0], patches[1], patch("controllers.console.app.wraps.enforce_rbac_access") as gate: - with pytest.raises(AppNotFoundError): - view(app_id="app-1") - - gate.assert_not_called() - assert calls == [] - - def test_binding_lookup_covers_archived_agents(self): - """An Agent App stays gated after its roster Agent is archived.""" - view, _ = _guarded_view() - _persist_app(self.sqlite_session, scope=AgentScope.ROSTER, status=AgentStatus.ARCHIVED) - patches = _patch_guard(self.account, rbac_enabled=True) - - with patches[0], patches[1], patch("controllers.console.app.wraps.enforce_rbac_access") as gate: - view(app_id="app-1") - - gate.assert_called_once() - - def test_resource_id_path_alias_is_resolved(self): - view, _ = _guarded_view() - _persist_app(self.sqlite_session, scope=AgentScope.ROSTER) - patches = _patch_guard(self.account, rbac_enabled=True) - - with patches[0], patches[1], patch("controllers.console.app.wraps.enforce_rbac_access") as gate: - assert view(resource_id="app-1") == "ok" - - gate.assert_called_once() - - def test_unknown_app_passes_through_for_downstream_handling(self): - view, calls = _guarded_view() - patches = _patch_guard(self.account, rbac_enabled=True) - - with patches[0], patches[1], patch("controllers.console.app.wraps.enforce_rbac_access") as gate: - assert view(app_id="app-1") == "ok" - - gate.assert_not_called() - assert calls == [{"app_id": "app-1"}] diff --git a/api/tests/unit_tests/controllers/console/app/test_annotation_security.py b/api/tests/unit_tests/controllers/console/app/test_annotation_security.py index 273cfbb8417..0aa896337e3 100644 --- a/api/tests/unit_tests/controllers/console/app/test_annotation_security.py +++ b/api/tests/unit_tests/controllers/console/app/test_annotation_security.py @@ -15,10 +15,12 @@ from werkzeug.datastructures import FileStorage from configs import dify_config from controllers.console.wraps import annotation_import_concurrency_limit, annotation_import_rate_limit +from enums import DeploymentEdition from models.account import Account from models.model import App, AppMode, IconType from services.annotation_service import AppAnnotationService from tasks.annotation.batch_import_annotations_task import batch_import_annotations_task +from tests.unit_tests.config_override import config_overrides_context def _account() -> Account: @@ -212,6 +214,7 @@ class TestAnnotationImportFileValidation: class TestAnnotationImportServiceValidation: """Test service layer validation for annotation import.""" + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_max_records_limit_enforced(self, sqlite_session: Session): """Test that files with too many records are rejected.""" @@ -228,8 +231,6 @@ class TestAnnotationImportServiceValidation: mock_auth.return_value = (_account(), "tenant_id") with patch("services.annotation_service.FeatureService") as mock_features: - mock_features.get_features.return_value.billing.enabled = False - result = AppAnnotationService.batch_import_app_annotations("app_id", file, sqlite_session) # Should return error about too many records @@ -273,6 +274,7 @@ class TestAnnotationImportServiceValidation: assert "error_msg" in result assert "malformed" in result["error_msg"].lower() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_valid_import_succeeds(self, sqlite_session: Session): """Test that valid import request succeeds.""" @@ -286,8 +288,6 @@ class TestAnnotationImportServiceValidation: mock_auth.return_value = (_account(), "tenant_id") with patch("services.annotation_service.FeatureService") as mock_features: - mock_features.get_features.return_value.billing.enabled = False - with patch("services.annotation_service.batch_import_annotations_task") as mock_task: with patch("services.annotation_service.redis_client"): result = AppAnnotationService.batch_import_app_annotations("app_id", file, sqlite_session) diff --git a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py b/api/tests/unit_tests/controllers/console/app/test_app_import_api.py index c2d6a756062..96739b27060 100644 --- a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py +++ b/api/tests/unit_tests/controllers/console/app/test_app_import_api.py @@ -343,7 +343,8 @@ class TestAppImportConfirmApi: ) redis_get = MagicMock( return_value=( - b'{"import_mode":"yaml-content","yaml_content":"app: {}","app_id":null,' + b'{"tenant_id":"tenant-1","account_id":"u1","import_mode":"yaml-content",' + b'"yaml_content":"app: {}","app_id":null,' b'"name":null,"description":null,"icon_type":null,"icon":null,"icon_background":null}' ) ) @@ -388,7 +389,8 @@ class TestAppImportConfirmApi: app_import_module.redis_client, "get", lambda *_args, **_kwargs: ( - b'{"import_mode":"yaml-content","yaml_content":"app: {}","app_id":"existing-app",' + b'{"tenant_id":"tenant-1","account_id":"u1","import_mode":"yaml-content",' + b'"yaml_content":"app: {}","app_id":"existing-app",' b'"name":null,"description":null,"icon_type":null,"icon":null,"icon_background":null}' ), ) diff --git a/api/tests/unit_tests/controllers/console/app/test_audio.py b/api/tests/unit_tests/controllers/console/app/test_audio.py index e9f01b00c48..1f8633923be 100644 --- a/api/tests/unit_tests/controllers/console/app/test_audio.py +++ b/api/tests/unit_tests/controllers/console/app/test_audio.py @@ -111,11 +111,11 @@ def test_agent_console_audio_api_uses_agent_draft( calls["asr"] = kwargs return {"text": "agent transcript"} - def enforce_rbac_access(**kwargs): + def enforce_rbac_checks(**kwargs): calls["rbac"] = kwargs monkeypatch.setattr(audio_module, "resolve_agent_runtime_app_model", resolve_agent_runtime_app_model) - monkeypatch.setattr(audio_module, "enforce_rbac_access", enforce_rbac_access) + monkeypatch.setattr(audio_module, "enforce_rbac_checks", enforce_rbac_checks) monkeypatch.setattr(AgentComposerService, "load_agent_soul_for_debug", load_agent_soul_for_debug) monkeypatch.setattr(AudioService, "transcript_agent_asr", transcript_agent_asr) @@ -138,13 +138,13 @@ def test_agent_console_audio_api_uses_agent_draft( assert response == {"text": "agent transcript"} assert calls["resolver"] == {"session": session, "tenant_id": "tenant-1", "agent_id": agent_id} - assert calls["rbac"] == { - "tenant_id": "tenant-1", - "account_id": "account-1", - "resource_type": audio_module.RBACResourceScope.APP, - "scene": audio_module.RBACPermission.APP_TEST_AND_RUN, - "path_args": {"app_id": "backing-app-1"}, - } + rbac_call = calls["rbac"] + assert rbac_call["tenant_id"] == "tenant-1" + assert rbac_call["account_id"] == "account-1" + assert rbac_call["path_args"] == {"app_id": "backing-app-1"} + (rbac_check,) = rbac_call["checks"] + assert rbac_check.scene is audio_module.RBACPermission.APP_TEST_AND_RUN + assert isinstance(rbac_check.locator, audio_module.PlainApp) assert calls["draft"] == { "tenant_id": "tenant-1", "agent_id": str(agent_id), @@ -216,7 +216,7 @@ def test_agent_console_audio_api_checks_rbac_with_backing_app_id( soul_loaded = True return AgentSoulConfig() - monkeypatch.setattr(audio_module, "enforce_rbac_access", deny_access) + monkeypatch.setattr(audio_module, "enforce_rbac_checks", deny_access) monkeypatch.setattr(AgentComposerService, "load_agent_soul_for_debug", load_agent_soul_for_debug) api = AgentChatMessageAudioApi() diff --git a/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py b/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py index 5e5762f9260..5db0cbe2a4c 100644 --- a/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py +++ b/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py @@ -315,19 +315,20 @@ class TestAppMCPServerRefreshController: "controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-1"), ), + patch("controllers.common.rbac.locators.agent_binding", return_value=None), + patch("controllers.common.rbac.locators.PlainApp.owner_id", return_value=None), patch( - "controllers.common.wraps.enforce_rbac_access", + "controllers.common.rbac.checks.RBACService.CheckAccess.check", side_effect=PermissionCheckedError, - ) as enforce_rbac_access, + ) as check_access, pytest.raises(PermissionCheckedError), ): method(AppMCPServerRefreshController(), app_id="app-1") - enforce_rbac_access.assert_called_once_with( - tenant_id="tenant-1", - account_id="account-1", - resource_type=RBACResourceScope.APP, + check_access.assert_called_once_with( + "tenant-1", + "account-1", scene=RBACPermission.APP_EDIT, - resource_required=True, - path_args={"app_id": "app-1"}, + resource_type=RBACResourceScope.APP, + resource_id="app-1", ) diff --git a/api/tests/unit_tests/controllers/console/app/test_message_api.py b/api/tests/unit_tests/controllers/console/app/test_message_api.py index ae6e994b6d5..bc797ef75e5 100644 --- a/api/tests/unit_tests/controllers/console/app/test_message_api.py +++ b/api/tests/unit_tests/controllers/console/app/test_message_api.py @@ -81,10 +81,18 @@ def test_app_message_routes_pass_injected_session( monkeypatch.setattr(message_module, "_get_message_detail", get_message_detail) assert unwrap(message_module.ChatMessageListApi.get)( - message_module.ChatMessageListApi(), session, current_user, app_model + message_module.ChatMessageListApi(), + message_module.ChatMessagesQuery(conversation_id="550e8400-e29b-41d4-a716-446655440001"), + session, + current_user, + app_model, ) == {"data": []} assert unwrap(message_module.MessageFeedbackApi.post)( - message_module.MessageFeedbackApi(), session, current_user, app_model + message_module.MessageFeedbackApi(), + message_module.MessageFeedbackPayload(message_id=message_id, rating="like"), + session, + current_user, + app_model, ) == {"result": "success"} assert unwrap(message_module.MessageSuggestedQuestionApi.get)( message_module.MessageSuggestedQuestionApi(), session, current_user, app_model, message_id @@ -111,6 +119,11 @@ def test_update_message_feedback_commits_injected_session(app: Flask, sqlite_ses with app.test_request_context(json={"message_id": message_id, "rating": "like", "content": "helpful"}): result = message_module._update_message_feedback( + args=message_module.MessageFeedbackPayload( + message_id=message_id, + rating="like", + content="helpful", + ), session=session, current_user=SimpleNamespace(id="account-1"), app_model=SimpleNamespace(id="app-1"), diff --git a/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py b/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py index 03922de106d..25f94e9aa67 100644 --- a/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py +++ b/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py @@ -11,6 +11,7 @@ import pytest from flask import Flask from werkzeug.exceptions import Forbidden +from controllers.common.rbac import PlainApp from controllers.console import flask_admission from controllers.console.app import ops_trace as ops_trace_module from controllers.console.app.error import ( @@ -138,19 +139,19 @@ def test_trace_config_mutations_require_app_tracing_permission_when_rbac_is_enab lambda: AccountWithTenant(account=account, tenant_id=WORKSPACE_ID), ) denied = MagicMock(side_effect=Forbidden()) - monkeypatch.setattr(flask_admission, "enforce_rbac_access", denied) + monkeypatch.setattr(flask_admission, "enforce_rbac_checks", denied) with app.test_request_context(), pytest.raises(Forbidden): _admission_injector(method)(None, app_id=UUID(APP_ID)) - denied.assert_called_once_with( - tenant_id=WORKSPACE_ID, - account_id=ACCOUNT_ID, - resource_type=ops_trace_module.RBACResourceScope.APP, - scene=ops_trace_module.RBACPermission.APP_TRACING_CONFIG, - resource_required=True, - path_args={"app_id": UUID(APP_ID)}, - ) + denied.assert_called_once() + call = denied.call_args.kwargs + assert call["tenant_id"] == WORKSPACE_ID + assert call["account_id"] == ACCOUNT_ID + assert call["path_args"] == {"app_id": UUID(APP_ID)} + (check,) = call["checks"] + assert check.scene == ops_trace_module.RBACPermission.APP_TRACING_CONFIG + assert isinstance(check.locator, PlainApp) def test_trace_config_get_preserves_read_access_for_normal_member() -> None: diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py index f3b0cb25953..5ef83ea902f 100644 --- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py +++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Iterator -from inspect import getclosurevars, unwrap +from inspect import unwrap from unittest.mock import ANY, PropertyMock, patch import pytest @@ -28,6 +28,7 @@ from services.entities.knowledge_entities.rag_pipeline_entities import PipelineT from services.errors.account import NoPermissionError from services.errors.rag_pipeline import RagPipelineResourceNotFoundError from tests.unit_tests.config_override import config_overrides_context +from tests.unit_tests.controllers.rbac_introspection import rbac_checks def _template_item() -> dict[str, object]: @@ -362,11 +363,8 @@ class TestCustomizedPipelineTemplateApi: class TestPublishCustomizedPipelineTemplateApi: def test_post_uses_pipeline_release_rbac_scene(self) -> None: - method = PublishCustomizedPipelineTemplateApi.post - while "scene" not in getclosurevars(method).nonlocals: - method = method.__wrapped__ - - assert getclosurevars(method).nonlocals["scene"] == module.RBACPermission.DATASET_PIPELINE_RELEASE + [check] = rbac_checks(PublishCustomizedPipelineTemplateApi.post) + assert check.scene == module.RBACPermission.DATASET_PIPELINE_RELEASE def test_post_validates_payload_and_returns_empty_204(self) -> None: api = PublishCustomizedPipelineTemplateApi() diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py index b2afb14d252..581adaafe37 100644 --- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py +++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py @@ -1,5 +1,5 @@ from collections.abc import Callable, Iterator -from inspect import getclosurevars, unwrap +from inspect import unwrap from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -9,6 +9,7 @@ from sqlalchemy import Engine from sqlalchemy.orm import Session, scoped_session, sessionmaker from controllers.common.errors import InvalidArgumentError, NotFoundError +from controllers.common.rbac import RBACResourceScope from controllers.console import console_ns from controllers.console.app.error import DraftWorkflowNotExist from controllers.console.datasets.rag_pipeline.rag_pipeline_draft_variable import ( @@ -21,7 +22,7 @@ from controllers.console.datasets.rag_pipeline.rag_pipeline_draft_variable impor RagPipelineVariableResetApi, WorkflowDraftVariablePatchPayload, ) -from controllers.console.wraps import RBACPermission, RBACResourceScope +from controllers.console.wraps import RBACPermission from core.workflow.llm_environment_variable import LLMEnvironmentVariable from core.workflow.variable_prefixes import SYSTEM_VARIABLE_NODE_ID from factories.variable_factory import build_segment @@ -30,6 +31,7 @@ from graphon.variables import IntegerVariable, StringVariable from models.account import Account, TenantAccountRole from models.dataset import Pipeline from models.workflow import Workflow, WorkflowDraftVariable, WorkflowType +from tests.unit_tests.controllers.rbac_introspection import rbac_checks @pytest.fixture @@ -102,12 +104,11 @@ def restx_config(app): def test_rag_draft_variable_routes_require_dataset_edit_permission() -> None: route = RagPipelineVariableApi.get legacy_gate = unwrap(route, stop=lambda decorator: "edit_permission_required" in decorator.__code__.co_qualname) - rbac_gate = unwrap(route, stop=lambda decorator: "scene" in getclosurevars(decorator).nonlocals) - assert "edit_permission_required" in legacy_gate.__code__.co_qualname - permissions = getclosurevars(rbac_gate).nonlocals - assert permissions["resource_type"] == RBACResourceScope.DATASET - assert permissions["scene"] == RBACPermission.DATASET_EDIT + + [check] = rbac_checks(route) + assert check.locator.scope == RBACResourceScope.DATASET + assert check.scene == RBACPermission.DATASET_EDIT class TestRagPipelineVariableCollectionApi: diff --git a/api/tests/unit_tests/controllers/console/tag/test_tags.py b/api/tests/unit_tests/controllers/console/tag/test_tags.py index 5d19e08a557..d40b84bd4dd 100644 --- a/api/tests/unit_tests/controllers/console/tag/test_tags.py +++ b/api/tests/unit_tests/controllers/console/tag/test_tags.py @@ -166,7 +166,7 @@ class TestTagListApi: app.test_request_context("/"), config_overrides_context(RBAC_ENABLED=True), patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")), - patch.object(module, "enforce_rbac_access") as enforce_rbac_access, + patch.object(module, "enforce_rbac_checks") as enforce_rbac_checks, ): unwrap(TagListApi().post)( TagListApi(), @@ -174,13 +174,13 @@ class TestTagListApi: request_context, ) - enforce_rbac_access.assert_called_once_with( - tenant_id="tenant-1", - account_id="user-1", - resource_type=module.RBACResourceScope.WORKSPACE, - scene=module.RBACPermission.SNIPPETS_CREATE_AND_MODIFY, - resource_required=False, - ) + enforce_rbac_checks.assert_called_once() + rbac_kwargs = enforce_rbac_checks.call_args.kwargs + assert rbac_kwargs["tenant_id"] == "tenant-1" + assert rbac_kwargs["account_id"] == "user-1" + (rbac_check,) = rbac_kwargs["checks"] + assert rbac_check.scene is module.RBACPermission.SNIPPETS_CREATE_AND_MODIFY + assert isinstance(rbac_check.locator, module.Workspace) def test_post_rejects_read_only_member(self, app: Flask, request_context: RequestContext) -> None: readonly = _account(TenantAccountRole.NORMAL) @@ -249,7 +249,7 @@ class TestTagUpdateDeleteApi: app.test_request_context("/"), config_overrides_context(RBAC_ENABLED=True), patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")), - patch.object(module, "enforce_rbac_access") as enforce_rbac_access, + patch.object(module, "enforce_rbac_checks") as enforce_rbac_checks, ): result, status = unwrap(TagUpdateDeleteApi().patch)( TagUpdateDeleteApi(), @@ -258,13 +258,13 @@ class TestTagUpdateDeleteApi: "tag-1", ) - enforce_rbac_access.assert_called_once_with( - tenant_id="tenant-1", - account_id="user-1", - resource_type=module.RBACResourceScope.WORKSPACE, - scene=module.RBACPermission.SNIPPETS_CREATE_AND_MODIFY, - resource_required=False, - ) + enforce_rbac_checks.assert_called_once() + rbac_kwargs = enforce_rbac_checks.call_args.kwargs + assert rbac_kwargs["tenant_id"] == "tenant-1" + assert rbac_kwargs["account_id"] == "user-1" + (rbac_check,) = rbac_kwargs["checks"] + assert rbac_check.scene is module.RBACPermission.SNIPPETS_CREATE_AND_MODIFY + assert isinstance(rbac_check.locator, module.Workspace) tags_service.update_tag.assert_called_once_with(request_context, "tag-1", UpdateTagInput(name="Updated")) assert status == 200 assert result["binding_count"] == "3" @@ -345,12 +345,12 @@ class TestTagUpdateDeleteApi: app.test_request_context("/"), config_overrides_context(RBAC_ENABLED=True), patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")), - patch.object(module, "enforce_rbac_access") as enforce_rbac_access, + patch.object(module, "enforce_rbac_checks") as enforce_rbac_checks, ): unwrap(TagUpdateDeleteApi().delete)(TagUpdateDeleteApi(), request_context, "tag-1") tags_service.get_tag_type.assert_called_once_with(request_context, "tag-1") - enforce_rbac_access.assert_called_once() + enforce_rbac_checks.assert_called_once() def test_delete_does_not_authorize_tag_outside_current_workspace( self, app: Flask, request_context: RequestContext, tags_service: MagicMock @@ -363,12 +363,12 @@ class TestTagUpdateDeleteApi: app.test_request_context("/"), config_overrides_context(RBAC_ENABLED=True), patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")), - patch.object(module, "enforce_rbac_access") as enforce_rbac_access, + patch.object(module, "enforce_rbac_checks") as enforce_rbac_checks, ): with pytest.raises(NotFound): unwrap(TagUpdateDeleteApi().delete)(TagUpdateDeleteApi(), request_context, "tag-1") - enforce_rbac_access.assert_not_called() + enforce_rbac_checks.assert_not_called() class TestTagBindings: diff --git a/api/tests/unit_tests/controllers/console/test_apikey.py b/api/tests/unit_tests/controllers/console/test_apikey.py index 8955ddf6bf7..d6ae0d4bd7f 100644 --- a/api/tests/unit_tests/controllers/console/test_apikey.py +++ b/api/tests/unit_tests/controllers/console/test_apikey.py @@ -57,9 +57,9 @@ def _make_account(role: TenantAccountRole) -> Account: return account -def _persist_app(session: Session, *, mode: AppMode = AppMode.CHAT) -> App: +def _persist_app(session: Session, *, mode: AppMode = AppMode.CHAT, app_id: str = "app-1") -> App: app = App( - id="app-1", + id=app_id, tenant_id="tenant-1", name="API key app", mode=mode, @@ -260,15 +260,23 @@ def test_api_key_lists_require_matching_rbac_permission(config_overrides: Callab cases = [ ( lambda: AppApiKeyListResource().get(resource_id=api_id), - [(RBACResourceScope.APP, RBACPermission.APP_RELEASE_AND_VERSION, True)], + { + "scene": RBACPermission.APP_RELEASE_AND_VERSION, + "resource_type": RBACResourceScope.APP, + "resource_id": str(api_id), + }, ), ( lambda: DatasetApiKeyApi().get(), - [(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE, False)], + {"scene": RBACPermission.DATASET_API_KEY_MANAGE, "resource_type": None, "resource_id": None}, ), ( lambda: DatasetApiKeyListResource().get(resource_id=api_id), - [(RBACResourceScope.DATASET, RBACPermission.DATASET_API_KEY_MANAGE, True)], + { + "scene": RBACPermission.DATASET_API_KEY_MANAGE, + "resource_type": RBACResourceScope.DATASET, + "resource_id": str(api_id), + }, ), ] @@ -276,20 +284,25 @@ def test_api_key_lists_require_matching_rbac_permission(config_overrides: Callab app.test_request_context("/"), patch("controllers.console.wraps.current_account_with_tenant", return_value=(account, "tenant-1")), patch("controllers.common.wraps.current_account_with_tenant", return_value=(account, "tenant-1")), + patch("controllers.common.rbac.locators.agent_binding", return_value=None), + patch("controllers.common.rbac.locators.PlainApp.owner_id", return_value=None), + patch("controllers.common.rbac.locators.DatasetId.owner_id", return_value=None), patch.object(BaseApiKeyListResource, "_get_api_key_list") as get_api_key_list, ): - for invoke, expected_gates in cases: + for invoke, expected_kwargs in cases: with patch( - "controllers.common.wraps.enforce_rbac_access", - side_effect=[None] * (len(expected_gates) - 1) + [Forbidden()], - ) as enforce_rbac_access: + "controllers.common.rbac.checks.RBACService.CheckAccess.check", return_value=False + ) as check_access: with pytest.raises(Forbidden): invoke() - assert [ - (kwargs["resource_type"], kwargs["scene"], kwargs["resource_required"]) - for _, kwargs in enforce_rbac_access.call_args_list - ] == expected_gates + check_access.assert_called_once_with( + "tenant-1", + account.id, + scene=expected_kwargs["scene"], + resource_type=expected_kwargs["resource_type"], + resource_id=expected_kwargs["resource_id"], + ) get_api_key_list.assert_not_called() diff --git a/api/tests/unit_tests/controllers/console/test_feature.py b/api/tests/unit_tests/controllers/console/test_feature.py index 5afc9fc1de4..04512fc3086 100644 --- a/api/tests/unit_tests/controllers/console/test_feature.py +++ b/api/tests/unit_tests/controllers/console/test_feature.py @@ -39,8 +39,11 @@ class TestFeatureApi: from controllers.console.feature import FeatureApi features = FeatureModel( - knowledge_rate_limit=42, + apps=LimitationModel(size=3, limit=10), + dify_builder_enabled=True, + skill_learning_policy="automatic", vector_space=LimitationModel(size=1, limit=2), + next_credit_reset_date=1775001600, ) feature_queries = _install_application_services(mocker) get_features = feature_queries.get_features @@ -52,9 +55,20 @@ class TestFeatureApi: request_context = _request_context() result = raw_get(api, request_context) - expected = features.model_dump() - expected.pop("vector_space") - assert result == expected + assert result == features.model_dump(mode="json") + assert result["apps"] == {"size": 3, "limit": 10} + assert result["dify_builder_enabled"] is True + retired_fields = { + "vector_space", + "next_credit_reset_date", + "docs_processing", + "knowledge_rate_limit", + "dataset_operator_enabled", + "skill_learning_policy", + } + schema = FeatureModel.model_json_schema(mode="serialization") + assert retired_fields.isdisjoint(result) + assert set(schema["properties"]) == set(schema["required"]) == set(result) get_features.assert_called_once_with(request_context) diff --git a/api/tests/unit_tests/controllers/console/test_oauth_custom_client_permissions.py b/api/tests/unit_tests/controllers/console/test_oauth_custom_client_permissions.py index 92b5ac14406..d53b4572526 100644 --- a/api/tests/unit_tests/controllers/console/test_oauth_custom_client_permissions.py +++ b/api/tests/unit_tests/controllers/console/test_oauth_custom_client_permissions.py @@ -1,28 +1,27 @@ -from inspect import getclosurevars, unwrap +from inspect import unwrap from types import FunctionType import pytest -from controllers.common.wraps import RBACPermission, RBACResourceScope +from controllers.common.rbac import RBACPermission, Workspace from controllers.console.datasets.rag_pipeline.datasource_auth import DatasourceAuthOauthCustomClient from controllers.console.workspace.tool_providers import ToolOAuthCustomClient +from tests.unit_tests.controllers.rbac_introspection import rbac_checks @pytest.mark.parametrize( - ("method", "legacy_gate", "resource_type"), + ("method", "legacy_gate"), [ - (ToolOAuthCustomClient.delete, "is_admin_or_owner_required", RBACResourceScope.WORKSPACE), - (DatasourceAuthOauthCustomClient.delete, "edit_permission_required", RBACResourceScope.DATASET), + (ToolOAuthCustomClient.delete, "is_admin_or_owner_required"), + (DatasourceAuthOauthCustomClient.delete, "edit_permission_required"), ], ) -def test_custom_oauth_client_delete_requires_management_permission( - method: FunctionType, legacy_gate: str, resource_type: RBACResourceScope -) -> None: +def test_custom_oauth_client_delete_requires_management_permission(method: FunctionType, legacy_gate: str) -> None: legacy_wrapper = unwrap(method, stop=lambda wrapper: legacy_gate in wrapper.__code__.co_qualname) assert legacy_gate in legacy_wrapper.__code__.co_qualname - rbac_wrapper = unwrap(method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname) - rbac_config = getclosurevars(rbac_wrapper).nonlocals - assert rbac_config["resource_type"] == resource_type - assert rbac_config["scene"] == RBACPermission.CREDENTIAL_MANAGE - assert rbac_config["resource_required"] is False + # Both routes pass resource_required=False, so their bundle resolves to a Workspace + # locator regardless of the resource_type they declared (see _single_check). + [check] = rbac_checks(method) + assert check.scene == RBACPermission.CREDENTIAL_MANAGE + assert isinstance(check.locator, Workspace) diff --git a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py index 0a33e67163b..6348a2f8ce9 100644 --- a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py +++ b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py @@ -128,7 +128,6 @@ def test_workflow_run_archive_endpoint_allows_admitted_role_when_rbac_is_enabled assert tenant_id == "tenant-1" assert exclude_vector_space return { - "enabled": True, "subscription": {"plan": CloudPlan.TEAM}, } diff --git a/api/tests/unit_tests/controllers/console/test_workspace_credential_mutation_permissions.py b/api/tests/unit_tests/controllers/console/test_workspace_credential_mutation_permissions.py index 9714a7cceb9..f89ccb3e765 100644 --- a/api/tests/unit_tests/controllers/console/test_workspace_credential_mutation_permissions.py +++ b/api/tests/unit_tests/controllers/console/test_workspace_credential_mutation_permissions.py @@ -1,16 +1,21 @@ -from inspect import getclosurevars, unwrap +from inspect import unwrap from types import FunctionType import pytest -from controllers.common.wraps import RBACPermission, RBACResourceScope +from controllers.common.rbac import AgentId, RBACPermission, Workspace from controllers.console.agent.composer import AgentComposerApi from controllers.console.agent.roster import AgentAppApi from controllers.console.datasets.data_source import DataSourceApi from controllers.console.datasets.rag_pipeline.datasource_auth import DatasourceAuth from controllers.console.workspace.model_providers import ModelProviderCredentialApi from controllers.console.workspace.models import ModelProviderModelCredentialApi -from controllers.console.workspace.tool_providers import ToolBuiltinProviderAddApi, ToolOAuthCustomClient +from controllers.console.workspace.tool_providers import ( + ToolBuiltinProviderAddApi, + ToolMCPDetailApi, + ToolOAuthCustomClient, +) +from tests.unit_tests.controllers.rbac_introspection import rbac_checks @pytest.mark.parametrize( @@ -27,11 +32,9 @@ def test_workspace_credential_mutations_require_management_permission( legacy_wrapper = unwrap(method, stop=lambda wrapper: "is_admin_or_owner_required" in wrapper.__code__.co_qualname) assert "is_admin_or_owner_required" in legacy_wrapper.__code__.co_qualname - rbac_wrapper = unwrap(method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname) - rbac_config = getclosurevars(rbac_wrapper).nonlocals - assert rbac_config["resource_type"] == RBACResourceScope.WORKSPACE - assert rbac_config["scene"] == permission - assert rbac_config["resource_required"] is False + [check] = rbac_checks(method) + assert check.scene == permission + assert isinstance(check.locator, Workspace) @pytest.mark.parametrize( @@ -49,11 +52,9 @@ def test_model_provider_credential_get_requires_admin_and_rbac( legacy_wrapper = unwrap(method, stop=lambda wrapper: "is_admin_or_owner_required" in wrapper.__code__.co_qualname) assert "is_admin_or_owner_required" in legacy_wrapper.__code__.co_qualname - rbac_wrapper = unwrap(method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname) - rbac_config = getclosurevars(rbac_wrapper).nonlocals - assert rbac_config["resource_type"] == RBACResourceScope.WORKSPACE - assert rbac_config["scene"] == RBACPermission.CREDENTIAL_MANAGE - assert rbac_config["resource_required"] is False + [check] = rbac_checks(method) + assert check.scene == RBACPermission.CREDENTIAL_MANAGE + assert isinstance(check.locator, Workspace) def test_tool_oauth_custom_client_get_requires_admin_and_rbac() -> None: @@ -64,11 +65,9 @@ def test_tool_oauth_custom_client_get_requires_admin_and_rbac() -> None: legacy_wrapper = unwrap(method, stop=lambda wrapper: "is_admin_or_owner_required" in wrapper.__code__.co_qualname) assert "is_admin_or_owner_required" in legacy_wrapper.__code__.co_qualname - rbac_wrapper = unwrap(method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname) - rbac_config = getclosurevars(rbac_wrapper).nonlocals - assert rbac_config["resource_type"] == RBACResourceScope.WORKSPACE - assert rbac_config["scene"] == RBACPermission.CREDENTIAL_MANAGE - assert rbac_config["resource_required"] is False + [check] = rbac_checks(method) + assert check.scene == RBACPermission.CREDENTIAL_MANAGE + assert isinstance(check.locator, Workspace) def test_datasource_auth_get_requires_edit_and_rbac() -> None: @@ -79,11 +78,9 @@ def test_datasource_auth_get_requires_edit_and_rbac() -> None: edit_wrapper = unwrap(method, stop=lambda wrapper: "edit_permission_required" in wrapper.__code__.co_qualname) assert "edit_permission_required" in edit_wrapper.__code__.co_qualname - rbac_wrapper = unwrap(method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname) - rbac_config = getclosurevars(rbac_wrapper).nonlocals - assert rbac_config["resource_type"] == RBACResourceScope.DATASET - assert rbac_config["scene"] == RBACPermission.CREDENTIAL_MANAGE - assert rbac_config["resource_required"] is False + [check] = rbac_checks(method) + assert check.scene == RBACPermission.CREDENTIAL_MANAGE + assert isinstance(check.locator, Workspace) @pytest.mark.parametrize( @@ -94,10 +91,18 @@ def test_datasource_auth_get_requires_edit_and_rbac() -> None: ], ) def test_agent_app_get_requires_rbac(method: FunctionType) -> None: - """GET endpoints that return agent app details or composer state must enforce - the same RBAC gates as their sibling PUT/DELETE methods.""" - rbac_wrapper = unwrap(method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname) - rbac_config = getclosurevars(rbac_wrapper).nonlocals - assert rbac_config["resource_type"] == RBACResourceScope.WORKSPACE - assert rbac_config["scene"] == RBACPermission.AGENT_MANAGE - assert rbac_config["resource_required"] is False + """GET endpoints that return agent app details or composer state must require + the agent preview scene on the agent resource, same as their sibling routes.""" + [check] = rbac_checks(method) + assert check.scene == RBACPermission.AGENT_PREVIEW + assert isinstance(check.locator, AgentId) + + +def test_tool_mcp_detail_get_requires_rbac() -> None: + """GET endpoint that returns MCP provider details must enforce + the workspace MCP management RBAC gate.""" + method = ToolMCPDetailApi.get + + [check] = rbac_checks(method) + assert check.scene == RBACPermission.MCP_MANAGE + assert isinstance(check.locator, Workspace) diff --git a/api/tests/unit_tests/controllers/console/test_workspace_members.py b/api/tests/unit_tests/controllers/console/test_workspace_members.py index 6557fba1107..2528b387623 100644 --- a/api/tests/unit_tests/controllers/console/test_workspace_members.py +++ b/api/tests/unit_tests/controllers/console/test_workspace_members.py @@ -29,7 +29,6 @@ def _build_feature_flags(): placeholder_quota = SimpleNamespace(limit=0, size=0) workspace_members = SimpleNamespace(enabled=False, is_available=lambda count: True) return SimpleNamespace( - billing=SimpleNamespace(enabled=False), workspace_members=workspace_members, members=placeholder_quota, apps=placeholder_quota, diff --git a/api/tests/unit_tests/controllers/console/test_wraps.py b/api/tests/unit_tests/controllers/console/test_wraps.py index aa3d966bdf7..54002f37246 100644 --- a/api/tests/unit_tests/controllers/console/test_wraps.py +++ b/api/tests/unit_tests/controllers/console/test_wraps.py @@ -4,14 +4,14 @@ from typing import override from unittest.mock import MagicMock, patch import pytest -from flask import Flask, request +from flask import Flask from flask_login import LoginManager, UserMixin from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.orm import Session from werkzeug.exceptions import HTTPException -from controllers.common.wraps import _extract_resource_id +from controllers.common.rbac import DatasetId, PlainApp, RBACCheck, Workspace from controllers.console import api as console_api from controllers.console import flask_admission from controllers.console import wraps as wraps_module @@ -41,10 +41,10 @@ from controllers.console.wraps import ( from enums import DeploymentEdition from libs.login import AccountWithTenant from machinery.context import RequestContext -from machinery.errors import ActiveWorkspaceRequiredError, AdmissionConfigurationError +from machinery.errors import ActiveWorkspaceRequiredError from models import Account, DifySetup from models.account import AccountStatus, TenantAccountRole -from models.dataset import Dataset, RateLimitLog +from models.dataset import RateLimitLog from services.entities.feature_entities import LicenseStatus from tests.unit_tests.config_override import config_overrides_context @@ -359,15 +359,13 @@ class TestCurrentContextInjection: ), patch("controllers.console.flask_admission.get_request_id", return_value="request-1"), patch("controllers.console.flask_admission.get_trace_id", return_value=None), - patch("controllers.console.flask_admission.enforce_rbac_access") as enforce_rbac_access, + patch("controllers.console.flask_admission.enforce_rbac_checks") as enforce_rbac_checks, ): class Handler: @flask_admission.console_account_admission( allowed_roles=frozenset({TenantAccountRole.ADMIN, TenantAccountRole.OWNER}), - rbac_resource_scope=RBACResourceScope.WORKSPACE, - rbac_permission=RBACPermission.CREDENTIAL_CREATE, - rbac_resource_required=False, + rbac_checks=[RBACCheck(RBACPermission.CREDENTIAL_CREATE, Workspace())], ) def post(self, request_context: RequestContext): return request_context @@ -378,18 +376,14 @@ class TestCurrentContextInjection: assert isinstance(result, RequestContext) assert result.active_workspace_id == "tenant-123" assert result.trace_id == "trace-1" - enforce_rbac_access.assert_called_once_with( - tenant_id="tenant-123", - account_id=current_user.id, - resource_type=RBACResourceScope.WORKSPACE, - scene=RBACPermission.CREDENTIAL_CREATE, - resource_required=False, - path_args={}, - ) - - def test_console_account_admission_rejects_incomplete_rbac_requirement(self): - with pytest.raises(AdmissionConfigurationError, match="configured together"): - flask_admission.console_account_admission(rbac_resource_scope=RBACResourceScope.WORKSPACE) + enforce_rbac_checks.assert_called_once() + call_kwargs = enforce_rbac_checks.call_args.kwargs + assert call_kwargs["tenant_id"] == "tenant-123" + assert call_kwargs["account_id"] == current_user.id + assert call_kwargs["path_args"] == {} + (check,) = call_kwargs["checks"] + assert check.scene is RBACPermission.CREDENTIAL_CREATE + assert isinstance(check.locator, Workspace) def test_console_account_admission_can_admit_uninitialized_accounts(self): current_user = make_account() @@ -501,67 +495,72 @@ class TestRbacPermissionRequired: def test_resource_scoped_check_uses_resource_id(self): current_user = make_account("account-1") - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_DELETE) + @rbac_permission_required(RBACCheck(RBACPermission.APP_DELETE, PlainApp())) def protected_view(**kwargs): return "ok" with ( - patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-1")), - patch("controllers.common.wraps._extract_resource_id", return_value="app-123") as mock_extract, - patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=False) as mock_owned, - patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=True) as mock_check, + Flask(__name__).test_request_context("/"), + patch( + "controllers.common.wraps.current_account_with_tenant", + return_value=(current_user, "tenant-1"), + ), + patch("controllers.common.rbac.locators.agent_binding", return_value=None) as mock_binding, + patch("controllers.common.rbac.locators.PlainApp.owner_id", return_value=None) as mock_owner, + patch("controllers.common.rbac.checks.RBACService.CheckAccess.check", return_value=True) as mock_check, ): assert protected_view(app_id="app-123") == "ok" - mock_extract.assert_called_once_with(RBACResourceScope.APP, "tenant-1", {"app_id": "app-123"}) - mock_owned.assert_called_once_with("tenant-1", "account-1", "app", "app-123") + mock_binding.assert_called_once_with("tenant-1", "app-123") + mock_owner.assert_called_once() mock_check.assert_called_once_with( "tenant-1", "account-1", - scene="app_delete", - resource_type="app", + scene=RBACPermission.APP_DELETE, + resource_type=RBACResourceScope.APP, resource_id="app-123", ) def test_workspace_scoped_check_skips_resource_id_extraction(self): current_user = make_account("account-2") - @rbac_permission_required( - RBACResourceScope.DATASET, RBACPermission.DATASET_CREATE_AND_MANAGEMENT, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_CREATE_AND_MANAGEMENT, Workspace())) def protected_view(): return "ok" with ( - patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-2")), - patch("controllers.common.wraps._extract_resource_id") as mock_extract, - patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=False) as mock_owned, - patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=True) as mock_check, + Flask(__name__).test_request_context("/"), + patch( + "controllers.common.wraps.current_account_with_tenant", + return_value=(current_user, "tenant-2"), + ), + patch("controllers.common.rbac.locators.DatasetId.owner_id") as mock_owner, + patch("controllers.common.rbac.checks.RBACService.CheckAccess.check", return_value=True) as mock_check, ): assert protected_view() == "ok" - mock_extract.assert_not_called() - mock_owned.assert_not_called() + mock_owner.assert_not_called() mock_check.assert_called_once_with( "tenant-2", "account-2", - scene="dataset_create_and_management", - resource_type="dataset", + scene=RBACPermission.DATASET_CREATE_AND_MANAGEMENT, + resource_type=None, resource_id=None, ) def test_workspace_scene_omits_resource_type(self): current_user = make_account("account-3") - @rbac_permission_required( - RBACResourceScope.WORKSPACE, RBACPermission.WORKSPACE_ROLE_MANAGE, resource_required=False - ) + @rbac_permission_required(RBACCheck(RBACPermission.WORKSPACE_ROLE_MANAGE, Workspace())) def protected_view(): return "ok" with ( - patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-3")), - patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=True) as mock_check, + patch( + "controllers.common.wraps.current_account_with_tenant", + return_value=(current_user, "tenant-3"), + ), + patch("controllers.common.rbac.checks.RBACService.CheckAccess.check", return_value=True) as mock_check, ): assert protected_view() == "ok" @@ -576,137 +575,46 @@ class TestRbacPermissionRequired: def test_resource_owned_app_skips_rbac_check(self): current_user = make_account("account-4") - @rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_DELETE) + @rbac_permission_required(RBACCheck(RBACPermission.APP_DELETE, PlainApp())) def protected_view(**kwargs): return "ok" with ( - patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-4")), - patch("controllers.common.wraps._extract_resource_id", return_value="app-123"), - patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=True) as mock_owned, - patch("controllers.common.wraps.RBACService.CheckAccess.check") as mock_check, + Flask(__name__).test_request_context("/"), + patch( + "controllers.common.wraps.current_account_with_tenant", + return_value=(current_user, "tenant-4"), + ), + patch("controllers.common.rbac.locators.agent_binding", return_value=None), + patch("controllers.common.rbac.locators.PlainApp.owner_id", return_value="account-4") as mock_owner, + patch("controllers.common.rbac.checks.RBACService.CheckAccess.check") as mock_check, ): assert protected_view(app_id="app-123") == "ok" - mock_owned.assert_called_once_with("tenant-4", "account-4", "app", "app-123") + mock_owner.assert_called_once() mock_check.assert_not_called() def test_resource_owned_dataset_skips_rbac_check(self): current_user = make_account("account-5") - @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT) + @rbac_permission_required(RBACCheck(RBACPermission.DATASET_EDIT, DatasetId())) def protected_view(**kwargs): return "ok" with ( - patch("controllers.common.wraps.current_account_with_tenant", return_value=(current_user, "tenant-5")), - patch("controllers.common.wraps._extract_resource_id", return_value="dataset-123"), - patch("controllers.common.wraps._is_resource_owned_by_current_user", return_value=True) as mock_owned, - patch("controllers.common.wraps.RBACService.CheckAccess.check") as mock_check, + Flask(__name__).test_request_context("/"), + patch( + "controllers.common.wraps.current_account_with_tenant", + return_value=(current_user, "tenant-5"), + ), + patch("controllers.common.rbac.locators.DatasetId.owner_id", return_value="account-5") as mock_owner, + patch("controllers.common.rbac.checks.RBACService.CheckAccess.check") as mock_check, ): assert protected_view(dataset_id="dataset-123") == "ok" - mock_owned.assert_called_once_with("tenant-5", "account-5", "dataset", "dataset-123") + mock_owner.assert_called_once() mock_check.assert_not_called() - def test_extract_resource_id_prefers_path_args(self): - app = Flask(__name__) - - with app.test_request_context("/"): - request.view_args = {"app_id": "view-app"} - - assert _extract_resource_id("app", "tenant-1", {"app_id": "path-app"}) == "path-app" - - def test_extract_resource_id_falls_back_to_request_view_args(self): - app = Flask(__name__) - - with app.test_request_context("/"): - request.view_args = {"app_id": "view-app"} - - assert _extract_resource_id("app", "tenant-1") == "view-app" - - def test_extract_resource_id_supports_legacy_route_aliases(self): - app = Flask(__name__) - - with app.test_request_context("/apps/app-1/api-keys"): - request.view_args = {"resource_id": "app-1"} - assert _extract_resource_id(RBACResourceScope.APP, "tenant-1") == "app-1" - - with app.test_request_context("/datasets/dataset-1/api-keys"): - request.view_args = {"resource_id": "dataset-1"} - assert _extract_resource_id(RBACResourceScope.DATASET, "tenant-1") == "dataset-1" - - def test_extract_resource_id_scopes_pipeline_resolution_to_the_calling_tenant(self, sqlite_session: Session): - app = Flask(__name__) - pipeline_id = "00000000-0000-0000-0000-000000000001" - current_tenant_id = "00000000-0000-0000-0000-000000000002" - foreign_dataset = Dataset( - id="00000000-0000-0000-0000-000000000003", - tenant_id="00000000-0000-0000-0000-000000000004", - name="Foreign decoy", - created_by="00000000-0000-0000-0000-000000000005", - pipeline_id=pipeline_id, - ) - current_dataset = Dataset( - id="00000000-0000-0000-0000-000000000006", - tenant_id=current_tenant_id, - name="Current tenant dataset", - created_by="00000000-0000-0000-0000-000000000007", - pipeline_id=pipeline_id, - ) - sqlite_session.add_all([foreign_dataset, current_dataset]) - - unscoped_dataset = sqlite_session.scalar(select(Dataset).where(Dataset.pipeline_id == pipeline_id)) - assert unscoped_dataset is foreign_dataset - - with ( - app.test_request_context("/rag/pipelines/pipeline-1"), - patch("controllers.common.wraps.db", SimpleNamespace(session=sqlite_session)), - ): - request.view_args = {"pipeline_id": pipeline_id} - assert _extract_resource_id(RBACResourceScope.DATASET, current_tenant_id) == current_dataset.id - - def test_extract_resource_id_resolves_agent_to_its_authz_app(self): - app = Flask(__name__) - - with ( - app.test_request_context("/agent/agent-1/chat-messages"), - patch("controllers.common.wraps.AgentRosterService") as mock_service, - ): - request.view_args = {"agent_id": "agent-1"} - mock_service.return_value.peek_authz_app_id.return_value = "parent-app-1" - - assert _extract_resource_id(RBACResourceScope.APP, "tenant-1") == "parent-app-1" - - def test_extract_resource_id_scopes_agent_resolution_to_the_calling_tenant(self): - """The tenant must reach the resolver, or an Agent id from any tenant resolves.""" - app = Flask(__name__) - - with ( - app.test_request_context("/agent/agent-1/chat-messages"), - patch("controllers.common.wraps.AgentRosterService") as mock_service, - ): - request.view_args = {"agent_id": "agent-1"} - mock_service.return_value.peek_authz_app_id.return_value = "parent-app-1" - - _extract_resource_id(RBACResourceScope.APP, "tenant-9") - - mock_service.return_value.peek_authz_app_id.assert_called_once_with( - tenant_id="tenant-9", agent_id="agent-1" - ) - - def test_extract_resource_id_keeps_agent_id_when_the_agent_does_not_resolve(self): - app = Flask(__name__) - - with ( - app.test_request_context("/agent/agent-1/chat-messages"), - patch("controllers.common.wraps.AgentRosterService") as mock_service, - ): - request.view_args = {"agent_id": "agent-1"} - mock_service.return_value.peek_authz_app_id.return_value = None - - assert _extract_resource_id(RBACResourceScope.APP, "tenant-1") == "agent-1" - def test_legacy_admin_decorator_noops_when_rbac_enabled(self): @is_admin_or_owner_required def protected_view(): @@ -876,7 +784,7 @@ class TestBillingPaidPlanRequired: def paid_view(): return "paid_success" - billing_info = {"enabled": True, "subscription": {"plan": plan}} + billing_info = {"subscription": {"plan": plan}} with ( patch( "controllers.console.wraps.current_account_with_tenant", @@ -889,18 +797,15 @@ class TestBillingPaidPlanRequired: assert result == "paid_success" get_info.assert_called_once_with("tenant123", exclude_vector_space=True) - @pytest.mark.parametrize( - ("enabled", "plan"), - [(False, "professional"), (True, "sandbox"), (True, "unknown")], - ) - def test_should_reject_non_paid_plan(self, enabled: bool, plan: str): + @pytest.mark.parametrize("plan", ["sandbox", "unknown"]) + def test_should_reject_non_paid_plan(self, plan: str): app = create_app_with_login() @cloud_edition_billing_paid_plan_required def paid_view(): return "paid_success" - billing_info = {"enabled": enabled, "subscription": {"plan": plan}} + billing_info = {"subscription": {"plan": plan}} with app.test_request_context(): with ( patch( @@ -919,11 +824,11 @@ class TestBillingPaidPlanRequired: class TestBillingResourceLimits: """Test billing resource limit decorators""" + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_should_allow_when_under_resource_limit(self): """Test that requests are allowed when under resource limits""" # Arrange mock_features = MagicMock() - mock_features.billing.enabled = True mock_features.members.limit = 10 mock_features.members.size = 5 @@ -973,12 +878,12 @@ class TestBillingResourceLimits: get_vector_space.assert_called_once_with("tenant123") get_features.assert_not_called() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_should_reject_when_over_resource_limit(self): """Test that requests are rejected when over resource limits""" # Arrange app = create_app_with_login() mock_features = MagicMock() - mock_features.billing.enabled = True mock_features.members.limit = 10 mock_features.members.size = 10 @@ -998,12 +903,12 @@ class TestBillingResourceLimits: assert exc_info.value.code == 403 assert "members has reached the limit" in str(exc_info.value.description) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_should_check_source_for_documents_limit(self): """Test document limit checks request source""" # Arrange app = create_app_with_login() mock_features = MagicMock() - mock_features.billing.enabled = True mock_features.documents_upload_quota.limit = 100 mock_features.documents_upload_quota.size = 100 diff --git a/api/tests/unit_tests/controllers/console/workspace/test_endpoint.py b/api/tests/unit_tests/controllers/console/workspace/test_endpoint.py index 99f9ff1af9a..eb328aaf8e8 100644 --- a/api/tests/unit_tests/controllers/console/workspace/test_endpoint.py +++ b/api/tests/unit_tests/controllers/console/workspace/test_endpoint.py @@ -6,6 +6,7 @@ from unittest.mock import patch import pytest from flask import Flask +from controllers.common.rbac import Workspace from controllers.console import console_ns from controllers.console.workspace.endpoint import ( DeprecatedEndpointCreateApi, @@ -24,10 +25,11 @@ from controllers.console.workspace.endpoint import ( EndpointUpdatePayload, LegacyEndpointUpdatePayload, ) -from controllers.console.wraps import RBACPermission, RBACResourceScope +from controllers.console.wraps import RBACPermission from core.entities.provider_entities import ProviderConfig, ProviderConfigType from core.plugin.entities.endpoint import EndpointEntityWithInstance, EndpointProviderDeclaration from core.plugin.impl.exc import PluginPermissionDeniedError +from tests.unit_tests.controllers.rbac_introspection import rbac_checks def _endpoint_entity() -> EndpointEntityWithInstance: @@ -65,13 +67,9 @@ def test_endpoint_lists_require_management_permission(method: FunctionType) -> N ) assert "is_admin_or_owner_required" in legacy_wrapper.__code__.co_qualname - rbac_wrapper = inspect.unwrap( - method, stop=lambda wrapper: "rbac_permission_required" in wrapper.__code__.co_qualname - ) - rbac_config = inspect.getclosurevars(rbac_wrapper).nonlocals - assert rbac_config["resource_type"] == RBACResourceScope.WORKSPACE - assert rbac_config["scene"] == RBACPermission.PLUGIN_MODEL_CONFIG - assert rbac_config["resource_required"] is False + [check] = rbac_checks(method) + assert check.scene == RBACPermission.PLUGIN_MODEL_CONFIG + assert isinstance(check.locator, Workspace) class TestEndpointCollectionApi: diff --git a/api/tests/unit_tests/controllers/console/workspace/test_members.py b/api/tests/unit_tests/controllers/console/workspace/test_members.py index aedf0c12fc8..20f9df2e652 100644 --- a/api/tests/unit_tests/controllers/console/workspace/test_members.py +++ b/api/tests/unit_tests/controllers/console/workspace/test_members.py @@ -150,7 +150,9 @@ class TestMemberInviteEmailApi: with patch("controllers.console.workspace.members.redis_client.lock", return_value=nullcontext()): yield - def test_invite_success(self, app: Flask): + @pytest.mark.parametrize("role", ["normal", "dataset_operator"]) + def test_invite_success(self, app: Flask, config_overrides, role: str): + config_overrides(DATASET_OPERATOR_ENABLED=True) api = MemberInviteEmailApi() method = unwrap(api.post) @@ -162,7 +164,7 @@ class TestMemberInviteEmailApi: payload = { "emails": ["A@TEST.com", "a@test.com"], - "role": "normal", + "role": role, "language": "en-US", } @@ -182,6 +184,7 @@ class TestMemberInviteEmailApi: mock_count.assert_not_called() mock_invite.assert_called_once() assert mock_invite.call_args.kwargs["email"] == "a@test.com" + assert mock_invite.call_args.kwargs["role"] == role def test_invite_limit_exceeded(self, app: Flask, config_overrides): config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE) @@ -263,18 +266,20 @@ class TestMemberInviteEmailApi: assert result["invitation_results"][0]["status"] == "already_member" assert result["invitation_results"][0]["message"] == "Account already in workspace." - def test_invite_invalid_role(self, app: Flask): + @pytest.mark.parametrize("role", ["owner", "dataset_operator"]) + def test_invite_invalid_role(self, app: Flask, config_overrides, role: str): + config_overrides(DATASET_OPERATOR_ENABLED=False) api = MemberInviteEmailApi() method = unwrap(api.post) payload = { "emails": ["a@test.com"], - "role": "owner", + "role": role, } with app.test_request_context("/", json=payload): with pytest.raises(InvalidMemberRoleError) as exc_info: - method(api, _account()) + method(api, _account(tenant=_tenant())) assert exc_info.value.error_code == "invalid_role" @@ -540,14 +545,16 @@ class TestCountNewMemberInvites: class TestMemberUpdateRoleApi: - def test_update_invalid_role(self, app: Flask): + @pytest.mark.parametrize("role", ["invalid-role", "dataset_operator"]) + def test_update_invalid_role(self, app: Flask, config_overrides, role: str): + config_overrides(DATASET_OPERATOR_ENABLED=False) api = MemberUpdateRoleApi() method = unwrap(api.put) - payload = {"role": "invalid-role"} + payload = {"role": role} with app.test_request_context("/", json=payload): - result, status = method(api, _account(), "id") + result, status = method(api, _account(tenant=_tenant()), "id") assert status == 400 diff --git a/api/tests/unit_tests/controllers/console/workspace/test_rbac.py b/api/tests/unit_tests/controllers/console/workspace/test_rbac.py index 861cce48d24..15af9f1614d 100644 --- a/api/tests/unit_tests/controllers/console/workspace/test_rbac.py +++ b/api/tests/unit_tests/controllers/console/workspace/test_rbac.py @@ -85,6 +85,25 @@ class TestMyPermissions: assert response["app"]["default_permission_keys"] == ["app.acl.deploy"] mock_get.assert_called_once() + def test_forwards_agent_id_query_param(self, app): + permissions = rbac_mod.svc.MyPermissionsResponse( + agent=rbac_mod.svc.ResourcePermissionSnapshot( + default_permission_keys=["agent.acl.preview"], + ) + ) + with ( + app.test_request_context("/workspaces/current/rbac/my-permissions?agent_id=agent-1"), + patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")), + patch( + "controllers.console.workspace.rbac.svc.RBACService.MyPermissions.get", + return_value=permissions, + ) as mock_get, + ): + response = inspect.unwrap(rbac_mod.RBACMyPermissionsApi.get)(rbac_mod.RBACMyPermissionsApi()) + + assert mock_get.call_args.kwargs["agent_id"] == "agent-1" + assert response["agent"]["default_permission_keys"] == ["agent.acl.preview"] + class TestAccessMatrixAccountNames: def test_hydrates_missing_account_names(self): @@ -332,172 +351,6 @@ class TestPaginationMapping: assert options.reverse is True -class TestResourceAccessScopeBindings: - def test_app_whitelist_all_schedules_member_policy_sync(self, app): - with ( - app.test_request_context( - "/workspaces/current/rbac/apps/app-1/whitelist", - method="PUT", - json={"automatic_include_workspace_members": True}, - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.AppAccess.replace_whitelist", - return_value=rbac_mod.svc.ResourceWhitelist(automatic_include_workspace_members=True), - ), - patch("controllers.console.workspace.rbac.initialize_created_app_rbac_access_task") as mock_sync_task, - ): - inspect.unwrap(rbac_mod.RBACAppWhitelistApi.put)(rbac_mod.RBACAppWhitelistApi(), "app-1") - - mock_sync_task.delay.assert_called_once_with("tenant-1", "acct-actor", app_id="app-1") - - def test_dataset_whitelist_all_schedules_member_policy_sync(self, app): - # Widening a dataset to the whole workspace only records the scope; without granting the - # default policy to the current members nobody actually gains access. - with ( - app.test_request_context( - "/workspaces/current/rbac/datasets/dataset-1/whitelist", - method="PUT", - json={"automatic_include_workspace_members": True}, - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.DatasetAccess.replace_whitelist", - return_value=rbac_mod.svc.ResourceWhitelist(automatic_include_workspace_members=True), - ), - patch("controllers.console.workspace.rbac.initialize_created_app_rbac_access_task") as mock_sync_task, - ): - inspect.unwrap(rbac_mod.RBACDatasetWhitelistApi.put)(rbac_mod.RBACDatasetWhitelistApi(), "dataset-1") - - mock_sync_task.delay.assert_called_once_with("tenant-1", "acct-actor", dataset_id="dataset-1") - - def test_dataset_whitelist_specific_does_not_schedule_member_policy_sync(self, app): - with ( - app.test_request_context( - "/workspaces/current/rbac/datasets/dataset-1/whitelist", - method="PUT", - json={"automatic_include_workspace_members": False}, - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.DatasetAccess.replace_whitelist", - return_value=rbac_mod.svc.ResourceWhitelist(automatic_include_workspace_members=False), - ), - patch("controllers.console.workspace.rbac.initialize_created_app_rbac_access_task") as mock_sync_task, - ): - inspect.unwrap(rbac_mod.RBACDatasetWhitelistApi.put)(rbac_mod.RBACDatasetWhitelistApi(), "dataset-1") - - mock_sync_task.delay.assert_not_called() - - def test_app_whitelist_config_returns_switch_state_only(self, app): - result = rbac_mod.svc.ResourceWhitelistConfig(automatic_include_workspace_members=True) - with ( - app.test_request_context("/workspaces/current/rbac/apps/app-1/whitelist_config"), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.AppAccess.whitelist_config", - return_value=result, - ) as mock_get, - ): - response = inspect.unwrap(rbac_mod.RBACAppWhitelistConfigApi.get)( - rbac_mod.RBACAppWhitelistConfigApi(), - "app-1", - ) - - assert response == {"automatic_include_workspace_members": True} - mock_get.assert_called_once_with("tenant-1", "acct-1", "app-1") - - def test_dataset_whitelist_config_returns_switch_state_only(self, app): - result = rbac_mod.svc.ResourceWhitelistConfig(automatic_include_workspace_members=False) - with ( - app.test_request_context("/workspaces/current/rbac/datasets/dataset-1/whitelist_config"), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.DatasetAccess.whitelist_config", - return_value=result, - ) as mock_get, - ): - response = inspect.unwrap(rbac_mod.RBACDatasetWhitelistConfigApi.get)( - rbac_mod.RBACDatasetWhitelistConfigApi(), - "dataset-1", - ) - - assert response == {"automatic_include_workspace_members": False} - mock_get.assert_called_once_with("tenant-1", "acct-1", "dataset-1") - - def test_app_user_access_policy_assignment_forwards_ids(self, app): - with ( - app.test_request_context( - "/workspaces/current/rbac/apps/app-1/users/acct-target/access-policies", - method="PUT", - json={"access_policy_ids": ["policy-1", "policy-2"]}, - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.AppAccess.replace_user_access_policies" - ) as mock_replace, - patch("controllers.console.workspace.rbac._dump", return_value={}), - ): - inspect.unwrap(rbac_mod.RBACAppUserAccessPolicyAssignmentApi.put)( - rbac_mod.RBACAppUserAccessPolicyAssignmentApi(), - "app-1", - "acct-target", - ) - - tenant_id, actor_id, app_id, target_id, payload = mock_replace.call_args.args - assert (tenant_id, actor_id, app_id, target_id) == ( - "tenant-1", - "acct-actor", - "app-1", - "acct-target", - ) - assert payload.access_policy_ids == ["policy-1", "policy-2"] - - def test_app_member_bindings_delete_forwards_account_ids(self, app): - with ( - app.test_request_context( - "/workspaces/current/rbac/apps/app-1/access-policies/policy-1/member-bindings", - method="DELETE", - json={"account_ids": ["acct-2", "acct-3"]}, - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")), - patch("controllers.console.workspace.rbac.svc.RBACService.AppAccess.delete_member_bindings") as mock_delete, - ): - response = inspect.unwrap(rbac_mod.RBACAppMemberBindingsApi.delete)( - rbac_mod.RBACAppMemberBindingsApi(), - "app-1", - "policy-1", - ) - - assert response == {"result": "success"} - tenant_id, actor_id, app_id, policy_id, payload = mock_delete.call_args.args - assert (tenant_id, actor_id, app_id, policy_id) == ("tenant-1", "acct-actor", "app-1", "policy-1") - assert payload.account_ids == ["acct-2", "acct-3"] - - def test_dataset_member_bindings_delete_forwards_account_ids(self, app): - with ( - app.test_request_context( - "/workspaces/current/rbac/datasets/dataset-1/access-policies/policy-1/member-bindings", - method="DELETE", - json={"account_ids": ["acct-2"]}, - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.DatasetAccess.delete_member_bindings" - ) as mock_delete, - ): - response = inspect.unwrap(rbac_mod.RBACDatasetMemberBindingsApi.delete)( - rbac_mod.RBACDatasetMemberBindingsApi(), - "dataset-1", - "policy-1", - ) - - assert response == {"result": "success"} - tenant_id, actor_id, dataset_id, policy_id, payload = mock_delete.call_args.args - assert (tenant_id, actor_id, dataset_id, policy_id) == ("tenant-1", "acct-actor", "dataset-1", "policy-1") - assert payload.account_ids == ["acct-2"] - - class TestPaginationForwarding: def test_access_policies_get_forwards_outer_pagination_params(self, app): with ( @@ -517,88 +370,6 @@ class TestPaginationForwarding: assert options.results_per_page == 25 assert options.reverse is False - def test_workspace_app_matrix_forwards_outer_pagination_params(self, app): - with ( - app.test_request_context("/workspaces/current/rbac/workspace/apps/access-policy?page=4&limit=10"), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")), - patch("controllers.console.workspace.rbac.svc.RBACService.WorkspaceAccess.app_matrix") as mock_list, - patch("controllers.console.workspace.rbac._dump", return_value={}), - ): - inspect.unwrap(rbac_mod.RBACWorkspaceAppMatrixApi.get)(rbac_mod.RBACWorkspaceAppMatrixApi()) - - _, kwargs = mock_list.call_args - options = kwargs["options"] - assert options.page_number == 4 - assert options.results_per_page == 10 - assert options.reverse is None - - def test_workspace_dataset_matrix_forwards_outer_pagination_params(self, app): - with ( - app.test_request_context( - "/workspaces/current/rbac/workspace/datasets/access-policy?page=5&limit=15&reverse=true" - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")), - patch("controllers.console.workspace.rbac.svc.RBACService.WorkspaceAccess.dataset_matrix") as mock_list, - patch("controllers.console.workspace.rbac._dump", return_value={}), - ): - inspect.unwrap(rbac_mod.RBACWorkspaceDatasetMatrixApi.get)(rbac_mod.RBACWorkspaceDatasetMatrixApi()) - - _, kwargs = mock_list.call_args - options = kwargs["options"] - assert options.page_number == 5 - assert options.results_per_page == 15 - assert options.reverse is True - - def test_app_user_access_policies_forwards_outer_pagination_params(self, app): - result = rbac_mod.svc.ResourceUserAccessPoliciesResponse() - with ( - app.test_request_context( - "/workspaces/current/rbac/apps/app-1/user-access-policies?page=2&limit=30&reverse=false" - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.AppAccess.user_access_policies", - return_value=result, - ) as mock_list, - patch("controllers.console.workspace.rbac._dump", return_value={}), - ): - inspect.unwrap(rbac_mod.RBACAppUserAccessPoliciesApi.get)( - rbac_mod.RBACAppUserAccessPoliciesApi(), - "app-1", - ) - - args, kwargs = mock_list.call_args - assert args == ("tenant-1", "acct-1", "app-1") - options = kwargs["options"] - assert options.page_number == 2 - assert options.results_per_page == 30 - assert options.reverse is False - - def test_dataset_user_access_policies_forwards_outer_pagination_params(self, app): - result = rbac_mod.svc.ResourceUserAccessPoliciesResponse() - with ( - app.test_request_context( - "/workspaces/current/rbac/datasets/dataset-1/user-access-policies?page=3&limit=40&reverse=true" - ), - patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-1")), - patch( - "controllers.console.workspace.rbac.svc.RBACService.DatasetAccess.user_access_policies", - return_value=result, - ) as mock_list, - patch("controllers.console.workspace.rbac._dump", return_value={}), - ): - inspect.unwrap(rbac_mod.RBACDatasetUserAccessPoliciesApi.get)( - rbac_mod.RBACDatasetUserAccessPoliciesApi(), - "dataset-1", - ) - - args, kwargs = mock_list.call_args - assert args == ("tenant-1", "acct-1", "dataset-1") - options = kwargs["options"] - assert options.page_number == 3 - assert options.results_per_page == 40 - assert options.reverse is True - class TestAccessPolicyBindingLockUnlock: def test_lock_forwards_binding_id(self, app): @@ -653,7 +424,7 @@ class TestWorkspaceRbacGuards: "controllers.common.wraps.current_account_with_tenant", return_value=(_account(), "tenant-1"), ), - patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=False), + patch("controllers.common.rbac.checks.RBACService.CheckAccess.check", return_value=False), patch("controllers.console.workspace.rbac.svc.RBACService.Roles.create") as mock_create, ): with pytest.raises(Forbidden): @@ -672,7 +443,7 @@ class TestWorkspaceRbacGuards: "controllers.common.wraps.current_account_with_tenant", return_value=(_account(), "tenant-1"), ), - patch("controllers.common.wraps.RBACService.CheckAccess.check", return_value=False), + patch("controllers.common.rbac.checks.RBACService.CheckAccess.check", return_value=False), patch("controllers.console.workspace.rbac.svc.RBACService.AccessPolicies.create") as mock_create, ): with pytest.raises(Forbidden): diff --git a/api/tests/unit_tests/controllers/console/workspace/test_rbac_resource_access_routes.py b/api/tests/unit_tests/controllers/console/workspace/test_rbac_resource_access_routes.py new file mode 100644 index 00000000000..f5c593603b6 --- /dev/null +++ b/api/tests/unit_tests/controllers/console/workspace/test_rbac_resource_access_routes.py @@ -0,0 +1,167 @@ +"""Contract tests for the generated app / dataset / agent access-permission routes. + +``controllers.console.workspace.rbac`` builds the same twelve endpoints for every +resource kind from ``_RESOURCE_ACCESS_ROUTES``. These tests pin the two things the +generation must not get wrong: the registered URLs (with their class names and HTTP +methods) and which inner-API client each handler reaches for. +""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable, Generator +from unittest.mock import MagicMock, patch + +import pytest +from flask import Flask + +from controllers.console import console_ns +from controllers.console.workspace import rbac as rbac_mod +from enums import DeploymentEdition +from services.enterprise import rbac_service as svc + +RESOURCE_ID = { + svc.RBACResourceType.APP: "app-1", + svc.RBACResourceType.DATASET: "dataset-1", + svc.RBACResourceType.AGENT: "agent-1", +} + +# The URL segment and path parameter of each resource kind, spelled out here instead of read +# back from the same enum the controller builds its URLs from, so a rename fails this test. +RESOURCE_URL_PARTS = { + svc.RBACResourceType.APP: ("apps", "app_id"), + svc.RBACResourceType.DATASET: ("datasets", "dataset_id"), + svc.RBACResourceType.AGENT: ("agents", "agent_id"), +} + + +def _segment(spec: rbac_mod._ResourceAccessRoutes) -> str: + return RESOURCE_URL_PARTS[spec.resource_type][0] + + +def _id_param(spec: rbac_mod._ResourceAccessRoutes) -> str: + return RESOURCE_URL_PARTS[spec.resource_type][1] + + +@pytest.fixture +def app() -> Flask: + flask_app = Flask(__name__) + flask_app.config["TESTING"] = True + return flask_app + + +@pytest.fixture(autouse=True) +def _rbac_config(config_overrides: Callable[..., None]) -> None: + config_overrides( + DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE, + RBAC_ENABLED=True, + LOGIN_DISABLED=True, + ) + + +@pytest.fixture(params=rbac_mod._RESOURCE_ACCESS_ROUTES, ids=lambda spec: spec.resource_type.value) +def spec(request: pytest.FixtureRequest) -> rbac_mod._ResourceAccessRoutes: + return request.param + + +@pytest.fixture +def apis(spec: rbac_mod._ResourceAccessRoutes) -> rbac_mod._ResourceAccessApis: + return rbac_mod._RESOURCE_ACCESS_APIS[spec.resource_type] + + +@pytest.fixture +def resource_id(spec: rbac_mod._ResourceAccessRoutes) -> str: + return RESOURCE_ID[spec.resource_type] + + +@pytest.fixture(autouse=True) +def _patched_current_ids() -> Generator[None]: + with patch("controllers.console.workspace.rbac._current_ids", return_value=("tenant-1", "acct-actor")): + yield + + +def _expected_routes(spec: rbac_mod._ResourceAccessRoutes) -> dict[str, tuple[str, set[str]]]: + resource = f"/workspaces/current/rbac/{_segment(spec)}/" + workspace = f"/workspaces/current/rbac/workspace/{_segment(spec)}" + prefix = spec.class_prefix + return { + f"/workspaces/current/rbac/role-permissions/catalog/{spec.resource_type.value}": ( + f"RBAC{prefix}CatalogApi", + {"GET"}, + ), + f"{resource}/access-policy": (f"RBAC{prefix}MatrixApi", {"GET"}), + f"{resource}/whitelist": (f"RBAC{prefix}WhitelistApi", {"GET", "PUT"}), + f"{resource}/whitelist_config": (f"RBAC{prefix}WhitelistConfigApi", {"GET"}), + f"{resource}/user-access-policies": (f"RBAC{prefix}UserAccessPoliciesApi", {"GET"}), + f"{resource}/users//access-policies": ( + f"RBAC{prefix}UserAccessPolicyAssignmentApi", + {"PUT"}, + ), + f"{resource}/access-policies//role-bindings": (f"RBAC{prefix}RoleBindingsApi", {"GET"}), + f"{resource}/access-policies//member-bindings": ( + f"RBAC{prefix}MemberBindingsApi", + {"GET", "DELETE"}, + ), + f"{workspace}/access-policy": (f"RBACWorkspace{prefix}MatrixApi", {"GET"}), + f"{workspace}/access-policies//role-bindings": ( + f"RBACWorkspace{prefix}RoleBindingsApi", + {"GET"}, + ), + f"{workspace}/access-policies//bindings": (f"RBACWorkspace{prefix}BindingsApi", {"PUT"}), + f"{workspace}/access-policies//member-bindings": ( + f"RBACWorkspace{prefix}MemberBindingsApi", + {"GET"}, + ), + } + + +def _registered_resource_by_url() -> dict[str, type]: + registered: dict[str, type] = {} + for route in console_ns.resources: + for url in route.urls: + registered[url] = route.resource + return registered + + +def test_every_resource_kind_registers_the_same_twelve_routes(spec: rbac_mod._ResourceAccessRoutes) -> None: + registered = _registered_resource_by_url() + + for url, (class_name, methods) in _expected_routes(spec).items(): + assert url in registered, f"{url} is not registered" + resource = registered[url] + assert resource.__name__ == class_name + assert set(resource.methods or ()) == methods + + +@pytest.mark.parametrize("automatic_include_workspace_members", [True, False]) +def test_whitelist_put_queues_the_seed_task_only_when_auto_including( + app: Flask, + apis: rbac_mod._ResourceAccessApis, + spec: rbac_mod._ResourceAccessRoutes, + resource_id: str, + automatic_include_workspace_members: bool, +) -> None: + replace = MagicMock( + return_value=svc.ResourceWhitelist( + automatic_include_workspace_members=automatic_include_workspace_members, + ) + ) + with ( + app.test_request_context( + f"/{_segment(spec)}/{resource_id}/whitelist", + method="PUT", + json={"automatic_include_workspace_members": automatic_include_workspace_members}, + ), + patch.object(spec.access, "replace_whitelist", replace), + patch("controllers.console.workspace.rbac.initialize_created_app_rbac_access_task") as seed_task, + ): + inspect.unwrap(vars(apis.whitelist)["put"])(apis.whitelist(), **{_id_param(spec): resource_id}) + + tenant_id, actor_id, target_id, payload = replace.call_args.args + assert (tenant_id, actor_id, target_id) == ("tenant-1", "acct-actor", resource_id) + assert payload.automatic_include_workspace_members is automatic_include_workspace_members + + if automatic_include_workspace_members: + seed_task.delay.assert_called_once_with("tenant-1", "acct-actor", **{_id_param(spec): resource_id}) + else: + seed_task.delay.assert_not_called() diff --git a/api/tests/unit_tests/controllers/console/workspace/test_snippets.py b/api/tests/unit_tests/controllers/console/workspace/test_snippets.py index e89aa6a6b57..d664fb3eb9a 100644 --- a/api/tests/unit_tests/controllers/console/workspace/test_snippets.py +++ b/api/tests/unit_tests/controllers/console/workspace/test_snippets.py @@ -1,14 +1,17 @@ from datetime import UTC, datetime from inspect import unwrap from types import SimpleNamespace -from unittest.mock import ANY, Mock +from unittest.mock import Mock import pytest from flask import Flask -from werkzeug.exceptions import NotFound +from pydantic import ValidationError +from sqlalchemy.orm import Session +from werkzeug.exceptions import BadRequest, NotFound from controllers.console.workspace import snippets as snippets_module from models.account import Account, TenantAccountRole +from models.snippet import CustomizedSnippet from services.snippet_dsl_service import ImportStatus, SnippetImportInfo @@ -39,30 +42,31 @@ def _account(account_id: str = "account-1") -> Account: return account -def _snippet(**overrides) -> SimpleNamespace: - data = { - "id": "snippet-1", - "tenant_id": "tenant-1", - "name": "Snippet", - "description": "Description", - "type": snippets_module.SnippetType.NODE, - "version": 1, - "use_count": 0, - "is_published": False, - "icon_info": None, - "graph_dict": {}, - "input_fields_list": [], - "tags": [], - "created_by": None, - "author_name": None, - "created_by_account": None, - "created_at": datetime.fromtimestamp(1_704_067_200, UTC), - "updated_by": None, - "updated_by_account": None, - "updated_at": datetime.fromtimestamp(1_704_153_600, UTC), - } - data.update(overrides) - return SimpleNamespace(**data) +def _snippet(**overrides) -> CustomizedSnippet: + """Build a real ``CustomizedSnippet`` row so session-backed accessors run against the test schema. + + The SQLite fixtures in ``tests/unit_tests/conftest.py`` provide the full schema, so the + ``get_*(session=...)`` accessors resolve through real queries instead of hand-written stubs. + """ + snippet = CustomizedSnippet( + tenant_id="tenant-1", + name="Snippet", + description="Description", + type=snippets_module.SnippetType.NODE, + version=1, + use_count=0, + is_published=False, + icon_info=None, + input_fields=None, + created_by=None, + created_at=datetime.fromtimestamp(1_704_067_200, UTC), + updated_by=None, + updated_at=datetime.fromtimestamp(1_704_153_600, UTC), + ) + snippet.id = "snippet-1" + for name, value in overrides.items(): + setattr(snippet, name, value) + return snippet def test_snippet_list_query_reads_repeated_values(app: Flask): @@ -98,7 +102,7 @@ def test_snippet_list_query_ignores_indexed_values(app: Flask): assert query.creators is None -def test_list_snippets_returns_pagination(app: Flask, monkeypatch: pytest.MonkeyPatch): +def test_list_snippets_returns_pagination(app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session): snippets = [_snippet()] tag_id = "11111111-1111-1111-1111-111111111111" get_snippets = Mock(return_value=(snippets, 1, False)) @@ -110,7 +114,7 @@ def test_list_snippets_returns_pagination(app: Flask, monkeypatch: pytest.Monkey with app.test_request_context( f"/workspaces/current/customized-snippets?page=2&limit=10&tag_ids={tag_id}&creators=account-2" ): - response, status_code = handler(api, "tenant-1") + response, status_code = handler(api, sqlite_session, "tenant-1") assert status_code == 200 assert response == { @@ -139,7 +143,7 @@ def test_list_snippets_returns_pagination(app: Flask, monkeypatch: pytest.Monkey } get_snippets.assert_called_once_with( tenant_id="tenant-1", - session=ANY, + session=sqlite_session, page=2, limit=10, keyword=None, @@ -149,7 +153,9 @@ def test_list_snippets_returns_pagination(app: Flask, monkeypatch: pytest.Monkey ) -def test_create_snippet_defaults_unknown_type_and_returns_created(app: Flask, monkeypatch: pytest.MonkeyPatch): +def test_create_snippet_defaults_unknown_type_and_returns_created( + app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session +): user = _account("account-1") snippet = _snippet() create_snippet = Mock(return_value=snippet) @@ -172,7 +178,7 @@ def test_create_snippet_defaults_unknown_type_and_returns_created(app: Flask, mo method="POST", json={"name": "Snippet", "type": "node", "description": "Description"}, ): - response, status_code = handler(api, req_data, "tenant-1", user) + response, status_code = handler(api, req_data, sqlite_session, "tenant-1", user) assert status_code == 201 assert response["id"] == "snippet-1" @@ -180,7 +186,7 @@ def test_create_snippet_defaults_unknown_type_and_returns_created(app: Flask, mo assert create_snippet.call_args.kwargs["snippet_type"] == snippets_module.SnippetType.NODE -def test_create_snippet_rejects_forbidden_nodes(app: Flask, monkeypatch: pytest.MonkeyPatch): +def test_create_snippet_rejects_forbidden_nodes(app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session): user = _account("account-1") create_snippet = Mock() monkeypatch.setattr(snippets_module.SnippetService, "create_snippet", create_snippet) @@ -213,14 +219,14 @@ def test_create_snippet_rejects_forbidden_nodes(app: Flask, monkeypatch: pytest. }, }, ): - response, status_code = handler(api, req_data, "tenant-1", user) + response, status_code = handler(api, req_data, sqlite_session, "tenant-1", user) assert status_code == 400 assert "knowledge-retrieval" in response["message"] create_snippet.assert_not_called() -def test_get_snippet_detail_raises_when_missing(app: Flask, monkeypatch: pytest.MonkeyPatch): +def test_get_snippet_detail_raises_when_missing(app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session): monkeypatch.setattr(snippets_module.SnippetService, "get_snippet_by_id", Mock(return_value=None)) api = snippets_module.CustomizedSnippetDetailApi() @@ -228,10 +234,10 @@ def test_get_snippet_detail_raises_when_missing(app: Flask, monkeypatch: pytest. with app.test_request_context("/workspaces/current/customized-snippets/snippet-1"): with pytest.raises(NotFound, match="Snippet not found"): - handler(api, "tenant-1", snippet_id="snippet-1") + handler(api, sqlite_session, "tenant-1", snippet_id="snippet-1") -def test_get_snippet_detail_returns_snippet(app: Flask, monkeypatch: pytest.MonkeyPatch): +def test_get_snippet_detail_returns_snippet(app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session): snippet = _snippet() monkeypatch.setattr(snippets_module.SnippetService, "get_snippet_by_id", Mock(return_value=snippet)) @@ -239,14 +245,38 @@ def test_get_snippet_detail_returns_snippet(app: Flask, monkeypatch: pytest.Monk handler = unwrap(api.get) with app.test_request_context("/workspaces/current/customized-snippets/snippet-1"): - response, status_code = handler(api, "tenant-1", snippet_id="snippet-1") + response, status_code = handler(api, sqlite_session, "tenant-1", snippet_id="snippet-1") assert status_code == 200 assert response["id"] == "snippet-1" assert response["name"] == "Snippet" -def test_patch_snippet_returns_400_for_empty_payload(app: Flask, monkeypatch: pytest.MonkeyPatch): +def test_get_snippet_detail_resolves_creator_through_the_request_session( + app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session +): + """The injected session is the one the accessors query, so a persisted creator resolves.""" + author = _account("11111111-1111-1111-1111-111111111111") + sqlite_session.add(author) + sqlite_session.commit() + + snippet = _snippet(created_by=author.id, updated_by=author.id) + monkeypatch.setattr(snippets_module.SnippetService, "get_snippet_by_id", Mock(return_value=snippet)) + + api = snippets_module.CustomizedSnippetDetailApi() + handler = unwrap(api.get) + + with app.test_request_context("/workspaces/current/customized-snippets/snippet-1"): + response, status_code = handler(api, sqlite_session, "tenant-1", snippet_id="snippet-1") + + assert status_code == 200 + assert response["created_by"] == {"id": author.id, "name": "Test User", "email": author.email} + assert response["updated_by"] == {"id": author.id, "name": "Test User", "email": author.email} + + +def test_patch_snippet_returns_400_for_empty_payload( + app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session +): snippet = _snippet() user = _account("user-1") monkeypatch.setattr(snippets_module.SnippetService, "get_snippet_by_id", Mock(return_value=snippet)) @@ -261,27 +291,20 @@ def test_patch_snippet_returns_400_for_empty_payload(app: Flask, monkeypatch: py method="PATCH", json={}, ): - response, status_code = handler(api, req_data, "tenant-1", user, snippet_id="snippet-1") + response, status_code = handler(api, req_data, sqlite_session, "tenant-1", user, snippet_id="snippet-1") assert status_code == 400 assert response == {"message": "No valid fields to update"} -def test_patch_snippet_updates_and_commits(app: Flask, monkeypatch: pytest.MonkeyPatch): +def test_patch_snippet_updates_and_commits(app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session): + _persist_snippet(sqlite_session) user = _account("account-1") snippet = _snippet() - updated_snippet = _snippet(name="New") - session = SimpleNamespace(merge=Mock(return_value=snippet), commit=Mock()) - update_snippet = Mock(return_value=updated_snippet) - - class SessionContext(_SessionContext): - def __init__(self, engine, *args, **kwargs): - super().__init__(engine, *args, session=session, **kwargs) + update_snippet = Mock(side_effect=_apply_update) monkeypatch.setattr(snippets_module.SnippetService, "get_snippet_by_id", Mock(return_value=snippet)) monkeypatch.setattr(snippets_module.SnippetService, "update_snippet", update_snippet) - monkeypatch.setattr(snippets_module, "Session", SessionContext) - monkeypatch.setattr(snippets_module, "db", SimpleNamespace(engine=object())) req_data = snippets_module.UpdateSnippetPayload(name="New", icon_info={"icon": "star"}) @@ -293,17 +316,125 @@ def test_patch_snippet_updates_and_commits(app: Flask, monkeypatch: pytest.Monke method="PATCH", json={"name": "New", "icon_info": {"icon": "star"}}, ): - response, status_code = handler(api, req_data, "tenant-1", user, snippet_id="snippet-1") + response, status_code = handler(api, req_data, sqlite_session, "tenant-1", user, snippet_id="snippet-1") assert status_code == 200 assert response["id"] == "snippet-1" assert response["name"] == "New" update_snippet.assert_called_once() + assert update_snippet.call_args.kwargs["session"] is sqlite_session assert update_snippet.call_args.kwargs["data"] == { "name": "New", "icon_info": {"icon": "star", "icon_background": None, "icon_type": None, "icon_url": None}, } - session.commit.assert_called_once() + assert _persisted_name(sqlite_session) == "New" + + +def test_patch_snippet_does_not_report_a_committed_write_as_a_bad_request( + app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session +): + """The ``except ValueError`` must scope the update call only, never the serialization. + + ``ValidationError`` subclasses ``ValueError``. Both routes end at a 400 either way — the app + registers a ``ValueError`` handler in ``libs/external_api.py`` — so what matters is *where* it + is handled: covering the serialization would blame the client's payload for a write that already + succeeded, and swallow the failure before it ever reaches the error handlers. The committed row + must survive regardless. + """ + _persist_snippet(sqlite_session) + user = _account("account-1") + snippet = _snippet() + + monkeypatch.setattr(snippets_module.SnippetService, "get_snippet_by_id", Mock(return_value=snippet)) + monkeypatch.setattr(snippets_module.SnippetService, "update_snippet", Mock(side_effect=_apply_update)) + monkeypatch.setattr(CustomizedSnippet, "get_graph_dict", _unserializable_graph) + + req_data = snippets_module.UpdateSnippetPayload(name="New") + + api = snippets_module.CustomizedSnippetDetailApi() + handler = unwrap(api.patch) + + with app.test_request_context( + "/workspaces/current/customized-snippets/snippet-1", + method="PATCH", + json={"name": "New"}, + ): + with pytest.raises(ValidationError): + handler(api, req_data, sqlite_session, "tenant-1", user, snippet_id="snippet-1") + + assert _persisted_name(sqlite_session) == "New" + + +def test_patch_snippet_does_not_persist_a_rejected_update( + app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session +): + """A rejected update must raise, not return a 400 tuple. + + ``with_session`` commits on any normal return, so returning ``{"message": ...}, 400`` would + durably persist whatever ``update_snippet`` wrote before it rejected the payload; raising routes + through the decorator's rollback instead. That commit lives *in the decorator*, so this test runs + the handler through it rather than through ``unwrap`` — the autouse ``_sqlite_session_factory`` + fixture already points ``with_session`` at the same database as ``sqlite_session``. + """ + _persist_snippet(sqlite_session) + user = _account("account-1") + snippet = _snippet() + + monkeypatch.setattr(snippets_module.SnippetService, "get_snippet_by_id", Mock(return_value=snippet)) + monkeypatch.setattr(snippets_module.SnippetService, "update_snippet", Mock(side_effect=_reject_update)) + + req_data = snippets_module.UpdateSnippetPayload(name="New") + + api = snippets_module.CustomizedSnippetDetailApi() + view = unwrap(api.patch) + + @snippets_module.with_session + def patch_through_decorator(resource, session: Session, snippet_id: str): + return view(resource, req_data, session, "tenant-1", user, snippet_id=snippet_id) + + with app.test_request_context( + "/workspaces/current/customized-snippets/snippet-1", + method="PATCH", + json={"name": "New"}, + ): + with pytest.raises(BadRequest, match="name already in use"): + patch_through_decorator(api, snippet_id="snippet-1") + + assert _persisted_name(sqlite_session) == "Snippet" + + +def _apply_update(*, session: Session, snippet: CustomizedSnippet, account_id: str, data: dict) -> CustomizedSnippet: + """Stand in for ``SnippetService.update_snippet``: write the payload onto the merged row.""" + del session, account_id + for field, value in data.items(): + setattr(snippet, field, value) + return snippet + + +def _reject_update(*, session: Session, snippet: CustomizedSnippet, account_id: str, data: dict) -> CustomizedSnippet: + """Stand in for an ``update_snippet`` that writes some fields and then rejects the payload.""" + _apply_update(session=session, snippet=snippet, account_id=account_id, data=data) + raise ValueError("name already in use") + + +def _unserializable_graph(self: CustomizedSnippet, *, session: Session) -> str: + """Return a non-dict graph so response validation fails after the write is committed.""" + del self, session + return "not-a-dict" + + +def _persist_snippet(session: Session) -> None: + """Persist the baseline row so the handler's ``merge`` takes the UPDATE path, as in production.""" + with Session(bind=session.get_bind()) as setup_session: + setup_session.add(_snippet()) + setup_session.commit() + + +def _persisted_name(session: Session) -> str | None: + """Read the snippet name back through a second session to prove what was committed.""" + with Session(bind=session.get_bind()) as verification_session: + stored = verification_session.get(CustomizedSnippet, "snippet-1") + return stored.name if stored else None def test_delete_snippet_deletes_and_commits(app: Flask, monkeypatch: pytest.MonkeyPatch): diff --git a/api/tests/unit_tests/controllers/files/test_image_preview.py b/api/tests/unit_tests/controllers/files/test_image_preview.py deleted file mode 100644 index b1f0efbcd5c..00000000000 --- a/api/tests/unit_tests/controllers/files/test_image_preview.py +++ /dev/null @@ -1,303 +0,0 @@ -import types -from datetime import UTC, datetime -from inspect import unwrap -from unittest.mock import patch - -import pytest -from werkzeug.exceptions import NotFound - -import controllers.files.image_preview as module -from extensions.storage.storage_type import StorageType -from models.enums import CreatorUserRole -from models.model import UploadFile - - -@pytest.fixture(autouse=True) -def mock_db(): - """ - Replace Flask-SQLAlchemy db with a plain object - to avoid touching Flask app context entirely. - """ - fake_db = types.SimpleNamespace(engine=object()) - module.db = fake_db - - -def _upload_file( - *, mime_type: str = "text/plain", size: int = 10, name: str = "test.txt", extension: str = "txt" -) -> UploadFile: - upload_file = UploadFile( - tenant_id="tenant-1", - storage_type=StorageType.LOCAL, - key="uploads/file-id", - name=name, - size=size, - extension=extension, - mime_type=mime_type, - created_by_role=CreatorUserRole.ACCOUNT, - created_by="account-1", - created_at=datetime.now(UTC), - used=False, - ) - upload_file.id = "file-id" - return upload_file - - -def fake_request(args: dict): - """Return a fake request object (NOT a Flask LocalProxy).""" - return types.SimpleNamespace(args=types.SimpleNamespace(to_dict=lambda flat=True: args)) - - -class TestImagePreviewApi: - @patch.object(module, "FileService") - def test_success(self, mock_file_service): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - } - ) - - generator = iter([b"img"]) - mock_file_service.return_value.get_image_preview.return_value = ( - generator, - "image/png", - ) - - api = module.ImagePreviewApi() - get_fn = unwrap(api.get) - - response = get_fn("file-id") - - assert response.mimetype == "image/png" - - @patch.object(module, "FileService") - def test_unsupported_file_type(self, mock_file_service): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - } - ) - - mock_file_service.return_value.get_image_preview.side_effect = ( - module.services.errors.file.UnsupportedFileTypeError() - ) - - api = module.ImagePreviewApi() - get_fn = unwrap(api.get) - - with pytest.raises(module.UnsupportedFileTypeError): - get_fn("file-id") - - -class TestFilePreviewApi: - @patch.object(module, "enforce_download_for_html") - @patch.object(module, "FileService") - def test_inline_preview_uses_upload_file_mimetype(self, mock_file_service, mock_enforce): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "as_attachment": False, - } - ) - - generator = iter([b"data"]) - upload_file = _upload_file( - mime_type="application/pdf", - size=100, - name="doc.pdf", - extension="pdf", - ) - - mock_file_service.return_value.get_file_generator_by_file_id.return_value = ( - generator, - upload_file, - ) - - api = module.FilePreviewApi() - get_fn = unwrap(api.get) - - response = get_fn("file-id") - - assert response.mimetype == "application/pdf" - assert response.headers["Content-Type"] == "application/pdf" - assert response.headers["Content-Length"] == "100" - assert "Accept-Ranges" not in response.headers - mock_enforce.assert_called_once() - - @pytest.mark.parametrize( - ("mime_type", "name", "extension"), - [ - ("Image/SVG+XML; charset=UTF-8", "image.png", "png"), - ("image/png", "image.SVG", "png"), - ("image/png", "image.png", ".SVG"), - ], - ids=("mime-type", "filename", "extension"), - ) - @patch.object(module, "FileService") - def test_svg_preview_forces_download(self, mock_file_service, mime_type, name, extension): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "as_attachment": False, - } - ) - - generator = iter([b""]) - upload_file = _upload_file( - mime_type=mime_type, - size=11, - name=name, - extension=extension, - ) - - mock_file_service.return_value.get_file_generator_by_file_id.return_value = ( - generator, - upload_file, - ) - - api = module.FilePreviewApi() - get_fn = unwrap(api.get) - - response = get_fn("file-id") - - assert response.headers["Content-Disposition"].startswith("attachment") - assert response.headers["Content-Type"] == "application/octet-stream" - assert response.headers["X-Content-Type-Options"] == "nosniff" - - @patch.object(module, "FileService") - def test_html_preview_still_forces_download(self, mock_file_service): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "as_attachment": False, - } - ) - - generator = iter([b""]) - upload_file = _upload_file( - mime_type="text/html", - size=25, - name="unsafe.html", - extension="html", - ) - - mock_file_service.return_value.get_file_generator_by_file_id.return_value = ( - generator, - upload_file, - ) - - api = module.FilePreviewApi() - get_fn = unwrap(api.get) - - response = get_fn("file-id") - - assert response.headers["Content-Disposition"].startswith("attachment") - assert response.headers["Content-Type"] == "application/octet-stream" - assert response.headers["X-Content-Type-Options"] == "nosniff" - - @patch.object(module, "enforce_download_for_html") - @patch.object(module, "FileService") - def test_as_attachment(self, mock_file_service, mock_enforce): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "as_attachment": True, - } - ) - - generator = iter([b"data"]) - upload_file = _upload_file( - mime_type="application/pdf", - name="doc.pdf", - extension="pdf", - ) - - mock_file_service.return_value.get_file_generator_by_file_id.return_value = ( - generator, - upload_file, - ) - - api = module.FilePreviewApi() - get_fn = unwrap(api.get) - - response = get_fn("file-id") - - assert response.headers["Content-Disposition"].startswith("attachment") - assert response.headers["Content-Type"] == "application/octet-stream" - mock_enforce.assert_called_once() - - @patch.object(module, "FileService") - def test_unsupported_file_type(self, mock_file_service): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "as_attachment": False, - } - ) - - mock_file_service.return_value.get_file_generator_by_file_id.side_effect = ( - module.services.errors.file.UnsupportedFileTypeError() - ) - - api = module.FilePreviewApi() - get_fn = unwrap(api.get) - - with pytest.raises(module.UnsupportedFileTypeError): - get_fn("file-id") - - -class TestWorkspaceWebappLogoApi: - @patch.object(module, "FileService") - @patch.object(module.TenantService, "get_custom_config") - def test_success(self, mock_config, mock_file_service): - mock_config.return_value = {"replace_webapp_logo": "logo-id"} - generator = iter([b"logo"]) - - mock_file_service.return_value.get_public_image_preview.return_value = ( - generator, - "image/png", - ) - - api = module.WorkspaceWebappLogoApi() - get_fn = unwrap(api.get) - - response = get_fn("workspace-id") - - assert response.mimetype == "image/png" - - @patch.object(module.TenantService, "get_custom_config") - def test_logo_not_configured(self, mock_config): - mock_config.return_value = {} - - api = module.WorkspaceWebappLogoApi() - get_fn = unwrap(api.get) - - with pytest.raises(NotFound): - get_fn("workspace-id") - - @patch.object(module, "FileService") - @patch.object(module.TenantService, "get_custom_config") - def test_unsupported_file_type(self, mock_config, mock_file_service): - mock_config.return_value = {"replace_webapp_logo": "logo-id"} - mock_file_service.return_value.get_public_image_preview.side_effect = ( - module.services.errors.file.UnsupportedFileTypeError() - ) - - api = module.WorkspaceWebappLogoApi() - get_fn = unwrap(api.get) - - with pytest.raises(module.UnsupportedFileTypeError): - get_fn("workspace-id") diff --git a/api/tests/unit_tests/controllers/files/test_plugin_file_upload.py b/api/tests/unit_tests/controllers/files/test_plugin_file_upload.py new file mode 100644 index 00000000000..704afa30878 --- /dev/null +++ b/api/tests/unit_tests/controllers/files/test_plugin_file_upload.py @@ -0,0 +1,332 @@ +import io +import types +from collections.abc import Callable +from inspect import unwrap +from unittest.mock import MagicMock, patch + +import pytest +from flask import Flask +from pydantic import ValidationError + +import controllers.files.plugin_file_upload as module +from controllers.files import bp as files_blueprint +from core.workflow.file_reference import build_file_reference +from enums import DeploymentEdition +from services.errors.file import FileTooLargeError as ServiceFileTooLargeError +from services.errors.file import UnsupportedFileTypeError as ServiceUnsupportedFileTypeError +from services.plugin_file_upload_service import PluginFileUploadAccessDeniedError, PluginFileUploadResult + + +class DummyFile: + def __init__( + self, + *, + filename: str | None = "report.pdf", + mimetype: str | None = "application/pdf", + content: bytes = b"content", + ) -> None: + self.filename = filename + self.mimetype = mimetype + self.stream = io.BytesIO(content) + + +def _fake_request(args: dict[str, object], *, file: DummyFile | None = None) -> types.SimpleNamespace: + return types.SimpleNamespace( + args=types.SimpleNamespace(to_dict=lambda **_kwargs: args), + files={"file": file} if file is not None else {}, + ) + + +def _result() -> PluginFileUploadResult: + return PluginFileUploadResult( + id="file-id", + reference=build_file_reference(record_id="file-id"), + name="report.pdf", + size=7, + extension=".pdf", + mime_type="application/pdf", + preview_url="https://files.example.com/files/tools/file-id.pdf?signed", + source_url=None, + original_url=None, + user_id="user-id", + tenant_id="tenant-id", + conversation_id="conversation-id", + file_key="tools/tenant-id/file.pdf", + ) + + +def _valid_args() -> dict[str, object]: + return { + "timestamp": "123", + "nonce": "nonce", + "sign": "signature", + "tenant_id": "tenant-id", + "user_id": "user-id", + "user_from": "end-user", + "conversation_id": "conversation-id", + "max_size": "1024", + } + + +@pytest.fixture +def files_app(config_overrides: Callable[..., None]) -> Flask: + config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) + app = Flask(__name__) + app.config["TESTING"] = True + app.register_blueprint(files_blueprint) + return app + + +class TestPluginUploadFileApi: + def test_upload_query_requires_the_signed_user_id(self) -> None: + args = _valid_args() + del args["user_id"] + + with pytest.raises(ValidationError): + module.PluginUploadQuery.model_validate(args) + + @patch.object(module, "application_services") + def test_upload_returns_the_existing_plugin_file_contract( + self, + application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + file = DummyFile() + monkeypatch.setattr(module, "request", _fake_request(_valid_args(), file=file)) + service = application_services.return_value.plugin_file_uploads + service.upload.return_value = _result() + + response, status = unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) + + assert status == 201 + assert response == { + "id": "file-id", + "reference": build_file_reference(record_id="file-id"), + "name": "report.pdf", + "size": 7, + "extension": ".pdf", + "mime_type": "application/pdf", + "created_by": None, + "created_at": None, + "preview_url": "https://files.example.com/files/tools/file-id.pdf?signed", + "source_url": None, + "original_url": None, + "user_id": "user-id", + "tenant_id": "tenant-id", + "conversation_id": "conversation-id", + "file_key": "tools/tenant-id/file.pdf", + } + service.upload.assert_called_once_with( + stream=file.stream, + filename="report.pdf", + mimetype="application/pdf", + tenant_id="tenant-id", + user_id="user-id", + user_from="end-user", + conversation_id="conversation-id", + timestamp="123", + nonce="nonce", + sign="signature", + max_size=1024, + ) + + def test_missing_file_has_a_specific_client_error(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(module, "request", _fake_request(_valid_args())) + + with pytest.raises(module.NoFileUploadedError): + unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) + + @pytest.mark.parametrize( + ("file", "expected_error"), + [ + pytest.param(DummyFile(filename=""), module.FilenameNotExistsError, id="filename"), + pytest.param(DummyFile(mimetype=""), module.UnsupportedFileTypeError, id="mimetype"), + ], + ) + def test_invalid_file_metadata_has_a_specific_client_error( + self, + monkeypatch: pytest.MonkeyPatch, + file: DummyFile, + expected_error: type[Exception], + ) -> None: + monkeypatch.setattr(module, "request", _fake_request(_valid_args(), file=file)) + + with pytest.raises(expected_error): + unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) + + @patch.object(module, "application_services") + def test_access_denied_is_reported_without_leaking_identity_details( + self, + application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr(module, "request", _fake_request(_valid_args(), file=DummyFile())) + application_services.return_value.plugin_file_uploads.upload.side_effect = PluginFileUploadAccessDeniedError() + + with pytest.raises(module.InvalidPluginFileUploadError) as error_info: + unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) + + assert error_info.value.code == 403 + assert error_info.value.error_code == "invalid_plugin_file_upload" + + @patch.object(module, "application_services") + def test_signed_size_limit_is_reported_as_413( + self, + application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr(module, "request", _fake_request(_valid_args(), file=DummyFile())) + application_services.return_value.plugin_file_uploads.upload.side_effect = ServiceFileTooLargeError( + "signed limit exceeded" + ) + + with pytest.raises(module.FileTooLargeError) as error_info: + unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) + + assert error_info.value.code == 413 + assert error_info.value.__cause__ is not None + + @patch.object(module, "application_services") + def test_unsupported_file_type_is_reported_as_415( + self, + application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr(module, "request", _fake_request(_valid_args(), file=DummyFile())) + application_services.return_value.plugin_file_uploads.upload.side_effect = ServiceUnsupportedFileTypeError() + + with pytest.raises(module.UnsupportedFileTypeError) as error_info: + unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) + + assert error_info.value.code == 415 + assert error_info.value.__cause__ is not None + + @patch.object(module, "application_services") + def test_unexpected_failure_is_not_relabelled_as_a_client_error( + self, + application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + storage_error = OSError("storage unavailable") + monkeypatch.setattr(module, "request", _fake_request(_valid_args(), file=DummyFile())) + application_services.return_value.plugin_file_uploads.upload.side_effect = storage_error + + with pytest.raises(OSError) as error_info: + unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) + + assert error_info.value is storage_error + + +class TestPluginUploadFileHttpContract: + @patch.object(module, "application_services") + def test_multipart_upload_returns_strict_201_and_consumer_fields( + self, + application_services: MagicMock, + files_app: Flask, + ) -> None: + application_services.return_value.plugin_file_uploads.upload.return_value = _result() + + response = files_app.test_client().post( + "/files/upload/for-plugin", + query_string=_valid_args(), + data={"file": (io.BytesIO(b"content"), "report.pdf")}, + content_type="multipart/form-data", + ) + + assert response.status_code == 201 + assert response.get_json() == { + "id": "file-id", + "reference": build_file_reference(record_id="file-id"), + "name": "report.pdf", + "size": 7, + "extension": ".pdf", + "mime_type": "application/pdf", + "created_by": None, + "created_at": None, + "preview_url": "https://files.example.com/files/tools/file-id.pdf?signed", + "source_url": None, + "original_url": None, + "user_id": "user-id", + "tenant_id": "tenant-id", + "conversation_id": "conversation-id", + "file_key": "tools/tenant-id/file.pdf", + } + + @patch.object(module, "application_services") + def test_invalid_signature_returns_a_structured_403( + self, + application_services: MagicMock, + files_app: Flask, + ) -> None: + application_services.return_value.plugin_file_uploads.upload.side_effect = PluginFileUploadAccessDeniedError() + + response = files_app.test_client().post( + "/files/upload/for-plugin", + query_string=_valid_args(), + data={"file": (io.BytesIO(b"content"), "report.pdf")}, + content_type="multipart/form-data", + ) + + assert response.status_code == 403 + assert response.get_json() == { + "code": "invalid_plugin_file_upload", + "message": "The plugin file upload request is invalid or expired.", + "status": 403, + } + + @patch.object(module, "application_services") + def test_signed_size_limit_returns_a_structured_413( + self, + application_services: MagicMock, + files_app: Flask, + ) -> None: + application_services.return_value.plugin_file_uploads.upload.side_effect = ServiceFileTooLargeError( + "signed limit exceeded" + ) + + response = files_app.test_client().post( + "/files/upload/for-plugin", + query_string=_valid_args(), + data={"file": (io.BytesIO(b"content"), "report.pdf")}, + content_type="multipart/form-data", + ) + + assert response.status_code == 413 + assert response.get_json() == { + "code": "file_too_large", + "message": "signed limit exceeded", + "status": 413, + } + + def test_missing_signed_user_id_returns_400_before_service_call(self, files_app: Flask) -> None: + query = _valid_args() + del query["user_id"] + + with patch.object(module, "application_services") as application_services: + response = files_app.test_client().post( + "/files/upload/for-plugin", + query_string=query, + data={"file": (io.BytesIO(b"content"), "report.pdf")}, + content_type="multipart/form-data", + ) + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_param" + application_services.assert_not_called() + + def test_missing_file_returns_a_structured_400(self, files_app: Flask) -> None: + with patch.object(module, "application_services") as application_services: + response = files_app.test_client().post( + "/files/upload/for-plugin", + query_string=_valid_args(), + data={}, + content_type="multipart/form-data", + ) + + assert response.status_code == 400 + assert response.get_json() == { + "code": "no_file_uploaded", + "message": "Please upload your file.", + "status": 400, + } + application_services.assert_not_called() diff --git a/api/tests/unit_tests/controllers/files/test_tool_files.py b/api/tests/unit_tests/controllers/files/test_tool_files.py index a41e2a056b1..3a7544dcbcf 100644 --- a/api/tests/unit_tests/controllers/files/test_tool_files.py +++ b/api/tests/unit_tests/controllers/files/test_tool_files.py @@ -1,168 +1,222 @@ import types +from collections.abc import Iterator from inspect import unwrap -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pytest from werkzeug.exceptions import Forbidden, NotFound import controllers.files.tool_files as module +from services.tool_file_download_service import ( + ToolFileDownload, + ToolFileDownloadAccessDeniedError, + ToolFileDownloadNotFoundError, +) -def fake_request(args: dict): - return types.SimpleNamespace(args=types.SimpleNamespace(to_dict=lambda flat=True: args)) +def _fake_request(args: dict[str, object]) -> types.SimpleNamespace: + return types.SimpleNamespace(args=types.SimpleNamespace(to_dict=lambda **_kwargs: args)) -class DummyToolFile: - def __init__(self, mime_type="text/plain", size=10, filename="tool.txt"): - self.mime_type = mime_type - self.size = size - self.filename = filename +def _set_request(monkeypatch: pytest.MonkeyPatch, args: dict[str, object]) -> None: + monkeypatch.setattr(module, "request", _fake_request(args)) -@pytest.fixture(autouse=True) -def mock_global_db(): - fake_db = types.SimpleNamespace(engine=object()) - module.global_db = fake_db +def _download( + *, + content: Iterator[bytes] | None = None, + mime_type: str | None = "text/plain", + filename: str | None = "tool.txt", + size: int = 10, +) -> ToolFileDownload: + return ToolFileDownload( + content=content if content is not None else iter([b"data"]), + mime_type=mime_type, + filename=filename, + size=size, + ) class TestToolFileApi: - @patch.object(module, "verify_tool_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") + @patch.object(module, "application_services") def test_success_stream( self, - mock_tool_file_manager, - mock_verify, - ): - module.request = fake_request( + mock_application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + _set_request( + monkeypatch, { "timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False, - } + }, ) - stream = iter([b"data"]) - tool_file = DummyToolFile(size=100) + service = mock_application_services.return_value.tool_file_downloads + service.get_signed_file.return_value = _download(content=stream, size=100) - mock_tool_file_manager.return_value.get_file_generator_by_tool_file_id.return_value = ( - stream, - tool_file, - ) - - api = module.ToolFileApi() - get_fn = unwrap(api.get) - - response = get_fn("file-id", "txt") + response = unwrap(module.ToolFileApi().get)("file-id", "txt") + assert response.response is stream assert response.mimetype == "text/plain" assert response.headers["Content-Length"] == "100" - mock_verify.assert_called_once_with( + assert response.direct_passthrough is True + service.get_signed_file.assert_called_once_with( file_id="file-id", timestamp="123", nonce="abc", sign="sig", ) - @patch.object(module, "verify_tool_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") - def test_as_attachment( + @patch.object(module, "application_services") + def test_zero_size_omits_content_length( self, - mock_tool_file_manager, - mock_verify, - ): - module.request = fake_request( + mock_application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + _set_request( + monkeypatch, + { + "timestamp": "123", + "nonce": "abc", + "sign": "sig", + "as_attachment": False, + }, + ) + mock_application_services.return_value.tool_file_downloads.get_signed_file.return_value = _download(size=0) + + response = unwrap(module.ToolFileApi().get)("file-id", "txt") + + assert "Content-Length" not in response.headers + + @patch.object(module, "application_services") + def test_as_attachment_preserves_mime_type( + self, + mock_application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + _set_request( + monkeypatch, { "timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": True, - } + }, ) - - stream = iter([b"data"]) - tool_file = DummyToolFile( + mock_application_services.return_value.tool_file_downloads.get_signed_file.return_value = _download( mime_type="application/pdf", - filename="doc.pdf", + filename="报告.pdf", ) - mock_tool_file_manager.return_value.get_file_generator_by_tool_file_id.return_value = ( - stream, - tool_file, + response = unwrap(module.ToolFileApi().get)("file-id", "pdf") + + assert response.headers["Content-Disposition"] == "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.pdf" + assert response.headers["Content-Type"] == "application/pdf" + + @pytest.mark.parametrize( + ("mime_type", "filename", "route_extension"), + [ + pytest.param("text/html", "file.txt", "txt", id="mime-type"), + pytest.param("text/plain", "file.HTML", "txt", id="filename"), + pytest.param("text/plain", "file.txt", "html", id="route-extension"), + ], + ) + @patch.object(module, "application_services") + def test_html_forces_download( + self, + mock_application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + mime_type: str, + filename: str, + route_extension: str, + ) -> None: + _set_request( + monkeypatch, + { + "timestamp": "123", + "nonce": "abc", + "sign": "sig", + "as_attachment": False, + }, + ) + mock_application_services.return_value.tool_file_downloads.get_signed_file.return_value = _download( + mime_type=mime_type, + filename=filename, ) - api = module.ToolFileApi() - get_fn = unwrap(api.get) - - response = get_fn("file-id", "pdf") + response = unwrap(module.ToolFileApi().get)("file-id", route_extension) assert response.headers["Content-Disposition"].startswith("attachment") - mock_verify.assert_called_once() + assert response.headers["Content-Type"] == "application/octet-stream" + assert response.headers["X-Content-Type-Options"] == "nosniff" - @patch.object(module, "verify_tool_file_signature", return_value=False) - def test_invalid_signature(self, mock_verify): - module.request = fake_request( + @patch.object(module, "application_services") + def test_invalid_signature( + self, + mock_application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + _set_request( + monkeypatch, { "timestamp": "123", "nonce": "abc", "sign": "bad-sig", "as_attachment": False, - } + }, + ) + mock_application_services.return_value.tool_file_downloads.get_signed_file.side_effect = ( + ToolFileDownloadAccessDeniedError() ) - api = module.ToolFileApi() - get_fn = unwrap(api.get) + with pytest.raises(Forbidden, match=r"Invalid request\."): + unwrap(module.ToolFileApi().get)("file-id", "txt") - with pytest.raises(Forbidden): - get_fn("file-id", "txt") - - @patch.object(module, "verify_tool_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") + @patch.object(module, "application_services") def test_file_not_found( self, - mock_tool_file_manager, - mock_verify, - ): - module.request = fake_request( + mock_application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + _set_request( + monkeypatch, { "timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False, - } + }, + ) + mock_application_services.return_value.tool_file_downloads.get_signed_file.side_effect = ( + ToolFileDownloadNotFoundError() ) - mock_tool_file_manager.return_value.get_file_generator_by_tool_file_id.return_value = ( - None, - None, - ) + with pytest.raises(NotFound, match="file is not found"): + unwrap(module.ToolFileApi().get)("file-id", "txt") - api = module.ToolFileApi() - get_fn = unwrap(api.get) - - with pytest.raises(NotFound): - get_fn("file-id", "txt") - - @patch.object(module, "verify_tool_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") - def test_unsupported_file_type( + @pytest.mark.parametrize("service_error", [RuntimeError("database unavailable"), OSError("storage unavailable")]) + @patch.object(module, "application_services") + def test_unexpected_error_is_not_converted( self, - mock_tool_file_manager, - mock_verify, - ): - module.request = fake_request( + mock_application_services: MagicMock, + monkeypatch: pytest.MonkeyPatch, + service_error: Exception, + ) -> None: + _set_request( + monkeypatch, { "timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False, - } + }, ) + mock_application_services.return_value.tool_file_downloads.get_signed_file.side_effect = service_error - mock_tool_file_manager.return_value.get_file_generator_by_tool_file_id.side_effect = Exception("boom") + with pytest.raises(type(service_error)) as error_info: + unwrap(module.ToolFileApi().get)("file-id", "txt") - api = module.ToolFileApi() - get_fn = unwrap(api.get) - - with pytest.raises(module.UnsupportedFileTypeError): - get_fn("file-id", "txt") + assert error_info.value is service_error diff --git a/api/tests/unit_tests/controllers/files/test_upload.py b/api/tests/unit_tests/controllers/files/test_upload.py deleted file mode 100644 index 7deb85df876..00000000000 --- a/api/tests/unit_tests/controllers/files/test_upload.py +++ /dev/null @@ -1,433 +0,0 @@ -import io -import types -from contextlib import contextmanager -from inspect import unwrap -from unittest.mock import MagicMock, patch - -import pytest -from sqlalchemy.orm import Session -from werkzeug.exceptions import Forbidden - -import controllers.files.upload as module -from core.workflow.file_reference import build_file_reference -from models import Account, TenantAccountJoin -from models.account import AccountStatus -from models.enums import EndUserType -from models.model import EndUser -from models.tools import ToolFile - - -def fake_request(args: dict, file=None): - return types.SimpleNamespace( - args=types.SimpleNamespace(to_dict=lambda flat=True: args), - files={"file": file} if file else {}, - ) - - -def _persist_account_memberships(session: Session) -> None: - account = Account(name="Tenant member", email="member@example.com", status=AccountStatus.ACTIVE) - account.id = "account-1" - decoy = Account(name="Other tenant member", email="decoy@example.com", status=AccountStatus.ACTIVE) - decoy.id = "account-outside-tenant" - session.add_all( - [ - account, - decoy, - TenantAccountJoin(tenant_id="tenant-1", account_id=account.id), - TenantAccountJoin(tenant_id="tenant-other", account_id=decoy.id), - ] - ) - session.commit() - - -def _end_user(user_id: str = "user-1") -> EndUser: - return EndUser( - id=user_id, - tenant_id="tenant-1", - type=EndUserType.SERVICE_API, - session_id="session-1", - ) - - -class DummyFile: - def __init__(self, filename="test.txt", mimetype="text/plain", content=b"data"): - self.filename = filename - self.mimetype = mimetype - self._content = content - self.stream = io.BytesIO(content) - - def read(self): - return self.stream.read() - - -class RecordingStream(io.BytesIO): - def __init__(self, content: bytes, events: list[str]): - super().__init__(content) - self.events = events - - def read(self, *args, **kwargs): - self.events.append("file-read") - return super().read(*args, **kwargs) - - -def _tool_file(*, name: str = "test.txt", mimetype: str = "text/plain") -> ToolFile: - tool_file = ToolFile( - user_id="user-1", - tenant_id="tenant-1", - conversation_id=None, - file_key="file-key", - mimetype=mimetype, - original_url="http://original", - name=name, - size=10, - ) - tool_file.id = "file-id" - return tool_file - - -class TestPluginUploadFileApi: - @patch.object(module, "verify_plugin_file_signature", return_value=True) - @patch.object(module, "get_user", return_value=_end_user()) - @patch.object(module, "sign_tool_file", return_value="signed-url") - @patch.object(module, "ToolFileManager") - def test_success_upload( - self, - mock_tool_file_manager, - mock_sign_tool_file, - mock_get_user, - mock_verify_signature, - ): - dummy_file = DummyFile(filename="report.docx", mimetype="application/octet-stream") - - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "user-1", - "conversation_id": "conversation-1", - }, - file=dummy_file, - ) - - tool_file_manager_instance = mock_tool_file_manager.return_value - tool_file_manager_instance.create_file_by_raw.return_value = _tool_file( - name="report.docx", - mimetype="application/octet-stream", - ) - - api = module.PluginUploadFileApi() - post_fn = unwrap(api.post) - - result, status_code = post_fn(api) - - assert status_code == 201 - assert result["id"] == "file-id" - assert result["reference"] == build_file_reference(record_id="file-id") - assert result["preview_url"] == "signed-url" - assert result["extension"] == ".docx" - mock_verify_signature.assert_called_once() - assert mock_verify_signature.call_args.kwargs["conversation_id"] == "conversation-1" - tool_file_manager_instance.create_file_by_raw.assert_called_once() - assert tool_file_manager_instance.create_file_by_raw.call_args.kwargs["conversation_id"] == "conversation-1" - mock_sign_tool_file.assert_called_once_with( - tool_file_id="file-id", - extension=".docx", - for_external=True, - ) - - @patch.object(module, "get_user") - @patch.object(module, "ToolFileManager") - @pytest.mark.parametrize("sqlite_session", [(Account, TenantAccountJoin)], indirect=True) - def test_account_upload_preserves_signed_account_owner( - self, - mock_tool_file_manager, - mock_get_user, - monkeypatch: pytest.MonkeyPatch, - sqlite_session: Session, - ): - _persist_account_memberships(sqlite_session) - events: list[str] = [] - dummy_file = DummyFile(filename="report.pdf", mimetype="application/pdf", content=b"account-owned") - dummy_file.stream = RecordingStream(b"account-owned", events) - - @contextmanager - def membership_session(): - events.append("membership-session-enter") - try: - yield sqlite_session - finally: - events.append("membership-session-exit") - - monkeypatch.setattr(module.session_factory, "create_session", membership_session) - monkeypatch.setattr( - module, - "request", - fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "account-1", - "user_from": "account", - }, - file=dummy_file, - ), - ) - tool_file_manager = mock_tool_file_manager.return_value - tool_file_manager.create_file_by_raw.side_effect = lambda **_kwargs: ( - events.append("storage-create-file") or _tool_file(name="report.pdf", mimetype="application/pdf") - ) - mock_tool_file_manager.sign_file.return_value = "signed-url" - - with patch.object( - module, - "verify_plugin_file_signature", - side_effect=lambda **_kwargs: events.append("signature-verify") or True, - ) as verify_signature: - api = module.PluginUploadFileApi() - result, status_code = unwrap(api.post)(api) - - assert status_code == 201 - assert result["reference"] == build_file_reference(record_id="file-id") - assert events == [ - "membership-session-enter", - "membership-session-exit", - "signature-verify", - "file-read", - "storage-create-file", - ] - mock_get_user.assert_not_called() - verify_signature.assert_called_once_with( - filename="report.pdf", - mimetype="application/pdf", - tenant_id="tenant-1", - user_id="account-1", - conversation_id=None, - user_from="account", - timestamp="123", - nonce="abc", - sign="sig", - max_size=None, - ) - tool_file_manager.create_file_by_raw.assert_called_once_with( - user_id="account-1", - tenant_id="tenant-1", - file_binary=b"account-owned", - mimetype="application/pdf", - filename="report.pdf", - conversation_id=None, - ) - - @patch.object(module, "verify_plugin_file_signature") - @patch.object(module, "get_user") - @patch.object(module, "ToolFileManager") - @pytest.mark.parametrize("sqlite_session", [(Account, TenantAccountJoin)], indirect=True) - def test_account_upload_rejects_owner_outside_tenant( - self, - mock_tool_file_manager, - mock_get_user, - mock_verify_signature, - monkeypatch: pytest.MonkeyPatch, - sqlite_session: Session, - ): - _persist_account_memberships(sqlite_session) - events: list[str] = [] - - @contextmanager - def membership_session(): - events.append("membership-session-enter") - try: - yield sqlite_session - finally: - events.append("membership-session-exit") - - monkeypatch.setattr(module.session_factory, "create_session", membership_session) - monkeypatch.setattr( - module, - "request", - fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "account-outside-tenant", - "user_from": "account", - }, - file=DummyFile(), - ), - ) - - api = module.PluginUploadFileApi() - with pytest.raises(Forbidden): - unwrap(api.post)(api) - - assert events == ["membership-session-enter", "membership-session-exit"] - mock_get_user.assert_not_called() - mock_verify_signature.assert_not_called() - mock_tool_file_manager.assert_not_called() - - def test_missing_file(self): - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "user-1", - } - ) - - api = module.PluginUploadFileApi() - post_fn = unwrap(api.post) - - with pytest.raises(Forbidden): - post_fn(api) - - @patch.object(module, "get_user", return_value=_end_user()) - @patch.object(module, "verify_plugin_file_signature", return_value=False) - def test_invalid_signature(self, mock_verify, mock_get_user): - dummy_file = DummyFile() - - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "bad", - "tenant_id": "tenant-1", - "user_id": "user-1", - }, - file=dummy_file, - ) - - api = module.PluginUploadFileApi() - post_fn = unwrap(api.post) - - with pytest.raises(Forbidden): - post_fn(api) - - @patch.object(module, "get_user", return_value=_end_user()) - @patch.object(module, "verify_plugin_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") - def test_file_too_large( - self, - mock_tool_file_manager, - mock_verify, - mock_get_user, - ): - dummy_file = DummyFile() - - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "user-1", - }, - file=dummy_file, - ) - - mock_tool_file_manager.return_value.create_file_by_raw.side_effect = ( - module.services.errors.file.FileTooLargeError("too large") - ) - - api = module.PluginUploadFileApi() - post_fn = unwrap(api.post) - - with pytest.raises(module.FileTooLargeError): - post_fn(api) - - @patch.object(module, "get_user", return_value=_end_user()) - @patch.object(module, "verify_plugin_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") - def test_signed_max_size_bounds_file_read( - self, - mock_tool_file_manager, - mock_verify, - mock_get_user, - ): - dummy_file = DummyFile(content=b"data") - dummy_file.stream = MagicMock() - dummy_file.stream.read.return_value = b"data" - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "user-1", - "max_size": "4", - }, - file=dummy_file, - ) - mock_tool_file_manager.return_value.create_file_by_raw.return_value = _tool_file() - mock_tool_file_manager.sign_file.return_value = "signed-url" - - unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) - - dummy_file.stream.read.assert_called_once_with(5) - assert mock_verify.call_args.kwargs["max_size"] == 4 - assert mock_tool_file_manager.return_value.create_file_by_raw.call_args.kwargs["file_binary"] == b"data" - - @patch.object(module, "get_user", return_value=_end_user()) - @patch.object(module, "verify_plugin_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") - def test_signed_max_size_rejects_oversized_file_before_creation( - self, - mock_tool_file_manager, - mock_verify, - mock_get_user, - ): - dummy_file = DummyFile(content=b"oversized") - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "user-1", - "max_size": "4", - }, - file=dummy_file, - ) - - with pytest.raises(module.FileTooLargeError): - unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi()) - - mock_tool_file_manager.assert_not_called() - - @patch.object(module, "get_user", return_value=_end_user()) - @patch.object(module, "verify_plugin_file_signature", return_value=True) - @patch.object(module, "ToolFileManager") - def test_unsupported_file_type( - self, - mock_tool_file_manager, - mock_verify, - mock_get_user, - ): - dummy_file = DummyFile() - - module.request = fake_request( - { - "timestamp": "123", - "nonce": "abc", - "sign": "sig", - "tenant_id": "tenant-1", - "user_id": "user-1", - }, - file=dummy_file, - ) - - mock_tool_file_manager.return_value.create_file_by_raw.side_effect = ( - module.services.errors.file.UnsupportedFileTypeError() - ) - - api = module.PluginUploadFileApi() - post_fn = unwrap(api.post) - - with pytest.raises(module.UnsupportedFileTypeError): - post_fn(api) diff --git a/api/tests/unit_tests/controllers/files/test_upload_file_delivery.py b/api/tests/unit_tests/controllers/files/test_upload_file_delivery.py new file mode 100644 index 00000000000..b390c526ac4 --- /dev/null +++ b/api/tests/unit_tests/controllers/files/test_upload_file_delivery.py @@ -0,0 +1,236 @@ +import types +from inspect import unwrap +from unittest.mock import patch + +import pytest +from werkzeug.exceptions import NotFound + +import controllers.files.upload_file_delivery as module +from services.errors.file import UnsupportedFileTypeError as UnsupportedFileTypeServiceError +from services.upload_file_delivery_service import ( + UploadFileDelivery, + UploadFileDeliveryNotFoundError, + UploadFileDeliveryRecord, +) + + +def _delivery( + *, + mime_type: str | None = "text/plain", + size: int = 10, + name: str = "test.txt", + extension: str = "txt", + content: bytes | None = None, +) -> UploadFileDelivery: + return UploadFileDelivery( + content=content if content is not None else iter([b"data"]), + file=UploadFileDeliveryRecord( + key="uploads/file-id", + name=name, + size=size, + extension=extension, + mime_type=mime_type, + ), + ) + + +def _fake_request(args: dict[str, object]): + return types.SimpleNamespace(args=types.SimpleNamespace(to_dict=lambda **_kwargs: args)) + + +class TestImagePreviewApi: + @patch.object(module, "application_services") + def test_success(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig"}) + service = mock_application_services.return_value.upload_file_delivery + service.get_signed_image_preview.return_value = _delivery(mime_type="image/png", extension="png") + + response = unwrap(module.ImagePreviewApi().get)("file-id") + + assert response.mimetype == "image/png" + service.get_signed_image_preview.assert_called_once_with( + file_id="file-id", + timestamp="123", + nonce="abc", + sign="sig", + ) + + @patch.object(module, "application_services") + def test_not_found(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig"}) + service = mock_application_services.return_value.upload_file_delivery + service.get_signed_image_preview.side_effect = UploadFileDeliveryNotFoundError( + "File not found or signature is invalid" + ) + + with pytest.raises(NotFound, match="File not found or signature is invalid"): + unwrap(module.ImagePreviewApi().get)("file-id") + + @patch.object(module, "application_services") + def test_unsupported_file_type(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig"}) + service = mock_application_services.return_value.upload_file_delivery + service.get_signed_image_preview.side_effect = UnsupportedFileTypeServiceError() + + with pytest.raises(module.UnsupportedFileTypeError): + unwrap(module.ImagePreviewApi().get)("file-id") + + +class TestFilePreviewApi: + @patch.object(module, "enforce_download_for_html") + @patch.object(module, "application_services") + def test_inline_preview_uses_file_metadata(self, mock_application_services, mock_enforce): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False}) + service = mock_application_services.return_value.upload_file_delivery + service.get_signed_file_preview.return_value = _delivery( + mime_type="application/pdf", + size=100, + name="doc.pdf", + extension="pdf", + ) + + response = unwrap(module.FilePreviewApi().get)("file-id") + + assert response.mimetype == "application/pdf" + assert response.headers["Content-Type"] == "application/pdf" + assert response.headers["Content-Length"] == "100" + assert "Accept-Ranges" not in response.headers + mock_enforce.assert_called_once_with( + response, + mime_type="application/pdf", + filename="doc.pdf", + extension="pdf", + ) + + @patch.object(module, "application_services") + def test_audio_preview_supports_ranges(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False}) + mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery( + mime_type="audio/mpeg", + extension="mp3", + ) + + response = unwrap(module.FilePreviewApi().get)("file-id") + + assert response.headers["Accept-Ranges"] == "bytes" + + @patch.object(module, "application_services") + def test_zero_size_omits_content_length(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False}) + mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery( + size=0 + ) + + response = unwrap(module.FilePreviewApi().get)("file-id") + + assert "Content-Length" not in response.headers + + @pytest.mark.parametrize( + ("mime_type", "name", "extension"), + [ + ("Image/SVG+XML; charset=UTF-8", "image.png", "png"), + ("image/png", "image.SVG", "png"), + ("image/png", "image.png", ".SVG"), + ], + ids=("mime-type", "filename", "extension"), + ) + @patch.object(module, "application_services") + def test_svg_preview_forces_download(self, mock_application_services, mime_type, name, extension): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False}) + mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery( + mime_type=mime_type, + size=11, + name=name, + extension=extension, + ) + + response = unwrap(module.FilePreviewApi().get)("file-id") + + assert response.headers["Content-Disposition"].startswith("attachment") + assert response.headers["Content-Type"] == "application/octet-stream" + assert response.headers["X-Content-Type-Options"] == "nosniff" + + @patch.object(module, "application_services") + def test_html_preview_still_forces_download(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False}) + mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery( + mime_type="text/html", + size=25, + name="unsafe.html", + extension="html", + ) + + response = unwrap(module.FilePreviewApi().get)("file-id") + + assert response.headers["Content-Disposition"].startswith("attachment") + assert response.headers["Content-Type"] == "application/octet-stream" + assert response.headers["X-Content-Type-Options"] == "nosniff" + + @patch.object(module, "application_services") + def test_as_attachment_encodes_filename(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": True}) + mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery( + mime_type="application/pdf", + name="报告.pdf", + extension="pdf", + ) + + response = unwrap(module.FilePreviewApi().get)("file-id") + + assert response.headers["Content-Disposition"] == "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.pdf" + assert response.headers["Content-Type"] == "application/octet-stream" + + @patch.object(module, "application_services") + def test_not_found(self, mock_application_services): + module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False}) + mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.side_effect = ( + UploadFileDeliveryNotFoundError("File not found or signature is invalid") + ) + + with pytest.raises(NotFound, match="File not found or signature is invalid"): + unwrap(module.FilePreviewApi().get)("file-id") + + +class TestWorkspaceWebappLogoApi: + @patch.object(module, "application_services") + def test_success(self, mock_application_services): + service = mock_application_services.return_value.upload_file_delivery + service.get_workspace_webapp_logo.return_value = _delivery( + content=b"logo", + mime_type="image/png", + extension="png", + ) + + response = unwrap(module.WorkspaceWebappLogoApi().get)("workspace-id") + + assert response.mimetype == "image/png" + service.get_workspace_webapp_logo.assert_called_once_with(workspace_id="workspace-id") + + @patch.object(module, "application_services") + def test_logo_not_configured(self, mock_application_services): + mock_application_services.return_value.upload_file_delivery.get_workspace_webapp_logo.side_effect = ( + UploadFileDeliveryNotFoundError("webapp logo is not found") + ) + + with pytest.raises(NotFound, match="webapp logo is not found"): + unwrap(module.WorkspaceWebappLogoApi().get)("workspace-id") + + @patch.object(module, "application_services") + def test_workspace_not_found_uses_default_404(self, mock_application_services): + mock_application_services.return_value.upload_file_delivery.get_workspace_webapp_logo.side_effect = ( + UploadFileDeliveryNotFoundError() + ) + + with pytest.raises(NotFound) as error: + unwrap(module.WorkspaceWebappLogoApi().get)("workspace-id") + + assert error.value.description == NotFound.description + + @patch.object(module, "application_services") + def test_unsupported_file_type(self, mock_application_services): + mock_application_services.return_value.upload_file_delivery.get_workspace_webapp_logo.side_effect = ( + UnsupportedFileTypeServiceError() + ) + + with pytest.raises(module.UnsupportedFileTypeError): + unwrap(module.WorkspaceWebappLogoApi().get)("workspace-id") diff --git a/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py b/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py index c92349c59ad..f7c8e653a49 100644 --- a/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py +++ b/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py @@ -12,8 +12,10 @@ from unittest.mock import patch import pytest from flask import Flask +from flask_restx import Resource from pydantic import ValidationError from sqlalchemy.orm import Session, scoped_session, sessionmaker +from werkzeug.exceptions import UnprocessableEntity from controllers.inner_api.workspace.workspace import ( EnterpriseWorkspace, @@ -29,6 +31,7 @@ from services.account_service import ( EnterpriseWorkspaceMemberAccountNotFoundError, EnterpriseWorkspaceMemberWorkspaceNotFoundError, ) +from tests.unit_tests.config_override import config_overrides_context @pytest.fixture @@ -145,10 +148,9 @@ class TestEnterpriseWorkspace: # Act — unwrap to bypass auth/setup decorators (tested in test_auth_wraps.py) unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = {"name": "My Workspace", "owner_email": "owner@example.com"} - result = unwrapped_post(api_instance) + payload = {"name": "My Workspace", "owner_email": "owner@example.com"} + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceCreatePayload.model_validate(payload)) # Assert assert result["message"] == "enterprise workspace created." @@ -168,10 +170,9 @@ class TestEnterpriseWorkspace: """Test that post() returns 404 when the owner account does not exist""" # Act unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = {"name": "My Workspace", "owner_email": "missing@example.com"} - result = unwrapped_post(api_instance) + payload = {"name": "My Workspace", "owner_email": "missing@example.com"} + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceCreatePayload.model_validate(payload)) # Assert assert result == ({"message": "owner account not found."}, 404) @@ -214,10 +215,9 @@ class TestEnterpriseWorkspaceNoOwnerEmail: # Act — unwrap to bypass auth/setup decorators (tested in test_auth_wraps.py) unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = {"name": "My Workspace"} - result = unwrapped_post(api_instance) + payload = {"name": "My Workspace"} + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceOwnerlessPayload.model_validate(payload)) # Assert assert result["message"] == "enterprise workspace created." @@ -251,16 +251,15 @@ class TestEnterpriseWorkspaceMember: mock_tenant_svc.join_enterprise_workspace_member.return_value = membership unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = { - "workspace_id": "workspace-id", - "account_id": "account-id", - "email": "member@example.com", - "role": "normal", - "operator_account_id": "operator-id", - } - result = unwrapped_post(api_instance) + payload = { + "workspace_id": "workspace-id", + "account_id": "account-id", + "email": "member@example.com", + "role": "normal", + "operator_account_id": "operator-id", + } + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload)) assert result["message"] == "enterprise workspace member joined." assert result["member"] == { @@ -281,15 +280,14 @@ class TestEnterpriseWorkspaceMember: mock_tenant_svc.join_enterprise_workspace_member.side_effect = EnterpriseWorkspaceMemberWorkspaceNotFoundError unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = { - "workspace_id": "missing-workspace", - "account_id": "account-id", - "email": "member@example.com", - "role": "normal", - } - result = unwrapped_post(api_instance) + payload = { + "workspace_id": "missing-workspace", + "account_id": "account-id", + "email": "member@example.com", + "role": "normal", + } + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload)) assert result == ({"message": "workspace not found."}, 404) mock_tenant_svc.join_enterprise_workspace_member.assert_called_once() @@ -299,15 +297,14 @@ class TestEnterpriseWorkspaceMember: mock_tenant_svc.join_enterprise_workspace_member.side_effect = EnterpriseWorkspaceMemberAccountNotFoundError unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = { - "workspace_id": "workspace-id", - "account_id": "missing-account", - "email": "member@example.com", - "role": "normal", - } - result = unwrapped_post(api_instance) + payload = { + "workspace_id": "workspace-id", + "account_id": "missing-account", + "email": "member@example.com", + "role": "normal", + } + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload)) assert result == ({"message": "account not found."}, 404) mock_tenant_svc.join_enterprise_workspace_member.assert_called_once() @@ -315,29 +312,56 @@ class TestEnterpriseWorkspaceMember: @pytest.mark.usefixtures("database_session") def test_post_rejects_owner_role(self, api_instance, app: Flask): unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = { - "workspace_id": "workspace-id", - "account_id": "account-id", - "email": "member@example.com", - "role": "owner", - } - result = unwrapped_post(api_instance) + payload = { + "workspace_id": "workspace-id", + "account_id": "account-id", + "email": "member@example.com", + "role": "owner", + } + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload)) assert result == ({"message": "cannot join workspace as owner."}, 400) @pytest.mark.usefixtures("database_session") def test_post_rejects_invalid_role(self, api_instance, app: Flask): unwrapped_post = inspect.unwrap(api_instance.post) - with app.test_request_context(): - with patch("controllers.inner_api.workspace.workspace.inner_api_ns") as mock_ns: - mock_ns.payload = { - "workspace_id": "workspace-id", - "account_id": "account-id", - "email": "member@example.com", - "role": "not-a-role", - } - result = unwrapped_post(api_instance) + payload = { + "workspace_id": "workspace-id", + "account_id": "account-id", + "email": "member@example.com", + "role": "not-a-role", + } + with app.test_request_context(json=payload): + result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload)) assert result == ({"message": "invalid workspace member role."}, 400) + + +class TestModelValidateDecorator: + """The handler tests unwrap the view, so this is what covers the decorators themselves.""" + + @pytest.mark.parametrize( + ("api_cls", "route"), + [ + (EnterpriseWorkspace, "/enterprise/workspace"), + (EnterpriseWorkspaceNoOwnerEmail, "/enterprise/workspace/ownerless"), + (EnterpriseWorkspaceMember, "/enterprise/workspace/member"), + ], + ) + def test_invalid_body_is_rejected_before_the_handler_runs( + self, app: Flask, api_cls: type[Resource], route: str + ) -> None: + api_instance = api_cls() + + with ( + config_overrides_context(INNER_API=True, INNER_API_KEY="inner-key"), + app.test_request_context(route, method="POST", json={}, headers={"X-Inner-Api-Key": "inner-key"}), + patch("controllers.console.wraps._is_setup_completed", return_value=True), + patch("controllers.inner_api.workspace.workspace.TenantService") as tenant_service, + ): + with pytest.raises(UnprocessableEntity) as exc_info: + api_instance.post() + + assert exc_info.value.code == 422 + tenant_service.assert_not_called() diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py b/api/tests/unit_tests/controllers/openapi/auth/test_composition.py index a6629caabcf..d61a38848f0 100644 --- a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py +++ b/api/tests/unit_tests/controllers/openapi/auth/test_composition.py @@ -1,7 +1,8 @@ import uuid +from controllers.common.rbac import PlainApp, RBACCheck from controllers.openapi.auth.composition import account_pipeline, auth_router, external_sso_pipeline -from controllers.openapi.auth.data import RBACRequirement, RequestContext +from controllers.openapi.auth.data import RequestContext from controllers.openapi.auth.flow import When from controllers.openapi.auth.pipeline import AuthPipeline, PipelineRoute, PipelineRouter from controllers.openapi.auth.verify import ( @@ -12,7 +13,7 @@ from controllers.openapi.auth.verify import ( check_workspace_mismatch, check_workspace_role, ) -from core.rbac import RBACPermission, RBACResourceScope +from core.rbac import RBACPermission from enums import DeploymentEdition from libs.oauth_bearer import Scope, TokenType from models.account import TenantAccountRole @@ -206,7 +207,7 @@ def _selected_auth_steps_with_rbac(rbac): def test_account_pipeline_selects_rbac_step_when_required(): - rbac = RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_VIEW_LAYOUT) + rbac = RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()) assert check_rbac_permission in _selected_auth_steps_with_rbac(rbac) diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py index 2d67cc84883..59776892903 100644 --- a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py +++ b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py @@ -1,5 +1,6 @@ from unittest.mock import patch +from controllers.common.rbac import PlainApp, RBACCheck from controllers.openapi.auth.conditions import ( EDITION_CLOUD, EDITION_COMMUNITY, @@ -18,8 +19,8 @@ from controllers.openapi.auth.conditions import ( data_cond, request_cond, ) -from controllers.openapi.auth.data import AuthData, RBACRequirement, RequestContext -from core.rbac import RBACPermission, RBACResourceScope +from controllers.openapi.auth.data import AuthData, RequestContext +from core.rbac import RBACPermission from enums import DeploymentEdition from libs.oauth_bearer import Scope, TokenType from models.account import TenantAccountRole @@ -153,7 +154,7 @@ def test_webapp_run_scoped_false_when_scope_none(): def _rbac_req(): - return RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_TEST_AND_RUN) + return RBACCheck(RBACPermission.APP_TEST_AND_RUN, PlainApp()) def test_has_rbac_true(): diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_verify.py b/api/tests/unit_tests/controllers/openapi/auth/test_verify.py index cf0082bc5d6..89c38c59e4d 100644 --- a/api/tests/unit_tests/controllers/openapi/auth/test_verify.py +++ b/api/tests/unit_tests/controllers/openapi/auth/test_verify.py @@ -6,7 +6,8 @@ import pytest from flask import Flask from werkzeug.exceptions import Forbidden, NotFound -from controllers.openapi.auth.data import AuthData, RBACRequirement +from controllers.common.rbac import PlainApp, RBACCheck +from controllers.openapi.auth.data import AuthData from controllers.openapi.auth.verify import ( check_acl, check_app_access, @@ -18,7 +19,7 @@ from controllers.openapi.auth.verify import ( check_workspace_mismatch, check_workspace_role, ) -from core.rbac import RBACPermission, RBACResourceScope +from core.rbac import RBACPermission from libs.oauth_bearer import Scope, TokenType from models.account import Tenant, TenantAccountRole from models.model import App @@ -85,25 +86,25 @@ def test_check_app_access_raises_when_not_member(): # --- check_rbac_permission --- -_RBAC_REQ = RBACRequirement(resource_type=RBACResourceScope.APP, scene=RBACPermission.APP_VIEW_LAYOUT) +_RBAC_REQ = RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()) def test_check_rbac_noop_when_no_requirement(): - with patch("controllers.openapi.auth.verify.enforce_rbac_access") as mock_enforce: + with patch("controllers.openapi.auth.verify.enforce_rbac_checks") as mock_enforce: check_rbac_permission(_data(rbac=None, caller_kind="account")) mock_enforce.assert_not_called() def test_check_rbac_noop_when_rbac_disabled(config_overrides: Callable[..., None]): config_overrides(RBAC_ENABLED=False) - with patch("controllers.openapi.auth.verify.enforce_rbac_access") as mock_enforce: + with patch("controllers.openapi.auth.verify.enforce_rbac_checks") as mock_enforce: check_rbac_permission(_data(rbac=_RBAC_REQ, caller_kind="account")) mock_enforce.assert_not_called() def test_check_rbac_skips_end_user_caller(): with ( - patch("controllers.openapi.auth.verify.enforce_rbac_access") as mock_enforce, + patch("controllers.openapi.auth.verify.enforce_rbac_checks") as mock_enforce, ): check_rbac_permission(_data(rbac=_RBAC_REQ, caller_kind="end_user")) mock_enforce.assert_not_called() @@ -126,17 +127,18 @@ def test_check_rbac_enforces_for_account_caller(): path_params={"app_id": "app-1"}, ) with ( - patch("controllers.openapi.auth.verify.enforce_rbac_access") as mock_enforce, + patch("controllers.openapi.auth.verify.enforce_rbac_checks") as mock_enforce, ): check_rbac_permission(data) - mock_enforce.assert_called_once_with( - tenant_id="t1", - account_id=str(account_id), - resource_type=RBACResourceScope.APP, - scene=RBACPermission.APP_VIEW_LAYOUT, - resource_required=True, - path_args={"app_id": "app-1"}, - ) + mock_enforce.assert_called_once() + call_kwargs = mock_enforce.call_args.kwargs + assert call_kwargs["tenant_id"] == "t1" + assert call_kwargs["account_id"] == str(account_id) + assert call_kwargs["path_args"] == {"app_id": "app-1"} + (check,) = call_kwargs["checks"] + assert isinstance(check, RBACCheck) + assert check.scene is RBACPermission.APP_VIEW_LAYOUT + assert isinstance(check.locator, PlainApp) def test_check_acl_raises_when_app_or_mode_missing(): diff --git a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py index a5cd7ca5b9c..33a726e9c41 100644 --- a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py +++ b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py @@ -42,6 +42,7 @@ from controllers.openapi.workspaces import ( WorkspaceMembersApi, WorkspaceSwitchApi, ) +from enums import DeploymentEdition from libs.oauth_bearer import AuthContext, Scope, SubjectType, TokenType, reset_auth_ctx, set_auth_ctx from models import Account, Tenant, TenantAccountJoin from models.account import AccountStatus, TenantAccountRole, TenantStatus @@ -55,6 +56,7 @@ from services.errors.account import ( NoPermissionError, RoleAlreadyAssignedError, ) +from tests.unit_tests.config_override import config_overrides_context if not hasattr(builtins, "MethodView"): builtins.MethodView = MethodView # type: ignore[attr-defined] @@ -444,7 +446,6 @@ def test_invite_happy_path_returns_invite_url_and_member_id( def _features( *, - billing_enabled: bool = False, members_size: int = 0, members_limit: int = 0, workspace_members_enabled: bool = False, @@ -452,17 +453,16 @@ def _features( workspace_members_limit: int = 0, ) -> SimpleNamespace: """Build a feature object matching the surface `_check_member_invite_quota` - reads: `.billing.enabled`, `.members.{size,limit}`, + reads: `.members.{size,limit}`, `.workspace_members.{enabled, is_available(N)}`. - Defaults model CE (both flags off, both caps inert). + Defaults leave both quotas unrestricted. """ def _is_available(n: int) -> bool: return workspace_members_size + n <= workspace_members_limit return SimpleNamespace( - billing=SimpleNamespace(enabled=billing_enabled), members=SimpleNamespace(size=members_size, limit=members_limit), workspace_members=SimpleNamespace( enabled=workspace_members_enabled, @@ -482,6 +482,7 @@ def _invite_request(app, ws_id: str, acct_id: uuid.UUID): ) +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_invite_blocked_by_saas_members_cap( app: Flask, bypass_pipeline, monkeypatch: pytest.MonkeyPatch, database_session: Session ): @@ -507,7 +508,7 @@ def test_invite_blocked_by_saas_members_cap( "FeatureService", SimpleNamespace( get_features=Mock( - return_value=_features(billing_enabled=True, members_size=10, members_limit=10), + return_value=_features(members_size=10, members_limit=10), ), ), ) @@ -520,13 +521,13 @@ def test_invite_blocked_by_saas_members_cap( invite_mock.assert_not_called() +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE) def test_invite_blocked_by_ee_workspace_members_license( app: Flask, bypass_pipeline, monkeypatch: pytest.MonkeyPatch, database_session: Session ): """EE License workspace_members cap → MemberLicenseExceeded (403). - Note: billing.enabled is False (EE without SaaS billing); only the - license cap fires. + Enterprise member limits come from the license. """ ws_id = str(uuid.uuid4()) acct_id = uuid.uuid4() diff --git a/api/tests/unit_tests/controllers/rbac_introspection.py b/api/tests/unit_tests/controllers/rbac_introspection.py new file mode 100644 index 00000000000..6d88ba375a0 --- /dev/null +++ b/api/tests/unit_tests/controllers/rbac_introspection.py @@ -0,0 +1,26 @@ +from collections.abc import Callable + +from controllers.common.rbac import RBAC_CHECKS_ATTR, RBACCheck + + +def rbac_checks(view: Callable[..., object]) -> tuple[RBACCheck, ...]: + current = view + while RBAC_CHECKS_ATTR not in current.__dict__: + wrapped = current.__dict__.get("__wrapped__") + if wrapped is None: + raise AssertionError(f"no decorator layer of {view!r} carries an rbac_checks bundle") + current = wrapped + return current.__dict__[RBAC_CHECKS_ATTR] + + +def all_rbac_checks(view: Callable[..., object]) -> list[RBACCheck]: + found: list[RBACCheck] = [] + seen_bundle_ids: set[int] = set() + current: Callable[..., object] | None = view + while current is not None: + bundle = current.__dict__.get(RBAC_CHECKS_ATTR) + if bundle is not None and id(bundle) not in seen_bundle_ids: + seen_bundle_ids.add(id(bundle)) + found.extend(bundle) + current = current.__dict__.get("__wrapped__") + return found diff --git a/api/tests/unit_tests/controllers/service_api/app/test_completion.py b/api/tests/unit_tests/controllers/service_api/app/test_completion.py index a83e8b9f734..3a479a1d351 100644 --- a/api/tests/unit_tests/controllers/service_api/app/test_completion.py +++ b/api/tests/unit_tests/controllers/service_api/app/test_completion.py @@ -559,7 +559,7 @@ class TestChatApiController: completion_module = sys.modules["controllers.service_api.app.completion"] apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) - billing_get_info = Mock(return_value={"enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}}) + billing_get_info = Mock(return_value={"subscription": {"plan": CloudPlan.SANDBOX}}) generate = Mock() monkeypatch.setattr(BillingService, "get_info", billing_get_info) monkeypatch.setattr(AppGenerateService, "generate", generate) @@ -583,13 +583,12 @@ class TestChatApiController: assert exc_info.value.error_code == "workflow_version_execution_not_allowed" @pytest.mark.parametrize( - ("deployment_edition", "billing_enabled", "plan", "workflow_id"), + ("deployment_edition", "plan", "workflow_id"), [ - (DeploymentEdition.COMMUNITY, True, CloudPlan.SANDBOX, str(uuid.uuid4())), - (DeploymentEdition.ENTERPRISE, True, CloudPlan.SANDBOX, str(uuid.uuid4())), - (DeploymentEdition.CLOUD, False, CloudPlan.SANDBOX, str(uuid.uuid4())), - (DeploymentEdition.CLOUD, True, CloudPlan.PROFESSIONAL, str(uuid.uuid4())), - (DeploymentEdition.CLOUD, True, CloudPlan.SANDBOX, None), + (DeploymentEdition.COMMUNITY, CloudPlan.SANDBOX, str(uuid.uuid4())), + (DeploymentEdition.ENTERPRISE, CloudPlan.SANDBOX, str(uuid.uuid4())), + (DeploymentEdition.CLOUD, CloudPlan.PROFESSIONAL, str(uuid.uuid4())), + (DeploymentEdition.CLOUD, CloudPlan.SANDBOX, None), ], ) def test_allows_default_or_entitled_workflow_version_execution( @@ -598,14 +597,13 @@ class TestChatApiController: monkeypatch: pytest.MonkeyPatch, orm_session: Session, deployment_edition: DeploymentEdition, - billing_enabled: bool, plan: CloudPlan, workflow_id: str | None, ) -> None: completion_module = sys.modules["controllers.service_api.app.completion"] apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=deployment_edition) - billing_get_info = Mock(return_value={"enabled": billing_enabled, "subscription": {"plan": plan}}) + billing_get_info = Mock(return_value={"subscription": {"plan": plan}}) generate = Mock(return_value={"result": "ok"}) monkeypatch.setattr(BillingService, "get_info", billing_get_info) monkeypatch.setattr(AppGenerateService, "generate", generate) diff --git a/api/tests/unit_tests/controllers/service_api/app/test_file_preview.py b/api/tests/unit_tests/controllers/service_api/app/test_file_preview.py index 33b6e83094e..f6e7e9cd1d9 100644 --- a/api/tests/unit_tests/controllers/service_api/app/test_file_preview.py +++ b/api/tests/unit_tests/controllers/service_api/app/test_file_preview.py @@ -1,285 +1,151 @@ -"""Unit tests for the Service API file-preview endpoint. +"""Unit tests for the Service API file-preview transport boundary.""" -Ownership checks run against persisted message, file, app, and upload rows so the -tests exercise the same SQLAlchemy statements and tenant boundary as production. -Storage remains mocked because it is the external I/O boundary of the endpoint. -""" - -import logging -from collections.abc import Iterator -from dataclasses import dataclass -from datetime import datetime -from decimal import Decimal -from typing import Protocol, cast +from inspect import unwrap from unittest.mock import Mock, patch -from uuid import uuid4 +from uuid import UUID, uuid4 import pytest -from sqlalchemy import event -from sqlalchemy.engine import Engine -from sqlalchemy.orm import Session +from flask import Response from controllers.service_api.app.error import FileAccessDeniedError, FileNotFoundError -from controllers.service_api.app.file_preview import FilePreviewApi -from extensions.storage.storage_type import StorageType -from graphon.file import FileTransferMethod, FileType -from models.base import TypeBase -from models.enums import ConversationFromSource, CreatorUserRole -from models.model import App, AppMode, Message, MessageFile, UploadFile +from controllers.service_api.app.file_preview import FilePreviewApi, FilePreviewQuery +from models.model import App, EndUser +from services.message_file_preview_service import ( + MessageFilePreview, + MessageFilePreviewAccessDeniedError, + MessageFilePreviewNotFoundError, + MessageFilePreviewRecord, +) -class _FilePreviewLogRecord(Protocol): - file_id: str - app_id: str - error: str - - -@dataclass(frozen=True) -class _Database: - """Expose the real test session through the interface used by the controller.""" - - session: Session - - -@dataclass(frozen=True) -class _PreviewRecords: - app: App - message: Message - message_file: MessageFile - upload_file: UploadFile - - -@pytest.fixture -def database(sqlite_engine: Engine) -> Iterator[_Database]: - """Create only the tables required by file ownership validation.""" - - models = (App, Message, MessageFile, UploadFile) - tables = [TypeBase.metadata.tables[model.__tablename__] for model in models] - TypeBase.metadata.create_all(sqlite_engine, tables=tables) - with Session(sqlite_engine, expire_on_commit=False) as session: - yield _Database(session) - - -@pytest.fixture -def file_preview_api() -> FilePreviewApi: - """Create the resource instance under test.""" - - return FilePreviewApi() - - -def _upload_file(*, tenant_id: str, file_id: str | None = None) -> UploadFile: - upload_file = UploadFile( - tenant_id=tenant_id, - storage_type=StorageType.LOCAL, - key="storage/key/test_file.jpg", - name="test_file.jpg", - size=1024, - extension="jpg", - mime_type="image/jpeg", - created_by_role=CreatorUserRole.ACCOUNT, - created_by=str(uuid4()), - created_at=datetime(2026, 1, 1), - used=True, - ) - if file_id is not None: - upload_file.id = file_id - return upload_file - - -def _persist_preview_records( - session: Session, +def _preview( *, - app_id: str | None = None, - app_tenant_id: str | None = None, - upload_tenant_id: str | None = None, -) -> _PreviewRecords: - app_id = app_id or str(uuid4()) - app_tenant_id = app_tenant_id or str(uuid4()) - upload_file = _upload_file(tenant_id=upload_tenant_id or app_tenant_id) - app = App( - id=app_id, - tenant_id=app_tenant_id, - name="Preview app", - description="", - mode=AppMode.CHAT, - icon_type=None, - icon="", - icon_background=None, - enable_site=True, - enable_api=True, + mime_type: str | None = "image/jpeg", + name: str = "test_file.jpg", + extension: str = "jpg", + size: int = 1024, +) -> MessageFilePreview: + return MessageFilePreview( + content=iter([b"file content"]), + file=MessageFilePreviewRecord( + key="storage/key/test_file.jpg", + name=name, + size=size, + extension=extension, + mime_type=mime_type, + ), ) - message = Message( - id=str(uuid4()), - app_id=app_id, - conversation_id=str(uuid4()), - _inputs={}, - query="preview", - message={}, - message_unit_price=Decimal(0), - answer="answer", - answer_unit_price=Decimal(0), - currency="USD", - from_source=ConversationFromSource.API, + + +def _app() -> App: + return App(id=str(uuid4()), tenant_id=str(uuid4())) + + +def _get( + *, + api: FilePreviewApi, + args: FilePreviewQuery, + app_model: App, + file_id: UUID, +) -> Response: + return unwrap(api.get)( + api, + args=args, + app_model=app_model, + end_user=Mock(spec=EndUser), + file_id=file_id, ) - message_file = MessageFile( - message_id=message.id, - type=FileType.IMAGE, - transfer_method=FileTransferMethod.LOCAL_FILE, - created_by_role=CreatorUserRole.ACCOUNT, - created_by=str(uuid4()), - upload_file_id=upload_file.id, - ) - session.add_all([app, message, message_file, upload_file]) - session.commit() - return _PreviewRecords(app=app, message=message, message_file=message_file, upload_file=upload_file) class TestFilePreviewApi: - """Exercise ownership validation and response construction.""" + @patch("controllers.service_api.app.file_preview.application_services") + def test_get_uses_authenticated_app_scope(self, mock_application_services: Mock) -> None: + app_model = _app() + file_id = uuid4() + preview = _preview() + service = mock_application_services.return_value.message_file_previews + service.get_preview.return_value = preview - def test_validate_file_ownership_success(self, file_preview_api: FilePreviewApi, database: _Database): - records = _persist_preview_records(database.session) + response = _get( + api=FilePreviewApi(), + args=FilePreviewQuery(), + app_model=app_model, + file_id=file_id, + ) - with patch("controllers.service_api.app.file_preview.db", database): - message_file, upload_file = file_preview_api._validate_file_ownership( - records.upload_file.id, records.app.id - ) - - assert message_file.id == records.message_file.id - assert upload_file.id == records.upload_file.id - assert upload_file.tenant_id == records.app.tenant_id - - def test_validate_file_ownership_file_not_found(self, file_preview_api: FilePreviewApi, database: _Database): - with patch("controllers.service_api.app.file_preview.db", database): - with pytest.raises(FileNotFoundError, match="File not found in message context"): - file_preview_api._validate_file_ownership(str(uuid4()), str(uuid4())) - - def test_validate_file_ownership_access_denied(self, file_preview_api: FilePreviewApi, database: _Database): - records = _persist_preview_records(database.session) - - with patch("controllers.service_api.app.file_preview.db", database): - with pytest.raises(FileAccessDeniedError, match="not owned by requesting app"): - file_preview_api._validate_file_ownership(records.upload_file.id, str(uuid4())) - - def test_validate_file_ownership_upload_file_not_found(self, file_preview_api: FilePreviewApi, database: _Database): - records = _persist_preview_records(database.session) - database.session.delete(records.upload_file) - database.session.commit() - - with patch("controllers.service_api.app.file_preview.db", database): - with pytest.raises(FileNotFoundError, match="Upload file record not found"): - file_preview_api._validate_file_ownership(records.upload_file.id, records.app.id) - - def test_validate_file_ownership_tenant_mismatch(self, file_preview_api: FilePreviewApi, database: _Database): - records = _persist_preview_records(database.session, upload_tenant_id=str(uuid4())) - - with patch("controllers.service_api.app.file_preview.db", database): - with pytest.raises(FileAccessDeniedError, match="tenant mismatch"): - file_preview_api._validate_file_ownership(records.upload_file.id, records.app.id) - - def test_validate_file_ownership_invalid_input(self, file_preview_api: FilePreviewApi): - with pytest.raises(FileAccessDeniedError, match="Invalid file or app identifier"): - file_preview_api._validate_file_ownership("", "app_id") - - with pytest.raises(FileAccessDeniedError, match="Invalid file or app identifier"): - file_preview_api._validate_file_ownership("file_id", "") + service.get_preview.assert_called_once_with( + file_id=str(file_id), + app_id=app_model.id, + tenant_id=app_model.tenant_id, + ) + assert response.response is preview.content + assert response.mimetype == "image/jpeg" @pytest.mark.parametrize( - ("as_attachment", "mime_type", "name", "extension", "size"), + ("service_error", "http_error"), [ - (False, "image/jpeg", "test_file.jpg", "jpg", 1024), - (True, "image/jpeg", "test_file.jpg", "jpg", 1024), - (False, "text/html", "unsafe.html", "html", 1024), - (False, "video/mp4", "test_file.mp4", "mp4", 1024), - (False, "image/jpeg", "test_file.jpg", "jpg", 0), + (MessageFilePreviewNotFoundError(), FileNotFoundError), + (MessageFilePreviewAccessDeniedError(), FileAccessDeniedError), ], ) - def test_build_file_response( + @patch("controllers.service_api.app.file_preview.application_services") + def test_get_maps_expected_errors( self, - file_preview_api: FilePreviewApi, - as_attachment: bool, - mime_type: str, - name: str, - extension: str, - size: int, - ): - upload_file = _upload_file(tenant_id=str(uuid4())) - upload_file.mime_type = mime_type - upload_file.name = name - upload_file.extension = extension - upload_file.size = size + mock_application_services: Mock, + service_error: Exception, + http_error: type[Exception], + ) -> None: + mock_application_services.return_value.message_file_previews.get_preview.side_effect = service_error - response = file_preview_api._build_file_response(Mock(), upload_file, as_attachment) + with pytest.raises(http_error): + _get( + api=FilePreviewApi(), + args=FilePreviewQuery(), + app_model=_app(), + file_id=uuid4(), + ) + + @patch("controllers.service_api.app.file_preview.application_services") + def test_get_does_not_mask_storage_errors(self, mock_application_services: Mock) -> None: + mock_application_services.return_value.message_file_previews.get_preview.side_effect = OSError("storage down") + + with pytest.raises(OSError, match="storage down"): + _get( + api=FilePreviewApi(), + args=FilePreviewQuery(), + app_model=_app(), + file_id=uuid4(), + ) + + @pytest.mark.parametrize( + ("preview", "as_attachment"), + [ + (_preview(), False), + (_preview(name="报告 1.jpg"), True), + (_preview(mime_type="text/html", name="unsafe.html", extension="html"), False), + (_preview(mime_type="video/mp4", name="video.mp4", extension="mp4"), False), + (_preview(size=0), False), + ], + ) + def test_build_file_response(self, preview: MessageFilePreview, as_attachment: bool) -> None: + response = FilePreviewApi()._build_file_response( + preview=preview, + as_attachment=as_attachment, + ) assert response.direct_passthrough is True - assert "Cache-Control" in response.headers - assert ("Content-Length" in response.headers) is bool(size) - if as_attachment or mime_type == "text/html": - assert "attachment" in response.headers["Content-Disposition"] - assert response.headers["Content-Type"] == "application/octet-stream" - else: - assert response.mimetype == mime_type - if mime_type == "text/html": - assert response.headers["X-Content-Type-Options"] == "nosniff" - if mime_type.startswith("video/"): - assert response.headers["Accept-Ranges"] == "bytes" - - @patch("controllers.service_api.app.file_preview.storage") - def test_components_use_validated_file( - self, mock_storage: Mock, file_preview_api: FilePreviewApi, database: _Database - ): - records = _persist_preview_records(database.session) - generator = Mock() - - with patch("controllers.service_api.app.file_preview.db", database): - message_file, upload_file = file_preview_api._validate_file_ownership( - records.upload_file.id, records.app.id + assert response.headers["Cache-Control"] == "public, max-age=3600" + assert ("Content-Length" in response.headers) is (preview.file.size > 0) + if as_attachment: + assert response.headers["Content-Disposition"] == ( + "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A%201.jpg" ) - response = file_preview_api._build_file_response(generator, upload_file, False) - - assert message_file.id == records.message_file.id - assert response.mimetype == "image/jpeg" - mock_storage.load.assert_not_called() - - @patch("controllers.service_api.app.file_preview.storage") - def test_storage_error_remains_external( - self, mock_storage: Mock, file_preview_api: FilePreviewApi, database: _Database - ): - records = _persist_preview_records(database.session) - mock_storage.load.side_effect = OSError("Storage error") - - with patch("controllers.service_api.app.file_preview.db", database): - _, upload_file = file_preview_api._validate_file_ownership(records.upload_file.id, records.app.id) - - with pytest.raises(OSError, match="Storage error"): - mock_storage.load(upload_file.key, stream=True) - - def test_validate_file_ownership_unexpected_error_logging( - self, - file_preview_api: FilePreviewApi, - database: _Database, - sqlite_engine: Engine, - caplog: pytest.LogCaptureFixture, - ): - file_id = str(uuid4()) - app_id = str(uuid4()) - - def fail_statement(*_args: object) -> None: - raise RuntimeError("Unexpected database error") - - event.listen(sqlite_engine, "before_cursor_execute", fail_statement) - try: - with patch("controllers.service_api.app.file_preview.db", database): - with caplog.at_level(logging.ERROR, logger="controllers.service_api.app.file_preview"): - with pytest.raises(FileAccessDeniedError, match="File access validation failed"): - file_preview_api._validate_file_ownership(file_id, app_id) - finally: - event.remove(sqlite_engine, "before_cursor_execute", fail_statement) - - assert len(caplog.records) == 1 - log_record = caplog.records[0] - assert log_record.getMessage() == "Unexpected error during file ownership validation" - record = cast(_FilePreviewLogRecord, log_record) - assert record.file_id == file_id - assert record.app_id == app_id - assert record.error == "Unexpected database error" + assert response.headers["Content-Type"] == "application/octet-stream" + elif preview.file.mime_type == "text/html": + assert response.headers["Content-Disposition"] == "attachment; filename*=UTF-8''unsafe.html" + assert response.headers["Content-Type"] == "application/octet-stream" + assert response.headers["X-Content-Type-Options"] == "nosniff" + else: + assert response.mimetype == preview.file.mime_type + if preview.file.mime_type == "video/mp4": + assert response.headers["Accept-Ranges"] == "bytes" diff --git a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py index 1c44c2397db..f631735796b 100644 --- a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py +++ b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py @@ -608,7 +608,7 @@ class TestWorkflowRunApi: config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) workflow_module = sys.modules["controllers.service_api.app.workflow"] - billing_get_info = Mock(return_value={"enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}}) + billing_get_info = Mock(return_value={"subscription": {"plan": CloudPlan.SANDBOX}}) generate = Mock(return_value={"result": "ok"}) monkeypatch.setattr(BillingService, "get_info", billing_get_info) monkeypatch.setattr(AppGenerateService, "generate", generate) @@ -667,7 +667,7 @@ class TestWorkflowRunByIdApi: config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) workflow_module = sys.modules["controllers.service_api.app.workflow"] - billing_get_info = Mock(return_value={"enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}}) + billing_get_info = Mock(return_value={"subscription": {"plan": CloudPlan.SANDBOX}}) generate = Mock() monkeypatch.setattr(BillingService, "get_info", billing_get_info) monkeypatch.setattr(AppGenerateService, "generate", generate) @@ -700,12 +700,11 @@ class TestWorkflowRunByIdApi: } @pytest.mark.parametrize( - ("deployment_edition", "billing_enabled", "plan"), + ("deployment_edition", "plan"), [ - (DeploymentEdition.COMMUNITY, True, CloudPlan.SANDBOX), - (DeploymentEdition.ENTERPRISE, True, CloudPlan.SANDBOX), - (DeploymentEdition.CLOUD, False, CloudPlan.SANDBOX), - (DeploymentEdition.CLOUD, True, CloudPlan.PROFESSIONAL), + (DeploymentEdition.COMMUNITY, CloudPlan.SANDBOX), + (DeploymentEdition.ENTERPRISE, CloudPlan.SANDBOX), + (DeploymentEdition.CLOUD, CloudPlan.PROFESSIONAL), ], ) def test_allows_execution_outside_enabled_sandbox_plan( @@ -713,14 +712,13 @@ class TestWorkflowRunByIdApi: app: Flask, monkeypatch: pytest.MonkeyPatch, deployment_edition: DeploymentEdition, - billing_enabled: bool, plan: CloudPlan, sqlite_session: Session, config_overrides: Callable[..., None], ) -> None: config_overrides(DEPLOYMENT_EDITION=deployment_edition) - billing_get_info = Mock(return_value={"enabled": billing_enabled, "subscription": {"plan": plan}}) + billing_get_info = Mock(return_value={"subscription": {"plan": plan}}) generate = Mock(return_value={"result": "ok"}) monkeypatch.setattr(BillingService, "get_info", billing_get_info) monkeypatch.setattr(AppGenerateService, "generate", generate) diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py b/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py index ca2fe02c02d..ace817a4bf3 100644 --- a/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py +++ b/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py @@ -1212,7 +1212,6 @@ class TestSegmentApiPost(SQLiteEndpointTest): mock_validate_token.return_value = _api_token(tenant_id) mock_features = Mock() - mock_features.billing.enabled = False mock_feature_svc.get_features.return_value = mock_features mock_vector_space = Mock() @@ -1555,7 +1554,6 @@ class TestDatasetSegmentApiUpdate(SQLiteEndpointTest): """Configure mocks to neutralise billing/auth decorators.""" mock_validate_token.return_value = _api_token(tenant_id) mock_features = Mock() - mock_features.billing.enabled = False mock_feature_svc.get_features.return_value = mock_features mock_vector_space = Mock() mock_vector_space.limit = 10 @@ -2054,7 +2052,6 @@ class TestChildChunkApiPost(SQLiteEndpointTest): def _setup_billing_mocks(mock_validate_token, mock_feature_svc, tenant_id: str): mock_validate_token.return_value = _api_token(tenant_id) mock_features = Mock() - mock_features.billing.enabled = False mock_feature_svc.get_features.return_value = mock_features mock_vector_space = Mock() mock_vector_space.limit = 10 @@ -2368,7 +2365,6 @@ class TestModelValidateDecorator(SQLiteEndpointTest): mock_validate_token.return_value = _api_token(tenant_id) mock_features = Mock() - mock_features.billing.enabled = False mock_feature_svc.get_features.return_value = mock_features mock_vector_space = Mock() diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_document.py b/api/tests/unit_tests/controllers/service_api/dataset/test_document.py index c297b95987e..5fc0837cc9f 100644 --- a/api/tests/unit_tests/controllers/service_api/dataset/test_document.py +++ b/api/tests/unit_tests/controllers/service_api/dataset/test_document.py @@ -48,6 +48,7 @@ from controllers.service_api.dataset.document import ( ) from controllers.service_api.dataset.error import ArchivedDocumentImmutableError from core.rag.index_processor.constant.index_type import IndexStructureType +from enums import DeploymentEdition from extensions.storage.storage_type import StorageType from models.account import Account from models.dataset import Dataset, Document, DocumentSegment @@ -65,6 +66,7 @@ from services.dataset_ref_service import DatasetRef from services.dataset_service import DocumentService from services.entities.knowledge_entities.knowledge_entities import ProcessRule, RetrievalModel from services.errors.file import FileTooLargeError as FileTooLargeServiceError +from tests.unit_tests.config_override import config_overrides_context def _document_data_source_info() -> dict[str, str]: @@ -658,6 +660,7 @@ class TestDocumentServiceFileOperations: class TestDocumentServiceSaveValidation: """Test validations during document saving.""" + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) @patch("services.dataset_service.DatasetService.check_doc_form") @patch("services.dataset_service.FeatureService.get_features") def test_save_document_validates_doc_form(self, mock_features, mock_check_form, sqlite_session: Session): @@ -665,7 +668,6 @@ class TestDocumentServiceSaveValidation: dataset = make_dataset(tenant_id="tenant_id") config = Mock() features = Mock() - features.billing.enabled = False mock_features.return_value = features class TestStopError(Exception): @@ -1416,7 +1418,6 @@ class TestDocumentAddByTextApi(SQLiteControllerTest): mock_validate_token.return_value = api_token mock_features = Mock() - mock_features.billing.enabled = False mock_feature_svc.get_features.return_value = mock_features mock_vector_space = Mock() @@ -1591,7 +1592,6 @@ def _setup_billing_mocks(mock_validate_token, mock_feature_svc, tenant_id: str): api_token = ApiToken(tenant_id=tenant_id, type=ApiTokenType.DATASET, token="dataset-token") mock_validate_token.return_value = api_token mock_features = Mock() - mock_features.billing.enabled = False mock_feature_svc.get_features.return_value = mock_features mock_vector_space = Mock() mock_vector_space.limit = 10 diff --git a/api/tests/unit_tests/controllers/service_api/test_wraps.py b/api/tests/unit_tests/controllers/service_api/test_wraps.py index fc872c6e44f..997017fddaa 100644 --- a/api/tests/unit_tests/controllers/service_api/test_wraps.py +++ b/api/tests/unit_tests/controllers/service_api/test_wraps.py @@ -314,6 +314,7 @@ class TestCloudEditionBillingResourceCheck: app.config["TESTING"] = True return app + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("controllers.service_api.wraps.validate_and_get_api_token") @patch("controllers.service_api.wraps.FeatureService.get_features") def test_allows_when_under_limit(self, mock_get_features, mock_validate_token, app: Flask): @@ -322,7 +323,6 @@ class TestCloudEditionBillingResourceCheck: mock_validate_token.return_value = Mock(tenant_id="tenant123") mock_features = Mock() - mock_features.billing.enabled = True mock_features.members.limit = 10 mock_features.members.size = 5 mock_get_features.return_value = mock_features @@ -381,7 +381,6 @@ class TestCloudEditionBillingResourceCheck: mock_get_vector_space.return_value = Mock(size=0, limit=50, usage_unknown=True) mock_get_features.return_value = SimpleNamespace( billing=SimpleNamespace( - enabled=True, subscription=SimpleNamespace(plan=CloudPlan.SANDBOX), ) ) @@ -411,7 +410,6 @@ class TestCloudEditionBillingResourceCheck: mock_get_vector_space.return_value = Mock(size=0, limit=50, usage_unknown=True) mock_get_features.return_value = SimpleNamespace( billing=SimpleNamespace( - enabled=True, subscription=SimpleNamespace(plan=plan), ) ) @@ -429,6 +427,7 @@ class TestCloudEditionBillingResourceCheck: assert result == "document_uploaded" mock_get_features.assert_called_once_with("tenant123", exclude_vector_space=True) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("controllers.service_api.wraps.validate_and_get_api_token") @patch("controllers.service_api.wraps.FeatureService.get_features") def test_loads_features_when_checking_non_vector_space_limit( @@ -439,7 +438,6 @@ class TestCloudEditionBillingResourceCheck: mock_validate_token.return_value = Mock(tenant_id="tenant123") mock_features = Mock() - mock_features.billing.enabled = True mock_features.documents_upload_quota.limit = 10 mock_features.documents_upload_quota.size = 5 mock_get_features.return_value = mock_features @@ -456,6 +454,7 @@ class TestCloudEditionBillingResourceCheck: assert result == "document_uploaded" mock_get_features.assert_called_once_with("tenant123", exclude_vector_space=True) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("controllers.service_api.wraps.validate_and_get_api_token") @patch("controllers.service_api.wraps.FeatureService.get_features") def test_rejects_when_at_limit(self, mock_get_features, mock_validate_token, app: Flask): @@ -464,7 +463,6 @@ class TestCloudEditionBillingResourceCheck: mock_validate_token.return_value = Mock(tenant_id="tenant123") mock_features = Mock() - mock_features.billing.enabled = True mock_features.members.limit = 10 mock_features.members.size = 10 mock_get_features.return_value = mock_features @@ -479,15 +477,15 @@ class TestCloudEditionBillingResourceCheck: add_member() assert "members has reached the limit" in str(exc_info.value) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) @patch("controllers.service_api.wraps.validate_and_get_api_token") @patch("controllers.service_api.wraps.FeatureService.get_features") def test_allows_when_billing_disabled(self, mock_get_features, mock_validate_token, app: Flask): - """Test that request is allowed when billing is disabled.""" + """Test that request is allowed outside Cloud.""" # Arrange mock_validate_token.return_value = Mock(tenant_id="tenant123") mock_features = Mock() - mock_features.billing.enabled = False mock_get_features.return_value = mock_features @cloud_edition_billing_resource_check("members", "app") @@ -512,6 +510,7 @@ class TestCloudEditionBillingKnowledgeLimitCheck: app.config["TESTING"] = True return app + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("controllers.service_api.wraps.validate_and_get_api_token") @patch("controllers.service_api.wraps.FeatureService.get_features") def test_rejects_add_segment_in_sandbox(self, mock_get_features, mock_validate_token, app: Flask): @@ -520,7 +519,6 @@ class TestCloudEditionBillingKnowledgeLimitCheck: mock_validate_token.return_value = Mock(tenant_id="tenant123") mock_features = Mock() - mock_features.billing.enabled = True mock_features.billing.subscription.plan = CloudPlan.SANDBOX mock_get_features.return_value = mock_features @@ -534,6 +532,7 @@ class TestCloudEditionBillingKnowledgeLimitCheck: add_segment() assert "upgrade to a paid plan" in str(exc_info.value) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("controllers.service_api.wraps.validate_and_get_api_token") @patch("controllers.service_api.wraps.FeatureService.get_features") def test_allows_other_operations_in_sandbox(self, mock_get_features, mock_validate_token, app: Flask): @@ -542,7 +541,6 @@ class TestCloudEditionBillingKnowledgeLimitCheck: mock_validate_token.return_value = Mock(tenant_id="tenant123") mock_features = Mock() - mock_features.billing.enabled = True mock_features.billing.subscription.plan = CloudPlan.SANDBOX mock_get_features.return_value = mock_features diff --git a/api/tests/unit_tests/controllers/test_rbac_route_resource_contract.py b/api/tests/unit_tests/controllers/test_rbac_route_resource_contract.py index 23cf107813d..0fd2a205b2f 100644 --- a/api/tests/unit_tests/controllers/test_rbac_route_resource_contract.py +++ b/api/tests/unit_tests/controllers/test_rbac_route_resource_contract.py @@ -1,102 +1,143 @@ -"""Guard against resource-scoped RBAC gates mounted on routes that carry no resource id. +"""Guard against resource-scoped RBAC gates mounted on routes their locator can't read. -``rbac_permission_required`` defaults to ``resource_required=True``, which makes -``_extract_resource_id`` raise ``ValueError`` when the matched path holds none of the -accepted identifiers. The request then fails with a 400 before the view ever runs, so the -endpoint is unreachable for every tenant with ``RBAC_ENABLED``. Creation endpoints and -other workspace-level actions must opt out with ``resource_required=False``. +Every RBAC gate is declared as one or more explicit ``RBACCheck(scene, Locator(...))`` +bundles, via ``rbac_permission_required(RBACCheck(...), ...)`` or +``console_account_admission(rbac_checks=[RBACCheck(...), ...])``. Each locator reads a +path parameter — its explicit ``param`` argument, or its class default (``PlainApp`` reads +``app_id``, ``DatasetId`` reads ``dataset_id``, etc.; ``Workspace`` reads none). A route +whose URL doesn't carry that parameter can never resolve the check. + +This check runs against the registered namespaces rather than the source text: both +decorators record their checks on the view function under ``RBAC_CHECKS_ATTR``, and reading +them back at runtime also covers resources built by a factory (the RBAC access-permission +endpoints in ``controllers/console/workspace/rbac.py``), which no AST scan can see. """ -import ast -from pathlib import Path +from __future__ import annotations -CONTROLLERS_DIR = Path(__file__).resolve().parents[3] / "controllers" +from collections.abc import Iterator -# Mirrors the lookup order in controllers/common/wraps.py::_extract_resource_id. -ACCEPTED_PATH_ARGS = { - "APP": ("app_id", "agent_id", "resource_id"), - "DATASET": ("dataset_id", "pipeline_id", "resource_id"), -} +import controllers.console # noqa: F401 -- importing the package registers every console route +import controllers.openapi # noqa: F401 -- same for the user-scoped OpenAPI routes +from controllers.common.rbac import RBAC_CHECKS_ATTR, RBACCheck +from controllers.console import console_ns +from controllers.openapi import openapi_ns + +NAMESPACES = (console_ns, openapi_ns) + +HTTP_METHODS = ("delete", "get", "head", "options", "patch", "post", "put") # Known violations tracked separately: DatasetDocumentSegmentBatchImportApi binds one class # to both the dataset-scoped import route and the job-scoped status route, so every method # on it is reachable at a path carrying only a job id. Its permission points are genuinely -# per-dataset, so it needs the route split rather than resource_required=False. Remove -# these entries with that fix. +# per-dataset, so it needs the route split rather than a Workspace() locator. Remove these +# entries with that fix. KNOWN_VIOLATIONS = { - ("console/datasets/datasets_segments.py", "DatasetDocumentSegmentBatchImportApi", "post"), - ("console/datasets/datasets_segments.py", "DatasetDocumentSegmentBatchImportApi", "get"), + ("DatasetDocumentSegmentBatchImportApi", "post"), + ("DatasetDocumentSegmentBatchImportApi", "get"), } - -def _decorator_name(node: ast.Call) -> str: - func = node.func - parts = [] - while isinstance(func, ast.Attribute): - parts.append(func.attr) - func = func.value - if isinstance(func, ast.Name): - parts.append(func.id) - return ".".join(reversed(parts)) +# The generated access-permission endpoints, spelled out here so this guard fails loudly if +# the factory stops registering them (or renames a URL) rather than silently checking less. +RBAC_ACCESS_RESOURCE_PARTS = (("apps", "app_id"), ("datasets", "dataset_id"), ("agents", "agent_id")) -def _attribute_name(node: ast.expr | None) -> str | None: - return node.attr if isinstance(node, ast.Attribute) else None +def _rbac_access_urls() -> set[str]: + urls: set[str] = set() + for segment, id_param in RBAC_ACCESS_RESOURCE_PARTS: + resource = f"/workspaces/current/rbac/{segment}/" + workspace = f"/workspaces/current/rbac/workspace/{segment}" + urls.update( + { + f"{resource}/access-policy", + f"{resource}/whitelist", + f"{resource}/whitelist_config", + f"{resource}/user-access-policies", + f"{resource}/users//access-policies", + f"{resource}/access-policies//role-bindings", + f"{resource}/access-policies//member-bindings", + f"{workspace}/access-policy", + f"{workspace}/access-policies//role-bindings", + f"{workspace}/access-policies//bindings", + f"{workspace}/access-policies//member-bindings", + } + ) + return urls -def _route_paths(class_node: ast.ClassDef) -> list[str]: - paths: list[str] = [] - for decorator in class_node.decorator_list: - if isinstance(decorator, ast.Call) and _decorator_name(decorator).endswith(".route"): - paths.extend( - arg.value for arg in decorator.args if isinstance(arg, ast.Constant) and isinstance(arg.value, str) - ) - return paths +def _class_attribute(resource: type, name: str) -> object | None: + """Look up ``name`` on ``resource`` through the MRO without ``getattr``.""" + for klass in resource.__mro__: + attributes = vars(klass) + if name in attributes: + return attributes[name] + return None + + +def _declared_checks(view: object) -> list[RBACCheck]: + """Collect the RBAC checks a decorator recorded anywhere in this view's wrapper chain. + + ``functools.wraps`` copies the recorded tuple onto every outer wrapper, so the same + bundle shows up at several levels; identity tells the copies apart from a second gate. + """ + checks: list[RBACCheck] = [] + seen: set[int] = set() + current = view + while current is not None: + attributes = vars(current) + recorded = attributes.get(RBAC_CHECKS_ATTR) + if recorded and id(recorded) not in seen: + seen.add(id(recorded)) + checks.extend(recorded) + current = attributes.get("__wrapped__") + return checks def _path_args(route: str) -> set[str]: - args = set() - args.update(segment.split(">")[0].split(":")[-1] for segment in route.split("<")[1:]) - return args + return {segment.split(">")[0].split(":")[-1] for segment in route.split("<")[1:]} -def _resource_scoped_gates(method: ast.FunctionDef | ast.AsyncFunctionDef) -> list[str]: - scopes = [] - for decorator in method.decorator_list: - if not (isinstance(decorator, ast.Call) and _decorator_name(decorator).endswith("rbac_permission_required")): - continue - keywords = {keyword.arg: keyword.value for keyword in decorator.keywords} - resource_required = keywords.get("resource_required") - if isinstance(resource_required, ast.Constant) and resource_required.value is False: - continue - scope = _attribute_name(decorator.args[0] if decorator.args else keywords.get("resource_type")) - if scope in ACCEPTED_PATH_ARGS: - scopes.append(scope) - return scopes +def _registered_methods() -> Iterator[tuple[type, str, object, tuple[str, ...]]]: + """Yield ``(resource class, method name, view function, urls)`` for every routed method.""" + for namespace in NAMESPACES: + for route in namespace.resources: + for method_name in HTTP_METHODS: + view = _class_attribute(route.resource, method_name) + if view is None: + continue + yield route.resource, method_name, view, tuple(route.urls) def test_resource_scoped_rbac_gates_have_a_resource_id_in_the_route() -> None: violations = [] - for path in sorted(CONTROLLERS_DIR.rglob("*.py")): - tree = ast.parse(path.read_text(encoding="utf-8")) - for class_node in (node for node in ast.walk(tree) if isinstance(node, ast.ClassDef)): - routes = _route_paths(class_node) - if not routes: - continue - methods = (node for node in class_node.body if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)) - for method in methods: - for scope in _resource_scoped_gates(method): - accepted = set(ACCEPTED_PATH_ARGS[scope]) - unscoped = [route for route in routes if not _path_args(route) & accepted] - if not unscoped: - continue - key = (path.relative_to(CONTROLLERS_DIR).as_posix(), class_node.name, method.name) - if key in KNOWN_VIOLATIONS: - continue - violations.append(f"{key[0]}::{key[1]}.{key[2]} scope={scope} routes={unscoped}") + for resource, method_name, view, urls in _registered_methods(): + if (resource.__name__, method_name) in KNOWN_VIOLATIONS: + continue - assert not violations, ( - "resource-scoped rbac_permission_required on routes without a resource id; " - "pass resource_required=False for workspace-level actions:\n" + "\n".join(violations) + for check in _declared_checks(view): + # Only ``_ParamLocator`` subclasses store a path parameter; ``Workspace`` reads none. + required_param = vars(check.locator).get("param") + if not isinstance(required_param, str): + continue + + unscoped = [url for url in urls if required_param not in _path_args(url)] + if unscoped: + violations.append( + f"{resource.__name__}.{method_name} " + f"locator={type(check.locator).__name__}({required_param!r}) " + f"scene={check.scene} routes={unscoped}" + ) + + assert not violations, "RBACCheck locator on a route that doesn't carry its required path parameter:\n" + "\n".join( + violations ) + + +def test_guard_reaches_the_generated_rbac_access_endpoints() -> None: + """The factory-built endpoints are the reason this guard is runtime-based; prove it sees them.""" + scanned_urls = {url for _, _, _, urls in _registered_methods() for url in urls} + + missing = sorted(_rbac_access_urls() - scanned_urls) + + assert not missing, "generated RBAC access routes are not reachable by this guard:\n" + "\n".join(missing) diff --git a/api/tests/unit_tests/controllers/test_swagger.py b/api/tests/unit_tests/controllers/test_swagger.py index 6f9f4677bb4..de0845c9ebd 100644 --- a/api/tests/unit_tests/controllers/test_swagger.py +++ b/api/tests/unit_tests/controllers/test_swagger.py @@ -15,8 +15,8 @@ def _swagger_config(config_overrides) -> None: USER_PROPERTY_SCHEMA = { "description": ( - "User identifier, unique within the application. This identifier scopes data access; resources created with " - "one `user` value are only visible when queried with the same `user` value." + "End-user identifier, defined by your app and unique within it. Identifies the end user for this request. " + "See [End User Identity](/api-reference/guides/end-user-identity) for endpoint-specific access rules." ), "type": "string", } @@ -298,6 +298,11 @@ def test_service_openapi_documents_decorator_user_contracts(): assert schema["properties"]["user"] == USER_PROPERTY_SCHEMA assert "user" in schema["required"] + for path in ("/workflows/run", "/workflows/{workflow_id}/run"): + rate_limit_description = paths[path]["post"]["responses"]["429"]["description"] + assert "upstream model provider rate limit" in rate_limit_description + assert "Dify Cloud workflow execution quota" in rate_limit_description + task_stop_user_descriptions = { "/completion-messages/{task_id}/stop": "Send the same", "/chat-messages/{task_id}/stop": "Send the same", @@ -477,10 +482,75 @@ def test_service_openapi_documents_conditional_payload_schemas(): with_text_branch, without_text_branch = document_update_schema["anyOf"] assert with_text_branch["properties"]["text"]["type"] == "string" assert with_text_branch["properties"]["name"]["type"] == "string" + assert "default" not in with_text_branch["properties"]["text"] + assert "default" not in with_text_branch["properties"]["name"] assert with_text_branch["required"] == ["name", "text"] assert without_text_branch["properties"]["text"]["type"] == "null" +def test_service_dataset_response_schemas_omit_console_permission_metadata(): + from controllers.console import bp as console_bp + from controllers.service_api import bp as service_api_bp + + app = Flask(__name__) + app.config["TESTING"] = True + app.config["RESTX_INCLUDE_ALL_MODELS"] = True + app.register_blueprint(console_bp) + app.register_blueprint(service_api_bp) + + service_payload = app.test_client().get("/v1/openapi.json").get_json() + service_schemas = service_payload["components"]["schemas"] + for name in ("DatasetDetailResponse", "DatasetDetailWithPartialMembersResponse"): + assert "permission_keys" not in service_schemas[name]["properties"] + assert service_schemas["DatasetListResponse"]["properties"]["data"]["items"] == { + "$ref": "#/components/schemas/DatasetDetailResponse" + } + + console_payload = app.test_client().get("/console/api/openapi.json").get_json() + console_schema = console_payload["components"]["schemas"]["DatasetDetailResponse"] + assert "permission_keys" in console_schema["properties"] + + +def test_service_delete_schemas_omit_unenforced_state_constraints(): + from controllers.service_api import bp as service_api_bp + + app = Flask(__name__) + app.config["TESTING"] = True + app.register_blueprint(service_api_bp) + paths = app.test_client().get("/v1/openapi.json").get_json()["paths"] + + delete_dataset = paths["/datasets/{dataset_id}"]["delete"] + assert "409" not in delete_dataset["responses"] + assert "must not be in use" not in delete_dataset["description"] + + delete_document = paths["/datasets/{dataset_id}/documents/{document_id}"]["delete"] + assert "document_indexing" not in json.dumps(delete_document["responses"]) + assert "archived_document_immutable" in delete_document["responses"]["403"]["description"] + + +def test_service_schemas_only_document_reachable_not_found_responses(): + from controllers.service_api import bp as service_api_bp + + app = Flask(__name__) + app.config["TESTING"] = True + app.register_blueprint(service_api_bp) + paths = app.test_client().get("/v1/openapi.json").get_json()["paths"] + + for path, method in ( + ("/apps/annotation-reply/{action}/status/{job_id}", "get"), + ("/info", "get"), + ("/meta", "get"), + ("/parameters", "get"), + ("/workflows/run", "post"), + ("/completion-messages", "post"), + ): + assert "404" not in paths[path][method]["responses"] + assert "400" in paths[path][method]["responses"] + + assert "404" in paths["/workflows/{workflow_id}/run"]["post"]["responses"] + assert "404" in paths["/chat-messages"]["post"]["responses"] + + def test_service_openapi_does_not_encode_docs_coverage_boundaries(): from controllers.service_api import bp as service_api_bp diff --git a/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py b/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py index 3dfa2be777d..a3d2c8d188a 100644 --- a/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py +++ b/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py @@ -9,10 +9,20 @@ from unittest.mock import MagicMock import pytest from flask import Flask -from sqlalchemy import Engine import controllers.web.human_input_file_upload as upload_module -from controllers.common.errors import NoFileUploadedError +from controllers.common.errors import ( + BlockedFileExtensionError, + FileTooLargeError, + NoFileUploadedError, + RemoteFileAccessDeniedError, + RemoteFileInvalidResponseError, + RemoteFileInvalidUrlError, + RemoteFileNotFoundError, + RemoteFileUnavailableError, + RemoteFileUrlBlockedError, + UnsupportedFileTypeError, +) from controllers.web.human_input_file_upload import ( HumanInputFileUploadApi, InvalidUploadTokenForbiddenError, @@ -23,7 +33,26 @@ from models import Account from models.account import AccountStatus from models.enums import CreatorUserRole from models.model import UploadFile -from services.human_input_file_upload_service import HumanInputUploadContext +from services.errors.file import ( + BlockedFileExtensionError as BlockedFileExtensionServiceError, +) +from services.errors.file import FileTooLargeError as FileTooLargeServiceError +from services.errors.file import UnsupportedFileTypeError as UnsupportedFileTypeServiceError +from services.human_input_file_upload_service import ( + HumanInputUploadContext, + InvalidUploadTokenError, +) +from services.remote_file_service import ( + RemoteFileAccessDeniedError as RemoteFileAccessDeniedServiceError, +) +from services.remote_file_service import ( + RemoteFileInvalidResponseError as RemoteFileInvalidResponseServiceError, +) +from services.remote_file_service import RemoteFileInvalidUrlError as RemoteFileInvalidUrlServiceError +from services.remote_file_service import RemoteFileNotFoundError as RemoteFileNotFoundServiceError +from services.remote_file_service import RemoteFileUnavailableError as RemoteFileUnavailableServiceError +from services.remote_file_service import RemoteFileUploadResult +from services.remote_file_service import RemoteFileUrlBlockedError as RemoteFileUrlBlockedServiceError @pytest.fixture @@ -69,23 +98,25 @@ def _upload_file() -> UploadFile: return upload_file -def _patch_upload_service(monkeypatch: pytest.MonkeyPatch, service: MagicMock) -> tuple[MagicMock, dict[str, object]]: - workflow_run_repository = MagicMock() - repo_factory = MagicMock(return_value=workflow_run_repository) - captured: dict[str, object] = {} +def _remote_upload_file() -> RemoteFileUploadResult: + return RemoteFileUploadResult( + id="file-1", + name="sample.txt", + size=6, + extension="txt", + url="signed:file-1", + mime_type="text/plain", + created_by="owner-1", + created_at=datetime(2024, 1, 1), + ) - def _service_factory(session_factory, workflow_run_repository): - captured["session_factory"] = session_factory - captured["workflow_run_repository"] = workflow_run_repository - return service +def _patch_upload_service(monkeypatch: pytest.MonkeyPatch, service: MagicMock) -> None: monkeypatch.setattr( - upload_module.DifyAPIRepositoryFactory, - "create_api_workflow_run_repository", - repo_factory, + upload_module, + "application_services", + lambda: SimpleNamespace(human_input_file_uploads=service), ) - monkeypatch.setattr(upload_module, "HumanInputFileUploadService", _service_factory) - return repo_factory, captured def test_human_input_file_upload_route_uses_unified_path() -> None: @@ -111,18 +142,12 @@ def test_local_upload_requires_authorization_before_reading_files(app: Flask) -> HumanInputFileUploadApi().post() -def test_local_upload_ignores_source_and_records_form_file_link( - monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine -) -> None: +def test_local_upload_delegates_to_human_input_upload_service(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None: service = MagicMock() - service.validate_upload_token.return_value = _upload_context() - repo_factory, captured = _patch_upload_service(monkeypatch, service) - - file_service = MagicMock() - file_service.upload_file.return_value = _upload_file() - file_service_cls = MagicMock(return_value=file_service) - monkeypatch.setattr(upload_module, "FileService", file_service_cls) - monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=sqlite_engine)) + context = _upload_context() + service.validate_upload_token.return_value = context + service.upload_local_file.return_value = _upload_file() + _patch_upload_service(monkeypatch, service) data = { "file": (BytesIO(b"content"), "sample.txt"), @@ -139,24 +164,18 @@ def test_local_upload_ignores_source_and_records_form_file_link( assert status == 201 assert result["id"] == "file-1" - file_service.upload_file.assert_called_once() - assert file_service.upload_file.call_args.kwargs["source"] is None - assert file_service.upload_file.call_args.kwargs["user"].id == "owner-1" - repo_factory.assert_called_once() - assert captured["workflow_run_repository"] is repo_factory.return_value - service.record_upload_file.assert_called_once_with( - context=service.validate_upload_token.return_value, - file_id="file-1", + service.upload_local_file.assert_called_once_with( + context=context, + filename="sample.txt", + content=b"content", + mimetype="text/plain", ) -def test_local_upload_missing_file_raises_after_valid_token( - monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine -) -> None: +def test_local_upload_missing_file_raises_after_valid_token(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None: service = MagicMock() service.validate_upload_token.return_value = _upload_context() _patch_upload_service(monkeypatch, service) - monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=sqlite_engine)) with app.test_request_context( "/api/human-input-forms/files", @@ -170,15 +189,10 @@ def test_local_upload_missing_file_raises_after_valid_token( service.validate_upload_token.assert_called_once_with("hitl_upload_token-1") -def test_remote_upload_validates_token_before_fetching_remote_url( - monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine -) -> None: +def test_remote_upload_validates_token_before_fetching_remote_url(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None: service = MagicMock() - service.validate_upload_token.side_effect = InvalidUploadTokenForbiddenError() + service.validate_upload_token.side_effect = InvalidUploadTokenError() _patch_upload_service(monkeypatch, service) - monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=sqlite_engine)) - ssrf_proxy = MagicMock() - monkeypatch.setattr(upload_module, "ssrf_proxy", ssrf_proxy) with app.test_request_context( "/api/human-input-forms/files", @@ -190,41 +204,15 @@ def test_remote_upload_validates_token_before_fetching_remote_url( with pytest.raises(InvalidUploadTokenForbiddenError): HumanInputFileUploadApi().post() - ssrf_proxy.head.assert_not_called() - ssrf_proxy.get.assert_not_called() + service.upload_remote_file.assert_not_called() -def test_remote_upload_records_form_file_link( - monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine -) -> None: +def test_remote_upload_delegates_to_human_input_upload_service(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None: service = MagicMock() - service.validate_upload_token.return_value = _upload_context() + context = _upload_context() + service.validate_upload_token.return_value = context + service.upload_remote_file.return_value = _remote_upload_file() _patch_upload_service(monkeypatch, service) - monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=sqlite_engine)) - - response = MagicMock() - response.status_code = 200 - response.content = b"remote" - response.request.method = "GET" - ssrf_proxy = MagicMock() - ssrf_proxy.head.return_value = response - monkeypatch.setattr(upload_module, "ssrf_proxy", ssrf_proxy) - monkeypatch.setattr( - upload_module, - "guess_file_info_from_response", - lambda _response: SimpleNamespace(filename="sample.txt", extension="txt", mimetype="text/plain", size=6), - ) - - file_service = MagicMock() - file_service.upload_file.return_value = _upload_file() - file_service_cls = MagicMock(return_value=file_service) - file_service_cls.is_file_size_within_limit.return_value = True - monkeypatch.setattr(upload_module, "FileService", file_service_cls) - monkeypatch.setattr( - upload_module.file_helpers, - "get_signed_file_url", - lambda upload_file_id: f"signed:{upload_file_id}", - ) with app.test_request_context( "/api/human-input-forms/files", @@ -237,10 +225,84 @@ def test_remote_upload_records_form_file_link( assert status == 201 assert result["url"] == "signed:file-1" - file_service.upload_file.assert_called_once() - assert file_service.upload_file.call_args.kwargs["source_url"] == "https://example.com/file.txt" - assert file_service.upload_file.call_args.kwargs["user"].id == "owner-1" - service.record_upload_file.assert_called_once_with( - context=service.validate_upload_token.return_value, - file_id="file-1", + service.upload_remote_file.assert_called_once_with( + context=context, + url="https://example.com/file.txt", ) + + +@pytest.mark.parametrize( + ("service_error", "http_error"), + [ + pytest.param(RemoteFileInvalidUrlServiceError(), RemoteFileInvalidUrlError, id="invalid-url"), + pytest.param(RemoteFileUrlBlockedServiceError(), RemoteFileUrlBlockedError, id="blocked-url"), + pytest.param(RemoteFileNotFoundServiceError(), RemoteFileNotFoundError, id="not-found"), + pytest.param(RemoteFileAccessDeniedServiceError(), RemoteFileAccessDeniedError, id="access-denied"), + pytest.param(RemoteFileUnavailableServiceError(), RemoteFileUnavailableError, id="unavailable"), + pytest.param(RemoteFileInvalidResponseServiceError(), RemoteFileInvalidResponseError, id="invalid-response"), + ], +) +def test_remote_upload_maps_remote_file_errors( + monkeypatch: pytest.MonkeyPatch, + app: Flask, + service_error: Exception, + http_error: type[Exception], +) -> None: + service = MagicMock() + service.validate_upload_token.return_value = _upload_context() + service.upload_remote_file.side_effect = service_error + _patch_upload_service(monkeypatch, service) + + with app.test_request_context( + "/api/human-input-forms/files", + method="POST", + headers={"Authorization": "Bearer hitl_upload_token-1"}, + data={"url": "https://example.com/file.txt"}, + content_type="multipart/form-data", + ): + with pytest.raises(http_error) as raised: + HumanInputFileUploadApi().post() + + assert raised.value.__cause__ is service_error + + +@pytest.mark.parametrize( + ("service_error", "http_error"), + [ + pytest.param(FileTooLargeServiceError(), FileTooLargeError, id="too-large"), + pytest.param(UnsupportedFileTypeServiceError(), UnsupportedFileTypeError, id="unsupported"), + pytest.param(BlockedFileExtensionServiceError("Blocked extension"), BlockedFileExtensionError, id="blocked"), + ], +) +@pytest.mark.parametrize("remote", [False, True], ids=["local", "remote"]) +def test_upload_maps_file_service_errors( + monkeypatch: pytest.MonkeyPatch, + app: Flask, + service_error: Exception, + http_error: type[Exception], + remote: bool, +) -> None: + service = MagicMock() + service.validate_upload_token.return_value = _upload_context() + if remote: + service.upload_remote_file.side_effect = service_error + data = {"url": "https://example.com/file.txt"} + else: + service.upload_local_file.side_effect = service_error + data = {"file": (BytesIO(b"content"), "sample.txt")} + _patch_upload_service(monkeypatch, service) + + with app.test_request_context( + "/api/human-input-forms/files", + method="POST", + headers={"Authorization": "Bearer hitl_upload_token-1"}, + data=data, + content_type="multipart/form-data", + ): + with pytest.raises(http_error) as raised: + HumanInputFileUploadApi().post() + + assert raised.value.__cause__ is service_error + if isinstance(service_error, FileTooLargeServiceError): + assert isinstance(raised.value, FileTooLargeError) + assert raised.value.description == "File size exceeded." diff --git a/api/tests/unit_tests/controllers/web/test_human_input_form.py b/api/tests/unit_tests/controllers/web/test_human_input_form.py index 5d9ba9e42e4..d53ba7d60ca 100644 --- a/api/tests/unit_tests/controllers/web/test_human_input_form.py +++ b/api/tests/unit_tests/controllers/web/test_human_input_form.py @@ -10,7 +10,7 @@ from uuid import uuid4 import pytest from flask import Flask from sqlalchemy import Engine -from sqlalchemy.orm import Session, sessionmaker +from sqlalchemy.orm import Session from werkzeug.exceptions import Forbidden import controllers.web.human_input_form as human_input_module @@ -268,9 +268,7 @@ def test_get_form_uses_runtime_select_options(monkeypatch: pytest.MonkeyPatch, a service_mock.resolve_form_inputs.assert_called_once_with(form) -def test_create_upload_token_returns_token_and_form_expiration( - monkeypatch: pytest.MonkeyPatch, app: Flask, sqlite_engine: Engine -): +def test_create_upload_token_returns_token_and_form_expiration(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None: """POST returns a HITL upload token for an active form token.""" expiration_time = datetime(2099, 1, 1, tzinfo=UTC) @@ -279,26 +277,11 @@ def test_create_upload_token_returns_token_and_form_expiration( upload_token="hitl_upload_token-1", expires_at=expiration_time, ) - workflow_run_repository = MagicMock() - repo_factory = MagicMock(return_value=workflow_run_repository) - captured: dict[str, object] = {} - - def _service_factory(session_factory, workflow_run_repository): - captured["session_factory"] = session_factory - captured["workflow_run_repository"] = workflow_run_repository - return service_mock - - monkeypatch.setattr( - human_input_module.DifyAPIRepositoryFactory, - "create_api_workflow_run_repository", - repo_factory, - ) monkeypatch.setattr( human_input_module, - "HumanInputFileUploadService", - _service_factory, + "application_services", + lambda: SimpleNamespace(human_input_file_uploads=service_mock), ) - monkeypatch.setattr(human_input_module, "db", SimpleNamespace(engine=sqlite_engine)) limiter_mock = MagicMock() limiter_mock.is_rate_limited.return_value = False @@ -313,11 +296,6 @@ def test_create_upload_token_returns_token_and_form_expiration( "upload_token": "hitl_upload_token-1", "expires_at": int(expiration_time.timestamp()), } - repo_factory.assert_called_once() - assert captured["workflow_run_repository"] is workflow_run_repository - session_factory = captured["session_factory"] - assert isinstance(session_factory, sessionmaker) - assert session_factory.kw["bind"] is sqlite_engine service_mock.issue_upload_token.assert_called_once_with("token-1") limiter_mock.increment_rate_limit.assert_called_once_with("203.0.113.10") diff --git a/api/tests/unit_tests/controllers/web/test_pydantic_models.py b/api/tests/unit_tests/controllers/web/test_pydantic_models.py index c2d5b24b3c6..6df9c271f80 100644 --- a/api/tests/unit_tests/controllers/web/test_pydantic_models.py +++ b/api/tests/unit_tests/controllers/web/test_pydantic_models.py @@ -258,7 +258,7 @@ from controllers.web.remote_files import RemoteFileUploadPayload class TestRemoteFileUploadPayload: def test_valid_url(self) -> None: p = RemoteFileUploadPayload(url="https://example.com/file.pdf") - assert str(p.url) == "https://example.com/file.pdf" + assert p.url == "https://example.com/file.pdf" def test_url_syntax_is_validated_by_remote_file_service(self) -> None: payload = RemoteFileUploadPayload(url="not-a-url") diff --git a/api/tests/unit_tests/controllers/web/test_saved_message.py b/api/tests/unit_tests/controllers/web/test_saved_message.py index fdb276f8f5a..22ec43a5b47 100644 --- a/api/tests/unit_tests/controllers/web/test_saved_message.py +++ b/api/tests/unit_tests/controllers/web/test_saved_message.py @@ -36,9 +36,9 @@ def _end_user() -> EndUser: ) -# The @model_validate decorator wraps the handler; tests call the undecorated -# function so they can pass the validated pydantic payload directly and skip -# the flask request-parsing step. +# The @with_session and @model_validate decorators wrap the handler; tests call +# the undecorated function so they can pass the validated pydantic payload and a +# stub session directly and skip the flask request-parsing step. _list_get = inspect.unwrap(SavedMessageListApi.get) _list_post = inspect.unwrap(SavedMessageListApi.post) @@ -51,7 +51,7 @@ class TestSavedMessageListApiGet: query = SavedMessageListQuery.model_validate({}) with app.test_request_context("/saved-messages"): with pytest.raises(NotCompletionAppError): - _list_get(SavedMessageListApi(), query, _chat_app(), _end_user()) + _list_get(SavedMessageListApi(), query, MagicMock(), _chat_app(), _end_user()) @patch("controllers.web.saved_message.SavedMessageService.pagination_by_last_id") def test_happy_path(self, mock_paginate: MagicMock, app: Flask) -> None: @@ -59,7 +59,7 @@ class TestSavedMessageListApiGet: query = SavedMessageListQuery.model_validate({"limit": 20}) with app.test_request_context("/saved-messages?limit=20"): - result = _list_get(SavedMessageListApi(), query, _completion_app(), _end_user()) + result = _list_get(SavedMessageListApi(), query, MagicMock(), _completion_app(), _end_user()) assert result["limit"] == 20 assert result["has_more"] is False @@ -73,14 +73,14 @@ class TestSavedMessageListApiPost: payload = SavedMessageCreatePayload.model_validate({"message_id": str(uuid4())}) with app.test_request_context("/saved-messages", method="POST"): with pytest.raises(NotCompletionAppError): - _list_post(SavedMessageListApi(), payload, _chat_app(), _end_user()) + _list_post(SavedMessageListApi(), payload, MagicMock(), _chat_app(), _end_user()) @patch("controllers.web.saved_message.SavedMessageService.save") def test_save_success(self, mock_save: MagicMock, app: Flask) -> None: payload = SavedMessageCreatePayload.model_validate({"message_id": str(uuid4())}) with app.test_request_context("/saved-messages", method="POST"): - result = _list_post(SavedMessageListApi(), payload, _completion_app(), _end_user()) + result = _list_post(SavedMessageListApi(), payload, MagicMock(), _completion_app(), _end_user()) assert result["result"] == "success" @@ -90,7 +90,7 @@ class TestSavedMessageListApiPost: with app.test_request_context("/saved-messages", method="POST"): with pytest.raises(NotFound, match="Message Not Exists"): - _list_post(SavedMessageListApi(), payload, _completion_app(), _end_user()) + _list_post(SavedMessageListApi(), payload, MagicMock(), _completion_app(), _end_user()) # --------------------------------------------------------------------------- diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py index 410efadba33..4a84bcc4689 100644 --- a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py +++ b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py @@ -11,7 +11,6 @@ from __future__ import annotations import contextlib import inspect -import json from decimal import Decimal from types import SimpleNamespace @@ -29,7 +28,6 @@ from core.app.apps.agent_app.errors import AgentSessionSnapshotIncompatibleError from core.app.apps.exc import GenerateTaskStoppedError from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom from core.app.entities.queue_entities import QueueAnnotationReplyEvent -from core.workflow.file_reference import build_file_reference from models import Account, AppModelConfig from models.agent import Agent, AgentConfigSnapshot, AgentScope, AgentSource, AgentStatus from models.agent_config_entities import AgentSoulConfig @@ -209,6 +207,10 @@ class TestGenerateSuccess: return_value=mocker.MagicMock(variables=[], tenant_id="tenant", app_id="app1"), ) mocker.patch(f"{MODULE}.ModelConfigConverter.convert", return_value=mocker.MagicMock(model="gpt-4o-mini")) + file_upload_config = mocker.MagicMock() + mocker.patch(f"{MODULE}.FileUploadConfigManager.convert", return_value=file_upload_config) + parsed_file = mocker.MagicMock() + build_files = mocker.patch(f"{MODULE}.file_factory.build_from_mappings", return_value=[parsed_file]) mocker.patch(f"{MODULE}.TraceQueueManager", return_value=mocker.MagicMock()) generate_entity = mocker.patch( f"{MODULE}.AgentAppGenerateEntity", return_value=mocker.MagicMock(task_id="t", user_id="user") @@ -248,7 +250,10 @@ class TestGenerateSuccess: conversation=None, ) assert session.get(AppModelConfig, "config-1") is config - assert generate_entity.call_args.kwargs["prompt_file_mappings"] == file_mappings + build_files.assert_called_once() + assert build_files.call_args.kwargs["mappings"] == file_mappings + assert generate_entity.call_args.kwargs["files"] == [parsed_file] + assert generate_entity.call_args.kwargs["file_upload_config"] is file_upload_config assert "agent_runtime_exit_intent" not in generate_entity.call_args.kwargs def test_generate_loads_existing_conversation(self, generator: AgentAppGenerator, mocker: MockerFixture): @@ -379,7 +384,8 @@ class TestGenerateWorker: is_resume=False, query="query", session_scope_config_version_id="s", - prompt_file_mappings=(), + files=(), + file_upload_config=None, ): generator._generate_worker( flask_app=mocker.MagicMock(), @@ -391,7 +397,8 @@ class TestGenerateWorker: agent_session_scope_config_version_id=session_scope_config_version_id, model_conf=mocker.MagicMock(model="m"), query=query, - prompt_file_mappings=prompt_file_mappings, + files=files, + file_upload_config=file_upload_config, ), queue_manager=queue_manager, conversation_id="conv", @@ -420,48 +427,22 @@ class TestGenerateWorker: assert runner.run.call_args.kwargs["agent_config_snapshot_id"] == "s" assert runner.run.call_args.kwargs["session_scope_snapshot_id"] is None - def test_worker_appends_prompt_files_to_backend_query(self, generator, mocker: MockerFixture): + def test_worker_passes_files_to_backend_runner_without_rewriting_query(self, generator, mocker: MockerFixture): runner, _ = self._wire(generator, mocker, guard_query="你看得见这张图片吗") queue_manager = mocker.MagicMock() - file_mappings = [ - { - "type": "image", - "transfer_method": "local_file", - "url": "", - "upload_file_id": "upload-file-1", - }, - { - "type": "document", - "transfer_method": "remote_url", - "url": "https://example.com/source.pdf", - "upload_file_id": "ignored", - }, - ] - expected_file_mappings = [ - { - "transfer_method": "local_file", - "reference": build_file_reference(record_id="upload-file-1"), - }, - { - "transfer_method": "remote_url", - "url": "https://example.com/source.pdf", - }, - ] + files = [mocker.MagicMock(), mocker.MagicMock()] self._call( generator, mocker, queue_manager, query="你看得见这张图片吗", - prompt_file_mappings=file_mappings, + files=files, ) - assert runner.run.call_args.kwargs["query"] == ( - "你看得见这张图片吗\nUser provided files: " - "use dify-agent file download with the listed transfer_method and reference/url " - "to get the files and investigate them\n" - f"{json.dumps(expected_file_mappings, ensure_ascii=False, separators=(',', ':'))}" - ) + assert runner.run.call_args.kwargs["query"] == "你看得见这张图片吗" + assert runner.run.call_args.kwargs["files"] == files + assert runner.run.call_args.kwargs["image_detail_config"] is None def test_input_guard_short_circuit_skips_backend(self, generator, mocker: MockerFixture): runner, _ = self._wire(generator, mocker, handled=True) diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py index aff8efd111e..17f5fcfd19a 100644 --- a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py +++ b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py @@ -319,7 +319,7 @@ class TestResolveAgent: @pytest.fixture(autouse=True) def _publish_visibility(self, monkeypatch: pytest.MonkeyPatch) -> None: def is_publish_visible(*, agent: Agent, **_kwargs: object) -> bool: - return bool(agent.active_config_is_published) + return agent.active_config_is_published monkeypatch.setattr( app_generator, diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py index db33a1ad03b..b93f0e6ff90 100644 --- a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py +++ b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py @@ -12,6 +12,7 @@ from dify_agent.layers.config import DifyConfigSkillConfig from dify_agent.layers.dify_core_tools import DifyCoreToolConfig, DifyCoreToolsLayerConfig from dify_agent.layers.dify_plugin import DifyPluginToolConfig, DifyPluginToolsLayerConfig from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig +from dify_agent.layers.user_prompt import DifyUserPromptLayerConfig from clients.agent_backend import ( DIFY_CONFIG_LAYER_ID, @@ -29,6 +30,9 @@ from core.app.apps.agent_app.runtime_request_builder import ( AgentAppRuntimeRequestBuildError, ) from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom +from core.workflow.file_reference import build_file_reference +from graphon.file import File, FileTransferMethod, FileType +from graphon.model_runtime.entities.message_entities import ImagePromptMessageContent from models.agent_config_entities import AgentSoulConfig from tests.unit_tests.config_override import apply_config_overrides @@ -168,6 +172,8 @@ def _ctx( query: str = "hello", agent_config_version_kind: str = "snapshot", session_snapshot: CompositorSessionSnapshot | None = None, + files: tuple[File, ...] = (), + image_detail_config: ImagePromptMessageContent.DETAIL | None = None, ) -> AgentAppRuntimeBuildContext: dify_context = SimpleNamespace( tenant_id="tenant-1", @@ -188,6 +194,8 @@ def _ctx( backend_binding_ref="binding-ref-1", agent_config_version_kind=agent_config_version_kind, # type: ignore[arg-type] session_snapshot=session_snapshot, + files=files, + image_detail_config=image_detail_config, ) @@ -204,6 +212,32 @@ def _soul_with_model() -> AgentSoulConfig: ) +def _image_file() -> File: + return File( + file_id="file-1", + file_type=FileType.IMAGE, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-file-1", + filename="earth.png", + extension=".png", + mime_type="image/png", + size=12, + ) + + +def _document_file() -> File: + return File( + file_id="file-2", + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-document-1", + filename="brief.pdf", + extension=".pdf", + mime_type="application/pdf", + size=24, + ) + + def _snapshot_for_layer_names(layer_names: list[str]) -> CompositorSessionSnapshot: return CompositorSessionSnapshot( layers=[ @@ -251,6 +285,135 @@ class TestAgentAppRuntimeRequestBuilder: assert "credentials" not in result.redacted_request["composition"]["layers"][-1]["config"] assert result.metadata["conversation_id"] == "conv-1" + def test_build_sends_images_directly_to_vision_model(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr( + "core.app.apps.agent_app.runtime_request_builder.resolve_model_supports_vision", + lambda **_kwargs: True, + ) + prompt_content_calls: list[tuple[File, ImagePromptMessageContent.DETAIL | None]] = [] + + def to_prompt_message_content( + file: File, + *, + image_detail_config: ImagePromptMessageContent.DETAIL | None, + ) -> ImagePromptMessageContent: + prompt_content_calls.append((file, image_detail_config)) + return ImagePromptMessageContent( + format="png", + url="https://files.example.com/earth.png?sign=secret", + mime_type="image/png", + filename="earth.png", + detail=image_detail_config or ImagePromptMessageContent.DETAIL.LOW, + ) + + monkeypatch.setattr( + "core.app.apps.agent_app.runtime_request_builder.file_manager.to_prompt_message_content", + to_prompt_message_content, + ) + builder = AgentAppRuntimeRequestBuilder(dify_tools_builder=_NoToolsBuilder()) # type: ignore[arg-type] + + result = builder.build( + _ctx( + _soul_with_model(), + query="Describe this image.", + files=(_image_file(),), + image_detail_config=ImagePromptMessageContent.DETAIL.HIGH, + ) + ) + layer = next(item for item in result.request.composition.layers if item.name == "agent_app_user_prompt") + config = DifyUserPromptLayerConfig.model_validate(layer.config) + + assert config.text == "Describe this image." + assert len(config.files) == 1 + image = config.files[0] + assert image.delivery == "multimodal" + assert image.type == "image" + assert image.url == "https://files.example.com/earth.png?sign=secret" + assert image.detail == "high" + assert prompt_content_calls == [(_image_file(), ImagePromptMessageContent.DETAIL.HIGH)] + + def test_build_keeps_image_locator_for_non_vision_model(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr( + "core.app.apps.agent_app.runtime_request_builder.resolve_model_supports_vision", + lambda **_kwargs: False, + ) + builder = AgentAppRuntimeRequestBuilder(dify_tools_builder=_NoToolsBuilder()) # type: ignore[arg-type] + + result = builder.build(_ctx(_soul_with_model(), query="Inspect the attachment.", files=(_image_file(),))) + layer = next(item for item in result.request.composition.layers if item.name == "agent_app_user_prompt") + config = DifyUserPromptLayerConfig.model_validate(layer.config) + + assert config.text == "Inspect the attachment." + assert [file.model_dump(exclude_none=True) for file in config.files] == [ + { + "delivery": "download", + "type": "image", + "transfer_method": "local_file", + "reference": build_file_reference(record_id="upload-file-1"), + } + ] + + def test_build_preserves_inline_base64_transport_for_vision_model(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr( + "core.app.apps.agent_app.runtime_request_builder.resolve_model_supports_vision", + lambda **_kwargs: True, + ) + monkeypatch.setattr( + "core.app.apps.agent_app.runtime_request_builder.file_manager.to_prompt_message_content", + lambda *_args, **_kwargs: ImagePromptMessageContent( + format="png", + base64_data="aW1hZ2UtYnl0ZXM=", + mime_type="image/png", + filename="earth.png", + detail="low", + ), + ) + builder = AgentAppRuntimeRequestBuilder(dify_tools_builder=_NoToolsBuilder()) # type: ignore[arg-type] + + result = builder.build(_ctx(_soul_with_model(), query="Describe this image.", files=(_image_file(),))) + layer = next(item for item in result.request.composition.layers if item.name == "agent_app_user_prompt") + config = DifyUserPromptLayerConfig.model_validate(layer.config) + + image = config.files[0] + assert image.delivery == "multimodal" + assert image.url is None + assert image.base64_data == "aW1hZ2UtYnl0ZXM=" + + def test_build_keeps_non_image_locator_when_vision_image_is_direct(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr( + "core.app.apps.agent_app.runtime_request_builder.resolve_model_supports_vision", + lambda **_kwargs: True, + ) + monkeypatch.setattr( + "core.app.apps.agent_app.runtime_request_builder.file_manager.to_prompt_message_content", + lambda *_args, **_kwargs: ImagePromptMessageContent( + format="png", + url="https://files.example.com/earth.png", + mime_type="image/png", + filename="earth.png", + detail="low", + ), + ) + builder = AgentAppRuntimeRequestBuilder(dify_tools_builder=_NoToolsBuilder()) # type: ignore[arg-type] + + result = builder.build( + _ctx(_soul_with_model(), files=(_image_file(), _document_file()), query="Compare the attachments.") + ) + layer = next(item for item in result.request.composition.layers if item.name == "agent_app_user_prompt") + config = DifyUserPromptLayerConfig.model_validate(layer.config) + + assert config.text == "Compare the attachments." + assert len(config.files) == 2 + image, download = config.files + assert image.delivery == "multimodal" + assert image.filename == "earth.png" + assert download.model_dump(exclude_none=True) == { + "delivery": "download", + "type": "document", + "transfer_method": "local_file", + "reference": build_file_reference(record_id="upload-document-1"), + } + @pytest.mark.parametrize( ("previous_prompt", "current_prompt"), [("", "You are Iris."), ("You are Iris.", "")], diff --git a/api/tests/unit_tests/core/app/llm/test_model_access.py b/api/tests/unit_tests/core/app/llm/test_model_access.py index 8c22d56223e..9bb0ef37712 100644 --- a/api/tests/unit_tests/core/app/llm/test_model_access.py +++ b/api/tests/unit_tests/core/app/llm/test_model_access.py @@ -5,10 +5,15 @@ import pytest from core.app.entities.app_invoke_entities import DifyRunContext from core.app.llm import model_access -from graphon.model_runtime.entities.model_entities import ModelPropertyKey +from graphon.model_runtime.entities.model_entities import ModelFeature, ModelPropertyKey -def _stub_model_factory(monkeypatch: pytest.MonkeyPatch, context_window: object) -> dict[str, object]: +def _stub_model_factory( + monkeypatch: pytest.MonkeyPatch, + context_window: object, + *, + features: list[ModelFeature] | None = None, +) -> dict[str, object]: calls: dict[str, object] = {} class FakeModelFactory: @@ -18,7 +23,10 @@ def _stub_model_factory(monkeypatch: pytest.MonkeyPatch, context_window: object) def init_model_instance(self, provider_name: str, model_name: str) -> object: calls["provider_name"] = provider_name calls["model_name"] = model_name - schema = SimpleNamespace(model_properties={ModelPropertyKey.CONTEXT_SIZE: context_window}) + schema = SimpleNamespace( + model_properties={ModelPropertyKey.CONTEXT_SIZE: context_window}, + features=features, + ) return SimpleNamespace(get_model_schema=lambda: schema) monkeypatch.setattr(model_access, "DifyModelFactory", FakeModelFactory) @@ -58,3 +66,24 @@ def test_resolve_model_context_window_ignores_invalid_schema_values( ) is None ) + + +@pytest.mark.parametrize( + ("features", "expected"), + [([ModelFeature.VISION], True), ([], False), (None, False)], +) +def test_resolve_model_supports_vision_reads_selected_model_schema( + monkeypatch: pytest.MonkeyPatch, + features: list[ModelFeature] | None, + expected: bool, +) -> None: + _stub_model_factory(monkeypatch, 128_000, features=features) + + assert ( + model_access.resolve_model_supports_vision( + run_context=cast(DifyRunContext, object()), + provider_name="openai", + model_name="gpt-4o", + ) + is expected + ) diff --git a/api/tests/unit_tests/core/ops/test_ops_trace_manager.py b/api/tests/unit_tests/core/ops/test_ops_trace_manager.py index f4bebc64c21..b37553f8510 100644 --- a/api/tests/unit_tests/core/ops/test_ops_trace_manager.py +++ b/api/tests/unit_tests/core/ops/test_ops_trace_manager.py @@ -14,7 +14,7 @@ from uuid import UUID import pytest from flask import Flask from sqlalchemy import Engine -from sqlalchemy.orm import Session, sessionmaker +from sqlalchemy.orm import Session, scoped_session, sessionmaker import core.ops.ops_trace_manager as module from core.ops.ops_trace_manager import OpsTraceManager, TraceQueueManager, TraceTask, TraceTaskName @@ -144,8 +144,9 @@ class RecordingDispatcher: @pytest.fixture def database(sqlite_engine: Engine, sqlite_session: Session) -> Iterator[Session]: + session_proxy = scoped_session(lambda: sqlite_session) with ( - patch.object(module.db, "session", sqlite_session), + patch.object(module.db, "session", session_proxy), patch.object(type(module.db), "engine", new_callable=PropertyMock, return_value=sqlite_engine), ): yield sqlite_session @@ -289,7 +290,11 @@ def _message_data(**overrides): "inputs": "inputs", } data.update(overrides) - return SimpleNamespace(**data, to_dict=lambda: data) + return SimpleNamespace( + **data, + agent_thoughts_with_session=lambda *, session: data["agent_thoughts"], + to_dict=lambda: data, + ) def test_encrypt_decrypt_obfuscate_and_cache( diff --git a/api/tests/unit_tests/core/tools/test_custom_tool_provider.py b/api/tests/unit_tests/core/tools/test_custom_tool_provider.py index 760a6b49657..78c5c071747 100644 --- a/api/tests/unit_tests/core/tools/test_custom_tool_provider.py +++ b/api/tests/unit_tests/core/tools/test_custom_tool_provider.py @@ -6,6 +6,7 @@ import json from dataclasses import dataclass from types import SimpleNamespace from typing import cast +from unittest.mock import MagicMock from uuid import uuid4 import pytest @@ -43,7 +44,7 @@ def _db_provider() -> ApiToolProvider: name="provider-a", description="desc", icon="icon.svg", - user=SimpleNamespace(name="Alice"), + user=MagicMock(return_value=SimpleNamespace(name="Alice")), tools=[bundle], ), ) @@ -68,7 +69,9 @@ def _persist_provider(session: Session, *, tenant_id: str, name: str = "provider def test_api_tool_provider_from_db_and_parse_tool_bundle() -> None: - controller = ApiToolProviderController.from_db(_db_provider(), ApiProviderAuthType.API_KEY_HEADER) + controller = ApiToolProviderController.from_db( + _db_provider(), ApiProviderAuthType.API_KEY_HEADER, session=MagicMock() + ) assert controller.provider_type == ToolProviderType.API assert any(c.name == "api_key_value" for c in controller.entity.credentials_schema) @@ -78,17 +81,19 @@ def test_api_tool_provider_from_db_and_parse_tool_bundle() -> None: def test_api_tool_provider_from_db_query_auth_and_none_auth() -> None: - query_controller = ApiToolProviderController.from_db(_db_provider(), ApiProviderAuthType.API_KEY_QUERY) + query_controller = ApiToolProviderController.from_db( + _db_provider(), ApiProviderAuthType.API_KEY_QUERY, session=MagicMock() + ) assert any(c.name == "api_key_query_param" for c in query_controller.entity.credentials_schema) - none_controller = ApiToolProviderController.from_db(_db_provider(), ApiProviderAuthType.NONE) + none_controller = ApiToolProviderController.from_db(_db_provider(), ApiProviderAuthType.NONE, session=MagicMock()) assert [c.name for c in none_controller.entity.credentials_schema] == ["auth_type"] def test_api_tool_provider_load_get_tools_and_get_tool( monkeypatch: pytest.MonkeyPatch, sqlite_session: Session ) -> None: - controller = ApiToolProviderController.from_db(_db_provider(), ApiProviderAuthType.NONE) + controller = ApiToolProviderController.from_db(_db_provider(), ApiProviderAuthType.NONE, session=MagicMock()) loaded = controller.load_bundled_tools(_db_provider().tools) assert len(loaded) == 1 diff --git a/api/tests/unit_tests/core/tools/test_signature.py b/api/tests/unit_tests/core/tools/test_signature.py index 7dc87014935..ed1b043087a 100644 --- a/api/tests/unit_tests/core/tools/test_signature.py +++ b/api/tests/unit_tests/core/tools/test_signature.py @@ -2,6 +2,9 @@ from __future__ import annotations +import base64 +import hashlib +import hmac from collections.abc import Callable from typing import Literal from urllib.parse import parse_qs, urlparse @@ -300,3 +303,23 @@ def test_verify_plugin_file_signature_rejects_invalid_signatures( ) is False ) + + +def test_verify_plugin_file_signature_rejects_malformed_signed_timestamp() -> None: + timestamp = "not-a-timestamp" + nonce = "nonce" + payload = f"upload|report.pdf|application/pdf|tenant-id|user-id||{timestamp}|{nonce}" + sign = base64.urlsafe_b64encode(hmac.new(b"unit-secret", payload.encode(), hashlib.sha256).digest()).decode() + + assert ( + verify_plugin_file_signature( + filename="report.pdf", + mimetype="application/pdf", + tenant_id="tenant-id", + user_id="user-id", + timestamp=timestamp, + nonce=nonce, + sign=sign, + ) + is False + ) diff --git a/api/tests/unit_tests/core/tools/test_tool_manager.py b/api/tests/unit_tests/core/tools/test_tool_manager.py index eeac6f35365..a2e4e2f1526 100644 --- a/api/tests/unit_tests/core/tools/test_tool_manager.py +++ b/api/tests/unit_tests/core/tools/test_tool_manager.py @@ -9,7 +9,7 @@ from dataclasses import dataclass from datetime import datetime from types import SimpleNamespace from typing import Any -from unittest.mock import Mock, patch +from unittest.mock import ANY, Mock, patch import pytest from sqlalchemy import event @@ -32,10 +32,44 @@ from models.base import TypeBase from models.tools import ApiToolProvider, BuiltinToolProvider, WorkflowToolProvider +class _CallableSessionProxy: + """Lets test code use a session directly while production obtains it from ``db.session()``.""" + + def __init__(self, session: Session) -> None: + self._session = session + + def __call__(self) -> Session: + return self._session + + def add(self, instance: object) -> None: + self._session.add(instance) + + def add_all(self, instances: list[object]) -> None: + self._session.add_all(instances) + + def commit(self) -> None: + self._session.commit() + + def expire_all(self) -> None: + self._session.expire_all() + + def get(self, entity: type[object], ident: object) -> object | None: + return self._session.get(entity, ident) + + def scalar(self, statement: Any, *args: Any, **kwargs: Any) -> Any: + return self._session.scalar(statement, *args, **kwargs) + + def scalars(self, statement: Any, *args: Any, **kwargs: Any) -> Any: + return self._session.scalars(statement, *args, **kwargs) + + def execute(self, statement: Any, *args: Any, **kwargs: Any) -> Any: + return self._session.execute(statement, *args, **kwargs) + + @dataclass(frozen=True) class _ToolDatabase: engine: Engine - session: Session + session: _CallableSessionProxy @pytest.fixture @@ -48,7 +82,7 @@ def tool_database(sqlite_engine: Engine) -> Iterator[_ToolDatabase]: ] TypeBase.metadata.create_all(sqlite_engine, tables=tables) with Session(sqlite_engine, expire_on_commit=False) as session: - yield _ToolDatabase(engine=sqlite_engine, session=session) + yield _ToolDatabase(engine=sqlite_engine, session=_CallableSessionProxy(session)) def _builtin_provider( @@ -962,7 +996,7 @@ def test_get_api_provider_controller_returns_controller_and_credentials( assert built_controller is controller assert credentials == provider.credentials - mock_from_db.assert_called_with(provider, ApiProviderAuthType.API_KEY_QUERY) + mock_from_db.assert_called_with(provider, ApiProviderAuthType.API_KEY_QUERY, session=ANY) controller.load_bundled_tools.assert_called_once_with(provider.tools) diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py index a1de053a81f..7f88c8eccad 100644 --- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py +++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py @@ -6,10 +6,16 @@ from unittest.mock import MagicMock import pytest from agenton.compositor import CompositorSessionSnapshot +from agenton.compositor.schemas import LayerSessionSnapshot +from agenton.layers.base import LifecycleState from sqlalchemy import Engine, event, func, select from sqlalchemy.orm import Session, sessionmaker -from core.workflow.nodes.agent_v2.session_store import WorkflowAgentSessionScope, WorkflowAgentWorkspaceStore +from core.workflow.nodes.agent_v2.session_store import ( + WorkflowAgentSessionScope, + WorkflowAgentWorkspaceStore, + resolve_workflow_agent_workspace_owner_scope, +) from graphon.enums import WorkflowNodeExecutionStatus from models.agent import ( AgentConfigVersionKind, @@ -41,16 +47,18 @@ def _scope() -> WorkflowAgentSessionScope: def _execution_row( *, + execution_id: str = "execution-1", + workflow_run_id: str = "run-1", binding_id: str | None = None, process_data: dict[str, object] | None = None, ) -> WorkflowNodeExecutionModel: return WorkflowNodeExecutionModel( - id="execution-1", + id=execution_id, tenant_id="tenant-1", app_id="app-1", workflow_id="workflow-1", triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN, - workflow_run_id="run-1", + workflow_run_id=workflow_run_id, index=1, predecessor_node_id=None, node_execution_id="node-execution-1", @@ -158,6 +166,101 @@ def test_scope_uses_node_and_workflow_binding_as_workspace_subscope() -> None: assert owner.owner_scope_key == "node-1:workflow-binding-1" +def test_resolve_workspace_owner_scope_uses_conversation_for_chatflow() -> None: + owner = resolve_workflow_agent_workspace_owner_scope( + tenant_id="tenant-1", + app_id="app-1", + conversation_id="conversation-1", + workflow_run_id="run-1", + node_id="node-1", + workflow_agent_binding_id="workflow-binding-1", + ) + assert owner.owner_type is AgentWorkspaceOwnerType.CONVERSATION + assert owner.owner_id == "conversation-1" + assert owner.owner_scope_key == "node-1:workflow-binding-1" + + +def test_resolve_workspace_owner_scope_keeps_workflow_run_for_pure_workflow() -> None: + owner = resolve_workflow_agent_workspace_owner_scope( + tenant_id="tenant-1", + app_id="app-1", + conversation_id=None, + workflow_run_id="run-1", + node_id="node-1", + workflow_agent_binding_id="workflow-binding-1", + node_execution_id="execution-1", + ) + assert owner.owner_type is AgentWorkspaceOwnerType.WORKFLOW_RUN + assert owner.owner_id == "run-1" + + +def test_conversation_scope_reuses_existing_binding_on_later_turn( + monkeypatch: pytest.MonkeyPatch, + sqlite_session: Session, +) -> None: + prior_snapshot = CompositorSessionSnapshot( + layers=[ + LayerSessionSnapshot( + name="history", + lifecycle_state=LifecycleState.SUSPENDED, + runtime_state={"turn": 1}, + ) + ] + ) + workspace = AgentWorkspace( + id="workspace-conversation", + tenant_id="tenant-1", + app_id="app-1", + owner_type=AgentWorkspaceOwnerType.CONVERSATION, + owner_id="conversation-1", + owner_scope_key="node-1:workflow-binding-1", + backend_workspace_ref="workspace-1-ref", + status=AgentWorkingResourceStatus.ACTIVE, + active_guard=1, + ) + prior_binding = AgentWorkspaceBinding( + id="binding-prior", + tenant_id="tenant-1", + app_id="app-1", + workspace_id=workspace.id, + agent_id="agent-1", + base_home_snapshot_id="home-1", + agent_config_version_id="config-1", + agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT, + backend_binding_ref="backend-binding-prior", + status=AgentWorkingResourceStatus.ACTIVE, + session_snapshot=prior_snapshot.model_dump_json(), + ) + execution = _execution_row( + execution_id="execution-2", + workflow_run_id="run-2", + process_data={"workflow_agent_binding_id": "workflow-binding-1"}, + ) + sqlite_session.add_all([_home_snapshot(), workspace, prior_binding, execution]) + sqlite_session.commit() + client = _install_backend_client(monkeypatch) + + scope = WorkflowAgentSessionScope( + tenant_id="tenant-1", + app_id="app-1", + workflow_id="workflow-1", + workflow_run_id="run-2", + node_id="node-1", + node_execution_id="execution-2", + workflow_agent_binding_id="workflow-binding-1", + agent_id="agent-1", + agent_config_snapshot_id="config-1", + conversation_id="conversation-1", + ) + stored = WorkflowAgentWorkspaceStore().load_or_create_node_execution_session(scope, home_snapshot_id="home-1") + + assert stored.workspace_id == workspace.id + assert stored.binding_id == prior_binding.id + assert stored.session_snapshot == prior_snapshot + client.create_execution_binding_sync.assert_not_called() + assert sqlite_session.scalar(select(func.count()).select_from(AgentWorkspaceBinding)) == 1 + + def test_load_existing_scope_reads_the_generation_from_the_persisted_binding(sqlite_session: Session) -> None: sqlite_session.add_all( [ @@ -417,3 +520,49 @@ def test_retire_workflow_run_returns_existing_retired_workspace(sqlite_session: sqlite_session.expire(workspace) assert workspace.status is AgentWorkingResourceStatus.RETIRED assert workspace_ids == [workspace.id] + + +def test_workflow_scope_creates_binding_without_existing_workspace_ref( + monkeypatch: pytest.MonkeyPatch, + sqlite_session: Session, +) -> None: + execution = _execution_row(process_data={"workflow_agent_binding_id": "workflow-binding-1"}) + sqlite_session.add_all([_home_snapshot(), execution]) + sqlite_session.commit() + client = _install_backend_client(monkeypatch) + + WorkflowAgentWorkspaceStore().load_or_create_node_execution_session(_scope(), home_snapshot_id="home-1") + + request = client.create_execution_binding_sync.call_args.args[0] + assert request.existing_workspace_ref is None + + +def test_conversation_scope_first_turn_creates_binding_without_existing_workspace_ref( + monkeypatch: pytest.MonkeyPatch, + sqlite_session: Session, +) -> None: + execution = _execution_row( + execution_id="execution-2", + workflow_run_id="run-2", + process_data={"workflow_agent_binding_id": "workflow-binding-1"}, + ) + sqlite_session.add_all([_home_snapshot(), execution]) + sqlite_session.commit() + client = _install_backend_client(monkeypatch) + + scope = WorkflowAgentSessionScope( + tenant_id="tenant-1", + app_id="app-1", + workflow_id="workflow-1", + workflow_run_id="run-2", + node_id="node-1", + node_execution_id="execution-2", + workflow_agent_binding_id="workflow-binding-1", + agent_id="agent-1", + agent_config_snapshot_id="config-1", + conversation_id="conversation-1", + ) + WorkflowAgentWorkspaceStore().load_or_create_node_execution_session(scope, home_snapshot_id="home-1") + + request = client.create_execution_binding_sync.call_args.args[0] + assert request.existing_workspace_ref is None diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.py index 2be0f0c358e..df115b908bf 100644 --- a/api/tests/unit_tests/extensions/test_ext_application_services.py +++ b/api/tests/unit_tests/extensions/test_ext_application_services.py @@ -13,6 +13,7 @@ from pydantic import ValidationError from sqlalchemy import select from sqlalchemy.orm import Session, sessionmaker +from core.tools.tool_file_manager import ToolFileManager from enums import DeploymentEdition, WebAppAccessMode from extensions import ext_application_services from extensions.ext_redis import RedisClientWrapper @@ -31,7 +32,11 @@ from repositories.account_repository import SQLAlchemyAccountRepository from repositories.app_site_command_repository import AppSiteCommandRepository from repositories.app_statistic_query_repository import AppStatisticQueryRepository from repositories.app_tracing_config_repository import SQLAlchemyAppTracingConfigRepository +from repositories.human_input_file_upload_repository import SQLAlchemyHumanInputFileUploadRepository +from repositories.message_file_preview_repository import MessageFilePreviewQueryRepository +from repositories.plugin_file_upload_repository import SQLAlchemyPluginFileUploadOwnerRepository from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository +from repositories.upload_file_delivery_repository import UploadFileDeliveryQueryRepository from repositories.workflow_app_log_query_repository import WorkflowAppLogQueryRepository from repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepository from services import account_forgot_password_service, recommended_app_catalog_gateway @@ -68,11 +73,17 @@ from services.compliance_download_service import ComplianceDownloadService from services.enterprise.enterprise_service import WebAppSettings from services.errors.enterprise import EnterpriseAPIError, EnterpriseAPINotFoundError from services.file_service import FileService +from services.human_input_file_upload_service import HumanInputFileUploadService from services.init_validation_service import InvalidInitializationPasswordError +from services.message_file_preview_service import MessageFilePreviewService from services.partner_tenant_binding_service import PartnerTenantBindingService +from services.plugin_file_upload_gateway import ToolFilePluginUploadGateway +from services.plugin_file_upload_service import PluginFileUploadService from services.retention.workflow_run.archive_download_task_cache import WorkflowRunArchiveDownloadTaskCache from services.retention.workflow_run.archive_log_service import WorkflowRunArchiveService from services.tag_application_service import TagApplicationService +from services.tool_file_download_service import ToolFileDownloadService +from services.upload_file_delivery_service import UploadFileDeliveryService from services.webapp_access_query_service import WebAppAccessUnavailableError from services.workflow_app_log_query_service import WorkflowAppLogQueryService from services.workflow_run_service import WorkflowRunService @@ -232,6 +243,68 @@ def test_build_application_services_reuses_file_service( assert services.web_app_runtime._file_service is services.files +def test_build_application_services_wires_message_file_previews( + sqlite_session_factory: sessionmaker[Session], +) -> None: + services = ext_application_services.build_application_services( + database_client=sqlite_session_factory, + deployment_edition=DeploymentEdition.COMMUNITY, + initialization_password="", + redis=MagicMock(spec=RedisClientWrapper), + ) + + assert isinstance(services.message_file_previews, MessageFilePreviewService) + assert isinstance(services.message_file_previews._files, MessageFilePreviewQueryRepository) + assert services.message_file_previews._files._session_factory is sqlite_session_factory + assert services.message_file_previews._storage is ext_application_services.storage + + +def test_build_application_services_wires_plugin_file_upload_boundary( + sqlite_session_factory: sessionmaker[Session], +) -> None: + services = ext_application_services.build_application_services( + database_client=sqlite_session_factory, + deployment_edition=DeploymentEdition.COMMUNITY, + initialization_password="", + redis=MagicMock(spec=RedisClientWrapper), + ) + + assert isinstance(services.plugin_file_uploads, PluginFileUploadService) + assert isinstance(services.plugin_file_uploads._owners, SQLAlchemyPluginFileUploadOwnerRepository) + assert services.plugin_file_uploads._owners._session_factory is sqlite_session_factory + assert isinstance(services.plugin_file_uploads._files, ToolFilePluginUploadGateway) + + +def test_build_application_services_wires_tool_file_downloads( + sqlite_session_factory: sessionmaker[Session], +) -> None: + services = ext_application_services.build_application_services( + database_client=sqlite_session_factory, + deployment_edition=DeploymentEdition.COMMUNITY, + initialization_password="", + redis=MagicMock(spec=RedisClientWrapper), + ) + + assert isinstance(services.tool_file_downloads, ToolFileDownloadService) + assert isinstance(services.tool_file_downloads._tool_files, ToolFileManager) + + +def test_build_application_services_wires_upload_file_delivery( + sqlite_session_factory: sessionmaker[Session], +) -> None: + services = ext_application_services.build_application_services( + database_client=sqlite_session_factory, + deployment_edition=DeploymentEdition.COMMUNITY, + initialization_password="", + redis=MagicMock(spec=RedisClientWrapper), + ) + + assert isinstance(services.upload_file_delivery, UploadFileDeliveryService) + assert isinstance(services.upload_file_delivery._files, UploadFileDeliveryQueryRepository) + assert services.upload_file_delivery._files._session_factory is sqlite_session_factory + assert services.upload_file_delivery._storage is ext_application_services.storage + + def test_build_application_services_wires_workflow_run_archives( sqlite_session_factory: sessionmaker[Session], ) -> None: @@ -254,6 +327,25 @@ def test_build_application_services_wires_workflow_run_archives( assert workflow_run_archives._sign_download_url is ext_application_services.sign_workflow_run_archive_download_url +def test_build_application_services_wires_human_input_file_uploads( + sqlite_session_factory: sessionmaker[Session], +) -> None: + services = ext_application_services.build_application_services( + database_client=sqlite_session_factory, + deployment_edition=DeploymentEdition.COMMUNITY, + initialization_password="", + redis=MagicMock(spec=RedisClientWrapper), + ) + + human_input_file_uploads = services.human_input_file_uploads + assert isinstance(human_input_file_uploads, HumanInputFileUploadService) + assert isinstance(human_input_file_uploads._uploads, SQLAlchemyHumanInputFileUploadRepository) + assert human_input_file_uploads._uploads._session_factory is sqlite_session_factory + assert human_input_file_uploads._remote_files is services.remote_files + assert human_input_file_uploads._files is services.files + assert services.remote_files._files is services.files + + def test_build_application_services_wires_app_site_boundary( sqlite_session_factory: sessionmaker[Session], ) -> None: diff --git a/api/tests/unit_tests/fields/test_snippet_fields.py b/api/tests/unit_tests/fields/test_snippet_fields.py index f3119012c58..aa46ddd83c3 100644 --- a/api/tests/unit_tests/fields/test_snippet_fields.py +++ b/api/tests/unit_tests/fields/test_snippet_fields.py @@ -1,17 +1,26 @@ +import json from datetime import UTC, datetime import pytest from sqlalchemy.orm import Session -from fields.snippet_fields import SnippetListItemResponse -from libs.helper import dump_response -from models import snippet as snippet_module +from fields.snippet_fields import snippet_list_item_response, snippet_response from models.account import Account -from models.snippet import CustomizedSnippet +from models.enums import TagType +from models.model import Tag, TagBinding +from models.snippet import CustomizedSnippet, SnippetType +from models.workflow import Workflow, WorkflowType + +TENANT_ID = "11111111-1111-1111-1111-111111111111" +WORKFLOW_ID = "22222222-2222-2222-2222-222222222222" +APP_ID = "33333333-3333-3333-3333-333333333333" +SNIPPET_ID = "44444444-4444-4444-4444-444444444444" +ACCOUNT_1_ID = "55555555-5555-5555-5555-555555555555" +ACCOUNT_2_ID = "55555555-5555-5555-5555-555555555556" @pytest.mark.parametrize("sqlite_session", [(CustomizedSnippet, Account)], indirect=True) -def test_snippet_list_fields_include_author_name(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> None: +def test_snippet_list_fields_include_author_name(sqlite_session: Session) -> None: account = Account(name="Alice", email="alice@example.com") account.id = "account-1" snippet = CustomizedSnippet( @@ -31,8 +40,72 @@ def test_snippet_list_fields_include_author_name(sqlite_session: Session, monkey ) sqlite_session.add_all([account, snippet]) sqlite_session.flush() - monkeypatch.setattr(snippet_module.db, "session", sqlite_session) - result = dump_response(SnippetListItemResponse, snippet) + result = snippet_list_item_response(snippet, session=sqlite_session).model_dump(mode="json") assert result["author_name"] == "Alice" + + +@pytest.fixture +def populated_snippet(sqlite_session: Session) -> CustomizedSnippet: + """Persist a snippet plus the workflow, accounts and tag its response resolves.""" + workflow = Workflow( + tenant_id=TENANT_ID, + app_id=APP_ID, + type=WorkflowType.WORKFLOW, + version="1", + graph=json.dumps({"nodes": [{"id": "llm-1"}], "edges": []}), + _features="{}", + created_by=ACCOUNT_1_ID, + ) + workflow.id = WORKFLOW_ID + author = Account(name="Ada", email="ada@example.com") + author.id = ACCOUNT_1_ID + editor = Account(name="Grace", email="grace@example.com") + editor.id = ACCOUNT_2_ID + tag = Tag(tenant_id=TENANT_ID, type=TagType.SNIPPET, name="Reusable", created_by=ACCOUNT_1_ID) + binding = TagBinding(tenant_id=TENANT_ID, tag_id=tag.id, target_id=SNIPPET_ID, created_by=ACCOUNT_1_ID) + sqlite_session.add_all((workflow, author, editor, tag, binding)) + sqlite_session.commit() + + return CustomizedSnippet( + id=SNIPPET_ID, + tenant_id=TENANT_ID, + name="Snippet", + description="Reusable node", + type=SnippetType.NODE, + workflow_id=WORKFLOW_ID, + is_published=True, + version=1, + use_count=0, + icon_info=None, + input_fields=json.dumps([{"variable": "query"}]), + created_by=ACCOUNT_1_ID, + updated_by=ACCOUNT_2_ID, + created_at=datetime.fromtimestamp(1704067200, tz=UTC), + updated_at=datetime.fromtimestamp(1704067201, tz=UTC), + ) + + +def test_snippet_response_resolves_fields_from_the_given_session( + populated_snippet: CustomizedSnippet, sqlite_session: Session +) -> None: + result = snippet_response(populated_snippet, session=sqlite_session).model_dump(mode="json") + + assert result["graph"] == {"nodes": [{"id": "llm-1"}], "edges": []} + assert result["input_fields"] == [{"variable": "query"}] + assert result["created_by"]["name"] == "Ada" + assert result["updated_by"]["name"] == "Grace" + assert [tag["name"] for tag in result["tags"]] == ["Reusable"] + + +def test_snippet_list_item_resolves_author_and_tags_from_the_given_session( + populated_snippet: CustomizedSnippet, sqlite_session: Session +) -> None: + result = snippet_list_item_response(populated_snippet, session=sqlite_session).model_dump(mode="json") + + assert result["author_name"] == "Ada" + assert [tag["name"] for tag in result["tags"]] == ["Reusable"] + # The list row carries the raw audit ids; only the detail response resolves them to accounts. + assert result["created_by"] == ACCOUNT_1_ID + assert result["updated_by"] == ACCOUNT_2_ID diff --git a/api/tests/unit_tests/models/test_app_annotation_setting_session_accessors.py b/api/tests/unit_tests/models/test_app_annotation_setting_session_accessors.py new file mode 100644 index 00000000000..23b86cd2c38 --- /dev/null +++ b/api/tests/unit_tests/models/test_app_annotation_setting_session_accessors.py @@ -0,0 +1,60 @@ +"""Regression coverage for the ``@property``→session-parameter refactor on +``AppAnnotationSetting.collection_binding_detail``. + +The legacy ``@property`` reached for the global ``db.session`` internally and has been converted +to a plain method taking an explicit ``session: Session`` (per the pattern established in +#40370/#40797/#41394/#41830, tracked in #40372). + +The accessor is exercised against the real ``sqlite_session`` fixture (a genuine SQLAlchemy +``Session`` bound to a pristine full-schema SQLite database) so the assertions cover actual query +behaviour rather than a mock's recorded call. +""" + +from uuid import uuid4 + +from sqlalchemy.orm import Session + +from models.dataset import DatasetCollectionBinding +from models.enums import CollectionBindingType +from models.model import AppAnnotationSetting + + +def _persist_collection_binding(session: Session) -> DatasetCollectionBinding: + binding = DatasetCollectionBinding( + collection_name="test_collection", + provider_name="test_provider", + model_name="test_model", + type=CollectionBindingType.DATASET, + ) + session.add(binding) + session.flush() + return binding + + +def _persist_setting(session: Session, *, collection_binding_id: str) -> AppAnnotationSetting: + setting = AppAnnotationSetting( + app_id=str(uuid4()), + score_threshold=0.8, + collection_binding_id=collection_binding_id, + created_user_id=str(uuid4()), + updated_user_id=str(uuid4()), + ) + session.add(setting) + session.flush() + return setting + + +class TestAppAnnotationSettingCollectionBindingDetail: + def test_returns_the_bound_collection_binding(self, sqlite_session: Session) -> None: + binding = _persist_collection_binding(sqlite_session) + setting = _persist_setting(sqlite_session, collection_binding_id=binding.id) + + result = setting.collection_binding_detail(session=sqlite_session) + + assert result is not None + assert result.id == binding.id + + def test_returns_none_when_binding_missing(self, sqlite_session: Session) -> None: + setting = _persist_setting(sqlite_session, collection_binding_id=str(uuid4())) + + assert setting.collection_binding_detail(session=sqlite_session) is None diff --git a/api/tests/unit_tests/models/test_app_models.py b/api/tests/unit_tests/models/test_app_models.py index d00060312ad..7c7e2a8163d 100644 --- a/api/tests/unit_tests/models/test_app_models.py +++ b/api/tests/unit_tests/models/test_app_models.py @@ -541,8 +541,9 @@ class TestConversationModel: # Assert assert conversation._inputs == inputs - def test_conversation_summary_or_query_with_summary(self): - """Test summary_or_query property when summary exists.""" + @pytest.mark.parametrize("sqlite_session", [(Conversation, Message)], indirect=True) + def test_conversation_summary_or_query_with_summary(self, sqlite_session: Session): + """Test summary_or_query_with_session when summary exists.""" # Arrange conversation = Conversation( app_id=str(uuid4()), @@ -555,14 +556,14 @@ class TestConversationModel: ) # Act - result = conversation.summary_or_query + result = conversation.summary_or_query_with_session(session=sqlite_session) # Assert assert result == "Test summary" @pytest.mark.parametrize("sqlite_session", [(Conversation, Message)], indirect=True) def test_conversation_summary_or_query_without_summary(self, sqlite_session: Session): - """Test summary_or_query property when summary is empty.""" + """Test summary_or_query_with_session when summary is empty.""" # Arrange conversation = Conversation( app_id=str(uuid4()), diff --git a/api/tests/unit_tests/models/test_dataset_models.py b/api/tests/unit_tests/models/test_dataset_models.py index 4d691214d2b..2ca01cf44f9 100644 --- a/api/tests/unit_tests/models/test_dataset_models.py +++ b/api/tests/unit_tests/models/test_dataset_models.py @@ -1662,6 +1662,34 @@ class TestChildChunkSessionAccessors: assert child_chunk.segment(session=sqlite_session) is None +class TestDatasetAvailableDocumentCount: + """Regression coverage for ``Dataset.get_available_document_count``. + + The accessor was a ``@property`` reaching for the global ``db.session``; it now takes a + caller-provided session, matching the other ``get_*`` accessors on ``Dataset``. + """ + + def test_counts_only_completed_enabled_documents(self, sqlite_session: Session): + dataset = _make_dataset(dataset_id=str(uuid4()), tenant_id=str(uuid4())) + completed = _make_document( + document_id=str(uuid4()), + dataset_id=dataset.id, + tenant_id=dataset.tenant_id, + indexing_status=IndexingStatus.COMPLETED, + ) + waiting = _make_document( + document_id=str(uuid4()), + dataset_id=dataset.id, + tenant_id=dataset.tenant_id, + position=2, + indexing_status=IndexingStatus.WAITING, + ) + sqlite_session.add_all([dataset, completed, waiting]) + sqlite_session.flush() + + assert dataset.get_available_document_count(session=sqlite_session) == 1 + + class TestDocumentSegmentNeighborAccessors: """Regression coverage for ``DocumentSegment.previous_segment`` and ``next_segment`` refactored to take a caller-provided session. diff --git a/api/tests/unit_tests/models/test_installed_app_session_accessors.py b/api/tests/unit_tests/models/test_installed_app_session_accessors.py new file mode 100644 index 00000000000..0b1f5a04058 --- /dev/null +++ b/api/tests/unit_tests/models/test_installed_app_session_accessors.py @@ -0,0 +1,51 @@ +"""Regression coverage for the ``@property``→session-parameter refactor on +``InstalledApp.tenant``. + +The legacy ``@property`` reached for the global ``db.session`` internally and has been converted +to a plain method taking an explicit ``session: Session`` (per the pattern established in +#40370/#40797/#41394/#41830/#41885, tracked in #40372). +""" + +from uuid import uuid4 + +from sqlalchemy.orm import Session + +from models.account import Tenant +from models.model import InstalledApp + + +def _persist_tenant(session: Session) -> Tenant: + tenant = Tenant(name="Test Tenant") + session.add(tenant) + session.flush() + return tenant + + +def _persist_installed_app(session: Session, *, tenant_id: str) -> InstalledApp: + installed_app = InstalledApp( + tenant_id=tenant_id, + app_id=str(uuid4()), + app_owner_tenant_id=str(uuid4()), + position=0, + is_pinned=False, + last_used_at=None, + ) + session.add(installed_app) + session.flush() + return installed_app + + +class TestInstalledAppTenant: + def test_returns_the_matching_tenant(self, sqlite_session: Session) -> None: + tenant = _persist_tenant(sqlite_session) + installed_app = _persist_installed_app(sqlite_session, tenant_id=tenant.id) + + result = installed_app.tenant(session=sqlite_session) + + assert result is not None + assert result.id == tenant.id + + def test_returns_none_when_tenant_missing(self, sqlite_session: Session) -> None: + installed_app = _persist_installed_app(sqlite_session, tenant_id=str(uuid4())) + + assert installed_app.tenant(session=sqlite_session) is None diff --git a/api/tests/unit_tests/models/test_message_annotation_session_accessors.py b/api/tests/unit_tests/models/test_message_annotation_session_accessors.py new file mode 100644 index 00000000000..6e2de3dbed3 --- /dev/null +++ b/api/tests/unit_tests/models/test_message_annotation_session_accessors.py @@ -0,0 +1,106 @@ +"""Regression coverage for the ``@property``→session-parameter refactor on Message +feedback/annotation accessors. + +Covers three of `api/models/model.py`'s legacy `@property` accessors that reached for the global +``db.session`` internally and have been removed in favour of their existing explicit-session +methods (per the pattern established in #40370/#40797/#41394/#41830, tracked in #40372): + +- ``MessageFeedback.from_account_with_session`` +- ``MessageAnnotation.account_with_session`` +- ``MessageAnnotation.annotation_create_account_with_session`` + +Each accessor is exercised against the real ``sqlite_session`` fixture (a genuine SQLAlchemy +``Session`` bound to a pristine full-schema SQLite database) so the assertions cover actual +query behaviour rather than a mock's recorded call. +""" + +from uuid import uuid4 + +from sqlalchemy.orm import Session + +from models.account import Account +from models.enums import FeedbackFromSource, FeedbackRating +from models.model import MessageAnnotation, MessageFeedback + + +def _persist_account(session: Session, *, email: str | None = None) -> Account: + account = Account(name="Test Account", email=email or "test@example.com") + session.add(account) + session.flush() + return account + + +def _persist_feedback(session: Session, *, app_id: str, from_account_id: str | None) -> MessageFeedback: + feedback = MessageFeedback( + app_id=app_id, + conversation_id=str(uuid4()), + message_id=str(uuid4()), + rating=FeedbackRating.LIKE, + from_source=FeedbackFromSource.USER, + from_account_id=from_account_id, + ) + session.add(feedback) + session.flush() + return feedback + + +def _persist_annotation(session: Session, *, app_id: str, account_id: str) -> MessageAnnotation: + annotation = MessageAnnotation( + app_id=app_id, + conversation_id=None, + message_id=None, + question="What is AI?", + content="AI stands for Artificial Intelligence.", + account_id=account_id, + ) + session.add(annotation) + session.flush() + return annotation + + +class TestMessageFeedbackFromAccount: + def test_returns_the_feedback_author(self, sqlite_session: Session) -> None: + account = _persist_account(sqlite_session) + feedback = _persist_feedback(sqlite_session, app_id=str(uuid4()), from_account_id=account.id) + + result = feedback.from_account_with_session(session=sqlite_session) + + assert result is not None + assert result.id == account.id + + def test_returns_none_when_account_missing(self, sqlite_session: Session) -> None: + feedback = _persist_feedback(sqlite_session, app_id=str(uuid4()), from_account_id=str(uuid4())) + + assert feedback.from_account_with_session(session=sqlite_session) is None + + +class TestMessageAnnotationAccount: + def test_returns_the_annotation_creator(self, sqlite_session: Session) -> None: + creator = _persist_account(sqlite_session, email="creator@example.com") + annotation = _persist_annotation(sqlite_session, app_id=str(uuid4()), account_id=creator.id) + + result = annotation.account_with_session(session=sqlite_session) + + assert result is not None + assert result.id == creator.id + + def test_returns_none_when_account_missing(self, sqlite_session: Session) -> None: + annotation = _persist_annotation(sqlite_session, app_id=str(uuid4()), account_id=str(uuid4())) + + assert annotation.account_with_session(session=sqlite_session) is None + + +class TestMessageAnnotationAnnotationCreateAccount: + def test_returns_the_annotation_creator(self, sqlite_session: Session) -> None: + creator = _persist_account(sqlite_session, email="creator2@example.com") + annotation = _persist_annotation(sqlite_session, app_id=str(uuid4()), account_id=creator.id) + + result = annotation.annotation_create_account_with_session(session=sqlite_session) + + assert result is not None + assert result.id == creator.id + + def test_returns_none_when_account_missing(self, sqlite_session: Session) -> None: + annotation = _persist_annotation(sqlite_session, app_id=str(uuid4()), account_id=str(uuid4())) + + assert annotation.annotation_create_account_with_session(session=sqlite_session) is None diff --git a/api/tests/unit_tests/models/test_snippet.py b/api/tests/unit_tests/models/test_snippet.py index 12500bb2d0c..3a03fbcebc6 100644 --- a/api/tests/unit_tests/models/test_snippet.py +++ b/api/tests/unit_tests/models/test_snippet.py @@ -1,8 +1,7 @@ -"""Snippet model properties backed by the shared SQLite test session.""" +"""Snippet model accessors backed by the shared SQLite test session.""" import json -import pytest from sqlalchemy.orm import Session from models import snippet as snippet_module @@ -18,24 +17,15 @@ APP_ID = "33333333-3333-3333-3333-333333333333" SNIPPET_ID = "44444444-4444-4444-4444-444444444444" ACCOUNT_1_ID = "55555555-5555-5555-5555-555555555555" ACCOUNT_2_ID = "55555555-5555-5555-5555-555555555556" -SQLITE_MODELS = (Workflow, Tag, TagBinding, Account) -@pytest.fixture -def snippet_session(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> Session: - """Expose the shared SQLite session to model properties that use the global Flask session.""" - monkeypatch.setattr(snippet_module.db, "session", sqlite_session) - return sqlite_session - - -def test_graph_dict_returns_empty_without_workflow_id() -> None: +def test_get_graph_dict_returns_empty_without_workflow_id(sqlite_session: Session) -> None: snippet = CustomizedSnippet(workflow_id=None) - assert snippet.graph_dict == {} + assert snippet.get_graph_dict(session=sqlite_session) == {} -@pytest.mark.parametrize("sqlite_session", [SQLITE_MODELS], indirect=True) -def test_graph_dict_loads_published_workflow_graph(snippet_session: Session) -> None: +def test_get_graph_dict_loads_published_workflow_graph(sqlite_session: Session) -> None: workflow = Workflow( tenant_id=TENANT_ID, app_id=APP_ID, @@ -46,18 +36,17 @@ def test_graph_dict_loads_published_workflow_graph(snippet_session: Session) -> created_by=ACCOUNT_1_ID, ) workflow.id = WORKFLOW_ID - snippet_session.add(workflow) - snippet_session.commit() + sqlite_session.add(workflow) + sqlite_session.commit() snippet = CustomizedSnippet(workflow_id=WORKFLOW_ID) - assert snippet.graph_dict == {"nodes": [{"id": "llm-1"}], "edges": []} + assert snippet.get_graph_dict(session=sqlite_session) == {"nodes": [{"id": "llm-1"}], "edges": []} -@pytest.mark.parametrize("sqlite_session", [SQLITE_MODELS], indirect=True) -def test_graph_dict_returns_empty_when_workflow_missing(snippet_session: Session) -> None: +def test_get_graph_dict_returns_empty_when_workflow_missing(sqlite_session: Session) -> None: snippet = CustomizedSnippet(workflow_id=WORKFLOW_ID) - assert snippet.graph_dict == {} + assert snippet.get_graph_dict(session=sqlite_session) == {} def test_input_fields_list_parses_json_or_returns_empty() -> None: @@ -67,45 +56,50 @@ def test_input_fields_list_parses_json_or_returns_empty() -> None: ] -@pytest.mark.parametrize("sqlite_session", [SQLITE_MODELS], indirect=True) -def test_tags_returns_query_results_or_empty(snippet_session: Session) -> None: +def test_get_tags_returns_query_results_or_empty(sqlite_session: Session) -> None: tag = Tag(tenant_id=TENANT_ID, type=TagType.SNIPPET, name="Reusable", created_by=ACCOUNT_1_ID) binding = TagBinding(tenant_id=TENANT_ID, tag_id=tag.id, target_id=SNIPPET_ID, created_by=ACCOUNT_1_ID) - snippet_session.add_all((tag, binding)) - snippet_session.commit() + sqlite_session.add_all((tag, binding)) + sqlite_session.commit() snippet = CustomizedSnippet(id=SNIPPET_ID, tenant_id=TENANT_ID) - assert snippet.tags == [tag] + assert snippet.get_tags(session=sqlite_session) == [tag] - snippet_session.delete(binding) - snippet_session.commit() - assert snippet.tags == [] + sqlite_session.delete(binding) + sqlite_session.commit() + assert snippet.get_tags(session=sqlite_session) == [] -@pytest.mark.parametrize("sqlite_session", [SQLITE_MODELS], indirect=True) -def test_account_properties_and_author_name(snippet_session: Session) -> None: +def test_get_account_accessors_and_author_name(sqlite_session: Session) -> None: account = Account(name="Ada", email="ada@example.com") account.id = ACCOUNT_1_ID updated_account = Account(name="Grace", email="grace@example.com") updated_account.id = ACCOUNT_2_ID - snippet_session.add_all((account, updated_account)) - snippet_session.commit() + sqlite_session.add_all((account, updated_account)) + sqlite_session.commit() snippet = CustomizedSnippet(created_by=ACCOUNT_1_ID, updated_by=ACCOUNT_2_ID) - assert snippet.created_by_account is account - assert snippet.author_name == "Ada" - assert snippet.updated_by_account is updated_account + assert snippet.get_created_by_account(session=sqlite_session) is account + assert snippet.get_author_name(session=sqlite_session) == "Ada" + assert snippet.get_updated_by_account(session=sqlite_session) is updated_account -def test_account_properties_return_none_without_account_ids() -> None: +def test_get_account_accessors_return_none_without_account_ids(sqlite_session: Session) -> None: snippet = CustomizedSnippet(created_by=None, updated_by=None) - assert snippet.created_by_account is None - assert snippet.author_name is None - assert snippet.updated_by_account is None + assert snippet.get_created_by_account(session=sqlite_session) is None + assert snippet.get_author_name(session=sqlite_session) is None + assert snippet.get_updated_by_account(session=sqlite_session) is None def test_version_str_returns_string_value() -> None: snippet = CustomizedSnippet(version=7) assert snippet.version_str == "7" + + +def test_session_backed_lookups_are_not_exposed_as_properties() -> None: + """Callers must pass a session; the model no longer reads the Flask-global ``db.session``.""" + assert not hasattr(snippet_module, "db") + for name in ("graph_dict", "tags", "created_by_account", "author_name", "updated_by_account"): + assert not hasattr(CustomizedSnippet, name) diff --git a/api/tests/unit_tests/models/test_tool_provider_session_accessors.py b/api/tests/unit_tests/models/test_tool_provider_session_accessors.py index 02506476d05..a5f906121f0 100644 --- a/api/tests/unit_tests/models/test_tool_provider_session_accessors.py +++ b/api/tests/unit_tests/models/test_tool_provider_session_accessors.py @@ -5,6 +5,7 @@ Covers four of `api/models/tools.py`'s legacy `@property` accessors that reached ``session: Session`` (per the pattern established in #40370/#40797/#41394, tracked in #40372): - ``ApiToolProvider.tenant`` +- ``ApiToolProvider.user`` - ``WorkflowToolProvider.user`` - ``WorkflowToolProvider.tenant`` - ``WorkflowToolProvider.app`` @@ -95,6 +96,25 @@ class TestApiToolProviderTenant: assert provider.tenant(session=sqlite_session) is None +class TestApiToolProviderUser: + def test_returns_persisted_user(self, sqlite_session: Session) -> None: + account = _persist_account(sqlite_session) + provider = _api_tool_provider(tenant_id=str(uuid4())) + provider.user_id = account.id + sqlite_session.add(provider) + sqlite_session.flush() + + result = provider.user(session=sqlite_session) + + assert result is not None + assert result.id == account.id + + def test_returns_none_when_user_missing(self, sqlite_session: Session) -> None: + provider = _api_tool_provider(tenant_id=str(uuid4())) + + assert provider.user(session=sqlite_session) is None + + class TestWorkflowToolProviderUser: def test_returns_persisted_user(self, sqlite_session: Session) -> None: tenant = _persist_tenant(sqlite_session) diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml index 42abc4e6e29..651f39a79f3 100644 --- a/api/tests/unit_tests/pyrefly.toml +++ b/api/tests/unit_tests/pyrefly.toml @@ -136,9 +136,8 @@ project-excludes = [ "controllers/console/workspace/test_snippets.py", "controllers/console/workspace/test_tool_providers.py", "controllers/console/workspace/test_workspace.py", - "controllers/files/test_image_preview.py", + "controllers/files/test_upload_file_delivery.py", "controllers/files/test_tool_files.py", - "controllers/files/test_upload.py", "controllers/inner_api/app/test_dsl.py", "controllers/inner_api/plugin/test_agent_config.py", "controllers/inner_api/plugin/test_plugin.py", diff --git a/api/tests/unit_tests/repositories/test_human_input_file_upload_repository.py b/api/tests/unit_tests/repositories/test_human_input_file_upload_repository.py new file mode 100644 index 00000000000..35639bc8aad --- /dev/null +++ b/api/tests/unit_tests/repositories/test_human_input_file_upload_repository.py @@ -0,0 +1,251 @@ +from datetime import datetime + +from sqlalchemy import select +from sqlalchemy.orm import Session, sessionmaker + +from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus +from models.account import Account, Tenant, TenantAccountJoin +from models.enums import CreatorUserRole, EndUserType +from models.human_input import ( + HumanInputForm, + HumanInputFormRecipient, + HumanInputFormUploadFile, + HumanInputFormUploadToken, + RecipientType, + StandaloneWebAppRecipientPayload, +) +from models.model import App, AppMode, EndUser, IconType +from repositories.human_input_file_upload_repository import SQLAlchemyHumanInputFileUploadRepository +from services.human_input_file_upload_service import HumanInputUploadFormRecord + +_TENANT_ID = "11111111-1111-1111-1111-111111111111" +_OTHER_TENANT_ID = "22222222-2222-2222-2222-222222222222" +_APP_ID = "33333333-3333-3333-3333-333333333333" +_OTHER_APP_ID = "44444444-4444-4444-4444-444444444444" +_ACCOUNT_ID = "55555555-5555-5555-5555-555555555555" +_END_USER_ID = "66666666-6666-6666-6666-666666666666" +_FORM_ID = "77777777-7777-7777-7777-777777777777" +_RECIPIENT_ID = "88888888-8888-8888-8888-888888888888" +_FILE_ID = "99999999-9999-9999-9999-999999999999" +_WORKFLOW_RUN_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" +_DELIVERY_ID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" +_FORM_TOKEN = "form-token" +_UPLOAD_TOKEN = "hitl_upload_token" +_CREATED_AT = datetime(2026, 1, 1) +_EXPIRATION_TIME = datetime(2099, 1, 1) + + +def _repository(session_factory: sessionmaker[Session]) -> SQLAlchemyHumanInputFileUploadRepository: + return SQLAlchemyHumanInputFileUploadRepository(session_factory=session_factory) + + +def _persist_form_and_recipient(session: Session) -> None: + session.add( + HumanInputForm( + id=_FORM_ID, + tenant_id=_TENANT_ID, + app_id=_APP_ID, + workflow_run_id=_WORKFLOW_RUN_ID, + form_kind=HumanInputFormKind.RUNTIME, + node_id="human-input", + form_definition="{}", + rendered_content="content", + expiration_time=_EXPIRATION_TIME, + created_at=_CREATED_AT, + ) + ) + session.add( + HumanInputFormRecipient( + id=_RECIPIENT_ID, + form_id=_FORM_ID, + delivery_id=_DELIVERY_ID, + recipient_type=RecipientType.STANDALONE_WEB_APP, + recipient_payload=StandaloneWebAppRecipientPayload().model_dump_json(), + access_token=_FORM_TOKEN, + ) + ) + session.commit() + + +def _persist_app_owner(session: Session) -> Account: + tenant = Tenant(name="Workspace") + tenant.id = _TENANT_ID + account = Account(name="Owner", email="owner@example.com") + account.id = _ACCOUNT_ID + session.add_all( + [ + tenant, + account, + TenantAccountJoin(tenant_id=_TENANT_ID, account_id=_ACCOUNT_ID, current=True), + App( + id=_APP_ID, + tenant_id=_TENANT_ID, + name="App", + description="", + mode=AppMode.WORKFLOW, + icon_type=IconType.EMOJI, + icon="app", + icon_background="#FFFFFF", + enable_site=True, + enable_api=True, + created_by=_ACCOUNT_ID, + updated_by=_ACCOUNT_ID, + ), + ] + ) + session.commit() + return account + + +def test_form_token_upload_token_grant_and_file_link_round_trip( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + _persist_form_and_recipient(sqlite_session) + repository = _repository(sqlite_session_factory) + + form = repository.get_form_by_recipient_token(_FORM_TOKEN) + + assert form is not None + assert form == HumanInputUploadFormRecord( + form_id=_FORM_ID, + recipient_id=_RECIPIENT_ID, + tenant_id=_TENANT_ID, + app_id=_APP_ID, + workflow_run_id=_WORKFLOW_RUN_ID, + form_kind=HumanInputFormKind.RUNTIME, + status=HumanInputFormStatus.WAITING, + submitted_at=None, + expiration_time=_EXPIRATION_TIME, + created_at=_CREATED_AT, + ) + assert repository.get_form_by_recipient_token("missing-token") is None + + repository.create_upload_token(form=form, upload_token=_UPLOAD_TOKEN) + grant = repository.get_upload_grant(_UPLOAD_TOKEN) + + assert grant is not None + assert grant.form == form + assert repository.get_upload_grant("missing-token") is None + + repository.add_file( + tenant_id=_TENANT_ID, + app_id=_APP_ID, + form_id=_FORM_ID, + upload_token_id=grant.upload_token_id, + file_id=_FILE_ID, + ) + + with sqlite_session_factory() as session: + token = session.scalar( + select(HumanInputFormUploadToken).where(HumanInputFormUploadToken.token == _UPLOAD_TOKEN) + ) + link = session.scalar( + select(HumanInputFormUploadFile).where(HumanInputFormUploadFile.upload_file_id == _FILE_ID) + ) + + assert token is not None + assert token.tenant_id == _TENANT_ID + assert token.app_id == _APP_ID + assert token.form_id == _FORM_ID + assert token.recipient_id == _RECIPIENT_ID + assert link is not None + assert link.tenant_id == _TENANT_ID + assert link.app_id == _APP_ID + assert link.form_id == _FORM_ID + assert link.upload_token_id == grant.upload_token_id + assert link.upload_file_id == _FILE_ID + + +def test_get_upload_owner_hydrates_account_for_tenant( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + _persist_app_owner(sqlite_session) + other_tenant = Tenant(name="Other Workspace") + other_tenant.id = _OTHER_TENANT_ID + sqlite_session.add(other_tenant) + sqlite_session.commit() + repository = _repository(sqlite_session_factory) + + owner = repository.get_upload_owner( + owner_id=_ACCOUNT_ID, + owner_role=CreatorUserRole.ACCOUNT, + tenant_id=_TENANT_ID, + app_id=_APP_ID, + ) + + assert isinstance(owner, Account) + assert owner.id == _ACCOUNT_ID + assert owner.current_tenant_id == _TENANT_ID + assert ( + repository.get_upload_owner( + owner_id=_ACCOUNT_ID, + owner_role=CreatorUserRole.ACCOUNT, + tenant_id=_OTHER_TENANT_ID, + app_id=_APP_ID, + ) + is None + ) + + +def test_get_upload_owner_scopes_end_user_to_tenant_and_app( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + _persist_app_owner(sqlite_session) + end_user = EndUser( + tenant_id=_TENANT_ID, + app_id=_APP_ID, + type=EndUserType.BROWSER, + is_anonymous=False, + session_id="session", + external_user_id="external-user", + ) + end_user.id = _END_USER_ID + sqlite_session.add(end_user) + sqlite_session.commit() + repository = _repository(sqlite_session_factory) + + owner = repository.get_upload_owner( + owner_id=_END_USER_ID, + owner_role=CreatorUserRole.END_USER, + tenant_id=_TENANT_ID, + app_id=_APP_ID, + ) + + assert isinstance(owner, EndUser) + assert owner.id == _END_USER_ID + assert ( + repository.get_upload_owner( + owner_id=_END_USER_ID, + owner_role=CreatorUserRole.END_USER, + tenant_id=_OTHER_TENANT_ID, + app_id=_APP_ID, + ) + is None + ) + assert ( + repository.get_upload_owner( + owner_id=_END_USER_ID, + owner_role=CreatorUserRole.END_USER, + tenant_id=_TENANT_ID, + app_id=_OTHER_APP_ID, + ) + is None + ) + + +def test_get_delivery_test_upload_owner_requires_matching_tenant( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + _persist_app_owner(sqlite_session) + repository = _repository(sqlite_session_factory) + + owner = repository.get_delivery_test_upload_owner(tenant_id=_TENANT_ID, app_id=_APP_ID) + + assert isinstance(owner, Account) + assert owner.id == _ACCOUNT_ID + assert owner.current_tenant_id == _TENANT_ID + assert repository.get_delivery_test_upload_owner(tenant_id=_OTHER_TENANT_ID, app_id=_APP_ID) is None diff --git a/api/tests/unit_tests/repositories/test_message_file_preview_repository.py b/api/tests/unit_tests/repositories/test_message_file_preview_repository.py new file mode 100644 index 00000000000..1a098d962ae --- /dev/null +++ b/api/tests/unit_tests/repositories/test_message_file_preview_repository.py @@ -0,0 +1,180 @@ +from datetime import datetime +from decimal import Decimal +from uuid import uuid4 + +import pytest +from sqlalchemy.engine import Engine +from sqlalchemy.orm import Session, sessionmaker + +from extensions.storage.storage_type import StorageType +from graphon.file import FileTransferMethod, FileType +from models.base import TypeBase +from models.enums import ConversationFromSource, CreatorUserRole +from models.model import Message, MessageFile, UploadFile +from repositories.message_file_preview_repository import MessageFilePreviewQueryRepository +from services.message_file_preview_service import ( + MessageFilePreviewAccessDeniedError, + MessageFilePreviewNotFoundError, + MessageFilePreviewRecord, +) + + +@pytest.fixture +def repository( + sqlite_engine: Engine, + sqlite_session_factory: sessionmaker[Session], +) -> MessageFilePreviewQueryRepository: + models = (Message, MessageFile, UploadFile) + tables = [TypeBase.metadata.tables[model.__tablename__] for model in models] + TypeBase.metadata.create_all(sqlite_engine, tables=tables) + return MessageFilePreviewQueryRepository(session_factory=sqlite_session_factory) + + +def _upload_file(*, file_id: str, tenant_id: str) -> UploadFile: + upload_file = UploadFile( + tenant_id=tenant_id, + storage_type=StorageType.LOCAL, + key="upload_files/tenant/file.pdf", + name="file.pdf", + size=42, + extension="pdf", + mime_type="application/pdf", + created_by_role=CreatorUserRole.END_USER, + created_by=str(uuid4()), + created_at=datetime(2026, 1, 1), + used=True, + ) + upload_file.id = file_id + return upload_file + + +def _message(*, app_id: str) -> Message: + return Message( + id=str(uuid4()), + app_id=app_id, + conversation_id=str(uuid4()), + _inputs={}, + query="preview", + message={}, + message_unit_price=Decimal(0), + answer="answer", + answer_unit_price=Decimal(0), + currency="USD", + from_source=ConversationFromSource.API, + ) + + +def _message_file(*, message_id: str, file_id: str) -> MessageFile: + return MessageFile( + message_id=message_id, + type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + created_by_role=CreatorUserRole.END_USER, + created_by=str(uuid4()), + upload_file_id=file_id, + ) + + +def _persist_message_file( + session: Session, + *, + app_id: str, + file_id: str, +) -> MessageFile: + message = _message(app_id=app_id) + message_file = _message_file(message_id=message.id, file_id=file_id) + session.add_all([message, message_file]) + return message_file + + +def test_get_for_app_returns_detached_file_metadata( + repository: MessageFilePreviewQueryRepository, + sqlite_session: Session, +) -> None: + file_id = str(uuid4()) + app_id = str(uuid4()) + tenant_id = str(uuid4()) + sqlite_session.add(_upload_file(file_id=file_id, tenant_id=tenant_id)) + _persist_message_file(sqlite_session, app_id=app_id, file_id=file_id) + sqlite_session.commit() + + result = repository.get_for_app(file_id=file_id, app_id=app_id, tenant_id=tenant_id) + + assert result == MessageFilePreviewRecord( + key="upload_files/tenant/file.pdf", + name="file.pdf", + size=42, + extension="pdf", + mime_type="application/pdf", + ) + + +def test_get_for_app_rejects_file_without_message_reference( + repository: MessageFilePreviewQueryRepository, + sqlite_session: Session, +) -> None: + file_id = str(uuid4()) + tenant_id = str(uuid4()) + sqlite_session.add(_upload_file(file_id=file_id, tenant_id=tenant_id)) + sqlite_session.commit() + + with pytest.raises(MessageFilePreviewNotFoundError): + repository.get_for_app(file_id=file_id, app_id=str(uuid4()), tenant_id=tenant_id) + + +def test_get_for_app_enforces_app_isolation( + repository: MessageFilePreviewQueryRepository, + sqlite_session: Session, +) -> None: + file_id = str(uuid4()) + tenant_id = str(uuid4()) + sqlite_session.add(_upload_file(file_id=file_id, tenant_id=tenant_id)) + _persist_message_file(sqlite_session, app_id=str(uuid4()), file_id=file_id) + sqlite_session.commit() + + with pytest.raises(MessageFilePreviewAccessDeniedError): + repository.get_for_app(file_id=file_id, app_id=str(uuid4()), tenant_id=tenant_id) + + +def test_get_for_app_rejects_missing_upload_file( + repository: MessageFilePreviewQueryRepository, + sqlite_session: Session, +) -> None: + file_id = str(uuid4()) + app_id = str(uuid4()) + _persist_message_file(sqlite_session, app_id=app_id, file_id=file_id) + sqlite_session.commit() + + with pytest.raises(MessageFilePreviewNotFoundError): + repository.get_for_app(file_id=file_id, app_id=app_id, tenant_id=str(uuid4())) + + +def test_get_for_app_enforces_tenant_isolation( + repository: MessageFilePreviewQueryRepository, + sqlite_session: Session, +) -> None: + file_id = str(uuid4()) + app_id = str(uuid4()) + sqlite_session.add(_upload_file(file_id=file_id, tenant_id=str(uuid4()))) + _persist_message_file(sqlite_session, app_id=app_id, file_id=file_id) + sqlite_session.commit() + + with pytest.raises(MessageFilePreviewAccessDeniedError): + repository.get_for_app(file_id=file_id, app_id=app_id, tenant_id=str(uuid4())) + + +def test_get_for_app_accepts_any_message_reference_owned_by_the_app( + repository: MessageFilePreviewQueryRepository, + sqlite_session: Session, +) -> None: + file_id = str(uuid4()) + app_id = str(uuid4()) + tenant_id = str(uuid4()) + sqlite_session.add(_upload_file(file_id=file_id, tenant_id=tenant_id)) + _persist_message_file(sqlite_session, app_id=str(uuid4()), file_id=file_id) + _persist_message_file(sqlite_session, app_id=app_id, file_id=file_id) + sqlite_session.commit() + + result = repository.get_for_app(file_id=file_id, app_id=app_id, tenant_id=tenant_id) + + assert result.key == "upload_files/tenant/file.pdf" diff --git a/api/tests/unit_tests/repositories/test_plugin_file_upload_repository.py b/api/tests/unit_tests/repositories/test_plugin_file_upload_repository.py new file mode 100644 index 00000000000..2e9fafc01cc --- /dev/null +++ b/api/tests/unit_tests/repositories/test_plugin_file_upload_repository.py @@ -0,0 +1,74 @@ +from sqlalchemy import func, select +from sqlalchemy.orm import Session, sessionmaker + +from models.account import Account, AccountStatus, TenantAccountJoin +from models.enums import EndUserType +from models.model import EndUser +from repositories.plugin_file_upload_repository import SQLAlchemyPluginFileUploadOwnerRepository + + +def _account(account_id: str) -> Account: + account = Account( + name=f"Account {account_id}", + email=f"{account_id}@example.com", + status=AccountStatus.ACTIVE, + ) + account.id = account_id + return account + + +def _end_user(*, user_id: str, tenant_id: str, session_id: str) -> EndUser: + return EndUser( + id=user_id, + tenant_id=tenant_id, + type=EndUserType.SERVICE_API, + session_id=session_id, + ) + + +def test_account_owner_must_belong_to_the_signed_tenant( + sqlite_session_factory: sessionmaker[Session], +) -> None: + member = _account("member-id") + other = _account("other-id") + with sqlite_session_factory.begin() as session: + session.add_all( + [ + member, + other, + TenantAccountJoin(tenant_id="tenant-id", account_id=member.id), + TenantAccountJoin(tenant_id="other-tenant-id", account_id=other.id), + ] + ) + + repository = SQLAlchemyPluginFileUploadOwnerRepository(session_factory=sqlite_session_factory) + + assert repository.owner_exists(tenant_id="tenant-id", user_id=member.id, user_from="account") is True + assert repository.owner_exists(tenant_id="tenant-id", user_id=other.id, user_from="account") is False + + +def test_end_user_owner_must_match_id_and_tenant( + sqlite_session_factory: sessionmaker[Session], +) -> None: + owner = _end_user(user_id="owner-id", tenant_id="tenant-id", session_id="shared-session") + other = _end_user(user_id="other-id", tenant_id="other-tenant-id", session_id="shared-session") + with sqlite_session_factory.begin() as session: + session.add_all([owner, other]) + + repository = SQLAlchemyPluginFileUploadOwnerRepository(session_factory=sqlite_session_factory) + + assert repository.owner_exists(tenant_id="tenant-id", user_id=owner.id, user_from=None) is True + assert repository.owner_exists(tenant_id="tenant-id", user_id=owner.id, user_from="end-user") is True + assert repository.owner_exists(tenant_id="tenant-id", user_id=other.id, user_from="end-user") is False + assert repository.owner_exists(tenant_id="tenant-id", user_id="shared-session", user_from=None) is False + + +def test_missing_end_user_is_not_created_during_authorization( + sqlite_session_factory: sessionmaker[Session], +) -> None: + repository = SQLAlchemyPluginFileUploadOwnerRepository(session_factory=sqlite_session_factory) + + assert repository.owner_exists(tenant_id="tenant-id", user_id="missing-id", user_from=None) is False + + with sqlite_session_factory() as session: + assert session.scalar(select(func.count()).select_from(EndUser)) == 0 diff --git a/api/tests/unit_tests/repositories/test_upload_file_delivery_repository.py b/api/tests/unit_tests/repositories/test_upload_file_delivery_repository.py new file mode 100644 index 00000000000..dcadbccec5c --- /dev/null +++ b/api/tests/unit_tests/repositories/test_upload_file_delivery_repository.py @@ -0,0 +1,129 @@ +from datetime import UTC, datetime + +import pytest +from sqlalchemy.orm import Session, sessionmaker + +from extensions.storage.storage_type import StorageType +from models.account import Tenant +from models.enums import CreatorUserRole +from models.model import UploadFile +from repositories.upload_file_delivery_repository import UploadFileDeliveryQueryRepository +from services.upload_file_delivery_service import UploadFileDeliveryNotFoundError, UploadFileDeliveryRecord + +WORKSPACE_ID = "11111111-1111-1111-1111-111111111111" +OTHER_WORKSPACE_ID = "22222222-2222-2222-2222-222222222222" +FILE_ID = "33333333-3333-3333-3333-333333333333" +OTHER_FILE_ID = "44444444-4444-4444-4444-444444444444" + + +def _upload_file(*, file_id: str = FILE_ID, tenant_id: str = WORKSPACE_ID) -> UploadFile: + upload_file = UploadFile( + tenant_id=tenant_id, + storage_type=StorageType.LOCAL, + key=f"upload_files/{tenant_id}/{file_id}.png", + name="logo.png", + size=42, + extension="png", + mime_type="image/png", + created_by_role=CreatorUserRole.ACCOUNT, + created_by="55555555-5555-5555-5555-555555555555", + created_at=datetime.now(UTC), + used=True, + ) + upload_file.id = file_id + return upload_file + + +def _workspace(*, workspace_id: str = WORKSPACE_ID, logo_file_id: str | None = None) -> Tenant: + workspace = Tenant(name=f"Workspace {workspace_id}") + workspace.id = workspace_id + if logo_file_id is not None: + workspace.custom_config_dict = {"replace_webapp_logo": logo_file_id} + return workspace + + +def _repository(session_factory: sessionmaker[Session]) -> UploadFileDeliveryQueryRepository: + return UploadFileDeliveryQueryRepository(session_factory=session_factory) + + +def test_get_by_id_returns_detached_record( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + upload_file = _upload_file() + sqlite_session.add(upload_file) + sqlite_session.commit() + + result = _repository(sqlite_session_factory).get_by_id(file_id=upload_file.id) + + assert result == UploadFileDeliveryRecord( + key=upload_file.key, + name=upload_file.name, + size=upload_file.size, + extension=upload_file.extension, + mime_type=upload_file.mime_type, + ) + + +def test_get_by_id_returns_none_when_file_does_not_exist( + sqlite_session_factory: sessionmaker[Session], +) -> None: + assert _repository(sqlite_session_factory).get_by_id(file_id=FILE_ID) is None + + +def test_get_workspace_logo_returns_workspace_owned_file( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + upload_file = _upload_file() + sqlite_session.add_all([_workspace(logo_file_id=upload_file.id), upload_file]) + sqlite_session.commit() + + result = _repository(sqlite_session_factory).get_workspace_logo(workspace_id=WORKSPACE_ID) + + assert result == UploadFileDeliveryRecord( + key=upload_file.key, + name=upload_file.name, + size=upload_file.size, + extension=upload_file.extension, + mime_type=upload_file.mime_type, + ) + + +def test_get_workspace_logo_rejects_missing_workspace( + sqlite_session_factory: sessionmaker[Session], +) -> None: + with pytest.raises(UploadFileDeliveryNotFoundError): + _repository(sqlite_session_factory).get_workspace_logo(workspace_id=WORKSPACE_ID) + + +def test_get_workspace_logo_rejects_workspace_without_configured_logo( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + sqlite_session.add(_workspace()) + sqlite_session.commit() + + with pytest.raises(UploadFileDeliveryNotFoundError, match="webapp logo is not found"): + _repository(sqlite_session_factory).get_workspace_logo(workspace_id=WORKSPACE_ID) + + +def test_get_workspace_logo_returns_none_when_configured_file_does_not_exist( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + sqlite_session.add(_workspace(logo_file_id=FILE_ID)) + sqlite_session.commit() + + assert _repository(sqlite_session_factory).get_workspace_logo(workspace_id=WORKSPACE_ID) is None + + +def test_get_workspace_logo_rejects_file_owned_by_another_workspace( + sqlite_session: Session, + sqlite_session_factory: sessionmaker[Session], +) -> None: + foreign_logo = _upload_file(file_id=OTHER_FILE_ID, tenant_id=OTHER_WORKSPACE_ID) + sqlite_session.add_all([_workspace(logo_file_id=foreign_logo.id), foreign_logo]) + sqlite_session.commit() + + assert _repository(sqlite_session_factory).get_workspace_logo(workspace_id=WORKSPACE_ID) is None diff --git a/api/tests/unit_tests/services/agent/test_workspace_service.py b/api/tests/unit_tests/services/agent/test_workspace_service.py index 2a239c6e726..cfa7d56a708 100644 --- a/api/tests/unit_tests/services/agent/test_workspace_service.py +++ b/api/tests/unit_tests/services/agent/test_workspace_service.py @@ -49,6 +49,7 @@ def _workspace( app_id: str = "app-1", owner_type: AgentWorkspaceOwnerType = AgentWorkspaceOwnerType.CONVERSATION, owner_id: str = "conversation-1", + owner_scope_key: str = "root", status: AgentWorkingResourceStatus = AgentWorkingResourceStatus.ACTIVE, updated_at: datetime | None = None, backend_workspace_ref: str = "workspace-ref", @@ -59,7 +60,7 @@ def _workspace( app_id=app_id, owner_type=owner_type, owner_id=owner_id, - owner_scope_key="root", + owner_scope_key=owner_scope_key, backend_workspace_ref=backend_workspace_ref, status=status, active_guard=1 if status is AgentWorkingResourceStatus.ACTIVE else None, @@ -329,6 +330,62 @@ def test_retire_workspace_retires_all_active_bindings(sqlite_session: Session) - assert all(binding.retired_at == workspace.retired_at for binding in bindings) +def test_resolve_active_binding_for_scope_returns_matching_participant(sqlite_session: Session) -> None: + workspace = _workspace(owner_scope_key="node-1:workflow-binding-1") + binding = _binding(binding_id="binding-chatflow", workspace_id=workspace.id) + sqlite_session.add_all([workspace, binding]) + sqlite_session.commit() + + resolved = AgentWorkspaceService.resolve_active_binding_for_scope( + session=sqlite_session, + scope=WorkspaceOwnerScope( + tenant_id="tenant-1", + app_id="app-1", + owner_type=AgentWorkspaceOwnerType.CONVERSATION, + owner_id="conversation-1", + owner_scope_key="node-1:workflow-binding-1", + ), + agent_id="agent-1", + ) + + assert resolved is not None + assert resolved.id == binding.id + + +def test_retire_all_for_conversation_retires_only_matching_conversation_workspaces( + sqlite_session: Session, +) -> None: + matching = _workspace( + workspace_id="workspace-chatflow", + owner_scope_key="node-1:workflow-binding-1", + ) + other_conversation = _workspace( + workspace_id="workspace-other-conversation", + owner_id="conversation-2", + owner_scope_key="node-2:workflow-binding-2", + ) + workflow_run = _workspace( + workspace_id="workspace-workflow-run", + owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN, + owner_id="run-1", + owner_scope_key="node-1:workflow-binding-1", + ) + sqlite_session.add_all([matching, other_conversation, workflow_run]) + sqlite_session.commit() + + retired_ids = AgentWorkspaceService.retire_all_for_conversation( + session=sqlite_session, + tenant_id="tenant-1", + app_id="app-1", + conversation_id="conversation-1", + ) + + assert retired_ids == [matching.id] + assert matching.status is AgentWorkingResourceStatus.RETIRED + assert other_conversation.status is AgentWorkingResourceStatus.ACTIVE + assert workflow_run.status is AgentWorkingResourceStatus.ACTIVE + + def test_retire_all_for_app_retires_only_active_workspaces_for_that_app(sqlite_session: Session) -> None: active = _workspace(workspace_id="workspace-active", owner_id="conversation-active") already_retired = _workspace( diff --git a/api/tests/unit_tests/services/dataset_service/test_save_document_with_dataset_id_mysql_snapshot.py b/api/tests/unit_tests/services/dataset_service/test_save_document_with_dataset_id_mysql_snapshot.py new file mode 100644 index 00000000000..e8af9b89ca1 --- /dev/null +++ b/api/tests/unit_tests/services/dataset_service/test_save_document_with_dataset_id_mysql_snapshot.py @@ -0,0 +1,70 @@ +"""Regression coverage for #41735. + +The pre-fix code in ``DocumentService.save_document_with_dataset_id`` +read ``UploadFile`` rows inside a single session that had its +``REPEATABLE READ`` snapshot pinned by an earlier ``Dataset`` SELECT. +When ``FileService.upload_text`` / ``upload_file`` committed the +``upload_files`` row in a SEPARATE session, the row was invisible to +*this* session until the snapshot was refreshed, and +``save_document_with_dataset_id`` reported ``One or more files not +found.`` even though the row was committed (verified via a second +session). + +The fix forces ``session.commit()`` immediately before the +``UploadFile`` lookup so the next SELECT starts a fresh snapshot. +This file pins that contract by reading the function source and +asserting the structural invariant directly. +""" + +from __future__ import annotations + +import inspect + +from services.dataset_service import DocumentService + + +def test_session_committed_before_upload_file_lookup() -> None: + """#41735: ``session.commit()`` must run BEFORE the ``UploadFile`` + SELECT so the SELECT sees rows committed by ``FileService.upload_text`` + on a different session. MySQL REPEATABLE READ keeps the original + snapshot for the rest of the transaction; the commit ends it so the + next SELECT starts a fresh transaction with a new snapshot. + PostgreSQL's default READ COMMITTED rebuilds the read view per + statement so the extra commit is a no-op there. + + Read the function source and assert that ``session.commit()`` is + called BEFORE the ``UploadFile`` SELECT — the same structural + invariant the reproduction in the issue depends on, without needing + a live MySQL database. + """ + source_lines = inspect.getsource(DocumentService.save_document_with_dataset_id).splitlines() + + upload_select_line = next( + (i for i, line in enumerate(source_lines) if "select(UploadFile)" in line), + None, + ) + assert upload_select_line is not None, "save_document_with_dataset_id must contain a select(UploadFile) call" + + # Find every ``session.commit()`` call, then keep the last one + # whose line number is BEFORE the UploadFile SELECT. If the fix is + # in place, that commit is the snapshot refresh. + last_commit_before_upload = -1 + for i, line in enumerate(source_lines): + if i >= upload_select_line: + break + if "session.commit()" in line: + last_commit_before_upload = i + + assert last_commit_before_upload >= 0, ( + "save_document_with_dataset_id must call session.commit() at least once before the UploadFile SELECT" + ) + + # The fix is a focused call: one extra ``session.commit()`` between + # the (already-existing) ``DocumentService.check_doc_form`` call and + # the ``select(UploadFile)`` call. Pin that there's a comment + # referencing #41735 right above the new commit so a future edit + # doesn't accidentally delete the snapshot refresh without + # understanding why it's there. + assert "#41735" in "\n".join(source_lines), ( + "The fix's invariant comment referencing issue #41735 must be present in save_document_with_dataset_id" + ) diff --git a/api/tests/unit_tests/services/dataset_service_test_helpers.py b/api/tests/unit_tests/services/dataset_service_test_helpers.py index 99157c63cab..6153afa3396 100644 --- a/api/tests/unit_tests/services/dataset_service_test_helpers.py +++ b/api/tests/unit_tests/services/dataset_service_test_helpers.py @@ -273,10 +273,9 @@ def _make_lock_context() -> MagicMock: return context_manager -def _make_features(*, enabled: bool, plan: str = CloudPlan.PROFESSIONAL) -> SimpleNamespace: +def _make_features(*, plan: str = CloudPlan.PROFESSIONAL) -> SimpleNamespace: return SimpleNamespace( billing=SimpleNamespace( - enabled=enabled, subscription=SimpleNamespace(plan=plan), ), documents_upload_quota=SimpleNamespace(limit=1000, size=0), diff --git a/api/tests/unit_tests/services/dify_builder/test_wiring.py b/api/tests/unit_tests/services/dify_builder/test_wiring.py index e7a4f5ecad2..7ebc9469bdb 100644 --- a/api/tests/unit_tests/services/dify_builder/test_wiring.py +++ b/api/tests/unit_tests/services/dify_builder/test_wiring.py @@ -1,10 +1,10 @@ import dataclasses -from unittest.mock import MagicMock, call, patch +from unittest.mock import MagicMock, patch import pytest from werkzeug.exceptions import Forbidden -from controllers.common.wraps import RBACPermission, RBACResourceScope +from controllers.common.rbac import PlainApp, RBACPermission from core.dify_builder.errors import BusyError, ConflictError, NotFoundError from core.dify_builder.models import Action, Actor from models import TenantAccountRole @@ -70,17 +70,19 @@ def test_authorize_app_legacy_requires_tenant_editor_role(monkeypatch: pytest.Mo monkeypatch.setattr(wiring.db.session, "scalar", scalar) monkeypatch.setattr(wiring.dify_config, "RBAC_ENABLED", False) enforce = MagicMock() - monkeypatch.setattr(wiring, "enforce_rbac_access", enforce) + monkeypatch.setattr(wiring, "enforce_rbac_checks", enforce) wiring._authorize_app(Actor(account_id="acc-1", tenant_id="ten-1"), "app-1", AppAccess.EDIT) enforce.assert_called_once_with( tenant_id="ten-1", account_id="acc-1", - resource_type=RBACResourceScope.APP, - scene=RBACPermission.APP_EDIT, + checks=enforce.call_args.kwargs["checks"], path_args={"app_id": "app-1"}, ) + check = enforce.call_args.kwargs["checks"][0] + assert check.scene is RBACPermission.APP_EDIT + assert isinstance(check.locator, PlainApp) def test_authorize_app_legacy_rejects_non_editor(monkeypatch: pytest.MonkeyPatch): @@ -113,20 +115,18 @@ def test_authorize_app_rbac_enforces_base_and_operation_permission( ) monkeypatch.setattr(wiring.dify_config, "RBAC_ENABLED", True) enforce = MagicMock() - monkeypatch.setattr(wiring, "enforce_rbac_access", enforce) + monkeypatch.setattr(wiring, "enforce_rbac_checks", enforce) wiring._authorize_app(Actor(account_id="acc-1", tenant_id="ten-1"), "app-1", access) - assert enforce.call_args_list == [ - call( - tenant_id="ten-1", - account_id="acc-1", - resource_type=RBACResourceScope.APP, - scene=scene, - path_args={"app_id": "app-1"}, - ) - for scene in scenes - ] + assert [item.kwargs["checks"][0].scene for item in enforce.call_args_list] == scenes + assert all(isinstance(item.kwargs["checks"][0].locator, PlainApp) for item in enforce.call_args_list) + assert all( + item.kwargs["tenant_id"] == "ten-1" + and item.kwargs["account_id"] == "acc-1" + and item.kwargs["path_args"] == {"app_id": "app-1"} + for item in enforce.call_args_list + ) def test_authorize_app_rejects_missing_or_foreign_app(monkeypatch: pytest.MonkeyPatch): diff --git a/api/tests/unit_tests/services/enterprise/test_rbac_agent_access.py b/api/tests/unit_tests/services/enterprise/test_rbac_agent_access.py new file mode 100644 index 00000000000..28fabd201eb --- /dev/null +++ b/api/tests/unit_tests/services/enterprise/test_rbac_agent_access.py @@ -0,0 +1,278 @@ +"""Unit tests for the agent-flavoured RBAC inner-API client. + +`RBACService.AgentAccess`, the agent methods on `RBACService.WorkspaceAccess` and +`RBACService.Catalog.agent` are all built from one generic resource-access client. +These tests monkeypatch `_inner_call` and assert the HTTP method, the exact endpoint, +the query/body keys and the returned model for every operation. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from services.enterprise import rbac_service as svc + +MODULE = "services.enterprise.rbac_service" + +TENANT = "tenant-1" +ACTOR = "acct-1" +AGENT = "agent-1" +POLICY = "policy-1" + + +@pytest.fixture +def inner_call() -> Iterator[MagicMock]: + with patch(f"{MODULE}._inner_call") as call: + call.return_value = {"automatic_include_workspace_members": True} + yield call + + +def _last(call: MagicMock) -> SimpleNamespace: + call.assert_called_once() + args, kwargs = call.call_args + return SimpleNamespace( + method=args[0], + endpoint=args[1], + tenant_id=kwargs.get("tenant_id"), + account_id=kwargs.get("account_id"), + json=kwargs.get("json"), + params=kwargs.get("params"), + ) + + +_AGENT_CASES: list[tuple[str, str, str, Callable[[], object]]] = [ + ( + "whitelist_resources", + "GET", + "/rbac/agents/whitelist/resources", + lambda: svc.RBACService.AgentAccess.whitelist_resources(TENANT, ACTOR), + ), + ( + "user_access_policies", + "GET", + "/rbac/agents/user-access-policies", + lambda: svc.RBACService.AgentAccess.user_access_policies(TENANT, ACTOR, agent_id=AGENT), + ), + ( + "replace_user_access_policies", + "PUT", + "/rbac/agents/user-access-policies", + lambda: svc.RBACService.AgentAccess.replace_user_access_policies( + TENANT, + ACTOR, + agent_id=AGENT, + target_account_id="member-1", + payload=svc.ReplaceUserAccessPolicies(access_policy_ids=[POLICY], account_ids=["member-1"]), + ), + ), + ( + "whitelist", + "GET", + "/rbac/agents/whitelist", + lambda: svc.RBACService.AgentAccess.whitelist(TENANT, ACTOR, agent_id=AGENT), + ), + ( + "whitelist_config", + "GET", + "/rbac/agents/whitelist", + lambda: svc.RBACService.AgentAccess.whitelist_config(TENANT, ACTOR, agent_id=AGENT), + ), + ( + "legacy_whitelist_config", + "GET", + "/rbac/agents/whitelist", + lambda: svc.RBACService.AgentAccess.legacy_whitelist_config(TENANT, ACTOR, agent_id=AGENT), + ), + ( + "replace_whitelist", + "PUT", + "/rbac/agents/whitelist", + lambda: svc.RBACService.AgentAccess.replace_whitelist( + TENANT, + ACTOR, + agent_id=AGENT, + payload=svc.ReplaceMemberBindings(automatic_include_workspace_members=True), + ), + ), + ( + "append_whitelist_members_batch", + "POST", + "/rbac/agents/whitelist/members/batch", + lambda: svc.RBACService.AgentAccess.append_whitelist_members_batch( + tenant_id=TENANT, + account_id=ACTOR, + data=[svc.AppendAgentWhitelistMembersBatchItem(agent_id=AGENT, account_ids=["member-1"], policy_id=POLICY)], + ), + ), + ( + "matrix", + "GET", + "/rbac/agents/access-policy", + lambda: svc.RBACService.AgentAccess.matrix(TENANT, ACTOR, agent_id=AGENT), + ), + ( + "list_role_bindings", + "GET", + "/rbac/agents/access-policy/role-bindings", + lambda: svc.RBACService.AgentAccess.list_role_bindings(TENANT, ACTOR, agent_id=AGENT, policy_id=POLICY), + ), + ( + "replace_role_bindings", + "PUT", + "/rbac/agents/access-policy/role-bindings", + lambda: svc.RBACService.AgentAccess.replace_role_bindings( + TENANT, ACTOR, agent_id=AGENT, policy_id=POLICY, payload=svc.ReplaceRoleBindings(role_ids=["role-1"]) + ), + ), + ( + "list_member_bindings", + "GET", + "/rbac/agents/access-policy/member-bindings", + lambda: svc.RBACService.AgentAccess.list_member_bindings(TENANT, ACTOR, agent_id=AGENT, policy_id=POLICY), + ), + ( + "delete_member_bindings", + "DELETE", + "/rbac/agents/access-policy/member-bindings", + lambda: svc.RBACService.AgentAccess.delete_member_bindings( + TENANT, ACTOR, agent_id=AGENT, policy_id=POLICY, payload=svc.DeleteMemberBindings(account_ids=["member-1"]) + ), + ), + ( + "replace_bindings", + "PUT", + "/rbac/agents/access-policy/bindings", + lambda: svc.RBACService.AgentAccess.replace_bindings( + TENANT, + ACTOR, + agent_id=AGENT, + policy_id=POLICY, + payload=svc.ReplaceBindings(role_ids=["role-1"], account_ids=["member-1"]), + ), + ), + ( + "workspace.agent_matrix", + "GET", + "/rbac/workspace/agents/access-policy", + lambda: svc.RBACService.WorkspaceAccess.agent_matrix(TENANT, ACTOR), + ), + ( + "workspace.list_agent_role_bindings", + "GET", + "/rbac/workspace/agents/access-policy/role-bindings", + lambda: svc.RBACService.WorkspaceAccess.list_agent_role_bindings(TENANT, ACTOR, POLICY), + ), + ( + "workspace.replace_agent_role_bindings", + "PUT", + "/rbac/workspace/agents/access-policy/role-bindings", + lambda: svc.RBACService.WorkspaceAccess.replace_agent_role_bindings( + TENANT, ACTOR, POLICY, svc.ReplaceRoleBindings(role_ids=["role-1"]) + ), + ), + ( + "workspace.list_agent_member_bindings", + "GET", + "/rbac/workspace/agents/access-policy/member-bindings", + lambda: svc.RBACService.WorkspaceAccess.list_agent_member_bindings(TENANT, ACTOR, POLICY), + ), + ( + "workspace.replace_agent_bindings", + "PUT", + "/rbac/workspace/agents/access-policy/bindings", + lambda: svc.RBACService.WorkspaceAccess.replace_agent_bindings( + TENANT, ACTOR, POLICY, svc.ReplaceBindings(role_ids=["role-1"], account_ids=["member-1"]) + ), + ), + ( + "catalog.agent", + "GET", + "/rbac/role-permissions/catalog/agent", + lambda: svc.RBACService.Catalog.agent(TENANT, account_id=ACTOR), + ), +] + + +@pytest.mark.parametrize( + ("method", "endpoint", "invoke"), + [(case[1], case[2], case[3]) for case in _AGENT_CASES], + ids=[case[0] for case in _AGENT_CASES], +) +def test_agent_operations_hit_the_agent_route( + inner_call: MagicMock, method: str, endpoint: str, invoke: Callable[[], object] +) -> None: + invoke() + + call = _last(inner_call) + assert call.method == method + assert call.endpoint == endpoint + assert "/apps/" not in call.endpoint + assert "/datasets/" not in call.endpoint + assert call.tenant_id == TENANT + assert call.account_id == ACTOR + params = call.params or {} + assert "app_id" not in params + assert "dataset_id" not in params + if AGENT in params.values(): + assert params.get("agent_id") == AGENT + + +_PARITY_CASES: list[tuple[str, Callable[[], object], Callable[[], object]]] = [ + ( + "whitelist_resources", + lambda: svc.RBACService.AppAccess.whitelist_resources(TENANT, ACTOR), + lambda: svc.RBACService.AgentAccess.whitelist_resources(TENANT, ACTOR), + ), + ( + "whitelist", + lambda: svc.RBACService.AppAccess.whitelist(TENANT, ACTOR, "res-1"), + lambda: svc.RBACService.AgentAccess.whitelist(TENANT, ACTOR, agent_id="res-1"), + ), + ( + "user_access_policies", + lambda: svc.RBACService.AppAccess.user_access_policies(TENANT, ACTOR, "res-1"), + lambda: svc.RBACService.AgentAccess.user_access_policies(TENANT, ACTOR, agent_id="res-1"), + ), + ( + "matrix", + lambda: svc.RBACService.AppAccess.matrix(TENANT, ACTOR, "res-1"), + lambda: svc.RBACService.AgentAccess.matrix(TENANT, ACTOR, agent_id="res-1"), + ), + ( + "list_role_bindings", + lambda: svc.RBACService.AppAccess.list_role_bindings(TENANT, ACTOR, "res-1", POLICY), + lambda: svc.RBACService.AgentAccess.list_role_bindings(TENANT, ACTOR, agent_id="res-1", policy_id=POLICY), + ), + ( + "list_member_bindings", + lambda: svc.RBACService.AppAccess.list_member_bindings(TENANT, ACTOR, "res-1", POLICY), + lambda: svc.RBACService.AgentAccess.list_member_bindings(TENANT, ACTOR, agent_id="res-1", policy_id=POLICY), + ), +] + + +@pytest.mark.parametrize( + ("app_call", "agent_call"), + [(case[1], case[2]) for case in _PARITY_CASES], + ids=[case[0] for case in _PARITY_CASES], +) +def test_same_path_and_param_shape_modulo_segment( + inner_call: MagicMock, + app_call: Callable[[], object], + agent_call: Callable[[], object], +) -> None: + app_call() + app = _last(inner_call) + inner_call.reset_mock() + agent_call() + agent = _last(inner_call) + + assert app.endpoint.replace("/apps/", "/agents/") == agent.endpoint + assert app.method == agent.method + + app_params = {("agent_id" if k == "app_id" else k): v for k, v in (app.params or {}).items()} + assert app_params == (agent.params or {}) diff --git a/api/tests/unit_tests/services/enterprise/test_rbac_service.py b/api/tests/unit_tests/services/enterprise/test_rbac_service.py index 078dbd2c38b..1d76cc79ff2 100644 --- a/api/tests/unit_tests/services/enterprise/test_rbac_service.py +++ b/api/tests/unit_tests/services/enterprise/test_rbac_service.py @@ -748,37 +748,42 @@ class TestMyPermissions: assert out.workspace.permission_keys == ["workspace.member.manage"] @pytest.mark.parametrize( - ("role", "workspace_keys", "app_keys", "dataset_keys"), + ("role", "workspace_keys", "app_keys", "dataset_keys", "agent_keys"), [ ( "owner", svc._LEGACY_WORKSPACE_OWNER_KEYS, svc._LEGACY_APP_OWNER_KEYS, svc._LEGACY_DATASET_OWNER_KEYS, + svc._LEGACY_AGENT_FULL_ACCESS_KEYS, ), ( "admin", svc._LEGACY_WORKSPACE_ADMIN_KEYS, svc._LEGACY_APP_ADMIN_KEYS, svc._LEGACY_DATASET_ADMIN_KEYS, + svc._LEGACY_AGENT_FULL_ACCESS_KEYS, ), ( "editor", svc._LEGACY_WORKSPACE_EDITOR_KEYS, svc._LEGACY_APP_EDITOR_KEYS, svc._LEGACY_DATASET_EDITOR_KEYS, + svc._LEGACY_AGENT_FULL_ACCESS_KEYS, ), ( "normal", svc._LEGACY_WORKSPACE_NORMAL_KEYS, svc._LEGACY_APP_NORMAL_KEYS, [], + svc._LEGACY_AGENT_PREVIEW_KEYS, ), ( "dataset_operator", svc._LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS, svc._LEGACY_APP_DATASET_OPERATOR_KEYS, svc._LEGACY_DATASET_DATASET_OPERATOR_KEYS, + svc._LEGACY_AGENT_PREVIEW_KEYS, ), ], ) @@ -789,6 +794,7 @@ class TestMyPermissions: workspace_keys: list[str], app_keys: list[str], dataset_keys: list[str], + agent_keys: list[str], sqlite_session: Session, config_overrides, ): @@ -804,8 +810,10 @@ class TestMyPermissions: assert len(out.workspace.permission_keys) == len(set(out.workspace.permission_keys)) assert out.app.default_permission_keys == app_keys assert out.dataset.default_permission_keys == dataset_keys + assert out.agent.default_permission_keys == agent_keys assert out.app.overrides == [] assert out.dataset.overrides == [] + assert out.agent.overrides == [] if role == "owner": assert "snippets.management" in out.workspace.permission_keys assert "app.acl.preview" in out.workspace.permission_keys @@ -859,6 +867,7 @@ class TestMyPermissions: assert out.workspace.permission_keys == [] assert out.app.default_permission_keys == [] assert out.dataset.default_permission_keys == [] + assert out.agent.default_permission_keys == [] def test_get_with_single_resource_filters(self, mock_send: MagicMock, sqlite_session: Session): mock_send.return_value = { @@ -878,6 +887,27 @@ class TestMyPermissions: assert call.params == {"app_id": "app-1"} assert out.app.overrides[0].resource_id == "app-1" + def test_get_forwards_agent_id_and_parses_agent_snapshot(self, mock_send: MagicMock, sqlite_session: Session): + mock_send.return_value = { + "workspace": {"permission_keys": []}, + "app": {"default_permission_keys": [], "overrides": []}, + "dataset": {"default_permission_keys": [], "overrides": []}, + "agent": { + "default_permission_keys": ["agent.acl.preview"], + "overrides": [{"resource_id": "agent-1", "permission_keys": ["agent.acl.edit"]}], + }, + } + + out = svc.RBACService.MyPermissions.get("tenant-1", "acct-1", agent_id="agent-1", session=sqlite_session) + + call = _call_args(mock_send) + assert call.method == "GET" + assert call.endpoint == "/rbac/my-permissions" + assert call.params == {"agent_id": "agent-1"} + assert out.agent.default_permission_keys == ["agent.acl.preview"] + assert out.agent.overrides[0].resource_id == "agent-1" + assert out.agent.overrides[0].permission_keys == ["agent.acl.edit"] + @pytest.mark.parametrize("sqlite_session", [(TenantAccountJoin,)], indirect=True) class TestMemberRoles: @@ -924,6 +954,7 @@ class TestMemberRoles: *svc._LEGACY_WORKSPACE_EDITOR_KEYS, *svc._LEGACY_APP_EDITOR_KEYS, *svc._LEGACY_DATASET_EDITOR_KEYS, + *svc._LEGACY_AGENT_FULL_ACCESS_KEYS, ] ) ) @@ -1126,9 +1157,8 @@ class TestListOption: } -class TestLegacyAgentManageKey: - def test_legacy_agent_manage_key_membership(self): - # Preserve Agent access for every legacy role while external RBAC is disabled. +class TestLegacyAgentKeys: + def test_legacy_workspace_keys_no_longer_carry_agent_manage(self): for keys in ( svc._LEGACY_WORKSPACE_OWNER_KEYS, svc._LEGACY_WORKSPACE_ADMIN_KEYS, @@ -1136,4 +1166,5 @@ class TestLegacyAgentManageKey: svc._LEGACY_WORKSPACE_NORMAL_KEYS, svc._LEGACY_WORKSPACE_DATASET_OPERATOR_KEYS, ): - assert "agent.manage" in keys + assert "agent.manage" not in keys + assert {"agent.acl.preview", "agent.acl.access_point_view"} <= set(keys) diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py index f7f8e377f41..75a45c8436c 100644 --- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py +++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py @@ -643,6 +643,15 @@ def test_confirm_import_rejects_non_serialized_pending_data( def test_import_pending_version_stores_redis(monkeypatch: pytest.MonkeyPatch, service: RagPipelineDslService) -> None: setex = Mock() monkeypatch.setattr(module.redis_client, "setex", setex) + missing_tenant = service.import_rag_pipeline( + account=Mock(id="account-1", current_tenant_id=None), + import_mode=ImportMode.YAML_CONTENT.value, + yaml_content=_valid_dsl(version="1.0.0"), + ) + assert missing_tenant.status == ImportStatus.FAILED + assert missing_tenant.error == "Current tenant is not set" + setex.assert_not_called() + result = service.import_rag_pipeline( account=_account(), import_mode=ImportMode.YAML_CONTENT.value, yaml_content=_valid_dsl(version="1.0.0") ) @@ -813,14 +822,27 @@ def test_confirm_import_updates_tenant_pipeline_and_dataset( pipeline_id=pipeline.id, ) redis_key = "app_import_info:import-1" + pending_json = pending.model_dump_json(exclude={"tenant_id", "account_id"}) monkeypatch.setattr( module.redis_client, "get", - Mock(side_effect=lambda key: pending.model_dump_json() if key == redis_key else None), + Mock(side_effect=lambda key: pending_json if key == redis_key else None), ) delete = Mock() monkeypatch.setattr(module.redis_client, "delete", delete) + load = Mock(wraps=module.yaml.safe_load) + monkeypatch.setattr(module.yaml, "safe_load", load) + create_or_update = Mock(wraps=service._create_or_update_pipeline) + monkeypatch.setattr(service, "_create_or_update_pipeline", create_or_update) monkeypatch.setattr(module.KnowledgeConfiguration, "model_validate", Mock(return_value=_knowledge_configuration())) + + assert service.confirm_import(import_id="import-1", account=_account()).status == ImportStatus.FAILED + load.assert_not_called() + create_or_update.assert_not_called() + delete.assert_not_called() + assert pipeline.name == "Pipeline" + pending_json = pending.model_dump_json() + for foreign_account in (_account(tenant_id="tenant-2"), _account(account_id="account-2")): assert service.confirm_import(import_id="import-1", account=foreign_account).status == ImportStatus.FAILED delete.assert_not_called() diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_task_proxy.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_task_proxy.py index ac6d4d5fd01..b9e5963c3f9 100644 --- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_task_proxy.py +++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_task_proxy.py @@ -5,11 +5,12 @@ from unittest.mock import Mock import pytest from pytest_mock import MockerFixture -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from extensions.storage.storage_type import StorageType from models.enums import CreatorUserRole from models.model import UploadFile from services.rag_pipeline.rag_pipeline_task_proxy import RagPipelineTaskProxy +from tests.unit_tests.config_override import config_overrides_context @pytest.fixture @@ -53,13 +54,12 @@ def test_delay_with_entities_calls_dispatch(mocker: MockerFixture, proxy) -> Non # --- _dispatch --- +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_dispatch_billing_sandbox_uses_default_tenant_queue(mocker: MockerFixture, proxy) -> None: upload_mock = mocker.patch.object(proxy, "_upload_invoke_entities", return_value="file-1") send_mock = mocker.patch.object(proxy, "_send_to_default_tenant_queue") - features = SimpleNamespace( - billing=SimpleNamespace(enabled=True, subscription=SimpleNamespace(plan=CloudPlan.SANDBOX)) - ) + features = SimpleNamespace(billing=SimpleNamespace(subscription=SimpleNamespace(plan=CloudPlan.SANDBOX))) mocker.patch.object(type(proxy), "features", new_callable=lambda: property(lambda self: features)) proxy._dispatch() @@ -68,13 +68,12 @@ def test_dispatch_billing_sandbox_uses_default_tenant_queue(mocker: MockerFixtur send_mock.assert_called_once_with("file-1") +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_dispatch_billing_non_sandbox_uses_priority_tenant_queue(mocker: MockerFixture, proxy) -> None: upload_mock = mocker.patch.object(proxy, "_upload_invoke_entities", return_value="file-1") send_mock = mocker.patch.object(proxy, "_send_to_priority_tenant_queue") - features = SimpleNamespace( - billing=SimpleNamespace(enabled=True, subscription=SimpleNamespace(plan=CloudPlan.PROFESSIONAL)) - ) + features = SimpleNamespace(billing=SimpleNamespace(subscription=SimpleNamespace(plan=CloudPlan.PROFESSIONAL))) mocker.patch.object(type(proxy), "features", new_callable=lambda: property(lambda self: features)) proxy._dispatch() @@ -83,11 +82,12 @@ def test_dispatch_billing_non_sandbox_uses_priority_tenant_queue(mocker: MockerF send_mock.assert_called_once_with("file-1") +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_dispatch_no_billing_uses_priority_direct_queue(mocker: MockerFixture, proxy) -> None: upload_mock = mocker.patch.object(proxy, "_upload_invoke_entities", return_value="file-1") send_mock = mocker.patch.object(proxy, "_send_to_priority_direct_queue") - features = SimpleNamespace(billing=SimpleNamespace(enabled=False, subscription=SimpleNamespace(plan="free"))) + features = SimpleNamespace(billing=SimpleNamespace(subscription=SimpleNamespace(plan="free"))) mocker.patch.object(type(proxy), "features", new_callable=lambda: property(lambda self: features)) proxy._dispatch() @@ -96,10 +96,11 @@ def test_dispatch_no_billing_uses_priority_direct_queue(mocker: MockerFixture, p send_mock.assert_called_once_with("file-1") +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_dispatch_raises_on_empty_upload_file_id(mocker: MockerFixture, proxy) -> None: mocker.patch.object(proxy, "_upload_invoke_entities", return_value="") - features = SimpleNamespace(billing=SimpleNamespace(enabled=False, subscription=SimpleNamespace(plan="free"))) + features = SimpleNamespace(billing=SimpleNamespace(subscription=SimpleNamespace(plan="free"))) mocker.patch.object(type(proxy), "features", new_callable=lambda: property(lambda self: features)) with pytest.raises(ValueError, match="upload_file_id is empty"): diff --git a/api/tests/unit_tests/services/test_annotation_service.py b/api/tests/unit_tests/services/test_annotation_service.py index 097f12e9482..ac2a69b0f40 100644 --- a/api/tests/unit_tests/services/test_annotation_service.py +++ b/api/tests/unit_tests/services/test_annotation_service.py @@ -22,6 +22,7 @@ from werkzeug.datastructures import FileStorage from werkzeug.exceptions import NotFound import services.annotation_service as annotation_service_module +from enums import DeploymentEdition from models.account import Account from models.dataset import DatasetCollectionBinding from models.enums import CollectionBindingType @@ -37,6 +38,7 @@ from models.model import ( ) from services.annotation_service import AppAnnotationService from services.app_ref_service import AnnotationRef, AppRef +from tests.unit_tests.config_override import config_overrides_context TENANT_ID = "tenant-1" OTHER_TENANT_ID = "tenant-2" @@ -593,16 +595,13 @@ class TestAppAnnotationServiceBatchImport: features: Any | None = None, ) -> dict[str, Any]: if features is None: - features = SimpleNamespace(billing=SimpleNamespace(enabled=False), annotation_quota_limit=None) + features = SimpleNamespace(annotation_quota_limit=None) with ( patch.object(annotation_service_module.pd, "read_csv", return_value=dataframe), patch.object(annotation_service_module.FeatureService, "get_features", return_value=features), - patch( - "configs.dify_config", - new=SimpleNamespace( - ANNOTATION_IMPORT_MAX_RECORDS=maximum, - ANNOTATION_IMPORT_MIN_RECORDS=minimum, - ), + config_overrides_context( + ANNOTATION_IMPORT_MAX_RECORDS=maximum, + ANNOTATION_IMPORT_MIN_RECORDS=minimum, ), ): return AppAnnotationService.batch_import_app_annotations(app.id, _file(content), sqlite_session) @@ -678,10 +677,10 @@ class TestAppAnnotationServiceBatchImport: assert "at least" in cast(str, result["error_msg"]) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_rejects_subscription_quota_overflow(self, sqlite_session: Session, current_user: Account) -> None: app = _persist_app(sqlite_session) features = SimpleNamespace( - billing=SimpleNamespace(enabled=True), annotation_quota_limit=SimpleNamespace(limit=1, size=1), ) @@ -694,10 +693,11 @@ class TestAppAnnotationServiceBatchImport: assert "exceeds the limit" in cast(str, result["error_msg"]) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_valid_import_enqueues_job(self, sqlite_session: Session, current_user: Account) -> None: app = _persist_app(sqlite_session) dataframe = pd.DataFrame({"q": ["q1"], "a": ["a1"]}) - features = SimpleNamespace(billing=SimpleNamespace(enabled=False), annotation_quota_limit=None) + features = SimpleNamespace(annotation_quota_limit=None) with ( patch.object(annotation_service_module.pd, "read_csv", return_value=dataframe), patch.object(annotation_service_module.FeatureService, "get_features", return_value=features), @@ -705,10 +705,7 @@ class TestAppAnnotationServiceBatchImport: patch.object(annotation_service_module, "redis_client") as redis, patch.object(annotation_service_module.uuid, "uuid4", return_value="uuid-3"), patch.object(annotation_service_module, "naive_utc_now", return_value=datetime.fromtimestamp(1)), - patch( - "configs.dify_config", - new=SimpleNamespace(ANNOTATION_IMPORT_MAX_RECORDS=5, ANNOTATION_IMPORT_MIN_RECORDS=1), - ), + config_overrides_context(ANNOTATION_IMPORT_MAX_RECORDS=5, ANNOTATION_IMPORT_MIN_RECORDS=1), ): result = AppAnnotationService.batch_import_app_annotations( app.id, _file(b"question,answer\nq,a\n"), sqlite_session @@ -722,22 +719,43 @@ class TestAppAnnotationServiceBatchImport: "uuid-3", [{"question": "q1", "answer": "a1"}], app.id, TENANT_ID, current_user.id ) + @pytest.mark.parametrize("limit", [0, 2], ids=["unlimited", "exactly-at-limit"]) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) + def test_import_with_available_quota_enqueues_job( + self, sqlite_session: Session, current_user: Account, limit: int + ) -> None: + app = _persist_app(sqlite_session) + features = SimpleNamespace(annotation_quota_limit=SimpleNamespace(limit=limit, size=1)) + with ( + patch.object(annotation_service_module.FeatureService, "get_features", return_value=features), + patch.object(annotation_service_module, "batch_import_annotations_task") as task, + patch.object(annotation_service_module, "redis_client"), + config_overrides_context(ANNOTATION_IMPORT_MAX_RECORDS=5, ANNOTATION_IMPORT_MIN_RECORDS=1), + ): + result = AppAnnotationService.batch_import_app_annotations( + app.id, _file(b"question,answer\nq,a\n"), sqlite_session + ) + + assert result["job_status"] == "waiting" + assert result["record_count"] == 1 + task.delay.assert_called_once_with( + result["job_id"], [{"question": "q", "answer": "a"}], app.id, TENANT_ID, current_user.id + ) + + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_unexpected_error_cleans_active_job( self, sqlite_session: Session, current_user: Account, caplog: pytest.LogCaptureFixture ) -> None: app = _persist_app(sqlite_session) dataframe = pd.DataFrame({"q": ["q1"], "a": ["a1"]}) - features = SimpleNamespace(billing=SimpleNamespace(enabled=False), annotation_quota_limit=None) + features = SimpleNamespace(annotation_quota_limit=None) with ( patch.object(annotation_service_module.pd, "read_csv", return_value=dataframe), patch.object(annotation_service_module.FeatureService, "get_features", return_value=features), patch.object(annotation_service_module, "redis_client") as redis, patch.object(annotation_service_module.uuid, "uuid4", return_value="uuid-4"), patch.object(annotation_service_module, "naive_utc_now", return_value=datetime.fromtimestamp(1)), - patch( - "configs.dify_config", - new=SimpleNamespace(ANNOTATION_IMPORT_MAX_RECORDS=5, ANNOTATION_IMPORT_MIN_RECORDS=1), - ), + config_overrides_context(ANNOTATION_IMPORT_MAX_RECORDS=5, ANNOTATION_IMPORT_MIN_RECORDS=1), ): redis.zadd.side_effect = RuntimeError("boom") redis.zrem.side_effect = RuntimeError("cleanup-failed") diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.py index 178041d2e48..da7efbe5acf 100644 --- a/api/tests/unit_tests/services/test_app_dsl_service.py +++ b/api/tests/unit_tests/services/test_app_dsl_service.py @@ -348,11 +348,17 @@ def test_pending_import_is_scoped_to_its_owner(monkeypatch: pytest.MonkeyPatch, monkeypatch.setattr("services.app_dsl_service.redis_client.get", pending_imports.get) monkeypatch.setattr("services.app_dsl_service.redis_client.delete", pending_imports.pop) - monkeypatch.setattr( - service, - "_create_or_update_app", - Mock(return_value=_app(app_id="app-1", mode=AppMode.WORKFLOW)), - ) + create_or_update = Mock(return_value=_app(app_id="app-1", mode=AppMode.WORKFLOW)) + monkeypatch.setattr(service, "_create_or_update_app", create_or_update) + load = Mock(wraps=yaml.safe_load) + monkeypatch.setattr("services.app_dsl_service.yaml.safe_load", load) + + pending_imports[redis_key] = pending_data.model_dump_json(exclude={"tenant_id", "account_id"}) + assert service.confirm_import(import_id=pending.id, account=creator).status == ImportStatus.FAILED + load.assert_not_called() + create_or_update.assert_not_called() + assert redis_key in pending_imports + pending_imports[redis_key] = pending_data.model_dump_json() for other_account in ( _account(tenant_id="tenant-2"), @@ -364,36 +370,60 @@ def test_pending_import_is_scoped_to_its_owner(monkeypatch: pytest.MonkeyPatch, assert redis_key not in pending_imports +def test_pending_import_requires_current_tenant(monkeypatch: pytest.MonkeyPatch, unbound_session: Session) -> None: + setex = Mock() + monkeypatch.setattr("services.app_dsl_service.redis_client.setex", setex) + account = _account() + account._current_tenant = None + + result = AppDslService(session=unbound_session).import_app( + account=account, + import_mode="yaml-content", + yaml_content="version: 99.0.0\nkind: app\napp: {name: Test, mode: workflow}\n", + ) + + assert result.status == ImportStatus.FAILED + assert result.error == "Current tenant is not set" + setex.assert_not_called() + + @pytest.mark.parametrize( - ("tenant_id", "account_id", "expected"), + ("caller_tenant_id", "caller_account_id", "expected"), [ ("tenant-1", "account-1", True), (None, "account-1", False), - ("tenant-1", None, False), ("tenant-2", "account-1", False), ("tenant-1", "account-2", False), ], ) def test_pending_import_owner_access( - tenant_id: str | None, - account_id: str | None, + caller_tenant_id: str | None, + caller_account_id: str, expected: bool, ) -> None: pending = PendingData( - tenant_id=tenant_id, - account_id=account_id, + tenant_id="tenant-1", + account_id="account-1", import_mode="yaml-content", yaml_content="", ) - assert pending.is_accessible_by(tenant_id="tenant-1", account_id="account-1") is expected + assert pending.is_accessible_by(tenant_id=caller_tenant_id, account_id=caller_account_id) is expected -def test_pending_import_owner_access_accepts_legacy_json() -> None: - pending = PendingData.model_validate_json('{"import_mode":"yaml-content","yaml_content":""}') +@pytest.mark.parametrize( + "payload", + [ + '{"import_mode":"yaml-content","yaml_content":"secret-token-123"}', + '{"tenant_id":"tenant-1","import_mode":"yaml-content","yaml_content":"secret-token-123"}', + '{"account_id":"account-1","import_mode":"yaml-content","yaml_content":"secret-token-123"}', + ], +) +def test_pending_import_owner_is_required(payload: str) -> None: + with pytest.raises(ValueError) as exc_info: + PendingData.model_validate_json(payload) - assert pending.is_accessible_by(tenant_id="tenant-1", account_id="account-1") - assert not pending.is_accessible_by(tenant_id=None, account_id="account-1") + assert "secret-token-123" not in str(exc_info.value) def test_create_or_update_app_loads_existing_model_config_with_service_session( @@ -542,38 +572,25 @@ def test_export_dsl_loads_model_config_and_annotation_reply_with_request_session load_annotation_reply_config.assert_called_once_with(service_session, app_id) -def test_ensure_agent_manage_permission_noops_when_rbac_disabled( - monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None] -) -> None: - config_overrides(RBAC_ENABLED=False) - check = Mock() - monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", check) - - AppDslService._ensure_agent_manage_permission(_account()) - - check.assert_not_called() - - -def test_ensure_agent_manage_permission_allows_agent_manager( - monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None] +def test_agent_import_of_new_agent_checks_function_scope( + monkeypatch: pytest.MonkeyPatch, + unbound_session: Session, + config_overrides: Callable[..., None], ) -> None: config_overrides(RBAC_ENABLED=True) check = Mock(return_value=True) monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", check) + account = _account() - AppDslService._ensure_agent_manage_permission(_account()) + AppDslService(session=unbound_session)._ensure_agent_import_permission(account, app=None) - check.assert_called_once_with("tenant-1", "account-1", scene=RBACPermission.AGENT_MANAGE) - - -def test_ensure_agent_manage_permission_rejects_without_agent_manage( - monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None] -) -> None: - config_overrides(RBAC_ENABLED=True) - monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", Mock(return_value=False)) - - with pytest.raises(NoPermissionError): - AppDslService._ensure_agent_manage_permission(_account()) + check.assert_called_once_with( + account.current_tenant_id, + account.id, + scene=RBACPermission.AGENT_IMPORT_EXPORT_DSL, + resource_type=None, + resource_id=None, + ) def test_create_or_update_app_gates_agent_mode_before_creation( diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.py index a2dadd3a04c..796439acc72 100644 --- a/api/tests/unit_tests/services/test_app_service.py +++ b/api/tests/unit_tests/services/test_app_service.py @@ -27,6 +27,7 @@ from models.model import App, AppMode, AppModelConfig, IconType from models.workflow import Workflow, WorkflowType from services.agent.errors import AgentAccessNotReadyError, AgentNameConflictError from services.app_service import AppListParams, AppService, CreateAppParams +from services.enterprise import rbac_service as enterprise_rbac_service def _persist_account(session: Session) -> Account: @@ -222,6 +223,63 @@ class TestCreateAppTransactionBoundary: ) +class TestCreateAppRBACAccessInitialization: + """`create_app` bootstraps RBAC access per app mode: agents get the agent flavour.""" + + @staticmethod + def _create(session: Session, account: Account, mode: AppMode) -> App: + with ( + patch("services.app_service.app_was_created.send"), + patch( + "services.app_service.SystemFeatureService.is_webapp_auth_enabled", + return_value=False, + ), + ): + return AppService().create_app( + account.current_tenant_id, + CreateAppParams(name=f"RBAC {mode.value}", mode=mode.value), + account, + session=session, + ) + + def test_agent_app_initializes_agent_access_and_skips_the_app_creator_sync( + self, sqlite_session: Session, config_overrides: Callable[..., None] + ) -> None: + config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, RBAC_ENABLED=True) + account = _persist_account(sqlite_session) + + with ( + patch( + "services.rbac_agent_access_service.enterprise_rbac_service.RBACService.AgentAccess.replace_whitelist" + ) as replace_whitelist, + patch("services.rbac_agent_access_service.initialize_created_app_rbac_access_task.delay") as seed_task, + patch( + "services.rbac_agent_access_service.enterprise_rbac_service.RBACService.AccessPolicies" + ".sync_creator_access_policy_member_bindings" + ) as creator_sync, + patch( + "services.app_service.enterprise_rbac_service.try_sync_creator_access_policy_member_bindings" + ) as app_creator_sync, + ): + app = self._create(sqlite_session, account, AppMode.AGENT) + + agent = sqlite_session.scalars(select(Agent).where(Agent.app_id == app.id)).one() + replace_whitelist.assert_called_once_with( + account.current_tenant_id, + account.id, + agent.id, + enterprise_rbac_service.ReplaceMemberBindings(automatic_include_workspace_members=True), + ) + seed_task.assert_called_once_with(account.current_tenant_id, account.id, agent_id=agent.id) + creator_sync.assert_called_once_with( + account.current_tenant_id, + account.id, + resource_type=enterprise_rbac_service.RBACResourceType.AGENT, + resource_id=agent.id, + ) + app_creator_sync.assert_not_called() + + @pytest.mark.parametrize( "update_status", [AppService.update_app_site_status, AppService.update_app_api_status], diff --git a/api/tests/unit_tests/services/test_batch_indexing_base.py b/api/tests/unit_tests/services/test_batch_indexing_base.py index 17420379427..929cd6251db 100644 --- a/api/tests/unit_tests/services/test_batch_indexing_base.py +++ b/api/tests/unit_tests/services/test_batch_indexing_base.py @@ -5,8 +5,9 @@ from unittest.mock import MagicMock, patch import pytest from core.entities.document_task import DocumentTask -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from services.document_indexing_proxy.batch_indexing_base import BatchDocumentIndexingProxy +from tests.unit_tests.config_override import config_overrides_context # --------------------------------------------------------------------------- # Concrete subclass for testing (the base class is abstract) @@ -275,13 +276,13 @@ class TestSendToTenantQueue: class TestDispatchRouting: """Tests for the _dispatch / delay routing logic inherited from the base class.""" - def _mock_features(self, enabled: bool, plan: CloudPlan) -> MagicMock: + def _mock_features(self, plan: CloudPlan) -> MagicMock: features = MagicMock() - features.billing.enabled = enabled features.billing.subscription.plan = plan return features - def test_should_send_to_normal_tenant_queue_when_billing_enabled_and_sandbox_plan(self) -> None: + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) + def test_should_send_to_normal_tenant_queue_in_cloud_with_sandbox_plan(self) -> None: """Sandbox plan routes to normal priority queue with tenant isolation.""" # Arrange proxy = make_proxy() @@ -289,7 +290,7 @@ class TestDispatchRouting: proxy._tenant_isolated_task_queue.get_task_key.return_value = None with patch("services.document_indexing_proxy.base.FeatureService.get_features") as mock_features: - mock_features.return_value = self._mock_features(enabled=True, plan=CloudPlan.SANDBOX) + mock_features.return_value = self._mock_features(plan=CloudPlan.SANDBOX) # Act with patch.object(proxy, "_send_to_default_tenant_queue") as mock_method: @@ -298,13 +299,14 @@ class TestDispatchRouting: # Assert mock_method.assert_called_once() - def test_should_send_to_priority_tenant_queue_when_billing_enabled_and_paid_plan(self) -> None: + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) + def test_should_send_to_priority_tenant_queue_in_cloud_with_paid_plan(self) -> None: """Non-sandbox paid plan routes to priority queue with tenant isolation.""" # Arrange proxy = make_proxy() with patch("services.document_indexing_proxy.base.FeatureService.get_features") as mock_features: - mock_features.return_value = self._mock_features(enabled=True, plan=CloudPlan.PROFESSIONAL) + mock_features.return_value = self._mock_features(plan=CloudPlan.PROFESSIONAL) # Act with patch.object(proxy, "_send_to_priority_tenant_queue") as mock_method: @@ -313,13 +315,14 @@ class TestDispatchRouting: # Assert mock_method.assert_called_once() - def test_should_send_to_priority_direct_queue_when_billing_not_enabled(self) -> None: + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) + def test_should_send_to_priority_direct_queue_outside_cloud(self) -> None: """Self-hosted / no billing → priority direct queue (no tenant isolation).""" # Arrange proxy = make_proxy() with patch("services.document_indexing_proxy.base.FeatureService.get_features") as mock_features: - mock_features.return_value = self._mock_features(enabled=False, plan=CloudPlan.SANDBOX) + mock_features.return_value = self._mock_features(plan=CloudPlan.SANDBOX) # Act with patch.object(proxy, "_send_to_priority_direct_queue") as mock_method: @@ -340,19 +343,20 @@ class TestDispatchRouting: # Assert mock_dispatch.assert_called_once() - def test_should_use_feature_service_for_billing_info(self) -> None: - """Verify that FeatureService.get_features is consulted during dispatch.""" + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) + def test_should_skip_feature_service_outside_cloud(self) -> None: + """Self-hosted dispatch does not load Cloud plan data.""" # Arrange proxy = make_proxy() with patch("services.document_indexing_proxy.base.FeatureService.get_features") as mock_features: - mock_features.return_value = self._mock_features(enabled=False, plan=CloudPlan.SANDBOX) + mock_features.return_value = self._mock_features(plan=CloudPlan.SANDBOX) with patch.object(proxy, "_send_to_priority_direct_queue"): # Act proxy._dispatch() # Assert - mock_features.assert_called_once_with(TENANT_ID, exclude_vector_space=True) + mock_features.assert_not_called() class TestBaseRouterHelpers: diff --git a/api/tests/unit_tests/services/test_billing_service.py b/api/tests/unit_tests/services/test_billing_service.py index cf587aed3fc..0e10220635b 100644 --- a/api/tests/unit_tests/services/test_billing_service.py +++ b/api/tests/unit_tests/services/test_billing_service.py @@ -430,21 +430,22 @@ class TestBillingServiceSubscriptionInfo: # Arrange tenant_id = "tenant-123" expected_response = { - "enabled": True, "subscription": {"plan": "professional", "interval": "month", "education": False}, "members": {"size": 1, "limit": 50}, "apps": {"size": 1, "limit": 200}, "vector_space": {"size": 0.0, "limit": 20480}, - "knowledge_rate_limit": {"limit": 1000}, "documents_upload_quota": {"size": 0, "limit": 1000}, "annotation_quota_limit": {"size": 0, "limit": 5000}, - "docs_processing": "top-priority", "can_replace_logo": True, "model_load_balancing_enabled": True, "knowledge_pipeline_publish_enabled": True, "next_credit_reset_date": 1775952000, } - mock_send_request.return_value = expected_response + mock_send_request.return_value = { + **expected_response, + "docs_processing": "top-priority", + "knowledge_rate_limit": {"limit": 1000}, + } # Act result = BillingService.get_info(tenant_id) @@ -458,14 +459,11 @@ class TestBillingServiceSubscriptionInfo: # Arrange tenant_id = "tenant-123" expected_response = { - "enabled": True, "subscription": {"plan": "professional", "interval": "month", "education": False}, "members": {"size": 1, "limit": 50}, "apps": {"size": 1, "limit": 200}, - "knowledge_rate_limit": {"limit": 1000}, "documents_upload_quota": {"size": 0, "limit": 1000}, "annotation_quota_limit": {"size": 0, "limit": 5000}, - "docs_processing": "top-priority", "can_replace_logo": True, "model_load_balancing_enabled": True, "knowledge_pipeline_publish_enabled": True, @@ -488,15 +486,12 @@ class TestBillingServiceSubscriptionInfo: # Arrange tenant_id = "tenant-123" expected_response = { - "enabled": True, "subscription": {"plan": "professional", "interval": "month", "education": False}, "members": {"size": 1, "limit": 50}, "apps": {"size": 1, "limit": 200}, "vector_space": None, - "knowledge_rate_limit": {"limit": 1000}, "documents_upload_quota": {"size": 0, "limit": 1000}, "annotation_quota_limit": {"size": 0, "limit": 5000}, - "docs_processing": "top-priority", "can_replace_logo": True, "model_load_balancing_enabled": True, "knowledge_pipeline_publish_enabled": True, @@ -544,15 +539,12 @@ class TestBillingServiceSubscriptionInfo: def test_get_info_preserves_unknown_vector_space_usage(self, mock_send_request): tenant_id = "tenant-123" expected_response = { - "enabled": True, "subscription": {"plan": "sandbox", "interval": "", "education": False}, "members": {"size": 1, "limit": 1}, "apps": {"size": 1, "limit": 10}, "vector_space": {"size": 0.0, "limit": 50, "usage_unknown": True}, - "knowledge_rate_limit": {"limit": 10}, "documents_upload_quota": {"size": 1, "limit": 50}, "annotation_quota_limit": {"size": 0, "limit": 10}, - "docs_processing": "standard", "can_replace_logo": False, "model_load_balancing_enabled": False, "knowledge_pipeline_publish_enabled": False, @@ -1750,15 +1742,12 @@ class TestBillingServiceIntegrationScenarios: # Step 1: Get current billing info mock_send_request.return_value = { - "enabled": True, "subscription": {"plan": "sandbox", "interval": "", "education": False}, "members": {"size": 0, "limit": 1}, "apps": {"size": 0, "limit": 5}, "vector_space": {"size": 0.0, "limit": 50}, - "knowledge_rate_limit": {"limit": 10}, "documents_upload_quota": {"size": 0, "limit": 50}, "annotation_quota_limit": {"size": 0, "limit": 10}, - "docs_processing": "standard", "can_replace_logo": False, "model_load_balancing_enabled": False, "knowledge_pipeline_publish_enabled": False, @@ -1822,7 +1811,6 @@ class TestBillingServiceSubscriptionInfoDataType: @pytest.fixture def normal_billing_response(self) -> dict: return { - "enabled": True, "subscription": { "plan": "team", "interval": "year", @@ -1831,10 +1819,8 @@ class TestBillingServiceSubscriptionInfoDataType: "members": {"size": 10, "limit": 50}, "apps": {"size": 80, "limit": 200}, "vector_space": {"size": 5120.75, "limit": 20480}, - "knowledge_rate_limit": {"limit": 1000}, "documents_upload_quota": {"size": 450, "limit": 1000}, "annotation_quota_limit": {"size": 1200, "limit": 5000}, - "docs_processing": "top-priority", "can_replace_logo": True, "model_load_balancing_enabled": True, "knowledge_pipeline_publish_enabled": True, @@ -1844,7 +1830,6 @@ class TestBillingServiceSubscriptionInfoDataType: @pytest.fixture def string_billing_response(self) -> dict: return { - "enabled": True, "subscription": { "plan": "team", "interval": "year", @@ -1853,10 +1838,8 @@ class TestBillingServiceSubscriptionInfoDataType: "members": {"size": "10", "limit": "50"}, "apps": {"size": "80", "limit": "200"}, "vector_space": {"size": 5120.75, "limit": "20480"}, - "knowledge_rate_limit": {"limit": "1000"}, "documents_upload_quota": {"size": "450", "limit": "1000"}, "annotation_quota_limit": {"size": "1200", "limit": "5000"}, - "docs_processing": "top-priority", "can_replace_logo": True, "model_load_balancing_enabled": True, "knowledge_pipeline_publish_enabled": True, @@ -1865,7 +1848,6 @@ class TestBillingServiceSubscriptionInfoDataType: @staticmethod def _assert_billing_info_types(result: dict): - assert isinstance(result["enabled"], bool) assert isinstance(result["subscription"]["plan"], str) assert isinstance(result["subscription"]["interval"], str) assert isinstance(result["subscription"]["education"], bool) @@ -1882,15 +1864,12 @@ class TestBillingServiceSubscriptionInfoDataType: if "usage_unknown" in result["vector_space"]: assert isinstance(result["vector_space"]["usage_unknown"], bool) - assert isinstance(result["knowledge_rate_limit"]["limit"], int) - assert isinstance(result["documents_upload_quota"]["size"], int) assert isinstance(result["documents_upload_quota"]["limit"], int) assert isinstance(result["annotation_quota_limit"]["size"], int) assert isinstance(result["annotation_quota_limit"]["limit"], int) - assert isinstance(result["docs_processing"], str) assert isinstance(result["can_replace_logo"], bool) assert isinstance(result["model_load_balancing_enabled"], bool) assert isinstance(result["knowledge_pipeline_publish_enabled"], bool) diff --git a/api/tests/unit_tests/services/test_conversation_service.py b/api/tests/unit_tests/services/test_conversation_service.py index 0f2d94a877f..43868748761 100644 --- a/api/tests/unit_tests/services/test_conversation_service.py +++ b/api/tests/unit_tests/services/test_conversation_service.py @@ -178,10 +178,10 @@ def test_delete_retires_then_commits_before_enqueue(monkeypatch: pytest.MonkeyPa sqlite_session.flush() events: list[str] = [] get_binding = MagicMock(return_value=_workspace_binding("conversation-binding-1")) - retire_binding = MagicMock(side_effect=lambda **_kwargs: events.append("retire") or "conversation-binding-1") + retire_conversation = MagicMock(side_effect=lambda **_kwargs: events.append("retire") or ["workspace-1"]) monkeypatch.setattr(ConversationService, "get_conversation", MagicMock(return_value=conversation)) monkeypatch.setattr(AgentWorkspaceService, "get_active_binding", get_binding) - monkeypatch.setattr(AgentWorkspaceService, "retire_binding", retire_binding) + monkeypatch.setattr(AgentWorkspaceService, "retire_all_for_conversation", retire_conversation) event.listen(sqlite_session, "after_commit", lambda _session: events.append("commit")) monkeypatch.setattr( conversation_service, @@ -196,7 +196,7 @@ def test_delete_retires_then_commits_before_enqueue(monkeypatch: pytest.MonkeyPa assert events == ["retire", "commit", "enqueue"] assert conversation.is_deleted is True assert get_binding.call_args.kwargs["binding_id"] == "conversation-binding-1" - assert retire_binding.call_args.kwargs["binding_id"] == "conversation-binding-1" + assert retire_conversation.call_args.kwargs["conversation_id"] == conversation.id delete_related.assert_called_once_with(conversation.id) @@ -219,7 +219,7 @@ def test_delete_commit_failure_does_not_enqueue(monkeypatch: pytest.MonkeyPatch, "get_active_binding", MagicMock(return_value=_workspace_binding("binding-1")), ) - monkeypatch.setattr(AgentWorkspaceService, "retire_binding", MagicMock(return_value="binding-1")) + monkeypatch.setattr(AgentWorkspaceService, "retire_all_for_conversation", MagicMock(return_value=["workspace-1"])) enqueue_collection = MagicMock() delete_related = MagicMock() monkeypatch.setattr(conversation_service, "enqueue_agent_resource_collection", enqueue_collection) diff --git a/api/tests/unit_tests/services/test_dataset_service_document.py b/api/tests/unit_tests/services/test_dataset_service_document.py index 18229ac3fb1..c70468e5f65 100644 --- a/api/tests/unit_tests/services/test_dataset_service_document.py +++ b/api/tests/unit_tests/services/test_dataset_service_document.py @@ -6,12 +6,14 @@ from datetime import datetime from sqlalchemy import event, select from sqlalchemy.orm import Session +from enums import DeploymentEdition from models.account import Tenant from models.dataset import Dataset, DatasetCollectionBinding, DocumentSegment from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus from models.model import UploadFile from models.source import DataSourceOauthBinding from services.dataset_ref_service import DatasetRefService +from tests.unit_tests.config_override import config_overrides_context from .dataset_service_test_helpers import ( Account, @@ -555,6 +557,7 @@ class TestDocumentServiceSaveDocumentWithoutDatasetId: with patch("services.dataset_service.current_user", account): yield account + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_without_dataset_id_creates_high_quality_dataset_with_default_retrieval_model( self, account_context, sqlite_session: Session ): @@ -581,7 +584,7 @@ class TestDocumentServiceSaveDocumentWithoutDatasetId: first_document = _document_row(name="VeryLongDocumentNameForDataset.txt") with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch( "services.dataset_service.DatasetCollectionBindingService.get_dataset_collection_binding", return_value=binding, @@ -617,6 +620,7 @@ class TestDocumentServiceSaveDocumentWithoutDatasetId: session=sqlite_session, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_without_dataset_id_uses_provided_retrieval_model( self, account_context, sqlite_session: Session ): @@ -644,7 +648,7 @@ class TestDocumentServiceSaveDocumentWithoutDatasetId: first_document = _document_row(name="Doc") with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch.object( DocumentService, "save_document_with_dataset_id", @@ -662,6 +666,7 @@ class TestDocumentServiceSaveDocumentWithoutDatasetId: assert dataset.collection_binding_id is None assert sqlite_session.get(Dataset, dataset.id) is dataset + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_save_document_without_dataset_id_rejects_sandbox_batch_upload( self, account_context, unbound_session: Session ): @@ -678,7 +683,7 @@ class TestDocumentServiceSaveDocumentWithoutDatasetId: with ( patch( "services.dataset_service.FeatureService.get_features", - return_value=_make_features(enabled=True, plan=CloudPlan.SANDBOX), + return_value=_make_features(plan=CloudPlan.SANDBOX), ), patch.object(DocumentService, "check_documents_upload_quota") as check_quota, ): @@ -1080,13 +1085,14 @@ class TestDocumentServiceSaveDocumentWithDatasetId: ): yield account + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_save_document_with_dataset_id_requires_file_info_for_upload_source( self, account_context, unbound_session: Session ): dataset = _dataset_row() knowledge_config = _make_upload_knowledge_config(file_ids=None) - with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=True)): + with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()): with pytest.raises(ValueError, match="File source info is required"): DocumentService.save_document_with_dataset_id( dataset, @@ -1095,6 +1101,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: session=unbound_session, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_save_document_with_dataset_id_blocks_batch_upload_for_sandbox_plan( self, account_context, unbound_session: Session ): @@ -1104,7 +1111,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: with ( patch( "services.dataset_service.FeatureService.get_features", - return_value=_make_features(enabled=True, plan=CloudPlan.SANDBOX), + return_value=_make_features(plan=CloudPlan.SANDBOX), ), patch.object(DocumentService, "check_documents_upload_quota") as check_quota, ): @@ -1118,6 +1125,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: check_quota.assert_not_called() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_save_document_with_dataset_id_enforces_batch_upload_limit( self, account_context, @@ -1129,7 +1137,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: knowledge_config = _make_upload_knowledge_config(file_ids=["file-1", "file-2"]) with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=True)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch.object(DocumentService, "check_documents_upload_quota") as check_quota, ): with pytest.raises(ValueError, match="batch upload limit of 1"): @@ -1142,6 +1150,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: check_quota.assert_not_called() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_updates_existing_document_and_data_source_type( self, account_context, sqlite_session: Session ): @@ -1151,7 +1160,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: updated_document.batch = "batch-existing" with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch.object( DocumentService, "update_document_with_dataset_id", return_value=updated_document ) as update_document, @@ -1168,13 +1177,14 @@ class TestDocumentServiceSaveDocumentWithDatasetId: assert batch == "batch-existing" update_document.assert_called_once_with(dataset, knowledge_config, account_context, session=sqlite_session) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_requires_data_source_for_new_documents( self, account_context, unbound_session: Session ): dataset = _dataset_row() knowledge_config = _make_upload_knowledge_config(data_source=None) - with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)): + with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()): with pytest.raises(ValueError, match="Data source is required when creating new documents"): DocumentService.save_document_with_dataset_id( dataset, @@ -1183,6 +1193,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: session=unbound_session, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_requires_existing_process_rule_for_custom_mode( self, account_context, sqlite_session: Session ): @@ -1194,7 +1205,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: process_rule=ProcessRule(mode="custom"), ) - with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)): + with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()): with pytest.raises(ValueError, match="No process rule found"): DocumentService.save_document_with_dataset_id( dataset, @@ -1203,6 +1214,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: session=sqlite_session, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_rejects_invalid_indexing_technique( self, account_context, unbound_session: Session ): @@ -1214,7 +1226,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: indexing_technique="broken-technique", ) - with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)): + with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()): with pytest.raises(ValueError, match="Indexing technique is invalid"): DocumentService.save_document_with_dataset_id( dataset, @@ -1223,6 +1235,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: session=unbound_session, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_returns_empty_for_invalid_process_rule_mode( self, account_context, unbound_session: Session ): @@ -1230,7 +1243,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: knowledge_config = _make_upload_knowledge_config(file_ids=["file-1"]) knowledge_config.process_rule = SimpleNamespace(mode="unsupported-mode", rules=None) - with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)): + with patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()): documents, batch = DocumentService.save_document_with_dataset_id( dataset, knowledge_config, @@ -1241,6 +1254,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: assert documents == [] assert batch == "" + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_upload_file_creates_and_reindexes_documents( self, account_context, sqlite_session: Session ): @@ -1254,7 +1268,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: sqlite_session.commit() with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, patch("services.dataset_service.DocumentIndexingTaskProxy") as document_proxy_cls, patch("services.dataset_service.DuplicateDocumentIndexingTaskProxy") as duplicate_proxy_cls, @@ -1285,6 +1299,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: duplicate_proxy_cls.assert_called_once_with(dataset.tenant_id, dataset.id, ["doc-duplicate"]) duplicate_proxy_cls.return_value.delay.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_notion_import_truncates_names_and_cleans_removed_pages( self, account_context, sqlite_session: Session ): @@ -1330,7 +1345,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: sqlite_session.commit() with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, patch("services.dataset_service.clean_notion_document_task") as clean_task, patch("services.dataset_service.DocumentIndexingTaskProxy") as document_proxy_cls, @@ -1353,6 +1368,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: document_proxy_cls.assert_called_once_with(dataset.tenant_id, dataset.id, ["doc-new"]) document_proxy_cls.return_value.delay.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_website_crawl_truncates_long_urls( self, account_context, sqlite_session: Session ): @@ -1379,7 +1395,7 @@ class TestDocumentServiceSaveDocumentWithDatasetId: doc_language="English", ) with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, patch("services.dataset_service.DocumentIndexingTaskProxy") as document_proxy_cls, ): @@ -1711,6 +1727,7 @@ class TestDocumentServiceSaveWithoutDatasetBilling: with patch("services.dataset_service.current_user", account): yield account + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_save_document_without_dataset_id_counts_notion_pages_for_quota( self, account_context, @@ -1741,7 +1758,7 @@ class TestDocumentServiceSaveWithoutDatasetBilling: ) ), ) - features = _make_features(enabled=True) + features = _make_features() document = _document_row(name="Doc") with ( @@ -1763,6 +1780,7 @@ class TestDocumentServiceSaveWithoutDatasetBilling: check_quota.assert_called_once_with(3, features) assert sqlite_session.get(Dataset, dataset.id) is dataset + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_save_document_without_dataset_id_enforces_batch_limit_for_website_urls( self, account_context, @@ -1786,7 +1804,7 @@ class TestDocumentServiceSaveWithoutDatasetBilling: ) with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=True)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch.object(DocumentService, "check_documents_upload_quota") as check_quota, ): with pytest.raises(ValueError, match="batch upload limit of 1"): @@ -1936,6 +1954,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: ): yield account + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_initializes_high_quality_dataset_from_default_embedding_model( self, account_context, sqlite_session: Session ): @@ -1955,7 +1974,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: binding.id = "binding-1" with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.ModelManager") as model_manager_cls, patch( "services.dataset_service.DatasetCollectionBindingService.get_dataset_collection_binding", @@ -1991,6 +2010,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: } get_binding.assert_called_once_with("default-provider", "default-embedding", sqlite_session) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_uses_explicit_embedding_and_retrieval_model( self, account_context, sqlite_session: Session ): @@ -2020,7 +2040,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: updated_document = _document_row(document_id="doc-1") with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.ModelManager") as model_manager_cls, patch( "services.dataset_service.DatasetCollectionBindingService.get_dataset_collection_binding", @@ -2038,6 +2058,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: assert dataset.embedding_model_provider == "explicit-provider" assert dataset.retrieval_model == knowledge_config.retrieval_model.model_dump() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_creates_custom_process_rule_for_new_upload_document( self, account_context, sqlite_session: Session ): @@ -2057,7 +2078,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: sqlite_session.commit() with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, patch("services.dataset_service.DocumentIndexingTaskProxy") as document_proxy_cls, patch("services.dataset_service.time.strftime", return_value="20260101010101"), @@ -2082,6 +2103,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: document_proxy_cls.assert_called_once_with("tenant-1", "dataset-1", [created_document.id]) document_proxy_cls.return_value.delay.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_creates_automatic_process_rule_for_new_upload_document( self, account_context, sqlite_session: Session ): @@ -2094,7 +2116,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: sqlite_session.commit() with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, patch("services.dataset_service.DocumentIndexingTaskProxy"), patch("services.dataset_service.time.strftime", return_value="20260101010101"), @@ -2114,6 +2136,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: assert created_rule.rules == json.dumps(DatasetProcessRule.AUTOMATIC_RULES) assert sqlite_session.get(Document, documents[0].id) is documents[0] + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_creates_fallback_automatic_process_rule_when_latest_is_missing( self, account_context, sqlite_session: Session ): @@ -2123,7 +2146,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: sqlite_session.commit() with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, patch("services.dataset_service.DocumentIndexingTaskProxy"), patch("services.dataset_service.time.strftime", return_value="20260101010101"), @@ -2142,6 +2165,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: assert created_rule.mode == "automatic" assert created_rule.rules == json.dumps(DatasetProcessRule.AUTOMATIC_RULES) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_raises_when_upload_file_lookup_is_incomplete( self, account_context, sqlite_session: Session ): @@ -2151,7 +2175,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: sqlite_session.commit() with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, patch("services.dataset_service.time.strftime", return_value="20260101010101"), patch("services.dataset_service.secrets.randbelow", return_value=23), @@ -2165,6 +2189,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: session=sqlite_session, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_requires_notion_info_list_for_notion_import( self, account_context, sqlite_session: Session ): @@ -2180,7 +2205,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: ) with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, ): mock_redis.lock.return_value = _make_lock_context() @@ -2193,6 +2218,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: session=sqlite_session, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_save_document_with_dataset_id_requires_website_info_list_for_website_crawl( self, account_context, sqlite_session: Session ): @@ -2208,7 +2234,7 @@ class TestDocumentServiceSaveDocumentAdditionalBranches: ) with ( - patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=False)), + patch("services.dataset_service.FeatureService.get_features", return_value=_make_features()), patch("services.dataset_service.redis_client") as mock_redis, ): mock_redis.lock.return_value = _make_lock_context() diff --git a/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py b/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py index 76dc9f584d2..6049e76227a 100644 --- a/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py +++ b/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py @@ -42,9 +42,8 @@ def fake_current_user(monkeypatch: pytest.MonkeyPatch): @pytest.fixture def fake_features(monkeypatch: pytest.MonkeyPatch): - """Features.billing.enabled == False to skip quota logic.""" features = types.SimpleNamespace( - billing=types.SimpleNamespace(enabled=False, subscription=types.SimpleNamespace(plan="ENTERPRISE")), + billing=types.SimpleNamespace(subscription=types.SimpleNamespace(plan="ENTERPRISE")), documents_upload_quota=types.SimpleNamespace(limit=10_000, size=0), ) monkeypatch.setattr( diff --git a/api/tests/unit_tests/services/test_document_indexing_task_proxy.py b/api/tests/unit_tests/services/test_document_indexing_task_proxy.py index c012b132cd9..ace9abcb49e 100644 --- a/api/tests/unit_tests/services/test_document_indexing_task_proxy.py +++ b/api/tests/unit_tests/services/test_document_indexing_task_proxy.py @@ -2,19 +2,19 @@ from unittest.mock import Mock, patch from core.entities.document_task import DocumentTask from core.rag.pipeline.queue import TenantIsolatedTaskQueue -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from services.document_indexing_proxy.document_indexing_task_proxy import DocumentIndexingTaskProxy +from tests.unit_tests.config_override import config_overrides_context class DocumentIndexingTaskProxyTestDataFactory: """Factory class for creating test data and mock objects for DocumentIndexingTaskProxy tests.""" @staticmethod - def create_mock_features(billing_enabled: bool = False, plan: CloudPlan | str | None = CloudPlan.SANDBOX) -> Mock: + def create_mock_features(plan: CloudPlan | str | None = CloudPlan.SANDBOX) -> Mock: """Create mock features with billing configuration.""" features = Mock() features.billing = Mock() - features.billing.enabled = billing_enabled features.billing.subscription = Mock() features.billing.subscription.plan = plan return features @@ -171,13 +171,12 @@ class TestDocumentIndexingTaskProxy: # Assert proxy._send_to_direct_queue.assert_called_once_with(proxy.PRIORITY_TASK_FUNC) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") - def test_dispatch_with_billing_enabled_sandbox_plan(self, mock_feature_service): - """Test _dispatch method when billing is enabled with sandbox plan.""" + def test_dispatch_with_cloud_sandbox_plan(self, mock_feature_service): + """Test _dispatch method in Cloud with Sandbox plan.""" # Arrange - mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.SANDBOX - ) + mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX) mock_feature_service.get_features.return_value = mock_features proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy() proxy._send_to_default_tenant_queue = Mock() @@ -188,13 +187,12 @@ class TestDocumentIndexingTaskProxy: # Assert proxy._send_to_default_tenant_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") - def test_dispatch_with_billing_enabled_non_sandbox_plan(self, mock_feature_service): - """Test _dispatch method when billing is enabled with non-sandbox plan.""" + def test_dispatch_with_cloud_paid_plan(self, mock_feature_service): + """Test _dispatch method in Cloud with a paid plan.""" # Arrange - mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.TEAM - ) + mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.TEAM) mock_feature_service.get_features.return_value = mock_features proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -205,11 +203,12 @@ class TestDocumentIndexingTaskProxy: # If billing enabled with non sandbox plan, should send to priority tenant queue proxy._send_to_priority_tenant_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) @patch("services.document_indexing_proxy.base.FeatureService") - def test_dispatch_with_billing_disabled(self, mock_feature_service): - """Test _dispatch method when billing is disabled.""" + def test_dispatch_outside_cloud(self, mock_feature_service): + """Test _dispatch method outside Cloud.""" # Arrange - mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(billing_enabled=False) + mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features() mock_feature_service.get_features.return_value = mock_features proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy() proxy._send_to_priority_direct_queue = Mock() @@ -220,13 +219,12 @@ class TestDocumentIndexingTaskProxy: # If billing disabled, for example: self-hosted or enterprise, should send to priority direct queue proxy._send_to_priority_direct_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") def test_delay_method(self, mock_feature_service): """Test delay method integration.""" # Arrange - mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.SANDBOX - ) + mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX) mock_feature_service.get_features.return_value = mock_features proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy() proxy._send_to_default_tenant_queue = Mock() @@ -253,11 +251,12 @@ class TestDocumentIndexingTaskProxy: assert task.dataset_id == dataset_id assert task.document_ids == document_ids + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") def test_dispatch_edge_case_empty_plan(self, mock_feature_service): """Test _dispatch method with empty plan string.""" # Arrange - mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(billing_enabled=True, plan="") + mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan="") mock_feature_service.get_features.return_value = mock_features proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -268,11 +267,12 @@ class TestDocumentIndexingTaskProxy: # Assert proxy._send_to_priority_tenant_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") def test_dispatch_edge_case_none_plan(self, mock_feature_service): """Test _dispatch method with None plan.""" # Arrange - mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(billing_enabled=True, plan=None) + mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=None) mock_feature_service.get_features.return_value = mock_features proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy() proxy._send_to_priority_tenant_queue = Mock() diff --git a/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py b/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py index 2af411b0d76..7a5039e94cf 100644 --- a/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py +++ b/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py @@ -2,21 +2,21 @@ from unittest.mock import Mock, patch from core.entities.document_task import DocumentTask from core.rag.pipeline.queue import TenantIsolatedTaskQueue -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from services.document_indexing_proxy.duplicate_document_indexing_task_proxy import ( DuplicateDocumentIndexingTaskProxy, ) +from tests.unit_tests.config_override import config_overrides_context class DuplicateDocumentIndexingTaskProxyTestDataFactory: """Factory class for creating test data and mock objects for DuplicateDocumentIndexingTaskProxy tests.""" @staticmethod - def create_mock_features(billing_enabled: bool = False, plan: CloudPlan | str | None = CloudPlan.SANDBOX) -> Mock: + def create_mock_features(plan: CloudPlan | str | None = CloudPlan.SANDBOX) -> Mock: """Create mock features with billing configuration.""" features = Mock() features.billing = Mock() - features.billing.enabled = billing_enabled features.billing.subscription = Mock() features.billing.subscription.plan = plan return features @@ -196,13 +196,12 @@ class TestDuplicateDocumentIndexingTaskProxy: # Assert proxy._send_to_direct_queue.assert_called_once_with(proxy.PRIORITY_TASK_FUNC) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") - def test_dispatch_with_billing_enabled_sandbox_plan(self, mock_feature_service): - """Test _dispatch method when billing is enabled with sandbox plan.""" + def test_dispatch_with_cloud_sandbox_plan(self, mock_feature_service): + """Test _dispatch method in Cloud with Sandbox plan.""" # Arrange - mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.SANDBOX - ) + mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX) mock_feature_service.get_features.return_value = mock_features proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy() proxy._send_to_default_tenant_queue = Mock() @@ -213,13 +212,12 @@ class TestDuplicateDocumentIndexingTaskProxy: # Assert proxy._send_to_default_tenant_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") - def test_dispatch_with_billing_enabled_non_sandbox_plan(self, mock_feature_service): - """Test _dispatch method when billing is enabled with non-sandbox plan.""" + def test_dispatch_with_cloud_paid_plan(self, mock_feature_service): + """Test _dispatch method in Cloud with a paid plan.""" # Arrange - mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.TEAM - ) + mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.TEAM) mock_feature_service.get_features.return_value = mock_features proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -231,11 +229,12 @@ class TestDuplicateDocumentIndexingTaskProxy: # If billing enabled with non sandbox plan, should send to priority tenant queue proxy._send_to_priority_tenant_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) @patch("services.document_indexing_proxy.base.FeatureService") - def test_dispatch_with_billing_disabled(self, mock_feature_service): - """Test _dispatch method when billing is disabled.""" + def test_dispatch_outside_cloud(self, mock_feature_service): + """Test _dispatch method outside Cloud.""" # Arrange - mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(billing_enabled=False) + mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features() mock_feature_service.get_features.return_value = mock_features proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy() proxy._send_to_priority_direct_queue = Mock() @@ -247,13 +246,12 @@ class TestDuplicateDocumentIndexingTaskProxy: # If billing disabled, for example: self-hosted or enterprise, should send to priority direct queue proxy._send_to_priority_direct_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") def test_delay_method(self, mock_feature_service): """Test delay method integration.""" # Arrange - mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.SANDBOX - ) + mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX) mock_feature_service.get_features.return_value = mock_features proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy() proxy._send_to_default_tenant_queue = Mock() @@ -265,13 +263,12 @@ class TestDuplicateDocumentIndexingTaskProxy: # If billing enabled with sandbox plan, should send to default tenant queue proxy._send_to_default_tenant_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") def test_dispatch_edge_case_empty_plan(self, mock_feature_service): """Test _dispatch method with empty plan string.""" # Arrange - mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan="" - ) + mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan="") mock_feature_service.get_features.return_value = mock_features proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -282,13 +279,12 @@ class TestDuplicateDocumentIndexingTaskProxy: # Assert proxy._send_to_priority_tenant_queue.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") def test_dispatch_edge_case_none_plan(self, mock_feature_service): """Test _dispatch method with None plan.""" # Arrange - mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=None - ) + mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=None) mock_feature_service.get_features.return_value = mock_features proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -345,12 +341,13 @@ class TestDuplicateDocumentIndexingTaskProxy: assert proxy._document_ids == document_ids assert len(proxy._document_ids) == 100 + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.document_indexing_proxy.base.FeatureService") def test_dispatch_with_professional_plan(self, mock_feature_service): """Test _dispatch method when billing is enabled with professional plan.""" # Arrange mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.PROFESSIONAL + plan=CloudPlan.PROFESSIONAL ) mock_feature_service.get_features.return_value = mock_features proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy() diff --git a/api/tests/unit_tests/services/test_feature_entities.py b/api/tests/unit_tests/services/test_feature_entities.py index 4b04d837036..f3c833e63cb 100644 --- a/api/tests/unit_tests/services/test_feature_entities.py +++ b/api/tests/unit_tests/services/test_feature_entities.py @@ -2,7 +2,7 @@ import pytest from pydantic import ValidationError from enums import CloudPlan -from services.entities.feature_entities import LicenseLimitationModel, SubscriptionModel +from services.entities.feature_entities import FeatureModel, LicenseLimitationModel, SubscriptionModel def test_subscription_model_uses_the_cloud_plan_value_set() -> None: @@ -40,3 +40,11 @@ def test_license_limitation_availability( limitation = LicenseLimitationModel(enabled=enabled, size=size, limit=limit) assert limitation.is_available(required) is expected + + +def test_feature_response_exposes_subscription_without_legacy_billing_switch() -> None: + features = FeatureModel(billing={"subscription": {"plan": "professional", "interval": "month"}}) + + assert features.model_dump(mode="json")["billing"] == { + "subscription": {"plan": "professional", "interval": "month"}, + } diff --git a/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py b/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py index d790121f35c..cb16e88a8b0 100644 --- a/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py +++ b/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py @@ -14,7 +14,6 @@ class HumanInputEmailDeliveryCase: name: str deployment_edition: DeploymentEdition tenant_id: str | None - billing_feature_enabled: bool plan: str expected: bool @@ -24,7 +23,6 @@ CASES = [ name="enterprise_edition", deployment_edition=DeploymentEdition.ENTERPRISE, tenant_id=None, - billing_feature_enabled=False, plan=CloudPlan.SANDBOX, expected=True, ), @@ -32,7 +30,6 @@ CASES = [ name="community_edition", deployment_edition=DeploymentEdition.COMMUNITY, tenant_id=None, - billing_feature_enabled=False, plan=CloudPlan.SANDBOX, expected=True, ), @@ -40,15 +37,6 @@ CASES = [ name="cloud_edition_requires_tenant", deployment_edition=DeploymentEdition.CLOUD, tenant_id=None, - billing_feature_enabled=True, - plan=CloudPlan.PROFESSIONAL, - expected=False, - ), - HumanInputEmailDeliveryCase( - name="billing_feature_off", - deployment_edition=DeploymentEdition.CLOUD, - tenant_id="tenant-1", - billing_feature_enabled=False, plan=CloudPlan.PROFESSIONAL, expected=False, ), @@ -56,7 +44,6 @@ CASES = [ name="professional_plan", deployment_edition=DeploymentEdition.CLOUD, tenant_id="tenant-1", - billing_feature_enabled=True, plan=CloudPlan.PROFESSIONAL, expected=True, ), @@ -64,7 +51,6 @@ CASES = [ name="team_plan", deployment_edition=DeploymentEdition.CLOUD, tenant_id="tenant-1", - billing_feature_enabled=True, plan=CloudPlan.TEAM, expected=True, ), @@ -72,7 +58,6 @@ CASES = [ name="sandbox_plan", deployment_edition=DeploymentEdition.CLOUD, tenant_id="tenant-1", - billing_feature_enabled=True, plan=CloudPlan.SANDBOX, expected=False, ), @@ -86,7 +71,6 @@ def test_resolve_human_input_email_delivery_enabled_matrix( ): config_overrides(DEPLOYMENT_EDITION=case.deployment_edition) features = FeatureModel() - features.billing.enabled = case.billing_feature_enabled features.billing.subscription.plan = case.plan result = FeatureService._resolve_human_input_email_delivery_enabled( diff --git a/api/tests/unit_tests/services/test_feature_service_knowledge_file_size_limit.py b/api/tests/unit_tests/services/test_feature_service_knowledge_file_size_limit.py index 5a38f1f71fd..cf6105373bb 100644 --- a/api/tests/unit_tests/services/test_feature_service_knowledge_file_size_limit.py +++ b/api/tests/unit_tests/services/test_feature_service_knowledge_file_size_limit.py @@ -9,15 +9,14 @@ from services.feature_service import FeatureService @pytest.mark.parametrize( - ("deployment_edition", "tenant_id", "billing_feature_enabled", "plan", "expected"), + ("deployment_edition", "tenant_id", "plan", "expected"), [ - (DeploymentEdition.COMMUNITY, "tenant-1", True, CloudPlan.PROFESSIONAL, 15), - (DeploymentEdition.ENTERPRISE, "tenant-1", True, CloudPlan.PROFESSIONAL, 15), - (DeploymentEdition.CLOUD, None, True, CloudPlan.PROFESSIONAL, 15), - (DeploymentEdition.CLOUD, "tenant-1", False, CloudPlan.PROFESSIONAL, 15), - (DeploymentEdition.CLOUD, "tenant-1", True, CloudPlan.SANDBOX, 15), - (DeploymentEdition.CLOUD, "tenant-1", True, CloudPlan.PROFESSIONAL, 50), - (DeploymentEdition.CLOUD, "tenant-1", True, CloudPlan.TEAM, 50), + (DeploymentEdition.COMMUNITY, "tenant-1", CloudPlan.PROFESSIONAL, 15), + (DeploymentEdition.ENTERPRISE, "tenant-1", CloudPlan.PROFESSIONAL, 15), + (DeploymentEdition.CLOUD, None, CloudPlan.PROFESSIONAL, 15), + (DeploymentEdition.CLOUD, "tenant-1", CloudPlan.SANDBOX, 15), + (DeploymentEdition.CLOUD, "tenant-1", CloudPlan.PROFESSIONAL, 50), + (DeploymentEdition.CLOUD, "tenant-1", CloudPlan.TEAM, 50), ], ) def test_get_knowledge_file_size_limit( @@ -25,7 +24,6 @@ def test_get_knowledge_file_size_limit( config_overrides: Callable[..., None], deployment_edition: DeploymentEdition, tenant_id: str | None, - billing_feature_enabled: bool, plan: CloudPlan, expected: int, ) -> None: @@ -36,7 +34,6 @@ def test_get_knowledge_file_size_limit( ) get_info = Mock( return_value={ - "enabled": billing_feature_enabled, "subscription": {"plan": plan}, } ) @@ -62,7 +59,6 @@ def test_paid_knowledge_file_size_limit_never_reduces_default( feature_service_module.BillingService, "get_info", lambda *_args, **_kwargs: { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL}, }, ) diff --git a/api/tests/unit_tests/services/test_feature_service_vector_space.py b/api/tests/unit_tests/services/test_feature_service_vector_space.py index 5a7cfc1dda4..913a8526a95 100644 --- a/api/tests/unit_tests/services/test_feature_service_vector_space.py +++ b/api/tests/unit_tests/services/test_feature_service_vector_space.py @@ -10,16 +10,13 @@ from services.feature_service import FeatureService def test_get_features_exclude_vector_space_sets_vector_space_to_none(config_overrides): tenant_id = "tenant-id" billing_info = { - "enabled": True, "subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "monthly", "education": False}, "members": {"size": 1, "limit": 10}, "apps": {"size": 2, "limit": 20}, "documents_upload_quota": {"size": 3, "limit": 100}, "annotation_quota_limit": {"size": 4, "limit": 50}, - "docs_processing": "standard", "can_replace_logo": True, "model_load_balancing_enabled": True, - "knowledge_rate_limit": {"limit": 100}, "knowledge_pipeline_publish_enabled": True, } @@ -27,7 +24,6 @@ def test_get_features_exclude_vector_space_sets_vector_space_to_none(config_over DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, CAN_REPLACE_LOGO=False, MODEL_LB_ENABLED=False, - DATASET_OPERATOR_ENABLED=False, EDUCATION_ENABLED=False, ) with ( diff --git a/api/tests/unit_tests/services/test_file_service.py b/api/tests/unit_tests/services/test_file_service.py index 470235cf610..6b979b24e87 100644 --- a/api/tests/unit_tests/services/test_file_service.py +++ b/api/tests/unit_tests/services/test_file_service.py @@ -398,87 +398,6 @@ class TestFileService: with pytest.raises(UnsupportedFileTypeError): file_service.get_file_preview("file_id", "tenant_id") - def test_get_image_preview_success(self, file_service: FileService, db_session: Session): - self._persist_upload_file(db_session, extension="jpg", mime_type="image/jpeg") - - with ( - patch("services.file_service.file_helpers.verify_image_signature") as mock_verify, - patch("services.file_service.storage") as mock_storage, - ): - mock_verify.return_value = True - mock_storage.load.return_value = iter([b"chunk1"]) - - # Execute - gen, mime = file_service.get_image_preview("file_id", "ts", "nonce", "sign") - - # Assert - assert list(gen) == [b"chunk1"] - assert mime == "image/jpeg" - - def test_get_image_preview_invalid_sig(self, file_service): - with patch("services.file_service.file_helpers.verify_image_signature") as mock_verify: - mock_verify.return_value = False - with pytest.raises(NotFound, match="File not found or signature is invalid"): - file_service.get_image_preview("file_id", "ts", "nonce", "sign") - - def test_get_image_preview_not_found(self, file_service: FileService): - with patch("services.file_service.file_helpers.verify_image_signature") as mock_verify: - mock_verify.return_value = True - with pytest.raises(NotFound, match="File not found or signature is invalid"): - file_service.get_image_preview("file_id", "ts", "nonce", "sign") - - def test_get_image_preview_unsupported_type(self, file_service: FileService, db_session: Session): - self._persist_upload_file(db_session) - with patch("services.file_service.file_helpers.verify_image_signature") as mock_verify: - mock_verify.return_value = True - with pytest.raises(UnsupportedFileTypeError): - file_service.get_image_preview("file_id", "ts", "nonce", "sign") - - def test_get_file_generator_by_file_id_success(self, file_service: FileService, db_session: Session): - upload_file = self._persist_upload_file(db_session) - - with ( - patch("services.file_service.file_helpers.verify_file_signature") as mock_verify, - patch("services.file_service.storage") as mock_storage, - ): - mock_verify.return_value = True - mock_storage.load.return_value = iter([b"chunk"]) - - gen, file = file_service.get_file_generator_by_file_id("file_id", "ts", "nonce", "sign") - assert list(gen) == [b"chunk"] - assert file.id == upload_file.id - assert file.key == upload_file.key - - def test_get_file_generator_by_file_id_invalid_sig(self, file_service): - with patch("services.file_service.file_helpers.verify_file_signature") as mock_verify: - mock_verify.return_value = False - with pytest.raises(NotFound, match="File not found or signature is invalid"): - file_service.get_file_generator_by_file_id("file_id", "ts", "nonce", "sign") - - def test_get_file_generator_by_file_id_not_found(self, file_service: FileService): - with patch("services.file_service.file_helpers.verify_file_signature") as mock_verify: - mock_verify.return_value = True - with pytest.raises(NotFound, match="File not found or signature is invalid"): - file_service.get_file_generator_by_file_id("file_id", "ts", "nonce", "sign") - - def test_get_public_image_preview_success(self, file_service: FileService, db_session: Session): - self._persist_upload_file(db_session, extension="png", mime_type="image/png") - - with patch("services.file_service.storage") as mock_storage: - mock_storage.load.return_value = b"image content" - gen, mime = file_service.get_public_image_preview("file_id") - assert gen == b"image content" - assert mime == "image/png" - - def test_get_public_image_preview_not_found(self, file_service: FileService): - with pytest.raises(NotFound, match="File not found or signature is invalid"): - file_service.get_public_image_preview("file_id") - - def test_get_public_image_preview_unsupported_type(self, file_service: FileService, db_session: Session): - self._persist_upload_file(db_session) - with pytest.raises(UnsupportedFileTypeError): - file_service.get_public_image_preview("file_id") - def test_get_file_content_success(self, file_service: FileService, db_session: Session): self._persist_upload_file(db_session) diff --git a/api/tests/unit_tests/services/test_human_input_file_upload_service.py b/api/tests/unit_tests/services/test_human_input_file_upload_service.py index 3447d866c63..2f1b15cf472 100644 --- a/api/tests/unit_tests/services/test_human_input_file_upload_service.py +++ b/api/tests/unit_tests/services/test_human_input_file_upload_service.py @@ -5,297 +5,219 @@ from types import SimpleNamespace from unittest.mock import MagicMock import pytest -from sqlalchemy import create_engine, select -from sqlalchemy.orm import sessionmaker -import models.account as account_module import services.human_input_file_upload_service as service_module from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus -from graphon.enums import WorkflowExecutionStatus from libs.datetime_utils import naive_utc_now -from models.account import Account, Tenant, TenantAccountJoin -from models.base import Base -from models.enums import CreatorUserRole, EndUserType, WorkflowRunTriggeredFrom -from models.human_input import ( - HumanInputForm, - HumanInputFormRecipient, - HumanInputFormUploadFile, - HumanInputFormUploadToken, +from models.account import Account +from models.enums import CreatorUserRole +from services.human_input_file_upload_service import ( + HITL_UPLOAD_TOKEN_PREFIX, + HumanInputFileUploadRepository, + HumanInputFileUploadService, + HumanInputUploadContext, + HumanInputUploadFormRecord, + HumanInputUploadGrantRecord, + InvalidUploadTokenError, ) -from models.model import App, AppMode, EndUser -from models.workflow import WorkflowRun, WorkflowType -from services.human_input_file_upload_service import HITL_UPLOAD_TOKEN_PREFIX, HumanInputFileUploadService -from services.human_input_service import FormSubmittedError +from services.human_input_service import FormNotFoundError, FormSubmittedError -@pytest.fixture -def session_maker(monkeypatch: pytest.MonkeyPatch): - engine = create_engine("sqlite:///:memory:") - monkeypatch.setattr(account_module, "db", SimpleNamespace(engine=engine)) - Base.metadata.create_all( - engine, - tables=[ - Tenant.__table__, - Account.__table__, - TenantAccountJoin.__table__, - App.__table__, - EndUser.__table__, - WorkflowRun.__table__, - HumanInputForm.__table__, - HumanInputFormRecipient.__table__, - HumanInputFormUploadToken.__table__, - HumanInputFormUploadFile.__table__, - ], - ) - try: - yield sessionmaker(bind=engine, expire_on_commit=False) - finally: - Base.metadata.drop_all( - engine, - tables=[ - HumanInputFormUploadFile.__table__, - HumanInputFormUploadToken.__table__, - HumanInputFormRecipient.__table__, - HumanInputForm.__table__, - WorkflowRun.__table__, - EndUser.__table__, - App.__table__, - TenantAccountJoin.__table__, - Account.__table__, - Tenant.__table__, - ], - ) - engine.dispose() - - -def _create_waiting_form( - session_maker, +def _active_form( *, - created_by_role: CreatorUserRole = CreatorUserRole.ACCOUNT, + workflow_run_id: str | None = "run-1", form_kind: HumanInputFormKind = HumanInputFormKind.RUNTIME, -) -> tuple[str, str, str]: - form_id = "00000000-0000-0000-0000-000000000001" - recipient_id = "00000000-0000-0000-0000-000000000002" - workflow_run_id = None - if form_kind == HumanInputFormKind.RUNTIME: - workflow_run_id = "00000000-0000-0000-0000-000000000012" - tenant_id = "00000000-0000-0000-0000-000000000010" - app_id = "00000000-0000-0000-0000-000000000011" + status: HumanInputFormStatus = HumanInputFormStatus.WAITING, +) -> HumanInputUploadFormRecord: now = naive_utc_now() - created_by = ( - "00000000-0000-0000-0000-000000000020" - if created_by_role == CreatorUserRole.ACCOUNT - else "00000000-0000-0000-0000-000000000021" + return HumanInputUploadFormRecord( + form_id="form-1", + recipient_id="recipient-1", + tenant_id="tenant-1", + app_id="app-1", + workflow_run_id=workflow_run_id, + form_kind=form_kind, + status=status, + submitted_at=None, + expiration_time=now + timedelta(hours=1), + created_at=now, + ) + + +def _upload_context() -> HumanInputUploadContext: + return HumanInputUploadContext( + tenant_id="tenant-1", + app_id="app-1", + form_id="form-1", + recipient_id="recipient-1", + upload_token_id="token-1", + owner=MagicMock(spec=Account), ) - with session_maker.begin() as session: - tenant = Tenant(name="tenant-1") - tenant.id = tenant_id - session.add(tenant) - if created_by_role == CreatorUserRole.ACCOUNT: - account = Account(name="owner", email="owner@example.com") - account.id = created_by - session.add(account) - session.add( - TenantAccountJoin( - tenant_id=tenant_id, - account_id=created_by, - current=True, - ) - ) - app_creator = created_by - else: - end_user = EndUser( - tenant_id=tenant_id, - app_id=app_id, - type=EndUserType.BROWSER, - is_anonymous=False, - session_id="session-1", - external_user_id="external-1", - ) - end_user.id = created_by - session.add(end_user) - app_creator = "00000000-0000-0000-0000-000000000020" - account = Account(name="owner", email="owner@example.com") - account.id = app_creator - session.add(account) - session.add( - TenantAccountJoin( - tenant_id=tenant_id, - account_id=app_creator, - current=True, - ) - ) - app = App( - tenant_id=tenant_id, - name="app-1", - description="", - mode=AppMode.WORKFLOW, - icon_type="emoji", - icon="app", - icon_background="#ffffff", - enable_site=True, - enable_api=True, - created_by=app_creator, - updated_by=app_creator, - ) - app.id = app_id - session.add(app) - if workflow_run_id is not None: - workflow_run = WorkflowRun( - tenant_id=tenant_id, - app_id=app_id, - workflow_id="00000000-0000-0000-0000-000000000013", - type=WorkflowType.WORKFLOW, - triggered_from=WorkflowRunTriggeredFrom.APP_RUN, - version="1", - graph="{}", - inputs="{}", - status=WorkflowExecutionStatus.RUNNING, - created_by_role=created_by_role, - created_by=created_by, - created_at=now, - ) - workflow_run.id = workflow_run_id - session.add(workflow_run) - session.add( - HumanInputForm( - id=form_id, - tenant_id=tenant_id, - app_id=app_id, - workflow_run_id=workflow_run_id, - form_kind=form_kind, - node_id="node-1", - form_definition="{}", - rendered_content="content", - expiration_time=now + timedelta(hours=1), - created_at=now, - ) - ) - session.add( - HumanInputFormRecipient( - id=recipient_id, - form_id=form_id, - delivery_id="00000000-0000-0000-0000-000000000003", - recipient_type="standalone_web_app", - recipient_payload='{"TYPE": "standalone_web_app"}', - access_token="form-token-1", - ) - ) - return form_id, recipient_id, created_by def _create_service( - session_maker, - workflow_run_repository: MagicMock | None = None, + *, + uploads: MagicMock | None = None, + workflow_runs: MagicMock | None = None, + files: MagicMock | None = None, + remote_files: MagicMock | None = None, ) -> HumanInputFileUploadService: return HumanInputFileUploadService( - session_maker, - workflow_run_repository=workflow_run_repository or MagicMock(), + uploads=uploads if uploads is not None else MagicMock(spec=HumanInputFileUploadRepository), + workflow_run_repository=workflow_runs if workflow_runs is not None else MagicMock(), + files=files if files is not None else MagicMock(), + remote_files=remote_files if remote_files is not None else MagicMock(), ) -def _get_workflow_run(session_maker) -> WorkflowRun: - with session_maker() as session: - workflow_run = session.get(WorkflowRun, "00000000-0000-0000-0000-000000000012") - assert workflow_run is not None - return workflow_run - - -def test_issue_upload_token_persists_token_without_technical_end_user( - monkeypatch: pytest.MonkeyPatch, - session_maker, -) -> None: - form_id, recipient_id, _created_by = _create_waiting_form(session_maker) +def test_issue_upload_token_persists_repository_record(monkeypatch: pytest.MonkeyPatch) -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + form = _active_form() + uploads.get_form_by_recipient_token.return_value = form monkeypatch.setattr(service_module.secrets, "token_urlsafe", lambda _bytes: "random-value") - token = _create_service(session_maker).issue_upload_token("form-token-1") + token = _create_service(uploads=uploads).issue_upload_token("form-token-1") assert token.upload_token == f"{HITL_UPLOAD_TOKEN_PREFIX}random-value" - with session_maker() as session: - token_model = session.scalar(select(HumanInputFormUploadToken)) - assert token_model is not None - assert token_model.form_id == form_id - assert token_model.recipient_id == recipient_id - assert token_model.token == token.upload_token - assert session.scalar(select(EndUser).limit(1)) is None + assert token.expires_at == form.expiration_time + uploads.get_form_by_recipient_token.assert_called_once_with("form-token-1") + uploads.create_upload_token.assert_called_once_with(form=form, upload_token=token.upload_token) -def test_validate_upload_token_returns_account_owner_and_record_file_link(session_maker) -> None: - form_id, recipient_id, created_by = _create_waiting_form(session_maker, created_by_role=CreatorUserRole.ACCOUNT) - token = _create_service(session_maker).issue_upload_token("form-token-1") - workflow_run_repository = MagicMock() - workflow_run_repository.get_workflow_run_by_id.return_value = _get_workflow_run(session_maker) +def test_issue_upload_token_rejects_unknown_form_token() -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + uploads.get_form_by_recipient_token.return_value = None - context = HumanInputFileUploadService( - session_maker, - workflow_run_repository=workflow_run_repository, - ).validate_upload_token(token.upload_token) - assert context.form_id == form_id - assert context.recipient_id == recipient_id - assert isinstance(context.owner, Account) - assert context.owner.id == created_by - assert context.owner.current_tenant_id == "00000000-0000-0000-0000-000000000010" - workflow_run_repository.get_workflow_run_by_id.assert_called_once_with( - tenant_id="00000000-0000-0000-0000-000000000010", - app_id="00000000-0000-0000-0000-000000000011", - run_id="00000000-0000-0000-0000-000000000012", + with pytest.raises(FormNotFoundError): + _create_service(uploads=uploads).issue_upload_token("missing-form-token") + + uploads.create_upload_token.assert_not_called() + + +@pytest.mark.parametrize("owner_role", [CreatorUserRole.ACCOUNT, CreatorUserRole.END_USER]) +def test_validate_upload_token_resolves_workflow_run_owner(owner_role: CreatorUserRole) -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + form = _active_form() + uploads.get_upload_grant.return_value = HumanInputUploadGrantRecord(upload_token_id="token-1", form=form) + owner = MagicMock() + uploads.get_upload_owner.return_value = owner + workflow_runs = MagicMock() + workflow_runs.get_workflow_run_by_id.return_value = SimpleNamespace( + created_by="owner-1", + created_by_role=owner_role, + tenant_id="tenant-1", + app_id="app-1", ) - _create_service(session_maker).record_upload_file( - context=context, - file_id="00000000-0000-0000-0000-000000000099", + context = _create_service(uploads=uploads, workflow_runs=workflow_runs).validate_upload_token("upload-token-1") + + assert context == HumanInputUploadContext( + tenant_id="tenant-1", + app_id="app-1", + form_id="form-1", + recipient_id="recipient-1", + upload_token_id="token-1", + owner=owner, + ) + workflow_runs.get_workflow_run_by_id.assert_called_once_with( + tenant_id="tenant-1", + app_id="app-1", + run_id="run-1", + ) + uploads.get_upload_owner.assert_called_once_with( + owner_id="owner-1", + owner_role=owner_role, + tenant_id="tenant-1", + app_id="app-1", ) - with session_maker() as session: - link = session.scalar(select(HumanInputFormUploadFile)) - assert link is not None - assert link.tenant_id == context.tenant_id - assert link.app_id == context.app_id - assert link.form_id == form_id - assert link.upload_token_id == context.upload_token_id + +def test_validate_upload_token_resolves_delivery_test_owner() -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + form = _active_form(workflow_run_id=None, form_kind=HumanInputFormKind.DELIVERY_TEST) + uploads.get_upload_grant.return_value = HumanInputUploadGrantRecord(upload_token_id="token-1", form=form) + owner = MagicMock(spec=Account) + uploads.get_delivery_test_upload_owner.return_value = owner + workflow_runs = MagicMock() + + context = _create_service(uploads=uploads, workflow_runs=workflow_runs).validate_upload_token("upload-token-1") + + assert context.owner is owner + uploads.get_delivery_test_upload_owner.assert_called_once_with(tenant_id="tenant-1", app_id="app-1") + workflow_runs.get_workflow_run_by_id.assert_not_called() -def test_validate_upload_token_returns_end_user_owner(session_maker) -> None: - form_id, recipient_id, created_by = _create_waiting_form(session_maker, created_by_role=CreatorUserRole.END_USER) - token = _create_service(session_maker).issue_upload_token("form-token-1") - workflow_run_repository = MagicMock() - workflow_run_repository.get_workflow_run_by_id.return_value = _get_workflow_run(session_maker) +def test_validate_upload_token_rejects_unknown_upload_token() -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + uploads.get_upload_grant.return_value = None - context = HumanInputFileUploadService( - session_maker, - workflow_run_repository=workflow_run_repository, - ).validate_upload_token(token.upload_token) - - assert context.form_id == form_id - assert context.recipient_id == recipient_id - assert isinstance(context.owner, EndUser) - assert context.owner.id == created_by + with pytest.raises(InvalidUploadTokenError): + _create_service(uploads=uploads).validate_upload_token("missing-upload-token") -def test_validate_upload_token_allows_delivery_test_form(session_maker) -> None: - form_id, recipient_id, _created_by = _create_waiting_form( - session_maker, - form_kind=HumanInputFormKind.DELIVERY_TEST, - ) - token = _create_service(session_maker).issue_upload_token("form-token-1") - - context = _create_service(session_maker).validate_upload_token(token.upload_token) - - assert context.form_id == form_id - assert context.recipient_id == recipient_id - assert isinstance(context.owner, Account) - assert context.owner.id == "00000000-0000-0000-0000-000000000020" - assert context.owner.current_tenant_id == "00000000-0000-0000-0000-000000000010" - - -def test_validate_upload_token_rejects_submitted_form(session_maker) -> None: - form_id, _recipient_id, _created_by = _create_waiting_form(session_maker) - token = _create_service(session_maker).issue_upload_token("form-token-1") - with session_maker.begin() as session: - form = session.get(HumanInputForm, form_id) - assert form is not None - form.status = HumanInputFormStatus.SUBMITTED - form.submitted_at = naive_utc_now() +def test_validate_upload_token_rejects_submitted_form() -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + form = _active_form(status=HumanInputFormStatus.SUBMITTED) + uploads.get_upload_grant.return_value = HumanInputUploadGrantRecord(upload_token_id="token-1", form=form) with pytest.raises(FormSubmittedError): - _create_service(session_maker).validate_upload_token(token.upload_token) + _create_service(uploads=uploads).validate_upload_token("upload-token-1") + + uploads.get_upload_owner.assert_not_called() + + +def test_upload_local_file_records_the_form_file_link() -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + files = MagicMock() + upload_file = MagicMock(id="file-1") + files.upload_file.return_value = upload_file + context = _upload_context() + + result = _create_service(uploads=uploads, files=files).upload_local_file( + context=context, + filename="sample.txt", + content=b"content", + mimetype="text/plain", + ) + + assert result is upload_file + files.upload_file.assert_called_once_with( + filename="sample.txt", + content=b"content", + mimetype="text/plain", + user=context.owner, + source=None, + ) + uploads.add_file.assert_called_once_with( + tenant_id="tenant-1", + app_id="app-1", + form_id="form-1", + upload_token_id="token-1", + file_id="file-1", + ) + + +def test_upload_remote_file_records_the_form_file_link() -> None: + uploads = MagicMock(spec=HumanInputFileUploadRepository) + remote_files = MagicMock() + upload_file = MagicMock(id="file-1") + remote_files.upload_from_url.return_value = upload_file + context = _upload_context() + + result = _create_service(uploads=uploads, remote_files=remote_files).upload_remote_file( + context=context, + url="https://example.com/sample.txt", + ) + + assert result is upload_file + remote_files.upload_from_url.assert_called_once_with( + url="https://example.com/sample.txt", + user=context.owner, + ) + uploads.add_file.assert_called_once_with( + tenant_id="tenant-1", + app_id="app-1", + form_id="form-1", + upload_token_id="token-1", + file_id="file-1", + ) diff --git a/api/tests/unit_tests/services/test_message_file_preview_service.py b/api/tests/unit_tests/services/test_message_file_preview_service.py new file mode 100644 index 00000000000..17599342a05 --- /dev/null +++ b/api/tests/unit_tests/services/test_message_file_preview_service.py @@ -0,0 +1,82 @@ +from unittest.mock import Mock + +import pytest + +from services.message_file_preview_service import ( + FileStreamStorage, + MessageFilePreviewAccessDeniedError, + MessageFilePreviewNotFoundError, + MessageFilePreviewQuery, + MessageFilePreviewRecord, + MessageFilePreviewService, +) + + +def _record() -> MessageFilePreviewRecord: + return MessageFilePreviewRecord( + key="upload_files/tenant/file.pdf", + name="file.pdf", + size=42, + extension="pdf", + mime_type="application/pdf", + ) + + +def test_get_preview_loads_the_authorized_file_stream() -> None: + files = Mock(spec=MessageFilePreviewQuery) + storage = Mock(spec=FileStreamStorage) + file = _record() + content = iter([b"content"]) + files.get_for_app.return_value = file + storage.load_stream.return_value = content + service = MessageFilePreviewService(files=files, storage=storage) + + preview = service.get_preview( + file_id="file-id", + app_id="app-id", + tenant_id="tenant-id", + ) + + files.get_for_app.assert_called_once_with( + file_id="file-id", + app_id="app-id", + tenant_id="tenant-id", + ) + storage.load_stream.assert_called_once_with(file.key) + assert preview.file is file + assert preview.content is content + + +@pytest.mark.parametrize( + "error", + [MessageFilePreviewNotFoundError(), MessageFilePreviewAccessDeniedError()], +) +def test_get_preview_does_not_load_denied_or_missing_files(error: Exception) -> None: + files = Mock(spec=MessageFilePreviewQuery) + storage = Mock(spec=FileStreamStorage) + files.get_for_app.side_effect = error + service = MessageFilePreviewService(files=files, storage=storage) + + with pytest.raises(type(error)): + service.get_preview( + file_id="file-id", + app_id="app-id", + tenant_id="tenant-id", + ) + + storage.load_stream.assert_not_called() + + +def test_get_preview_does_not_mask_storage_errors() -> None: + files = Mock(spec=MessageFilePreviewQuery) + storage = Mock(spec=FileStreamStorage) + files.get_for_app.return_value = _record() + storage.load_stream.side_effect = OSError("storage down") + service = MessageFilePreviewService(files=files, storage=storage) + + with pytest.raises(OSError, match="storage down"): + service.get_preview( + file_id="file-id", + app_id="app-id", + tenant_id="tenant-id", + ) diff --git a/api/tests/unit_tests/services/test_plugin_file_upload_gateway.py b/api/tests/unit_tests/services/test_plugin_file_upload_gateway.py new file mode 100644 index 00000000000..193cbc8e116 --- /dev/null +++ b/api/tests/unit_tests/services/test_plugin_file_upload_gateway.py @@ -0,0 +1,89 @@ +from unittest.mock import MagicMock, patch + +from core.tools.tool_file_manager import ToolFileManager +from core.workflow.file_reference import build_file_reference +from models.tools import ToolFile +from services.plugin_file_upload_gateway import ToolFilePluginUploadGateway +from services.plugin_file_upload_service import PluginFileUploadResult + + +def _tool_file() -> ToolFile: + file = ToolFile( + user_id="user-id", + tenant_id="tenant-id", + conversation_id="conversation-id", + file_key="tools/tenant-id/generated.pdf", + mimetype="application/pdf", + original_url=None, + name="report.pdf", + size=7, + ) + file.id = "file-id" + return file + + +def test_store_adapts_tool_file_to_transport_neutral_result() -> None: + tool_files = MagicMock(spec=ToolFileManager) + tool_files.create_file_by_raw.return_value = _tool_file() + gateway = ToolFilePluginUploadGateway(tool_files=tool_files) + + with patch("services.plugin_file_upload_gateway.sign_tool_file", return_value="signed-url") as sign_file: + result = gateway.store( + user_id="user-id", + tenant_id="tenant-id", + conversation_id="conversation-id", + content=b"content", + mimetype="application/pdf", + filename="report.pdf", + ) + + assert result == PluginFileUploadResult( + id="file-id", + reference=build_file_reference(record_id="file-id"), + name="report.pdf", + size=7, + extension=".pdf", + mime_type="application/pdf", + preview_url="signed-url", + source_url=None, + original_url=None, + user_id="user-id", + tenant_id="tenant-id", + conversation_id="conversation-id", + file_key="tools/tenant-id/generated.pdf", + ) + tool_files.create_file_by_raw.assert_called_once_with( + user_id="user-id", + tenant_id="tenant-id", + conversation_id="conversation-id", + file_binary=b"content", + mimetype="application/pdf", + filename="report.pdf", + ) + sign_file.assert_called_once_with( + tool_file_id="file-id", + extension=".pdf", + for_external=True, + ) + + +def test_filename_extension_wins_over_generic_mimetype() -> None: + tool_files = MagicMock(spec=ToolFileManager) + file = _tool_file() + file.name = "report.docx" + file.mimetype = "application/octet-stream" + tool_files.create_file_by_raw.return_value = file + gateway = ToolFilePluginUploadGateway(tool_files=tool_files) + + with patch("services.plugin_file_upload_gateway.sign_tool_file", return_value="signed-url"): + result = gateway.store( + user_id="user-id", + tenant_id="tenant-id", + conversation_id=None, + content=b"content", + mimetype="application/octet-stream", + filename="report.docx", + ) + + assert result.extension == ".docx" + assert result.mime_type == "application/octet-stream" diff --git a/api/tests/unit_tests/services/test_plugin_file_upload_service.py b/api/tests/unit_tests/services/test_plugin_file_upload_service.py new file mode 100644 index 00000000000..f247c04a11a --- /dev/null +++ b/api/tests/unit_tests/services/test_plugin_file_upload_service.py @@ -0,0 +1,198 @@ +import io +from unittest.mock import Mock, patch + +import pytest + +from services.errors.file import FileTooLargeError +from services.plugin_file_upload_service import ( + PluginFileUploadAccessDeniedError, + PluginFileUploadFiles, + PluginFileUploadOwnerQuery, + PluginFileUploadResult, + PluginFileUploadService, + PluginUploadUserFrom, +) + + +def _result() -> PluginFileUploadResult: + return PluginFileUploadResult( + id="file-id", + reference="reference", + name="report.pdf", + size=4, + extension=".pdf", + mime_type="application/pdf", + preview_url="signed-url", + source_url=None, + original_url=None, + user_id="user-id", + tenant_id="tenant-id", + conversation_id=None, + file_key="file-key", + ) + + +@pytest.fixture +def owners() -> Mock: + query = Mock(spec=PluginFileUploadOwnerQuery) + query.owner_exists.return_value = True + return query + + +@pytest.fixture +def files() -> Mock: + gateway = Mock(spec=PluginFileUploadFiles) + gateway.store.return_value = _result() + return gateway + + +@pytest.fixture +def service(owners: Mock, files: Mock) -> PluginFileUploadService: + return PluginFileUploadService(owners=owners, files=files) + + +def _upload( + service: PluginFileUploadService, + *, + stream: io.BytesIO | Mock | None = None, + user_id: str = "user-id", + user_from: PluginUploadUserFrom = None, + max_size: int | None = None, +) -> PluginFileUploadResult: + return service.upload( + stream=stream or io.BytesIO(b"data"), + filename="report.pdf", + mimetype="application/pdf", + tenant_id="tenant-id", + user_id=user_id, + user_from=user_from, + conversation_id="conversation-id", + timestamp="123", + nonce="nonce", + sign="signature", + max_size=max_size, + ) + + +@pytest.mark.parametrize("user_from", [None, "end-user", "account"]) +def test_valid_ticket_authorizes_owner_then_stores_file( + service: PluginFileUploadService, + owners: Mock, + files: Mock, + user_from: PluginUploadUserFrom, +) -> None: + stream = io.BytesIO(b"data") + + with patch("services.plugin_file_upload_service.verify_plugin_file_signature", return_value=True) as verify: + result = _upload(service, stream=stream, user_from=user_from) + + assert result == _result() + verify.assert_called_once_with( + filename="report.pdf", + mimetype="application/pdf", + tenant_id="tenant-id", + user_id="user-id", + conversation_id="conversation-id", + user_from=user_from, + timestamp="123", + nonce="nonce", + sign="signature", + max_size=None, + ) + owners.owner_exists.assert_called_once_with( + tenant_id="tenant-id", + user_id="user-id", + user_from=user_from, + ) + files.store.assert_called_once_with( + user_id="user-id", + tenant_id="tenant-id", + conversation_id="conversation-id", + content=b"data", + mimetype="application/pdf", + filename="report.pdf", + ) + + +def test_invalid_signature_has_no_database_or_stream_side_effect( + service: PluginFileUploadService, + owners: Mock, + files: Mock, +) -> None: + stream = Mock() + + with patch("services.plugin_file_upload_service.verify_plugin_file_signature", return_value=False): + with pytest.raises(PluginFileUploadAccessDeniedError): + _upload(service, stream=stream) + + owners.owner_exists.assert_not_called() + stream.read.assert_not_called() + files.store.assert_not_called() + + +def test_unknown_owner_is_rejected_before_reading_or_storing( + service: PluginFileUploadService, + owners: Mock, + files: Mock, +) -> None: + stream = Mock() + owners.owner_exists.return_value = False + + with patch("services.plugin_file_upload_service.verify_plugin_file_signature", return_value=True): + with pytest.raises(PluginFileUploadAccessDeniedError): + _upload(service, stream=stream, user_from="account") + + stream.read.assert_not_called() + files.store.assert_not_called() + + +def test_signed_size_reads_only_one_byte_beyond_the_limit( + service: PluginFileUploadService, + files: Mock, +) -> None: + stream = Mock() + stream.read.return_value = b"data" + + with patch("services.plugin_file_upload_service.verify_plugin_file_signature", return_value=True): + _upload(service, stream=stream, max_size=4) + + stream.read.assert_called_once_with(5) + assert files.store.call_args.kwargs["content"] == b"data" + + +def test_zero_signed_size_accepts_an_empty_file( + service: PluginFileUploadService, + files: Mock, +) -> None: + stream = Mock() + stream.read.return_value = b"" + + with patch("services.plugin_file_upload_service.verify_plugin_file_signature", return_value=True): + _upload(service, stream=stream, max_size=0) + + stream.read.assert_called_once_with(1) + assert files.store.call_args.kwargs["content"] == b"" + + +@pytest.mark.parametrize( + ("max_size", "content"), + [ + pytest.param(4, b"12345", id="positive-limit"), + pytest.param(0, b"1", id="zero-limit"), + ], +) +def test_signed_size_rejects_oversized_content_before_storage( + service: PluginFileUploadService, + files: Mock, + max_size: int, + content: bytes, +) -> None: + stream = Mock() + stream.read.return_value = content + + with patch("services.plugin_file_upload_service.verify_plugin_file_signature", return_value=True): + with pytest.raises(FileTooLargeError, match="signed upload limit"): + _upload(service, stream=stream, max_size=max_size) + + stream.read.assert_called_once_with(max_size + 1) + files.store.assert_not_called() diff --git a/api/tests/unit_tests/services/test_rag_pipeline_task_proxy.py b/api/tests/unit_tests/services/test_rag_pipeline_task_proxy.py index f89fb17f6e0..2b73d643387 100644 --- a/api/tests/unit_tests/services/test_rag_pipeline_task_proxy.py +++ b/api/tests/unit_tests/services/test_rag_pipeline_task_proxy.py @@ -7,22 +7,22 @@ import pytest from core.app.entities.rag_pipeline_invoke_entities import RagPipelineInvokeEntity from core.rag.pipeline.queue import TenantIsolatedTaskQueue -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from extensions.storage.storage_type import StorageType from models.enums import CreatorUserRole from models.model import UploadFile from services.rag_pipeline.rag_pipeline_task_proxy import RagPipelineTaskProxy +from tests.unit_tests.config_override import config_overrides_context class RagPipelineTaskProxyTestDataFactory: """Factory class for creating test data and mock objects for RagPipelineTaskProxy tests.""" @staticmethod - def create_mock_features(billing_enabled: bool = False, plan: CloudPlan = CloudPlan.SANDBOX) -> Mock: + def create_mock_features(plan: CloudPlan = CloudPlan.SANDBOX) -> Mock: """Create mock features with billing configuration.""" features = Mock() features.billing = Mock() - features.billing.enabled = billing_enabled features.billing.subscription = Mock() features.billing.subscription.plan = plan return features @@ -330,17 +330,16 @@ class TestRagPipelineTaskProxy: # Assert proxy._send_to_direct_queue.assert_called_once_with(upload_file_id, mock_task) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.rag_pipeline.rag_pipeline_task_proxy.FeatureService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.FileService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.db") - def test_dispatch_with_billing_enabled_sandbox_plan( + def test_dispatch_with_cloud_sandbox_plan( self, mock_db: MagicMock, mock_file_service_class: MagicMock, mock_feature_service: MagicMock ): - """Test _dispatch method when billing is enabled with sandbox plan.""" + """Test _dispatch method in Cloud with Sandbox plan.""" # Arrange - mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.SANDBOX - ) + mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX) mock_feature_service.get_features.return_value = mock_features proxy = RagPipelineTaskProxyTestDataFactory.create_rag_pipeline_task_proxy() proxy._send_to_default_tenant_queue = Mock() @@ -356,17 +355,14 @@ class TestRagPipelineTaskProxy: # If billing is enabled with sandbox plan, should send to default tenant queue proxy._send_to_default_tenant_queue.assert_called_once_with("file-123") + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.rag_pipeline.rag_pipeline_task_proxy.FeatureService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.FileService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.db") - def test_dispatch_with_billing_enabled_non_sandbox_plan( - self, mock_db, mock_file_service_class, mock_feature_service - ): - """Test _dispatch method when billing is enabled with non-sandbox plan.""" + def test_dispatch_with_cloud_paid_plan(self, mock_db, mock_file_service_class, mock_feature_service): + """Test _dispatch method in Cloud with a paid plan.""" # Arrange - mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.TEAM - ) + mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.TEAM) mock_feature_service.get_features.return_value = mock_features proxy = RagPipelineTaskProxyTestDataFactory.create_rag_pipeline_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -382,15 +378,16 @@ class TestRagPipelineTaskProxy: # If billing is enabled with non-sandbox plan, should send to priority tenant queue proxy._send_to_priority_tenant_queue.assert_called_once_with("file-123") + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) @patch("services.rag_pipeline.rag_pipeline_task_proxy.FeatureService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.FileService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.db") - def test_dispatch_with_billing_disabled( + def test_dispatch_outside_cloud( self, mock_db: MagicMock, mock_file_service_class: MagicMock, mock_feature_service: MagicMock ): - """Test _dispatch method when billing is disabled.""" + """Test _dispatch method outside Cloud.""" # Arrange - mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(billing_enabled=False) + mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features() mock_feature_service.get_features.return_value = mock_features proxy = RagPipelineTaskProxyTestDataFactory.create_rag_pipeline_task_proxy() proxy._send_to_priority_direct_queue = Mock() @@ -422,6 +419,7 @@ class TestRagPipelineTaskProxy: with pytest.raises(ValueError, match="upload_file_id is empty"): proxy._dispatch() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.rag_pipeline.rag_pipeline_task_proxy.FeatureService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.FileService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.db") @@ -430,7 +428,7 @@ class TestRagPipelineTaskProxy: ): """Test _dispatch method with empty plan string.""" # Arrange - mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(billing_enabled=True, plan="") + mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(plan="") mock_feature_service.get_features.return_value = mock_features proxy = RagPipelineTaskProxyTestDataFactory.create_rag_pipeline_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -446,6 +444,7 @@ class TestRagPipelineTaskProxy: # Assert proxy._send_to_priority_tenant_queue.assert_called_once_with("file-123") + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.rag_pipeline.rag_pipeline_task_proxy.FeatureService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.FileService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.db") @@ -454,7 +453,7 @@ class TestRagPipelineTaskProxy: ): """Test _dispatch method with None plan.""" # Arrange - mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(billing_enabled=True, plan=None) + mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(plan=None) mock_feature_service.get_features.return_value = mock_features proxy = RagPipelineTaskProxyTestDataFactory.create_rag_pipeline_task_proxy() proxy._send_to_priority_tenant_queue = Mock() @@ -470,6 +469,7 @@ class TestRagPipelineTaskProxy: # Assert proxy._send_to_priority_tenant_queue.assert_called_once_with("file-123") + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @patch("services.rag_pipeline.rag_pipeline_task_proxy.FeatureService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.FileService") @patch("services.rag_pipeline.rag_pipeline_task_proxy.db") @@ -478,9 +478,7 @@ class TestRagPipelineTaskProxy: ): """Test delay method integration.""" # Arrange - mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features( - billing_enabled=True, plan=CloudPlan.SANDBOX - ) + mock_features = RagPipelineTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX) mock_feature_service.get_features.return_value = mock_features proxy = RagPipelineTaskProxyTestDataFactory.create_rag_pipeline_task_proxy() proxy._dispatch = Mock() diff --git a/api/tests/unit_tests/services/test_rbac_agent_access_service.py b/api/tests/unit_tests/services/test_rbac_agent_access_service.py new file mode 100644 index 00000000000..92cd40fa5ff --- /dev/null +++ b/api/tests/unit_tests/services/test_rbac_agent_access_service.py @@ -0,0 +1,56 @@ +"""Unit tests for the RBAC bootstrap applied to a newly created agent.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from unittest.mock import MagicMock, patch + +import pytest + +from services import rbac_agent_access_service +from services.enterprise import rbac_service as enterprise_rbac_service + +MODULE = "services.rbac_agent_access_service" + +TENANT = "tenant-1" +AGENT = "agent-1" +CREATOR = "account-1" + + +@pytest.fixture +def rbac_calls(config_overrides: Callable[..., None]) -> Iterator[MagicMock]: + config_overrides(RBAC_ENABLED=True) + recorder = MagicMock() + with ( + patch(f"{MODULE}.enterprise_rbac_service.RBACService.AgentAccess.replace_whitelist") as replace_whitelist, + patch(f"{MODULE}.initialize_created_app_rbac_access_task.delay") as seed_task, + patch( + f"{MODULE}.enterprise_rbac_service.RBACService.AccessPolicies.sync_creator_access_policy_member_bindings" + ) as creator_sync, + ): + recorder.attach_mock(replace_whitelist, "replace_whitelist") + recorder.attach_mock(seed_task, "seed_task") + recorder.attach_mock(creator_sync, "creator_sync") + yield recorder + + +def test_initialize_agent_rbac_access_seeds_scope_members_and_creator_policy( + rbac_calls: MagicMock, +) -> None: + rbac_agent_access_service.initialize_agent_rbac_access(tenant_id=TENANT, agent_id=AGENT, creator_account_id=CREATOR) + + rbac_calls.replace_whitelist.assert_called_once_with( + TENANT, + CREATOR, + AGENT, + enterprise_rbac_service.ReplaceMemberBindings(automatic_include_workspace_members=True), + ) + rbac_calls.seed_task.assert_called_once_with(TENANT, CREATOR, agent_id=AGENT) + rbac_calls.creator_sync.assert_called_once_with( + TENANT, + CREATOR, + resource_type=enterprise_rbac_service.RBACResourceType.AGENT, + resource_id=AGENT, + ) + + assert [call[0] for call in rbac_calls.mock_calls] == ["seed_task", "creator_sync", "replace_whitelist"] diff --git a/api/tests/unit_tests/services/test_snippet_dsl_service.py b/api/tests/unit_tests/services/test_snippet_dsl_service.py index b1318b1edce..900f321c43b 100644 --- a/api/tests/unit_tests/services/test_snippet_dsl_service.py +++ b/api/tests/unit_tests/services/test_snippet_dsl_service.py @@ -3,6 +3,7 @@ from types import SimpleNamespace from unittest.mock import Mock import pytest +import yaml from sqlalchemy import event from sqlalchemy.orm import Session @@ -318,6 +319,17 @@ workflow: edges: [] """ + account_without_tenant = _account() + account_without_tenant._current_tenant = None + missing_tenant = service.import_snippet( + account=account_without_tenant, + import_mode=ImportMode.YAML_CONTENT.value, + yaml_content=yaml_content, + ) + assert missing_tenant.status == ImportStatus.FAILED + assert missing_tenant.error == "Current tenant is not set" + setex.assert_not_called() + result = service.import_snippet( account=_account(), import_mode=ImportMode.YAML_CONTENT.value, @@ -459,12 +471,21 @@ workflow: create_or_update = Mock(return_value=snippet) monkeypatch.setattr(service, "_create_or_update_snippet", create_or_update) redis_key = "snippet_import_info:import-1" + pending_json = pending.model_dump_json(exclude={"tenant_id", "account_id"}) monkeypatch.setattr( "services.snippet_dsl_service.redis_client.get", - Mock(side_effect=lambda key: pending.model_dump_json() if key == redis_key else None), + Mock(side_effect=lambda key: pending_json if key == redis_key else None), ) redis_delete = Mock() monkeypatch.setattr("services.snippet_dsl_service.redis_client.delete", redis_delete) + load = Mock(wraps=yaml.safe_load) + monkeypatch.setattr("services.snippet_dsl_service.yaml.safe_load", load) + + assert service.confirm_import(import_id="import-1", account=account).status == ImportStatus.FAILED + load.assert_not_called() + create_or_update.assert_not_called() + redis_delete.assert_not_called() + pending_json = pending.model_dump_json() for other_account in ( _account(tenant_id="tenant-2"), @@ -491,6 +512,8 @@ def test_confirm_import_returns_failed_for_non_mapping_yaml( service: SnippetDslService, monkeypatch: pytest.MonkeyPatch ): pending = SnippetPendingData( + tenant_id="tenant-1", + account_id="account-1", import_mode="yaml-content", yaml_content="- item", snippet_id=None, @@ -509,6 +532,8 @@ def test_confirm_import_returns_failed_when_create_or_update_raises( rollback_events: list[str] = [] event.listen(sqlite_session, "after_rollback", lambda _session: rollback_events.append("rollback")) pending = SnippetPendingData( + tenant_id="tenant-1", + account_id="account-1", import_mode="yaml-content", yaml_content="version: 0.1.0\nkind: snippet\nsnippet:\n name: Bad\n", snippet_id="snippet-1", diff --git a/api/tests/unit_tests/services/test_summary_index_service.py b/api/tests/unit_tests/services/test_summary_index_service.py index 1eb1baa40a3..c35318749e7 100644 --- a/api/tests/unit_tests/services/test_summary_index_service.py +++ b/api/tests/unit_tests/services/test_summary_index_service.py @@ -281,6 +281,45 @@ def test_vectorize_summary_final_failure_updates_error_status(monkeypatch: pytes error_session.commit.assert_called_once() +def test_vectorize_summary_failure_with_provided_session_does_not_open_error_session( + monkeypatch: pytest.MonkeyPatch, +) -> None: + dataset = _dataset() + segment = _segment() + summary = _summary_record(summary_content="sum", node_id=None) + + monkeypatch.setattr(summary_module.uuid, "uuid4", MagicMock(return_value="uuid-1")) + monkeypatch.setattr(summary_module.helper, "generate_text_hash", MagicMock(return_value="hash-1")) + monkeypatch.setattr( + summary_module, + "Vector", + MagicMock(return_value=MagicMock(add_texts=MagicMock(side_effect=RuntimeError("boom")))), + ) + monkeypatch.setattr( + summary_module.ModelManager, + "for_tenant", + MagicMock(return_value=MagicMock(get_model_instance=MagicMock(return_value=None))), + ) + + session = MagicMock(name="provided_session") + create_session_mock = MagicMock() + monkeypatch.setattr( + summary_module, + "session_factory", + SimpleNamespace(create_session=create_session_mock), + ) + + with pytest.raises(RuntimeError, match="boom"): + SummaryIndexService.vectorize_summary(summary, segment, dataset, session=session) + + create_session_mock.assert_not_called() + session.add.assert_called_once_with(summary) + session.commit.assert_not_called() + session.flush.assert_not_called() + assert summary.status == SummaryStatus.ERROR + assert summary.error == "Vectorization failed: boom" + + def test_batch_create_summary_records_no_segments_noop(monkeypatch: pytest.MonkeyPatch) -> None: create_session_mock = MagicMock() monkeypatch.setattr(summary_module, "session_factory", SimpleNamespace(create_session=create_session_mock)) diff --git a/api/tests/unit_tests/services/test_tool_file_download_service.py b/api/tests/unit_tests/services/test_tool_file_download_service.py new file mode 100644 index 00000000000..43f6110e769 --- /dev/null +++ b/api/tests/unit_tests/services/test_tool_file_download_service.py @@ -0,0 +1,94 @@ +from collections.abc import Iterator +from unittest.mock import Mock, patch + +import pytest + +from graphon.file import File, FileTransferMethod, FileType +from services.tool_file_download_service import ( + ToolFileDownload, + ToolFileDownloadAccessDeniedError, + ToolFileDownloadNotFoundError, + ToolFileDownloadService, + ToolFileDownloadSource, +) + + +def _file() -> File: + return File( + file_id="file-id", + tenant_id="tenant-id", + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.TOOL_FILE, + related_id="file-id", + filename="tool.txt", + extension=".txt", + mime_type="text/plain", + size=12, + storage_key="tools/tenant-id/file.txt", + ) + + +@pytest.fixture +def tool_files() -> Mock: + return Mock(spec=ToolFileDownloadSource) + + +@pytest.fixture +def service(tool_files: Mock) -> ToolFileDownloadService: + return ToolFileDownloadService(tool_files=tool_files) + + +def test_invalid_signature_does_not_load_file(service: ToolFileDownloadService, tool_files: Mock) -> None: + with patch("services.tool_file_download_service.verify_tool_file_signature", return_value=False) as verify: + with pytest.raises(ToolFileDownloadAccessDeniedError): + service.get_signed_file(file_id="file-id", timestamp="1", nonce="nonce", sign="invalid") + + verify.assert_called_once_with(file_id="file-id", timestamp="1", nonce="nonce", sign="invalid") + tool_files.get_file_generator_by_tool_file_id.assert_not_called() + + +def test_missing_file_is_reported_after_signature_validation( + service: ToolFileDownloadService, + tool_files: Mock, +) -> None: + tool_files.get_file_generator_by_tool_file_id.return_value = (None, None) + + with patch("services.tool_file_download_service.verify_tool_file_signature", return_value=True): + with pytest.raises(ToolFileDownloadNotFoundError): + service.get_signed_file(file_id="missing", timestamp="1", nonce="nonce", sign="valid") + + tool_files.get_file_generator_by_tool_file_id.assert_called_once_with(tool_file_id="missing") + + +def test_signed_file_returns_stream_and_metadata( + service: ToolFileDownloadService, + tool_files: Mock, +) -> None: + stream: Iterator[bytes] = iter([b"a", b"b"]) + tool_files.get_file_generator_by_tool_file_id.return_value = (stream, _file()) + + with patch("services.tool_file_download_service.verify_tool_file_signature", return_value=True): + result = service.get_signed_file(file_id="file-id", timestamp="1", nonce="nonce", sign="valid") + + assert result == ToolFileDownload( + content=stream, + mime_type="text/plain", + filename="tool.txt", + size=12, + ) + tool_files.get_file_generator_by_tool_file_id.assert_called_once_with(tool_file_id="file-id") + + +@pytest.mark.parametrize("source_error", [RuntimeError("database unavailable"), OSError("storage unavailable")]) +def test_source_error_is_not_converted( + service: ToolFileDownloadService, + tool_files: Mock, + source_error: Exception, +) -> None: + tool_files.get_file_generator_by_tool_file_id.side_effect = source_error + + with patch("services.tool_file_download_service.verify_tool_file_signature", return_value=True): + with pytest.raises(type(source_error)) as error_info: + service.get_signed_file(file_id="file-id", timestamp="1", nonce="nonce", sign="valid") + + assert error_info.value is source_error diff --git a/api/tests/unit_tests/services/test_upload_file_delivery_service.py b/api/tests/unit_tests/services/test_upload_file_delivery_service.py new file mode 100644 index 00000000000..b7ec99e508a --- /dev/null +++ b/api/tests/unit_tests/services/test_upload_file_delivery_service.py @@ -0,0 +1,175 @@ +from unittest.mock import Mock, patch + +import pytest + +from services.errors.file import UnsupportedFileTypeError +from services.upload_file_delivery_service import ( + UploadFileDelivery, + UploadFileDeliveryNotFoundError, + UploadFileDeliveryQuery, + UploadFileDeliveryRecord, + UploadFileDeliveryService, + UploadFileStorage, +) + + +def _record(*, extension: str = "png") -> UploadFileDeliveryRecord: + return UploadFileDeliveryRecord( + key="upload_files/tenant-id/file-id", + name=f"file.{extension}", + size=7, + extension=extension, + mime_type="image/png" if extension == "png" else "text/plain", + ) + + +@pytest.fixture +def files() -> Mock: + return Mock(spec=UploadFileDeliveryQuery) + + +@pytest.fixture +def storage() -> Mock: + return Mock(spec=UploadFileStorage) + + +@pytest.fixture +def service(files: Mock, storage: Mock) -> UploadFileDeliveryService: + return UploadFileDeliveryService(files=files, storage=storage) + + +def test_invalid_image_signature_does_not_query_or_load_file( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + with patch("services.upload_file_delivery_service.file_helpers.verify_image_signature", return_value=False): + with pytest.raises(UploadFileDeliveryNotFoundError): + service.get_signed_image_preview(file_id="file-id", timestamp="1", nonce="nonce", sign="invalid") + + files.get_by_id.assert_not_called() + storage.load_stream.assert_not_called() + storage.load_once.assert_not_called() + + +def test_invalid_file_signature_does_not_query_or_load_file( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + with patch("services.upload_file_delivery_service.file_helpers.verify_file_signature", return_value=False): + with pytest.raises(UploadFileDeliveryNotFoundError): + service.get_signed_file_preview(file_id="file-id", timestamp="1", nonce="nonce", sign="invalid") + + files.get_by_id.assert_not_called() + storage.load_stream.assert_not_called() + storage.load_once.assert_not_called() + + +def test_signed_image_preview_loads_image_stream( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + file = _record() + content = iter((b"content",)) + files.get_by_id.return_value = file + storage.load_stream.return_value = content + + with patch("services.upload_file_delivery_service.file_helpers.verify_image_signature", return_value=True): + result = service.get_signed_image_preview(file_id="file-id", timestamp="1", nonce="nonce", sign="valid") + + assert result == UploadFileDelivery(content=content, file=file) + files.get_by_id.assert_called_once_with(file_id="file-id") + storage.load_stream.assert_called_once_with(file.key) + + +def test_signed_image_preview_rejects_non_image_before_loading( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + files.get_by_id.return_value = _record(extension="txt") + + with patch("services.upload_file_delivery_service.file_helpers.verify_image_signature", return_value=True): + with pytest.raises(UnsupportedFileTypeError): + service.get_signed_image_preview(file_id="file-id", timestamp="1", nonce="nonce", sign="valid") + + storage.load_stream.assert_not_called() + + +def test_signed_file_preview_allows_non_image( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + file = _record(extension="txt") + content = iter((b"content",)) + files.get_by_id.return_value = file + storage.load_stream.return_value = content + + with patch("services.upload_file_delivery_service.file_helpers.verify_file_signature", return_value=True): + result = service.get_signed_file_preview(file_id="file-id", timestamp="1", nonce="nonce", sign="valid") + + assert result == UploadFileDelivery(content=content, file=file) + storage.load_stream.assert_called_once_with(file.key) + + +def test_signed_file_preview_reports_missing_file( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + files.get_by_id.return_value = None + + with patch("services.upload_file_delivery_service.file_helpers.verify_file_signature", return_value=True): + with pytest.raises(UploadFileDeliveryNotFoundError): + service.get_signed_file_preview(file_id="missing", timestamp="1", nonce="nonce", sign="valid") + + storage.load_stream.assert_not_called() + + +def test_workspace_logo_loads_content_once( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + file = _record() + files.get_workspace_logo.return_value = file + storage.load_once.return_value = b"content" + + result = service.get_workspace_webapp_logo(workspace_id="workspace-id") + + assert result == UploadFileDelivery(content=b"content", file=file) + files.get_workspace_logo.assert_called_once_with(workspace_id="workspace-id") + storage.load_once.assert_called_once_with(file.key) + storage.load_stream.assert_not_called() + + +def test_workspace_logo_reports_missing_file( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + files.get_workspace_logo.return_value = None + + with pytest.raises(UploadFileDeliveryNotFoundError): + service.get_workspace_webapp_logo(workspace_id="workspace-id") + + storage.load_once.assert_not_called() + + +def test_storage_error_is_not_converted( + service: UploadFileDeliveryService, + files: Mock, + storage: Mock, +) -> None: + storage_error = OSError("storage unavailable") + files.get_by_id.return_value = _record(extension="txt") + storage.load_stream.side_effect = storage_error + + with patch("services.upload_file_delivery_service.file_helpers.verify_file_signature", return_value=True): + with pytest.raises(OSError) as error_info: + service.get_signed_file_preview(file_id="file-id", timestamp="1", nonce="nonce", sign="valid") + + assert error_info.value is storage_error diff --git a/api/tests/unit_tests/services/test_vector_space_admission_service.py b/api/tests/unit_tests/services/test_vector_space_admission_service.py index b29eb45f1be..267d35f7757 100644 --- a/api/tests/unit_tests/services/test_vector_space_admission_service.py +++ b/api/tests/unit_tests/services/test_vector_space_admission_service.py @@ -549,9 +549,22 @@ def test_billing_plan_lookup_excludes_vector_space_and_is_cached() -> None: service = VectorSpaceAdmissionService() with patch( "services.vector_space_admission_service.BillingService.get_info", - return_value={"enabled": True, "subscription": {"plan": "professional"}}, + return_value={"subscription": {"plan": "professional"}}, ) as get_info: assert service._get_plan("tenant-1") == CloudPlan.PROFESSIONAL assert service._get_plan("tenant-1") == CloudPlan.PROFESSIONAL get_info.assert_called_once_with("tenant-1", exclude_vector_space=True) + + +def test_unknown_billing_plan_is_not_logged(caplog: pytest.LogCaptureFixture) -> None: + service = VectorSpaceAdmissionService() + upstream_plan = "unexpected-private-plan" + with patch( + "services.vector_space_admission_service.BillingService.get_info", + return_value={"subscription": {"plan": upstream_plan}}, + ): + assert service._get_plan("tenant-1") is None + + assert "unknown plan tenant_id=tenant-1" in caplog.text + assert upstream_plan not in caplog.text diff --git a/api/tests/unit_tests/services/test_web_app_runtime_query_service.py b/api/tests/unit_tests/services/test_web_app_runtime_query_service.py index 5464c33ec91..487d0f80b67 100644 --- a/api/tests/unit_tests/services/test_web_app_runtime_query_service.py +++ b/api/tests/unit_tests/services/test_web_app_runtime_query_service.py @@ -2,6 +2,7 @@ from unittest.mock import MagicMock, create_autospec import pytest +from enums import DeploymentEdition from services.app_definition_query_service import AppSiteConfiguration from services.entities.feature_entities import FeatureModel from services.file_service import FileService @@ -62,6 +63,7 @@ def _runtime_record( def _service( runtime: MagicMock, *, + deployment_edition: DeploymentEdition = DeploymentEdition.COMMUNITY, file_service: MagicMock | None = None, workspace_features: MagicMock | None = None, ) -> WebAppRuntimeQueryService: @@ -75,6 +77,7 @@ def _service( file_service=file_service, workspace_features=workspace_features, files_url=_FILES_URL, + deployment_edition=deployment_edition, ) @@ -87,13 +90,25 @@ def test_get_bootstrap_rejects_unavailable_runtime(record: WebAppRuntimeRecord | _service(runtime).get_bootstrap("app-1") +@pytest.mark.parametrize( + ("deployment_edition", "copyright_enabled", "expected_copyright", "expected_placeholder"), + [ + (DeploymentEdition.CLOUD, False, None, None), + (DeploymentEdition.CLOUD, True, "Copyright", "Ask anything"), + (DeploymentEdition.COMMUNITY, False, "Copyright", "Ask anything"), + (DeploymentEdition.ENTERPRISE, False, "Copyright", "Ask anything"), + ], +) def test_get_bootstrap_applies_feature_and_branding_policy_after_record_load( workspace_features: MagicMock, + deployment_edition: DeploymentEdition, + copyright_enabled: bool, + expected_copyright: str | None, + expected_placeholder: str | None, ) -> None: runtime: MagicMock = create_autospec(WebAppRuntimeQuery, instance=True, spec_set=True) record = _runtime_record() - features = FeatureModel(can_replace_logo=True, webapp_copyright_enabled=False) - features.billing.enabled = True + features = FeatureModel(can_replace_logo=True, webapp_copyright_enabled=copyright_enabled) events: list[str] = [] runtime.get_runtime_record.side_effect = lambda _app_id: events.append("record") or record workspace_features.side_effect = lambda _tenant_id, **_kwargs: events.append("features") or features @@ -104,6 +119,7 @@ def test_get_bootstrap_applies_feature_and_branding_policy_after_record_load( runtime, file_service=file_service, workspace_features=workspace_features, + deployment_edition=deployment_edition, ).get_bootstrap("app-1") assert result == WebAppBootstrap( @@ -112,8 +128,8 @@ def test_get_bootstrap_applies_feature_and_branding_policy_after_record_load( enable_site=True, site={ **record.site._asdict(), - "copyright": None, - "input_placeholder": None, + "copyright": expected_copyright, + "input_placeholder": expected_placeholder, "icon_url": "https://icon", }, plan="pro", diff --git a/api/tests/unit_tests/services/test_workspace_credit_pool.py b/api/tests/unit_tests/services/test_workspace_credit_pool.py index 8d88bd0b28d..aef101dcdc4 100644 --- a/api/tests/unit_tests/services/test_workspace_credit_pool.py +++ b/api/tests/unit_tests/services/test_workspace_credit_pool.py @@ -27,7 +27,6 @@ def test_get_effective_credit_pool_prefers_available_paid_pool( quota_used=quota_used, ) billing_info = { - "enabled": True, "subscription": {"plan": CloudPlan.TEAM}, "next_credit_reset_date": 1775001600, } @@ -59,7 +58,6 @@ def test_get_effective_credit_pool_exposes_exhausted_trial_pool(unbound_session: exhausted_at=1772323200, ) billing_info = { - "enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}, } config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) diff --git a/api/tests/unit_tests/services/test_workspace_service.py b/api/tests/unit_tests/services/test_workspace_service.py index 9d01cb7b847..3a63cfc985b 100644 --- a/api/tests/unit_tests/services/test_workspace_service.py +++ b/api/tests/unit_tests/services/test_workspace_service.py @@ -19,7 +19,6 @@ def test_get_current_workspace_summary_sandbox_uses_trial_only() -> None: quota_used=20, ) billing_info = { - "enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}, } config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @@ -61,7 +60,6 @@ def test_get_current_workspace_summary_falls_back_from_exhausted_paid_pool() -> quota_used=40, ) billing_info = { - "enabled": True, "subscription": {"plan": CloudPlan.TEAM}, } config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) diff --git a/api/tests/unit_tests/services/tools/test_tools_transform_service.py b/api/tests/unit_tests/services/tools/test_tools_transform_service.py index 04e1651c7e0..5c04ded9d7e 100644 --- a/api/tests/unit_tests/services/tools/test_tools_transform_service.py +++ b/api/tests/unit_tests/services/tools/test_tools_transform_service.py @@ -1,4 +1,4 @@ -from unittest.mock import MagicMock, Mock, patch +from unittest.mock import ANY, MagicMock, Mock, patch from core.tools.__base.tool import Tool from core.tools.entities.api_entities import ToolApiEntity, ToolProviderApiEntity @@ -512,31 +512,39 @@ class TestApiProviderToController: def test_api_key_header_auth(self): db_provider = MagicMock() db_provider.credentials = {"auth_type": "api_key_header"} - with patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: + with patch(f"{MODULE}.db.session"), patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: ctrl_cls.from_db.return_value = MagicMock() ToolTransformService.api_provider_to_controller(db_provider) - ctrl_cls.from_db.assert_called_once_with(db_provider=db_provider, auth_type=ApiProviderAuthType.API_KEY_HEADER) + ctrl_cls.from_db.assert_called_once_with( + db_provider=db_provider, auth_type=ApiProviderAuthType.API_KEY_HEADER, session=ANY + ) def test_api_key_query_auth(self): db_provider = MagicMock() db_provider.credentials = {"auth_type": "api_key_query"} - with patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: + with patch(f"{MODULE}.db.session"), patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: ctrl_cls.from_db.return_value = MagicMock() ToolTransformService.api_provider_to_controller(db_provider) - ctrl_cls.from_db.assert_called_once_with(db_provider=db_provider, auth_type=ApiProviderAuthType.API_KEY_QUERY) + ctrl_cls.from_db.assert_called_once_with( + db_provider=db_provider, auth_type=ApiProviderAuthType.API_KEY_QUERY, session=ANY + ) def test_legacy_api_key_maps_to_header(self): db_provider = MagicMock() db_provider.credentials = {"auth_type": "api_key"} - with patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: + with patch(f"{MODULE}.db.session"), patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: ctrl_cls.from_db.return_value = MagicMock() ToolTransformService.api_provider_to_controller(db_provider) - ctrl_cls.from_db.assert_called_once_with(db_provider=db_provider, auth_type=ApiProviderAuthType.API_KEY_HEADER) + ctrl_cls.from_db.assert_called_once_with( + db_provider=db_provider, auth_type=ApiProviderAuthType.API_KEY_HEADER, session=ANY + ) def test_unknown_auth_defaults_to_none(self): db_provider = MagicMock() db_provider.credentials = {"auth_type": "something_else"} - with patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: + with patch(f"{MODULE}.db.session"), patch(f"{MODULE}.ApiToolProviderController") as ctrl_cls: ctrl_cls.from_db.return_value = MagicMock() ToolTransformService.api_provider_to_controller(db_provider) - ctrl_cls.from_db.assert_called_once_with(db_provider=db_provider, auth_type=ApiProviderAuthType.NONE) + ctrl_cls.from_db.assert_called_once_with( + db_provider=db_provider, auth_type=ApiProviderAuthType.NONE, session=ANY + ) diff --git a/api/tests/unit_tests/tasks/test_dataset_indexing_task.py b/api/tests/unit_tests/tasks/test_dataset_indexing_task.py index e12e8b1b243..7ef6aaac1bf 100644 --- a/api/tests/unit_tests/tasks/test_dataset_indexing_task.py +++ b/api/tests/unit_tests/tasks/test_dataset_indexing_task.py @@ -15,7 +15,7 @@ from sqlalchemy.orm import Session from core.indexing_runner import DocumentIsPausedError from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType -from enums import CloudPlan +from enums import CloudPlan, DeploymentEdition from extensions.ext_redis import redis_client from models.dataset import Dataset, Document from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus @@ -27,7 +27,7 @@ from tasks.document_indexing_task import ( normal_document_indexing_task, priority_document_indexing_task, ) -from tests.unit_tests.config_override import apply_config_overrides +from tests.unit_tests.config_override import apply_config_overrides, config_overrides_context @pytest.fixture @@ -68,13 +68,12 @@ def indexing_runner(monkeypatch: pytest.MonkeyPatch) -> MagicMock: def _features( *, - billing_enabled: bool = False, plan: CloudPlan = CloudPlan.PROFESSIONAL, vector_limit: int = 1000, vector_size: int = 0, ) -> SimpleNamespace: return SimpleNamespace( - billing=SimpleNamespace(enabled=billing_enabled, subscription=SimpleNamespace(plan=plan)), + billing=SimpleNamespace(subscription=SimpleNamespace(plan=plan)), vector_space=SimpleNamespace(limit=vector_limit, size=vector_size), ) @@ -137,6 +136,7 @@ def _persisted_documents(session: Session, document_ids: list[str]) -> list[Docu class TestTaskEnqueuing: + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_self_hosted_dispatches_directly_to_priority_task( self, tenant_id: str, dataset_id: str, document_ids: list[str], mock_redis: MagicMock ) -> None: @@ -144,7 +144,6 @@ class TestTaskEnqueuing: patch.object(DocumentIndexingTaskProxy, "features") as features, patch.object(DocumentIndexingTaskProxy, "PRIORITY_TASK_FUNC", Mock()) as task, ): - features.billing.enabled = False DocumentIndexingTaskProxy(tenant_id, dataset_id, document_ids).delay() task.delay.assert_called_once_with( @@ -153,6 +152,7 @@ class TestTaskEnqueuing: document_ids=document_ids, ) + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @pytest.mark.parametrize( ("plan", "task_attribute"), [ @@ -173,13 +173,13 @@ class TestTaskEnqueuing: patch.object(DocumentIndexingTaskProxy, "features") as features, patch.object(DocumentIndexingTaskProxy, task_attribute, Mock()) as task, ): - features.billing.enabled = True features.billing.subscription.plan = plan DocumentIndexingTaskProxy(tenant_id, dataset_id, document_ids).delay() mock_redis.setex.assert_called() task.delay.assert_called_once() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) def test_running_tenant_task_queues_followup_work( self, tenant_id: str, dataset_id: str, document_ids: list[str], mock_redis: MagicMock ) -> None: @@ -188,7 +188,6 @@ class TestTaskEnqueuing: patch.object(DocumentIndexingTaskProxy, "features") as features, patch.object(DocumentIndexingTaskProxy, "PRIORITY_TASK_FUNC", Mock()) as task, ): - features.billing.enabled = True features.billing.subscription.plan = CloudPlan.PROFESSIONAL DocumentIndexingTaskProxy(tenant_id, dataset_id, document_ids).delay() @@ -285,12 +284,13 @@ class TestDocumentIndexing: get_features.assert_not_called() runner_class.assert_not_called() + @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD) @pytest.mark.parametrize( ("features", "batch_limit", "message"), [ - (_features(billing_enabled=True), 1, "batch upload limit"), - (_features(billing_enabled=True, plan=CloudPlan.SANDBOX), 100, "does not support batch upload"), - (_features(billing_enabled=True, vector_limit=100, vector_size=100), 100, "over the limit"), + (_features(), 1, "batch upload limit"), + (_features(plan=CloudPlan.SANDBOX), 100, "does not support batch upload"), + (_features(vector_limit=100, vector_size=100), 100, "over the limit"), ], ) def test_validation_failure_marks_every_scoped_document_error( diff --git a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py index be96c1d6285..b9d96fc01db 100644 --- a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py +++ b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py @@ -51,6 +51,49 @@ def test_initialize_created_app_rbac_access_task_batches_workspace_members(monke assert call.kwargs["payload"].access_policy_ids == [task_module.APP_RBAC_DEFAULT_ACCESS_POLICY_ID] +@pytest.mark.parametrize( + ("id_kwarg", "resource_id", "access_class"), + [ + ("app_id", "app-1", "AppAccess"), + ("dataset_id", "dataset-1", "DatasetAccess"), + ("agent_id", "agent-1", "AgentAccess"), + ], +) +def test_initialize_created_app_rbac_access_task_targets_the_resource_that_was_passed( + monkeypatch: pytest.MonkeyPatch, id_kwarg: str, resource_id: str, access_class: str +): + import tasks.initialize_created_app_rbac_access_task as task_module + + apply_config_overrides(monkeypatch, RBAC_ENABLED=True) + monkeypatch.setattr( + task_module.TenantService, + "iter_member_account_id_batches", + lambda tenant_id, batch_size, session: iter([["acct-1"]]), + ) + rbac_service = task_module.enterprise_rbac_service.RBACService + access_clients = { + "AppAccess": rbac_service.AppAccess, + "DatasetAccess": rbac_service.DatasetAccess, + "AgentAccess": rbac_service.AgentAccess, + } + replace_calls = {} + for name, client in access_clients.items(): + replace_calls[name] = MagicMock() + monkeypatch.setattr(client, "replace_user_access_policies", replace_calls[name]) + + initialize_created_app_rbac_access_task.run("tenant-1", "actor-1", **{id_kwarg: resource_id}) + + for name, mock in replace_calls.items(): + if name != access_class: + mock.assert_not_called() + + called = replace_calls[access_class] + called.assert_called_once() + assert called.call_args.kwargs[id_kwarg] == resource_id + assert called.call_args.kwargs["target_account_id"] is None + assert called.call_args.kwargs["payload"].account_ids == ["acct-1"] + + def test_initialize_created_app_rbac_access_task_retries_on_failure(monkeypatch: pytest.MonkeyPatch): import tasks.initialize_created_app_rbac_access_task as task_module from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task @@ -87,6 +130,8 @@ def test_sync_joined_workspace_member_rbac_access_task_appends_auto_included_res rbac.ResourceWhitelistConfigResource(resource_type=rbac.RBACResourceType.APP, resource_id="app-1"), rbac.ResourceWhitelistConfigResource(resource_type=rbac.RBACResourceType.DATASET, resource_id="dataset-1"), rbac.ResourceWhitelistConfigResource(resource_type=rbac.RBACResourceType.APP, resource_id="app-2"), + rbac.ResourceWhitelistConfigResource(resource_type=rbac.RBACResourceType.AGENT, resource_id="agent-1"), + rbac.ResourceWhitelistConfigResource(resource_type=rbac.RBACResourceType.AGENT, resource_id="agent-2"), ] configs = rbac.ResourceWhitelistConfigsResponse( data=[ @@ -105,17 +150,29 @@ def test_sync_joined_workspace_member_rbac_access_task_appends_auto_included_res resource_id="app-2", automatic_include_workspace_members=False, ), + rbac.ResourceWhitelistConfigItem( + resource_type=rbac.RBACResourceType.AGENT, + resource_id="agent-1", + automatic_include_workspace_members=True, + ), + rbac.ResourceWhitelistConfigItem( + resource_type=rbac.RBACResourceType.AGENT, + resource_id="agent-2", + automatic_include_workspace_members=False, + ), ] ) batch_get = MagicMock(return_value=configs) app_append = MagicMock() dataset_append = MagicMock() + agent_append = MagicMock() apply_config_overrides(monkeypatch, RBAC_ENABLED=True) monkeypatch.setattr(task_module, "_iter_resource_config_batches", lambda tenant_id, batch_size: iter([resources])) monkeypatch.setattr(rbac.RBACService.ResourceWhitelistConfigs, "batch_get", batch_get) monkeypatch.setattr(rbac.RBACService.AppAccess, "append_whitelist_members_batch", app_append) monkeypatch.setattr(rbac.RBACService.DatasetAccess, "append_whitelist_members_batch", dataset_append) + monkeypatch.setattr(rbac.RBACService.AgentAccess, "append_whitelist_members_batch", agent_append) sync_joined_workspace_member_rbac_access_task.run("tenant-1", "member-1", "actor-1") @@ -141,3 +198,11 @@ def test_sync_joined_workspace_member_rbac_access_task_appends_auto_included_res assert dataset_call["data"][0].dataset_id == "dataset-1" assert dataset_call["data"][0].account_ids == ["member-1"] assert dataset_call["data"][0].policy_id == task_module.APP_RBAC_DEFAULT_ACCESS_POLICY_ID + + agent_append.assert_called_once() + agent_call = agent_append.call_args.kwargs + assert agent_call["tenant_id"] == "tenant-1" + assert agent_call["account_id"] == "actor-1" + assert [item.agent_id for item in agent_call["data"]] == ["agent-1"] + assert agent_call["data"][0].account_ids == ["member-1"] + assert agent_call["data"][0].policy_id == task_module.APP_RBAC_DEFAULT_ACCESS_POLICY_ID diff --git a/api/tests/unit_tests/tasks/test_retry_document_indexing_task.py b/api/tests/unit_tests/tasks/test_retry_document_indexing_task.py index e5e1961112d..47d02381da9 100644 --- a/api/tests/unit_tests/tasks/test_retry_document_indexing_task.py +++ b/api/tests/unit_tests/tasks/test_retry_document_indexing_task.py @@ -4,13 +4,16 @@ from uuid import uuid4 from sqlalchemy.orm import Session from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType +from enums import DeploymentEdition from models import Account, Tenant, TenantAccountJoin from models.account import TenantAccountRole from models.dataset import Dataset, Document from models.enums import DatasetRuntimeMode, DataSourceType, DocumentCreatedFrom, IndexingStatus from tasks.retry_document_indexing_task import retry_document_indexing_task +from tests.unit_tests.config_override import config_overrides_context +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_retry_enforces_vector_space_admission(sqlite_session: Session) -> None: tenant = Tenant(name="Retry tenant") user = Account(name="Retry user", email=f"retry-{uuid4()}@example.com") @@ -49,7 +52,6 @@ def test_retry_enforces_vector_space_admission(sqlite_session: Session) -> None: sqlite_session.add_all([tenant, user, membership, dataset, document]) sqlite_session.commit() features = MagicMock() - features.billing.enabled = False with ( patch("tasks.retry_document_indexing_task.FeatureService.get_features", return_value=features), diff --git a/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py b/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py index b5f88f1a706..041e9ba55e5 100644 --- a/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py +++ b/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py @@ -5,9 +5,11 @@ from sqlalchemy import select from sqlalchemy.orm import Session from core.rag.index_processor.constant.index_type import IndexStructureType +from enums import DeploymentEdition from models.dataset import Dataset, Document, DocumentSegment from models.enums import DataSourceType, DocumentCreatedFrom from tasks.sync_website_document_indexing_task import sync_website_document_indexing_task +from tests.unit_tests.config_override import config_overrides_context def _dataset(tenant_id: str) -> Dataset: @@ -66,6 +68,7 @@ def test_rejects_document_outside_dataset_before_side_effects(sqlite_session: Se processor_factory.assert_not_called() +@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY) def test_cleanup_is_owner_scoped_and_skips_empty_vector_ids(sqlite_session: Session) -> None: tenant_id = str(uuid.uuid4()) dataset = _dataset(tenant_id) @@ -83,7 +86,6 @@ def test_cleanup_is_owner_scoped_and_skips_empty_vector_ids(sqlite_session: Sess sqlite_session.commit() features = MagicMock() - features.billing.enabled = False with ( patch("tasks.sync_website_document_indexing_task.FeatureService.get_features", return_value=features), patch("tasks.sync_website_document_indexing_task.IndexProcessorFactory") as processor_factory, diff --git a/api/uv.lock b/api/uv.lock index ffb54ba5bc8..73c9585efc5 100644 --- a/api/uv.lock +++ b/api/uv.lock @@ -374,6 +374,50 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/91/be/317c2c55b8bbec407257d45f5c8d1b6867abc76d12043f2d3d58c538a4ea/asgiref-3.11.0-py3-none-any.whl", hash = "sha256:1db9021efadb0d9512ce8ffaf72fcef601c7b73a8807a1bb2ef143dc6b14846d", size = 24096, upload-time = "2025-11-19T15:32:19.004Z" }, ] +[[package]] +name = "ast-serialize" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/c0/5bb6885a9608d86ee5712c0d88bc405d3a49f3e44231576e130ea2f53d34/ast_serialize-0.9.0.tar.gz", hash = "sha256:79fe8be1c934aa572940d1811d8dbe4d1b6f22291e3f16755c9b062e9ac92fb7", size = 951293, upload-time = "2026-09-02T15:50:45.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/f9/a4af1bf8b35927814c09d90c3965dbfaa75c489ba34372bffafbc2209f40/ast_serialize-0.9.0-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:383f56e3ae925f154632458f01b4bfcde3dd382f3ec04f5c7f6d72f76524ff48", size = 1226344, upload-time = "2026-09-02T15:49:49.79Z" }, + { url = "https://files.pythonhosted.org/packages/1d/6d/d3a95823a803c21f5c9df595a0bb93aada22e7aa22bf875fe00d89422d7f/ast_serialize-0.9.0-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:b9ef3d4173907bd19aa8f1683be9f06e7862e6cdf2ca6bca3633305c0df32063", size = 1207384, upload-time = "2026-09-02T15:49:51.22Z" }, + { url = "https://files.pythonhosted.org/packages/f0/97/6e7f46c8455b738609c29d1b7655307a168c4b40ce4c7a2c678c8ed9cf2e/ast_serialize-0.9.0-cp315-abi3.abi3t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9482672ca8ec09f85cd050a053fb88c30c882c8e20ce7a140d8defe19c0ef2eb", size = 1273139, upload-time = "2026-09-02T15:49:52.679Z" }, + { url = "https://files.pythonhosted.org/packages/f0/6e/25b70733f061766865cb04d913dc5332037c595796b871d52ab5b569abb8/ast_serialize-0.9.0-cp315-abi3.abi3t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a6a568d1d489f0669a31aed90ca4845aa7f08e1b8cd5d05e1905dbdc3ae9b2b0", size = 1278242, upload-time = "2026-09-02T15:49:54.236Z" }, + { url = "https://files.pythonhosted.org/packages/9a/f0/b7820399d9c5a0b7f07c239b6da93d2e21a1b3785137fa00e16528e414b3/ast_serialize-0.9.0-cp315-abi3.abi3t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5a4dd005d4095a13eb312dc712c943c7730f262b000a87df963925328a38ffdb", size = 1541009, upload-time = "2026-09-02T15:49:56.149Z" }, + { url = "https://files.pythonhosted.org/packages/08/56/5146f1d2a77516e697f6f42825df79137e43560675cb4605c467775f8b4a/ast_serialize-0.9.0-cp315-abi3.abi3t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:207ac73afa1f4654840593853c130eac2591dd942434176eea33f730afb3359b", size = 1290898, upload-time = "2026-09-02T15:49:57.502Z" }, + { url = "https://files.pythonhosted.org/packages/69/c4/87cd16228796d703de795a369b90b0f57f0f017f90f55c4c5876e3513a03/ast_serialize-0.9.0-cp315-abi3.abi3t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9ae01129e2cc5d57a3c434d8a990019de039350310a2e1dd3c9f61311964cf25", size = 1291742, upload-time = "2026-09-02T15:49:58.982Z" }, + { url = "https://files.pythonhosted.org/packages/cc/eb/13465c297268c5170b2bb746d75f37a8fad44a94a89b593071affc1071d0/ast_serialize-0.9.0-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:4c522377f383670abfe21c94edc3032cb3bd34d8fcacd280fa9556907d4edd4b", size = 1300180, upload-time = "2026-09-02T15:50:00.454Z" }, + { url = "https://files.pythonhosted.org/packages/0a/a7/10b84c4274b2507b0ed9cc1654058ad64bcedb6ac574753d6a461bc6e204/ast_serialize-0.9.0-cp315-abi3.abi3t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4cd886f6e900f5e13f758cb8ef359652e690e4f3f9c257a7269e095940534167", size = 1345857, upload-time = "2026-09-02T15:50:01.875Z" }, + { url = "https://files.pythonhosted.org/packages/c7/dc/2702182c9773a15de9aabfaf66da7cb87548a56a6bac24f0c9176a4a13c3/ast_serialize-0.9.0-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:f3f0f3359cf0f22bf096b07021ffe6bf0ec88ac8a2cf7ce5f4701af973112faa", size = 1448544, upload-time = "2026-09-02T15:50:03.496Z" }, + { url = "https://files.pythonhosted.org/packages/59/b5/eeef2124c9563b9861707ef4db91f153f3bb37b3e0cca9543bb88a4e9e53/ast_serialize-0.9.0-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:6c428444656cffbd32c1e76626c6eec5237b58c8fcb0b5d3df75941cd50c4f3c", size = 1551572, upload-time = "2026-09-02T15:50:04.982Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8c/81d18349f1dffdcfeb80671bd737e342c86348e183692d9d0d8f573d1385/ast_serialize-0.9.0-cp315-abi3.abi3t-musllinux_1_2_i686.whl", hash = "sha256:54f0babed5e2a4eb86a0716ac612aff33f933e7572e5bc067adcdbe672a26321", size = 1548118, upload-time = "2026-09-02T15:50:06.522Z" }, + { url = "https://files.pythonhosted.org/packages/d4/1f/339131b60d1b0df13d9f3470cfac70f858b5649188ea01b2e7b39caeb720/ast_serialize-0.9.0-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:1b779fdaee34d19900a5ba5fd6bd4cefe225650081f9de28de256eacee5113c2", size = 1674707, upload-time = "2026-09-02T15:50:07.919Z" }, + { url = "https://files.pythonhosted.org/packages/18/0a/ca77596fa229d88f96eca180d45dbe8efa11306f8b2b4f4ee301b3fe465f/ast_serialize-0.9.0-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:4db7f524eaa857fbe650cac33b9cedb5ccda14393d40f640b75dfb06aa13c98c", size = 1473618, upload-time = "2026-09-02T15:50:09.312Z" }, + { url = "https://files.pythonhosted.org/packages/88/5c/6aebeb54dd226b480014ff4488e150aa23b1de3204e2bf3f87de27e6542a/ast_serialize-0.9.0-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:d2a37795a90809da6094825e7063118b4cf723b8701b134973b4566ed8b9ea09", size = 1492025, upload-time = "2026-09-02T15:50:10.755Z" }, + { url = "https://files.pythonhosted.org/packages/75/e6/c355d470a230f778311c28b80f6d934a497d094139f07230433eea18651b/ast_serialize-0.9.0-cp315-abi3.abi3t-win32.whl", hash = "sha256:4411d1cba9eeecb301365343a7e96813b4a44fcdb20181557867ff7e751804cf", size = 1113010, upload-time = "2026-09-02T15:50:12.337Z" }, + { url = "https://files.pythonhosted.org/packages/fe/0d/66609ace58564727b68731293cc986c2ea1d5e6ef40e96571e7fb515f0af/ast_serialize-0.9.0-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:b5c3724faf780e25def89c369eb6340a15dff06ac348160c61781e2373a4cd10", size = 1146404, upload-time = "2026-09-02T15:50:13.761Z" }, + { url = "https://files.pythonhosted.org/packages/b1/fd/da28e1c85f05fb9976f247d2a3aefce68866cb2939abcbdbddd9a5e3b835/ast_serialize-0.9.0-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:1de0933a4c1d104d77d6e75f053f5e628b54cf8f9fea809b8250cb04cda07bd3", size = 1118328, upload-time = "2026-09-02T15:50:15.214Z" }, + { url = "https://files.pythonhosted.org/packages/92/e4/175b0a64d6c96bc1b96598c6474ce8d1ef34e0b774bcf7183f4ce696fb10/ast_serialize-0.9.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:dac690f99538d9df0d23ce0299e946add2744b007a36b480a292fe361c82553d", size = 1232635, upload-time = "2026-09-02T15:50:18.133Z" }, + { url = "https://files.pythonhosted.org/packages/28/0c/d51d8463aca43aaa833fdf1f25134d6cc1b483764896decca61306ad1f6e/ast_serialize-0.9.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:2223ead73b5a5399d39610cf9c4164ad0b2bf2025226626b87ae15226d93d3f7", size = 1219313, upload-time = "2026-09-02T15:50:19.497Z" }, + { url = "https://files.pythonhosted.org/packages/ef/19/c88bdc64f86095a9d6ab325ae422b2a5e1395cd63cd8aa539003d4d4ae1d/ast_serialize-0.9.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b7c5f5838408fb000d76abd14e886836412b7ec7eccd028dbb5ed5819780008", size = 1279981, upload-time = "2026-09-02T15:50:20.811Z" }, + { url = "https://files.pythonhosted.org/packages/86/58/a492075826df1753896dc8e8f6ababae4016d8883b670ee3a1c34788b154/ast_serialize-0.9.0-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1e05701fde79affa1cc53e391867f9da3eb03fa8501f87354292796b0f8398fd", size = 1286319, upload-time = "2026-09-02T15:50:22.203Z" }, + { url = "https://files.pythonhosted.org/packages/ae/79/3f6754eaa42fd2a6c36aac066890870cd44cbe0e25f75a67b1b99a2f4d82/ast_serialize-0.9.0-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d013c36eb2f2ac0cb7d4d0e79918a92ab00fbce8f1542fe47f34a46e06168f82", size = 1551547, upload-time = "2026-09-02T15:50:23.528Z" }, + { url = "https://files.pythonhosted.org/packages/b1/05/8cfb7caadfaf28febaa6b61d31d778262f87f9366eda4dd9bd07ac940b75/ast_serialize-0.9.0-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:19cde5c2110f7b90ab1210a599178524f6c9f34862b20ba2b9aa7832c67bb35d", size = 1302468, upload-time = "2026-09-02T15:50:24.99Z" }, + { url = "https://files.pythonhosted.org/packages/aa/e2/750a0b136bb02ff8e4a17d65a3a78cd478ee50724704df8215797a226ba3/ast_serialize-0.9.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1514f4a39704e2e815f9fc675fc13f19f694f212086b520110840782cf3c5295", size = 1300563, upload-time = "2026-09-02T15:50:26.354Z" }, + { url = "https://files.pythonhosted.org/packages/ab/17/4c0aa852ff1e4f2d6723e8ce827136c1e1febf2845d7941ccc45426778de/ast_serialize-0.9.0-cp39-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:30651ccdec6d23c49ee4711b1a1096d8dbd3be38eecf2f09fdd98a608ce7ac24", size = 1308999, upload-time = "2026-09-02T15:50:27.901Z" }, + { url = "https://files.pythonhosted.org/packages/4d/1b/6e73d0a29aedb0db30cc68f2557acaac06cd24c9783ccb90f84f89e4ce87/ast_serialize-0.9.0-cp39-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d9a46caf5e3f2cd266e8638b2f4ea8bf54cf376f015f8418397b4633fdb38e9b", size = 1358191, upload-time = "2026-09-02T15:50:29.237Z" }, + { url = "https://files.pythonhosted.org/packages/dc/38/2cf5d552de99e0e9804a16fea73e54d0a7382498adddf57c0f6dc09cbc70/ast_serialize-0.9.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:aed6e413c6c22a23c33c47a01dd2adce01d7a7ed408748e896903f47d0a1aa47", size = 1458944, upload-time = "2026-09-02T15:50:30.77Z" }, + { url = "https://files.pythonhosted.org/packages/4b/0b/5ef87adf955b6a027f616eb7b55f55a154c35ba600e9dd2d06ad2d30e5c2/ast_serialize-0.9.0-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:871fb7c5b049897ee137b67efad7fe4545ad270f7eccd970da877833f8e63aa7", size = 1563421, upload-time = "2026-09-02T15:50:32.188Z" }, + { url = "https://files.pythonhosted.org/packages/81/dd/9ced05a17feeb0f83e84010d80f5a1b7b7aa19e75f0376f4d3780803654c/ast_serialize-0.9.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:bb378efb5537b43f38660e2e6d6e138a40885cf191d43443bb3ff7ff47e9cd9b", size = 1558536, upload-time = "2026-09-02T15:50:33.861Z" }, + { url = "https://files.pythonhosted.org/packages/5f/8b/8ad486e44fc7081a2471055befc433dddc2e51c3a88dff141b3026f64602/ast_serialize-0.9.0-cp39-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:b373beff65b01fcffca5aaad3269ae629f3a998b09efdd3635e48039008a5dec", size = 1682749, upload-time = "2026-09-02T15:50:35.257Z" }, + { url = "https://files.pythonhosted.org/packages/dd/4c/7c282aba9cfb0b92d79fac45c04e4557d9a7f08d872e5a43577a50867e30/ast_serialize-0.9.0-cp39-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:25c8d517c45cf2b1820fc2af6ac593783654818f79d05646d25d624360678a4e", size = 1482441, upload-time = "2026-09-02T15:50:37.319Z" }, + { url = "https://files.pythonhosted.org/packages/a4/3a/e45914e8cad81b660915f3784d255460a6384183b76bfc2089fdd79ec7df/ast_serialize-0.9.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1675dc46578298ae00936164a160997801a6ca2385913150d8d16df634296cf3", size = 1499042, upload-time = "2026-09-02T15:50:38.76Z" }, + { url = "https://files.pythonhosted.org/packages/99/09/6988921dec19c810beef53539fec2e90ae551cd93853b3303a99fe45f772/ast_serialize-0.9.0-cp39-abi3-win32.whl", hash = "sha256:20fce3885eeff05a3d6afefa845c8168016e3ea1f6fc9cdc84c8db28b863a550", size = 1116391, upload-time = "2026-09-02T15:50:40.229Z" }, + { url = "https://files.pythonhosted.org/packages/fd/eb/839598a22a1f9af56d39e188451cad93dbcb0ce6539a45ac18fb8bf123fa/ast_serialize-0.9.0-cp39-abi3-win_amd64.whl", hash = "sha256:161914666a21d48b681982146ac0fa4086ef099d91c637cf595387f5f06aa099", size = 1156055, upload-time = "2026-09-02T15:50:42.05Z" }, + { url = "https://files.pythonhosted.org/packages/0d/45/c7cd8d36d3b506bbd02db5066fae3340284781168f0d08dac25deef5f69d/ast_serialize-0.9.0-cp39-abi3-win_arm64.whl", hash = "sha256:74473258a5c55855d5306c864a5c799fbff03a0f0ea1197346b2b5cc5b4ea48a", size = 1128237, upload-time = "2026-09-02T15:50:43.496Z" }, +] + [[package]] name = "attrs" version = "25.4.0" @@ -627,15 +671,15 @@ wheels = [ [[package]] name = "boto3-stubs" -version = "1.43.10" +version = "1.43.88" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "botocore-stubs" }, { name = "types-s3transfer" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0a/67/969b5bc0581ef6f22b2371bdc33d66a50fe907993e0528cb34a7f3fa59f7/boto3_stubs-1.43.10.tar.gz", hash = "sha256:05575658b827e7a12a45629e1a987317e1e679dccabe5ebde5a2101528c76cf8", size = 102665, upload-time = "2026-05-18T20:47:00.528Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/c8/1870e13be5528f80ec80e1b0db4c97fb13d144a7ddf152efa8e3fe4d68e4/boto3_stubs-1.43.88.tar.gz", hash = "sha256:619e49bf83d3841ec1b8b0f955568c4b53dffce58ab80d3c4038d8cbf2d79029", size = 104602, upload-time = "2026-09-03T19:52:13.735Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2b/42/90eb347eda878b15def1f0bb0971779b1829a0fc6b9c0fe3ff823de09833/boto3_stubs-1.43.10-py3-none-any.whl", hash = "sha256:0ce5dec421a45ef1b8ddd32e68d0b8bb78ea7447c5ddf8231420ccaa6e71e0f5", size = 70667, upload-time = "2026-05-18T20:46:54.359Z" }, + { url = "https://files.pythonhosted.org/packages/15/df/8af1c1f4f39361e6a937e10d911622712b6ecaf2f77e4ad9753b17ddf348/boto3_stubs-1.43.88-py3-none-any.whl", hash = "sha256:d1966ef6c45cb1d93765c1f42fe5cc2e6d7de1e64814087a8148a8cafff8d51f", size = 71512, upload-time = "2026-09-03T19:52:10.577Z" }, ] [package.optional-dependencies] @@ -1100,26 +1144,26 @@ wheels = [ [[package]] name = "coverage" -version = "7.13.5" +version = "7.16.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9d/e0/70553e3000e345daff267cec284ce4cbf3fc141b6da229ac52775b5428f1/coverage-7.13.5.tar.gz", hash = "sha256:c81f6515c4c40141f83f502b07bbfa5c240ba25bbe73da7b33f1e5b6120ff179", size = 915967, upload-time = "2026-03-17T10:33:18.341Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d1/f5/deb1a27aa20746c0278ac998c4179e272004699b2d33959ce020c5ac1615/coverage-7.16.0.tar.gz", hash = "sha256:077f0964087883176ff6ab9b074694cae29f8c708273b13ca62c183c6ed716cd", size = 945620, upload-time = "2026-08-28T21:54:37.74Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/c3/a396306ba7db865bf96fc1fb3b7fd29bcbf3d829df642e77b13555163cd6/coverage-7.13.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:460cf0114c5016fa841214ff5564aa4864f11948da9440bc97e21ad1f4ba1e01", size = 219554, upload-time = "2026-03-17T10:30:42.208Z" }, - { url = "https://files.pythonhosted.org/packages/a6/16/a68a19e5384e93f811dccc51034b1fd0b865841c390e3c931dcc4699e035/coverage-7.13.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0e223ce4b4ed47f065bfb123687686512e37629be25cc63728557ae7db261422", size = 219908, upload-time = "2026-03-17T10:30:43.906Z" }, - { url = "https://files.pythonhosted.org/packages/29/72/20b917c6793af3a5ceb7fb9c50033f3ec7865f2911a1416b34a7cfa0813b/coverage-7.13.5-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:6e3370441f4513c6252bf042b9c36d22491142385049243253c7e48398a15a9f", size = 251419, upload-time = "2026-03-17T10:30:45.545Z" }, - { url = "https://files.pythonhosted.org/packages/8c/49/cd14b789536ac6a4778c453c6a2338bc0a2fb60c5a5a41b4008328b9acc1/coverage-7.13.5-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:03ccc709a17a1de074fb1d11f217342fb0d2b1582ed544f554fc9fc3f07e95f5", size = 254159, upload-time = "2026-03-17T10:30:47.204Z" }, - { url = "https://files.pythonhosted.org/packages/9d/00/7b0edcfe64e2ed4c0340dac14a52ad0f4c9bd0b8b5e531af7d55b703db7c/coverage-7.13.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3f4818d065964db3c1c66dc0fbdac5ac692ecbc875555e13374fdbe7eedb4376", size = 255270, upload-time = "2026-03-17T10:30:48.812Z" }, - { url = "https://files.pythonhosted.org/packages/93/89/7ffc4ba0f5d0a55c1e84ea7cee39c9fc06af7b170513d83fbf3bbefce280/coverage-7.13.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:012d5319e66e9d5a218834642d6c35d265515a62f01157a45bcc036ecf947256", size = 257538, upload-time = "2026-03-17T10:30:50.77Z" }, - { url = "https://files.pythonhosted.org/packages/81/bd/73ddf85f93f7e6fa83e77ccecb6162d9415c79007b4bc124008a4995e4a7/coverage-7.13.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8dd02af98971bdb956363e4827d34425cb3df19ee550ef92855b0acb9c7ce51c", size = 251821, upload-time = "2026-03-17T10:30:52.5Z" }, - { url = "https://files.pythonhosted.org/packages/a0/81/278aff4e8dec4926a0bcb9486320752811f543a3ce5b602cc7a29978d073/coverage-7.13.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f08fd75c50a760c7eb068ae823777268daaf16a80b918fa58eea888f8e3919f5", size = 253191, upload-time = "2026-03-17T10:30:54.543Z" }, - { url = "https://files.pythonhosted.org/packages/70/ee/fe1621488e2e0a58d7e94c4800f0d96f79671553488d401a612bebae324b/coverage-7.13.5-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:843ea8643cf967d1ac7e8ecd4bb00c99135adf4816c0c0593fdcc47b597fcf09", size = 251337, upload-time = "2026-03-17T10:30:56.663Z" }, - { url = "https://files.pythonhosted.org/packages/37/a6/f79fb37aa104b562207cc23cb5711ab6793608e246cae1e93f26b2236ed9/coverage-7.13.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:9d44d7aa963820b1b971dbecd90bfe5fe8f81cff79787eb6cca15750bd2f79b9", size = 255404, upload-time = "2026-03-17T10:30:58.427Z" }, - { url = "https://files.pythonhosted.org/packages/75/f0/ed15262a58ec81ce457ceb717b7f78752a1713556b19081b76e90896e8d4/coverage-7.13.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:7132bed4bd7b836200c591410ae7d97bf7ae8be6fc87d160b2bd881df929e7bf", size = 250903, upload-time = "2026-03-17T10:31:00.093Z" }, - { url = "https://files.pythonhosted.org/packages/0f/e9/9129958f20e7e9d4d56d51d42ccf708d15cac355ff4ac6e736e97a9393d2/coverage-7.13.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a698e363641b98843c517817db75373c83254781426e94ada3197cabbc2c919c", size = 252780, upload-time = "2026-03-17T10:31:01.916Z" }, - { url = "https://files.pythonhosted.org/packages/a4/d7/0ad9b15812d81272db94379fe4c6df8fd17781cc7671fdfa30c76ba5ff7b/coverage-7.13.5-cp312-cp312-win32.whl", hash = "sha256:bdba0a6b8812e8c7df002d908a9a2ea3c36e92611b5708633c50869e6d922fdf", size = 222093, upload-time = "2026-03-17T10:31:03.642Z" }, - { url = "https://files.pythonhosted.org/packages/29/3d/821a9a5799fac2556bcf0bd37a70d1d11fa9e49784b6d22e92e8b2f85f18/coverage-7.13.5-cp312-cp312-win_amd64.whl", hash = "sha256:d2c87e0c473a10bffe991502eac389220533024c8082ec1ce849f4218dded810", size = 222900, upload-time = "2026-03-17T10:31:05.651Z" }, - { url = "https://files.pythonhosted.org/packages/d4/fa/2238c2ad08e35cf4f020ea721f717e09ec3152aea75d191a7faf3ef009a8/coverage-7.13.5-cp312-cp312-win_arm64.whl", hash = "sha256:bf69236a9a81bdca3bff53796237aab096cdbf8d78a66ad61e992d9dac7eb2de", size = 221515, upload-time = "2026-03-17T10:31:07.293Z" }, - { url = "https://files.pythonhosted.org/packages/9e/ee/a4cf96b8ce1e566ed238f0659ac2d3f007ed1d14b181bcb684e19561a69a/coverage-7.13.5-py3-none-any.whl", hash = "sha256:34b02417cf070e173989b3db962f7ed56d2f644307b2cf9d5a0f258e13084a61", size = 211346, upload-time = "2026-03-17T10:33:15.691Z" }, + { url = "https://files.pythonhosted.org/packages/bc/9c/8d2688694f53dc0b0f0e4783c7eb3c4bb1e79beaf1411879f6dabedf4607/coverage-7.16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d1c77c3579ac42798f8b7eed6d3dd258debacca32c8753fc8a1f6eaf1db644f5", size = 223194, upload-time = "2026-08-28T21:51:27.767Z" }, + { url = "https://files.pythonhosted.org/packages/ca/11/f002163dd688aa3fa49ac6a424b7c2705c7fcf80fba18ec9f586d77827ca/coverage-7.16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1f81cb1554c3712e41649ed5dc98656b50b958e4da12f0f5adb681ce3db92831", size = 223553, upload-time = "2026-08-28T21:51:29.46Z" }, + { url = "https://files.pythonhosted.org/packages/81/65/f9d469e97c4554372a710650a109004a2434dfc56f577142e5d6057fa0cc/coverage-7.16.0-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:6e701938ec9081d3e400a0c9a9a8ae0f7ca44214741daeac4454b1c6ef6dbd19", size = 255054, upload-time = "2026-08-28T21:51:31.54Z" }, + { url = "https://files.pythonhosted.org/packages/95/29/dd89fd39af1a3b6e9a9c3eddeaf03f6376ba517d43d6cbf8b519177e2a10/coverage-7.16.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:719a3feb6220dd32ed932d4c3676d17fb8739e2643b29c0e7c3af400ff80ac44", size = 257790, upload-time = "2026-08-28T21:51:33.374Z" }, + { url = "https://files.pythonhosted.org/packages/0a/64/208d26cedc525d6b5db9c492cf9130784c42d9eb08d22badaa7b806005ad/coverage-7.16.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:87771ecf986cff55e87413238cd5e4f54d949c2074bd6fc1657d26a56314ee24", size = 258904, upload-time = "2026-08-28T21:51:35.096Z" }, + { url = "https://files.pythonhosted.org/packages/1f/98/28e2752aa9a8baee5798edade9c95602ca200f4e7eeb503eb64df42e5921/coverage-7.16.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:47d5e1fc0b321c8308a2aacee0497c435b08acaa629b7059798fdf6fc3006352", size = 261165, upload-time = "2026-08-28T21:51:36.744Z" }, + { url = "https://files.pythonhosted.org/packages/eb/77/fa6ae699a0ea2bc12acb38a85d96b786fea0f833c12b5756056350e0e547/coverage-7.16.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:01b18b8a6c9cec8d5f45550e2501426ed982cf2c35016b0acd2ba9b5d8b2fb06", size = 255416, upload-time = "2026-08-28T21:51:38.495Z" }, + { url = "https://files.pythonhosted.org/packages/89/c8/5ee46d1de7d34cb00ba08b5c50da1971114dbc09ca9898ccc32975ec74dd/coverage-7.16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:32c56b5b47c50635081445ac404dd08c2d591b9c837c22570aa9e182c3b42cd4", size = 256825, upload-time = "2026-08-28T21:51:40.27Z" }, + { url = "https://files.pythonhosted.org/packages/15/f6/d59e1c0693ad48855fe20169fbf6ee5befefe5887a7fabf5f0bcb464a2dc/coverage-7.16.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:6ad3bbad240ab937512156bc944fdee63ac4dd34a7558a3094548fd4c1150c02", size = 254970, upload-time = "2026-08-28T21:51:43.136Z" }, + { url = "https://files.pythonhosted.org/packages/df/7b/b51bbe05b3a7565927fccfb1be42b8b3c1f4ab15e53d91b303e9923969aa/coverage-7.16.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4c1f16d5555a195295d0dc9c902612270e3dfed6a11f3bf7bc470b7b6a79ed3c", size = 259039, upload-time = "2026-08-28T21:51:44.983Z" }, + { url = "https://files.pythonhosted.org/packages/fa/04/d513f816456a8a43c1859abe88a37d01d7d2515b6c3e24ebb3c9b1dd44ec/coverage-7.16.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f6c9c21a8bf0d19788f3c5f3e020c90317a0a63ef60521b376003801e21250fb", size = 254539, upload-time = "2026-08-28T21:51:46.733Z" }, + { url = "https://files.pythonhosted.org/packages/dc/54/5542190ceb97e0d1333a4ce0c8f95b2ef2efe790f1ad018a4b61766f849e/coverage-7.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:06f20145a9eb5bf1fd1dde3c0bc2af2e7c22135ab07ca6284d6ada7cc3904c4e", size = 256410, upload-time = "2026-08-28T21:51:48.363Z" }, + { url = "https://files.pythonhosted.org/packages/ee/28/78643f361ff6bb5b2ade90f8bfc8395fe9ca367a18c101f8991215b4c65b/coverage-7.16.0-cp312-cp312-win32.whl", hash = "sha256:916cf8d25c1ce148f7eceb1d45afc9724841200110adc4e53250391852debd91", size = 225239, upload-time = "2026-08-28T21:51:50.22Z" }, + { url = "https://files.pythonhosted.org/packages/67/61/8e76b36c36b1a033dc933dd2480db96b04ce3be975793ce3fad122e7174d/coverage-7.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:78f8b56261d608be102c62edd3a60b66bcd0b581f3f86fdcabaf8b8d95adc950", size = 225775, upload-time = "2026-08-28T21:51:51.912Z" }, + { url = "https://files.pythonhosted.org/packages/c8/f3/bb4787a4b81c1792ca69b502f5f730dbbb609f73fed552ab074c6b92cb8b/coverage-7.16.0-cp312-cp312-win_arm64.whl", hash = "sha256:577c2ac8c0036f6f8edd3a7783a9e67302b17771d1abf0fd2ed246e3158be51b", size = 225159, upload-time = "2026-08-28T21:51:53.667Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5a/234e8fadf85c3cc48cb31c247b9e8e0c7f06ece80f5b29f9b8c241f9da4c/coverage-7.16.0-py3-none-any.whl", hash = "sha256:245f7de6d023a5bba375dbec9f2e0869bfa26ac0cc639bbb7b4c814884000b73", size = 214977, upload-time = "2026-08-28T21:54:35.189Z" }, ] [[package]] @@ -1684,68 +1728,68 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ - { name = "boto3-stubs", specifier = ">=1.43.10" }, + { name = "boto3-stubs", specifier = ">=1.43.88" }, { name = "celery-types", specifier = ">=0.23.0" }, - { name = "coverage", specifier = ">=7.13.4" }, - { name = "dotenv-linter", specifier = ">=0.7.0" }, - { name = "faker", specifier = ">=40.15.0" }, - { name = "hypothesis", specifier = ">=6.152.4" }, - { name = "import-linter", specifier = ">=2.3" }, + { name = "coverage", specifier = ">=7.16.0" }, + { name = "dotenv-linter", specifier = ">=0.9.0" }, + { name = "faker", specifier = ">=40.38.0" }, + { name = "hypothesis", specifier = ">=6.167.1" }, + { name = "import-linter", specifier = ">=2.14" }, { name = "lxml-stubs", specifier = ">=0.5.1" }, - { name = "mypy", specifier = ">=1.20.2" }, - { name = "pandas-stubs", specifier = ">=3.0.0" }, + { name = "mypy", specifier = ">=2.3.1" }, + { name = "pandas-stubs", specifier = ">=3.0.5.260730" }, { name = "pyrefly", specifier = ">=1.2.0" }, - { name = "pytest", specifier = ">=9.0.3" }, - { name = "pytest-benchmark", specifier = ">=5.2.3" }, + { name = "pytest", specifier = ">=9.1.1" }, + { name = "pytest-benchmark", specifier = ">=5.3.0" }, { name = "pytest-cov", specifier = ">=7.1.0" }, - { name = "pytest-env", specifier = ">=1.6.0" }, + { name = "pytest-env", specifier = ">=1.7.0" }, { name = "pytest-mock", specifier = ">=3.15.1" }, { name = "pytest-timeout", specifier = ">=2.4.0" }, { name = "pytest-xdist", specifier = ">=3.8.0" }, - { name = "ruff", specifier = ">=0.15.12" }, - { name = "scipy-stubs", specifier = ">=1.17.1.4" }, + { name = "ruff", specifier = ">=0.16.6" }, + { name = "scipy-stubs", specifier = ">=1.18.1.0" }, { name = "testcontainers", specifier = ">=4.14.2" }, - { name = "types-aiofiles", specifier = ">=25.1.0" }, + { name = "types-aiofiles", specifier = ">=25.1.0.20260518" }, { name = "types-beautifulsoup4", specifier = ">=4.12.0" }, { name = "types-bleach", specifier = ">=6.4.0.20260728" }, - { name = "types-cachetools", specifier = ">=7.0.0.20260503" }, - { name = "types-cffi", specifier = ">=2.0.0.20260429" }, - { name = "types-colorama", specifier = ">=0.4.15" }, + { name = "types-cachetools", specifier = ">=7.0.0.20260713" }, + { name = "types-cffi", specifier = ">=2.1.0.20260827" }, + { name = "types-colorama", specifier = ">=0.4.15.20260508" }, { name = "types-croniter", specifier = ">=6.2.4.20260711" }, - { name = "types-defusedxml", specifier = ">=0.7.0" }, - { name = "types-deprecated", specifier = ">=1.3.1" }, - { name = "types-docutils", specifier = ">=0.22.3" }, - { name = "types-flask-cors", specifier = ">=6.0.0" }, - { name = "types-flask-migrate", specifier = ">=4.1.0" }, - { name = "types-gevent", specifier = ">=26.4.0" }, - { name = "types-greenlet", specifier = ">=3.5.0.20260428" }, - { name = "types-html5lib", specifier = ">=1.1.11" }, - { name = "types-jmespath", specifier = ">=1.1.0.20260408" }, - { name = "types-markdown", specifier = ">=3.10.2" }, - { name = "types-oauthlib", specifier = ">=3.3.0" }, - { name = "types-objgraph", specifier = ">=3.6.0" }, - { name = "types-olefile", specifier = ">=0.47.0" }, - { name = "types-openpyxl", specifier = ">=3.1.5" }, - { name = "types-pexpect", specifier = ">=4.9.0" }, - { name = "types-protobuf", specifier = ">=7.34.1.20260503" }, - { name = "types-psutil", specifier = ">=7.2.2" }, - { name = "types-psycopg2", specifier = ">=2.9.21.20260422" }, - { name = "types-pygments", specifier = ">=2.20.0" }, - { name = "types-pymysql", specifier = ">=1.1.0" }, + { name = "types-defusedxml", specifier = ">=0.7.0.20260504" }, + { name = "types-deprecated", specifier = ">=1.3.1.20260728" }, + { name = "types-docutils", specifier = ">=0.23.0.20260827" }, + { name = "types-flask-cors", specifier = ">=6.0.3.20260712" }, + { name = "types-flask-migrate", specifier = ">=4.1.0.20260508" }, + { name = "types-gevent", specifier = ">=26.8.0.20260811" }, + { name = "types-greenlet", specifier = ">=3.5.0.20260518" }, + { name = "types-html5lib", specifier = ">=1.1.11.20260518" }, + { name = "types-jmespath", specifier = ">=1.1.0.20260724" }, + { name = "types-markdown", specifier = ">=3.10.2.20260712" }, + { name = "types-oauthlib", specifier = ">=3.3.0.20260724" }, + { name = "types-objgraph", specifier = ">=3.6.0.20260508" }, + { name = "types-olefile", specifier = ">=0.47.0.20260508" }, + { name = "types-openpyxl", specifier = ">=3.1.5.20260827" }, + { name = "types-pexpect", specifier = ">=4.9.0.20260518" }, + { name = "types-protobuf", specifier = ">=7.35.1.20260827" }, + { name = "types-psutil", specifier = ">=7.2.2.20260827" }, + { name = "types-psycopg2", specifier = ">=2.9.21.20260724" }, + { name = "types-pygments", specifier = ">=2.21.0.20260819" }, + { name = "types-pymysql", specifier = ">=1.2.0.20260807" }, { name = "types-pyopenssl", specifier = ">=24.1.0" }, - { name = "types-python-dateutil", specifier = ">=2.9.0" }, - { name = "types-python-http-client", specifier = ">=3.3.7.20260408" }, + { name = "types-python-dateutil", specifier = ">=2.9.0.20260807" }, + { name = "types-python-http-client", specifier = ">=3.3.7.20260518" }, { name = "types-pytz", specifier = ">=2026.3.1.20260727" }, - { name = "types-pywin32", specifier = ">=311.0.0" }, - { name = "types-pyyaml", specifier = ">=6.0.12" }, + { name = "types-pywin32", specifier = ">=312.0.0.20260827" }, + { name = "types-pyyaml", specifier = ">=6.0.12.20260815" }, { name = "types-redis", specifier = ">=4.6.0.20241004" }, - { name = "types-regex", specifier = ">=2026.4.4" }, - { name = "types-setuptools", specifier = ">=82.0.0.20260408" }, - { name = "types-shapely", specifier = ">=2.1.0" }, - { name = "types-simplejson", specifier = ">=3.20.0.20260408" }, - { name = "types-six", specifier = ">=1.17.0.20260408" }, - { name = "types-tensorflow", specifier = ">=2.18.0.20260408" }, - { name = "types-tqdm", specifier = ">=4.67.3.20260408" }, + { name = "types-regex", specifier = ">=2026.9.3.20260903" }, + { name = "types-setuptools", specifier = ">=84.0.0.20260812" }, + { name = "types-shapely", specifier = ">=2.1.0.20260728" }, + { name = "types-simplejson", specifier = ">=4.1.0.20260724" }, + { name = "types-six", specifier = ">=1.17.0.20260724" }, + { name = "types-tensorflow", specifier = ">=2.18.0.20260827" }, + { name = "types-tqdm", specifier = ">=4.70.0.20260827" }, { name = "types-ujson", specifier = ">=5.10.0" }, { name = "xinference-client", specifier = ">=2.7.0" }, ] @@ -2326,7 +2370,7 @@ wheels = [ [[package]] name = "dotenv-linter" -version = "0.7.0" +version = "0.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, @@ -2335,9 +2379,9 @@ dependencies = [ { name = "lark" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1e/e5/515ca4e069b70ba0be477ab0a193855c08066f9ef1a9350dcfbdc8f12f87/dotenv_linter-0.7.0.tar.gz", hash = "sha256:24ed93c1028d6305d6787e51773badf3346e53012ad4f5ada9cf747d2da6de13", size = 14033, upload-time = "2025-04-28T17:40:00.771Z" } +sdist = { url = "https://files.pythonhosted.org/packages/22/54/bb420b27c943d2ed2df82a5341a3ad687b029072e150e30efcf97eadbb15/dotenv_linter-0.9.0.tar.gz", hash = "sha256:2adf8f6d1e70cbb6faca2240926960e5cfcc450c3fdb8bd2da345fbc52bcfa8d", size = 16692, upload-time = "2026-07-31T06:41:20.781Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6e/5e/e26881b8d6bd6498c1a7225fba8ead3626a9f4b2d7d29dd272a875753d0d/dotenv_linter-0.7.0-py3-none-any.whl", hash = "sha256:0ffdf0c7435bd638aba5ff6cc9ea53bf093488bf1c722e363e902008659bb1fb", size = 19806, upload-time = "2025-04-28T17:39:58.395Z" }, + { url = "https://files.pythonhosted.org/packages/0c/d7/e1349cd3d04e8eb6392e5122ce85f9795017ff16685de5b0d36b567d459e/dotenv_linter-0.9.0-py3-none-any.whl", hash = "sha256:7e04c9a9d77dc3d36765d8d06d5131eb15f6177640e07ed9bc857262fa2c64e1", size = 24317, upload-time = "2026-07-31T06:41:21.762Z" }, ] [[package]] @@ -2422,14 +2466,14 @@ wheels = [ [[package]] name = "faker" -version = "40.15.0" +version = "40.38.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "tzdata", marker = "sys_platform == 'win32'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/7f/13/6741787bd91c4109c7bed047d68273965cd52ce8a5f773c471b949334b6d/faker-40.15.0.tar.gz", hash = "sha256:20f3a6ec8c266b74d4c554e34118b21c3c2056c0b4a519d15c8decb3a4e6e795", size = 1967447, upload-time = "2026-04-17T20:05:27.555Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f2/55/baeae0ecb04ef56c92d6ac1ef7b3b965af0502ac9863fc85db7afc0884fd/faker-40.38.0.tar.gz", hash = "sha256:72e421098664edf38478f4269a5d5a539337de5da18883ce67cb1e6bb96b0b3a", size = 2029190, upload-time = "2026-09-01T19:19:46.958Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/a7/a600f8f30d4505e89166de51dd121bd540ab8e560e8cf0901de00a81de8c/faker-40.15.0-py3-none-any.whl", hash = "sha256:71ab3c3370da9d2205ab74ffb0fd51273063ad562b3a3bb69d0026a20923e318", size = 2004447, upload-time = "2026-04-17T20:05:25.437Z" }, + { url = "https://files.pythonhosted.org/packages/f1/b8/48cb8733de8448023983f64e81d7f731ce1459c21e93b9b29657e5c48cab/faker-40.38.0-py3-none-any.whl", hash = "sha256:69927515d61759c8a257540b8a91891cd622ba1c24a386b62a0a777e44ba46a9", size = 2065931, upload-time = "2026-09-01T19:19:45.234Z" }, ] [[package]] @@ -3434,14 +3478,52 @@ wheels = [ [[package]] name = "hypothesis" -version = "6.152.4" +version = "6.167.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "sortedcontainers" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fa/c7/3147bd903d6b18324a016d43a259cf5b4bb4545e1ead6773dc8a0374e70a/hypothesis-6.152.4.tar.gz", hash = "sha256:31c8f9ce619716f543e2710b489b1633c833586641d9e6c94cee03f109a5afc4", size = 466444, upload-time = "2026-04-27T20:18:37.594Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c2/c9/8cee74c1390b2932406faaab76980f18946f258fa5a8afca17189b3bc655/hypothesis-6.167.1.tar.gz", hash = "sha256:62eefcb4d2791423626e9901c3027a6e0c5ffda2ac0b44b3c7e797ab9d2d5a4c", size = 505849, upload-time = "2026-08-30T19:53:09.05Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/19/89/0f50dd0d92e8a7dffc24f69ab910ff81db89b2f082ba42682bd57695e4d2/hypothesis-6.152.4-py3-none-any.whl", hash = "sha256:e730fd93c7578182efadc7f90b3c5437ee4d55edf738930eb5043c81ac1d97e8", size = 532145, upload-time = "2026-04-27T20:18:35.043Z" }, + { url = "https://files.pythonhosted.org/packages/53/4d/3592ca336deafbd3e9b0f47dc4c727aa32d30e765ef6370da8ecd590d388/hypothesis-6.167.1-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:d28118fd70e4e15ff9c308a98b312b544b6145ae45aaa3b566328c1fdee8058f", size = 785476, upload-time = "2026-08-30T19:51:02.154Z" }, + { url = "https://files.pythonhosted.org/packages/18/bf/e33c431148994cbcb3332c6df94b833ecfb4aa6a8e51ea4b83da55ddd581/hypothesis-6.167.1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:e517be7f82a0a917758cc489a88b826b5371f56381fd94b4a8a09ce82d8de406", size = 781033, upload-time = "2026-08-30T19:51:27.314Z" }, + { url = "https://files.pythonhosted.org/packages/94/a3/e0de9a82c7e790a1def0801076e0ef43110f98e95ed54a3554877d0cb66d/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:26f8cec74c4fad7aeb0852cb34c2134b16db05d878ad3946a53337dace7016f4", size = 1117814, upload-time = "2026-08-30T19:53:04.109Z" }, + { url = "https://files.pythonhosted.org/packages/71/a4/8dd6bdc909324d1c39da1c86d65f75512ae049c159952af4cfe8feb5f8d4/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fd202d02d129197a5e771f8a11c7d30559927284c23ec3a8bd4f37a7955964d1", size = 1141639, upload-time = "2026-08-30T19:51:50.399Z" }, + { url = "https://files.pythonhosted.org/packages/fa/bd/c13ed6145c360d0770415efd7d5a7e63c29905aeef52ab88004fe7e7f924/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b1e393ab01b71f683ba2a783785871cc6b81a6e41017780c64a5bc0b99759ae", size = 1143334, upload-time = "2026-08-30T19:50:38.045Z" }, + { url = "https://files.pythonhosted.org/packages/c0/a8/060d79ed8504b54ced9ad16f33d674b1b98a9debe9733c02709d7dd5c71c/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8c385c7741893404306f9e5559ab3835432e85e7c153e25f854c502c410bbcbb", size = 1163345, upload-time = "2026-08-30T19:53:06.583Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f7/6e68e2b705f729a6f7b4f41030022b1a5264c5434d3bcd917233d6801c6a/hypothesis-6.167.1-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:94920ca1fae70c26b0bd3fabbeef9437ffc17a39fe85696fb9a86187d92f6dba", size = 1123029, upload-time = "2026-08-30T19:52:03.134Z" }, + { url = "https://files.pythonhosted.org/packages/a5/c0/d274fe37ed5ecd5ad8ed555edc1f5e2abc8e1c3be3d5404b7edd5cc353a8/hypothesis-6.167.1-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b8d90ded2ffdc7e56b5e571993f384b52fade0a7b424e614f999cc2491789970", size = 1154003, upload-time = "2026-08-30T19:50:55.053Z" }, + { url = "https://files.pythonhosted.org/packages/b4/2f/2b5bb386f43fc965eb86fd69fcb2bd62c08cb6d7c6708a40dc39b3b97440/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:40cd5de7dd252942a08480639f5850594b1aca4a463e8a7f15e1fb6c2c3760c1", size = 1293729, upload-time = "2026-08-30T19:52:59.481Z" }, + { url = "https://files.pythonhosted.org/packages/ac/32/22436b072d79011fe81abb933edcd2476057c7b971588c5f3caf07519a88/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:b9c33f921ddc7fea93660eca408b25fe755516e22ec7ab21cb9951031f1cd608", size = 1419248, upload-time = "2026-08-30T19:50:52.903Z" }, + { url = "https://files.pythonhosted.org/packages/9e/3e/abf39faaff0f78112112a82316a5c9fe472574480c1ecee526734775b812/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:495989cf0a5ee03f7f9598ee9efeaabf15fd861ec52b5a9d6435849453e17e5d", size = 1274903, upload-time = "2026-08-30T19:52:27.25Z" }, + { url = "https://files.pythonhosted.org/packages/29/83/69b89ed5692ba3aad117facfb9ce099633a22c35acc3d64829b72253ec8c/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:bc73c46ce8ff93b0eb220f2b75adcbd9fcc9112078a74d3522d2532ad8069bad", size = 1294185, upload-time = "2026-08-30T19:50:35.038Z" }, + { url = "https://files.pythonhosted.org/packages/2b/1e/55dfcbe45c72df0a5c5b86a6b7c9365121acab69c2cc060bd55336a48c8f/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:36e83e1d7e97aaacbf6cd778e14a841344f848a674b20dfe4fe997546a6a2151", size = 1330013, upload-time = "2026-08-30T19:52:54.841Z" }, + { url = "https://files.pythonhosted.org/packages/3b/a6/0a36cead4ccff58bedb5d1aa2f894f7a580c317424b4fa788c6b22232b2d/hypothesis-6.167.1-cp310-abi3-win32.whl", hash = "sha256:fb4d87454d2459c2ccb541a4c61c92ce13058b91305ed3304695a409a1d886e4", size = 671942, upload-time = "2026-08-30T19:51:32.732Z" }, + { url = "https://files.pythonhosted.org/packages/ec/5b/360285ed42109f5ef48d98ca9ffcf71d1477130c0ff1f1a8d535c8507259/hypothesis-6.167.1-cp310-abi3-win_amd64.whl", hash = "sha256:5e35f98b427bf438a946203426b485dd5b62485f3d5a69a0e0862870a545e518", size = 678637, upload-time = "2026-08-30T19:50:33.573Z" }, + { url = "https://files.pythonhosted.org/packages/79/2d/cc084c1a8bfa296048ec0461f0fa11731abe0097f5c2310c8d39d94c8dc4/hypothesis-6.167.1-cp310-abi3-win_arm64.whl", hash = "sha256:dd6a0808a2eb8b5b1ac06bca4244eee18ed2c0e7b105599e1662203d164317b5", size = 676657, upload-time = "2026-08-30T19:51:34.494Z" }, + { url = "https://files.pythonhosted.org/packages/72/82/07987292cfb59c73ce6574e2912c015f678d5aa4d8c0712b78ae4415a535/hypothesis-6.167.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:1937ae4e23f7dde6d4202d3d08c2633bcd535a091bdf866b8799abaabcb1e6f0", size = 787050, upload-time = "2026-08-30T19:51:10.782Z" }, + { url = "https://files.pythonhosted.org/packages/c7/e9/0d37051bec44ec433d87da03c9a7fe389b1b58210790c1f166af249bf941/hypothesis-6.167.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1434bbd25d05aaf75c4e6829b4cad8e9931b690f840d92b747b2e6e5af575922", size = 778617, upload-time = "2026-08-30T19:50:31.939Z" }, + { url = "https://files.pythonhosted.org/packages/13/2a/60c18a493215c22c9cfcb4574b381497bd1971eed9fb5f9831b26e73cffb/hypothesis-6.167.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:af3c09428e553b1dd2f9abbc4738377c58bf6d74cb0b8b528cc1dde3a9cdfbe8", size = 1116743, upload-time = "2026-08-30T19:50:49.293Z" }, + { url = "https://files.pythonhosted.org/packages/12/1f/b6796f11d6502e0b1764aec99f2792ca60382b6a45e26bbe163dc5757980/hypothesis-6.167.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:04f807b85d425a7005e8a24498ca832bf5590f0d306737471d94c842569cecef", size = 1162718, upload-time = "2026-08-30T19:52:47.544Z" }, + { url = "https://files.pythonhosted.org/packages/a8/6c/e3cf35474b799e299fa08980b6756f500d730781686916ab65f87cbc0613/hypothesis-6.167.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:803c6a98ff66cee4caf03245bfd00e442a907264031b994a3a650dc6e4786f51", size = 1292417, upload-time = "2026-08-30T19:50:56.822Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4c/875803c80c373a1628f8eb62f215ad23ce7b50ed61f884d6be0838ebea4a/hypothesis-6.167.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:21a7122ddf072906083e3704fe3961ecbc49d7d30a9b51bcd525d977b3afe65e", size = 1329035, upload-time = "2026-08-30T19:51:46.659Z" }, + { url = "https://files.pythonhosted.org/packages/90/a8/a8daed3796623884471dc0ee8ed63917b1e2b979b4074bcea19a964fcd71/hypothesis-6.167.1-cp312-cp312-win_amd64.whl", hash = "sha256:a2837c60d782eb0b8a910c541264675b9d11486e186af8c82a5e2920b5fe4fe8", size = 675966, upload-time = "2026-08-30T19:51:56.58Z" }, + { url = "https://files.pythonhosted.org/packages/b0/45/59abecd75e52b9dfb5b3eb991276f54954c44917a1c83d148cfb3580bd39/hypothesis-6.167.1-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:c25c556d51d55d94988dc0a2c716d471ff19cf9632cd33f5e6db2914d802428a", size = 785097, upload-time = "2026-08-30T19:51:12.528Z" }, + { url = "https://files.pythonhosted.org/packages/01/7c/e6d978dc9564ba70352da60c00f55f6ad7d66d99ecbf336a228978206cb4/hypothesis-6.167.1-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:b57e950f9d5c93ca335bc612e8fa8fb49abb187c3fc9d5e7d9966d52eb27d747", size = 776798, upload-time = "2026-08-30T19:50:47.247Z" }, + { url = "https://files.pythonhosted.org/packages/d1/a4/f8ecedcf96790aab69d750afe3fcbf503229d0bb4e0c32be655385a4fc8c/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0807ae8d399162827fc1c396ab4c697a41921c2a2baacfada439771e9dc2b867", size = 1115116, upload-time = "2026-08-30T19:52:16.029Z" }, + { url = "https://files.pythonhosted.org/packages/7e/97/8bca7c262ac4fcb1ee684c04e4ba75f26541d3a30417e3743d19912d257e/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:546fef39c7aadba74bf3e592585694a71340d1775e9b3274bb3f94106dbde4b7", size = 1137812, upload-time = "2026-08-30T19:51:25.507Z" }, + { url = "https://files.pythonhosted.org/packages/d6/07/9cb4a7fc2aa2b2ad063b446c378f0d7acfa5303e84afd1b1374ba23fd6f3/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a17a5618b6a5b84f17c8acb3bce37122647cf7a3e48b660a39d68a773bd627dd", size = 1140384, upload-time = "2026-08-30T19:52:05.264Z" }, + { url = "https://files.pythonhosted.org/packages/1c/18/813bf7efa18f11ce938a0da22a7518a54db46d4a181ebf4cb0a8061c263f/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0ff5ad833480c1e34ae902cb52fc00802b08ac6c87bd22d7e5f04fd925869608", size = 1160569, upload-time = "2026-08-30T19:51:40.099Z" }, + { url = "https://files.pythonhosted.org/packages/52/1d/6658d9294ed33bb17da4acf06fe63b010b205ea1861f6921c38060793255/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:630eb37df80b5bc4ec6f391b13caaecc06942ff5da3aadebacf85f53bbc55757", size = 1120605, upload-time = "2026-08-30T19:53:01.848Z" }, + { url = "https://files.pythonhosted.org/packages/a6/81/a75821c0e879223a2635b8eded84ae874cb6c711b23e9930668008d0b13f/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bc4e65f7c43b187f7a40964706b5ded1073e0c1839e9fb5e041d7ed973bb65fe", size = 1149479, upload-time = "2026-08-30T19:51:30.972Z" }, + { url = "https://files.pythonhosted.org/packages/4e/f2/c8c3faf4ec796d6dbf36b84662806696434aef38616e5a65b46188c04262/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:e849f518cbc4e76ab15f2f1473c60dd3103da8d32399187325ceb84309105976", size = 1290423, upload-time = "2026-08-30T19:50:51.114Z" }, + { url = "https://files.pythonhosted.org/packages/a4/e3/e0903abe7e8634cedb5414931452e82daacdd3b8b46d6348bbefcaa45f2a/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:5c5a26d4d3dca0c84e01bde41df4cabaa5a373c7393f9eef372d19fe93b07ccd", size = 1415749, upload-time = "2026-08-30T19:51:48.456Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9b/03f09c1ecac1dfb0f4cd7fcc6dc50d9c6ea8067b295a728e242650bafe32/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:4819adbc5911648f6bfaeb574f276add184b4b49f54731dbde46fd71256bb157", size = 1272086, upload-time = "2026-08-30T19:52:29.368Z" }, + { url = "https://files.pythonhosted.org/packages/7c/7c/7a63bfc0bfbaf000f71352c4faac72ff611376330a2ce2e9a1bf4668848a/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:3ad7206de9c398c8da5745b69b5ba2ef45100082eeb174656490bc4f262b112c", size = 1291553, upload-time = "2026-08-30T19:52:07.545Z" }, + { url = "https://files.pythonhosted.org/packages/e8/5c/8065bdab53bc81743ca68fc76ca53fc7531a5b3f01c0de4ba40467955d6a/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:96d5e8017a9508f06c8a61a6130cb0d0b4810847ed5c76923cb5cfb9952b31af", size = 1327734, upload-time = "2026-08-30T19:51:42.306Z" }, + { url = "https://files.pythonhosted.org/packages/0d/a0/5c15d480aea3a8e6e5c17c7cb1170171707ac643ffd319473bc194743ad8/hypothesis-6.167.1-cp315-abi3.abi3t-win32.whl", hash = "sha256:a4e4de36a397cba49d949d89cbc26135977c15f9d797caa95317962ceb5b5674", size = 669115, upload-time = "2026-08-30T19:51:14.192Z" }, + { url = "https://files.pythonhosted.org/packages/1b/36/4cf494bc96384189fedb7d3f272580315f2284a9f8a7f6a59796612eb76d/hypothesis-6.167.1-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:f6fe9c40ab14def363d9e7ab22863fa31652bd5e08f8495b34ff7bd0062b3f8d", size = 675438, upload-time = "2026-08-30T19:51:06.881Z" }, + { url = "https://files.pythonhosted.org/packages/b0/7f/db1a37e5f45be32c0e64f9ed1268eba56aeedcb2ef20d195fa60c6610347/hypothesis-6.167.1-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:627ce3bd166799a6c0ddcf1351049be5b9a772d5bce436216d42b41a935f42c0", size = 673123, upload-time = "2026-08-30T19:52:13.991Z" }, ] [[package]] @@ -3455,7 +3537,7 @@ wheels = [ [[package]] name = "import-linter" -version = "2.11" +version = "2.14" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "click" }, @@ -3463,9 +3545,9 @@ dependencies = [ { name = "rich" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ba/66/55b697a17bb15c6cb88d97d73716813f5427281527b90f02cc0a600abc6e/import_linter-2.11.tar.gz", hash = "sha256:5abc3394797a54f9bae315e7242dc98715ba485f840ac38c6d3192c370d0085e", size = 1153682, upload-time = "2026-03-06T12:11:38.198Z" } +sdist = { url = "https://files.pythonhosted.org/packages/54/ee/709dfd34cd2729b6d2dfa1381fd3c1370e0e3e5d4ce7d0643fd8c12652c1/import_linter-2.14.tar.gz", hash = "sha256:8e6304d9a9ddfbd39f6ac990710d95aaf9ac71eb1ba81ac8ce53e1ef2f9773d3", size = 1283529, upload-time = "2026-08-28T11:28:36.511Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e9/aa/2ed2c89543632ded7196e0d93dcc6c7fe87769e88391a648c4a298ea864a/import_linter-2.11-py3-none-any.whl", hash = "sha256:3dc54cae933bae3430358c30989762b721c77aa99d424f56a08265be0eeaa465", size = 637315, upload-time = "2026-03-06T12:11:36.599Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f1/a9ef72a7ad4a49e77e4df579dd23e2bbf84f1b7da9087a744b086657929e/import_linter-2.14-py3-none-any.whl", hash = "sha256:0039771a991f9a309055ac6fa18340b0024d0bb88722f9dd2834f0d930a2224c", size = 639603, upload-time = "2026-08-28T11:28:35.091Z" }, ] [[package]] @@ -3749,23 +3831,25 @@ wheels = [ [[package]] name = "librt" -version = "0.8.1" +version = "0.15.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/56/9c/b4b0c54d84da4a94b37bd44151e46d5e583c9534c7e02250b961b1b6d8a8/librt-0.8.1.tar.gz", hash = "sha256:be46a14693955b3bd96014ccbdb8339ee8c9346fbe11c1b78901b55125f14c73", size = 177471, upload-time = "2026-02-17T16:13:06.101Z" } +sdist = { url = "https://files.pythonhosted.org/packages/36/9b/356320fbae2ac8467e21c5e73e1389c80468e4998c62cc7d3536cc51b614/librt-0.15.0.tar.gz", hash = "sha256:4e66cbe84437497d951b799d3e1551291b6fb3d643820a7014b3655d57a59162", size = 214338, upload-time = "2026-08-07T10:49:42.663Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/21/d39b0a87ac52fc98f621fb6f8060efb017a767ebbbac2f99fbcbc9ddc0d7/librt-0.8.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a28f2612ab566b17f3698b0da021ff9960610301607c9a5e8eaca62f5e1c350a", size = 66516, upload-time = "2026-02-17T16:11:41.604Z" }, - { url = "https://files.pythonhosted.org/packages/69/f1/46375e71441c43e8ae335905e069f1c54febee63a146278bcee8782c84fd/librt-0.8.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:60a78b694c9aee2a0f1aaeaa7d101cf713e92e8423a941d2897f4fa37908dab9", size = 68634, upload-time = "2026-02-17T16:11:43.268Z" }, - { url = "https://files.pythonhosted.org/packages/0a/33/c510de7f93bf1fa19e13423a606d8189a02624a800710f6e6a0a0f0784b3/librt-0.8.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:758509ea3f1eba2a57558e7e98f4659d0ea7670bff49673b0dde18a3c7e6c0eb", size = 198941, upload-time = "2026-02-17T16:11:44.28Z" }, - { url = "https://files.pythonhosted.org/packages/dd/36/e725903416409a533d92398e88ce665476f275081d0d7d42f9c4951999e5/librt-0.8.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:039b9f2c506bd0ab0f8725aa5ba339c6f0cd19d3b514b50d134789809c24285d", size = 209991, upload-time = "2026-02-17T16:11:45.462Z" }, - { url = "https://files.pythonhosted.org/packages/30/7a/8d908a152e1875c9f8eac96c97a480df425e657cdb47854b9efaa4998889/librt-0.8.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5bb54f1205a3a6ab41a6fd71dfcdcbd278670d3a90ca502a30d9da583105b6f7", size = 224476, upload-time = "2026-02-17T16:11:46.542Z" }, - { url = "https://files.pythonhosted.org/packages/a8/b8/a22c34f2c485b8903a06f3fe3315341fe6876ef3599792344669db98fcff/librt-0.8.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:05bd41cdee35b0c59c259f870f6da532a2c5ca57db95b5f23689fcb5c9e42440", size = 217518, upload-time = "2026-02-17T16:11:47.746Z" }, - { url = "https://files.pythonhosted.org/packages/79/6f/5c6fea00357e4f82ba44f81dbfb027921f1ab10e320d4a64e1c408d035d9/librt-0.8.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:adfab487facf03f0d0857b8710cf82d0704a309d8ffc33b03d9302b4c64e91a9", size = 225116, upload-time = "2026-02-17T16:11:49.298Z" }, - { url = "https://files.pythonhosted.org/packages/f2/a0/95ced4e7b1267fe1e2720a111685bcddf0e781f7e9e0ce59d751c44dcfe5/librt-0.8.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:153188fe98a72f206042be10a2c6026139852805215ed9539186312d50a8e972", size = 217751, upload-time = "2026-02-17T16:11:50.49Z" }, - { url = "https://files.pythonhosted.org/packages/93/c2/0517281cb4d4101c27ab59472924e67f55e375bc46bedae94ac6dc6e1902/librt-0.8.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:dd3c41254ee98604b08bd5b3af5bf0a89740d4ee0711de95b65166bf44091921", size = 218378, upload-time = "2026-02-17T16:11:51.783Z" }, - { url = "https://files.pythonhosted.org/packages/43/e8/37b3ac108e8976888e559a7b227d0ceac03c384cfd3e7a1c2ee248dbae79/librt-0.8.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e0d138c7ae532908cbb342162b2611dbd4d90c941cd25ab82084aaf71d2c0bd0", size = 241199, upload-time = "2026-02-17T16:11:53.561Z" }, - { url = "https://files.pythonhosted.org/packages/4b/5b/35812d041c53967fedf551a39399271bbe4257e681236a2cf1a69c8e7fa1/librt-0.8.1-cp312-cp312-win32.whl", hash = "sha256:43353b943613c5d9c49a25aaffdba46f888ec354e71e3529a00cca3f04d66a7a", size = 54917, upload-time = "2026-02-17T16:11:54.758Z" }, - { url = "https://files.pythonhosted.org/packages/de/d1/fa5d5331b862b9775aaf2a100f5ef86854e5d4407f71bddf102f4421e034/librt-0.8.1-cp312-cp312-win_amd64.whl", hash = "sha256:ff8baf1f8d3f4b6b7257fcb75a501f2a5499d0dda57645baa09d4d0d34b19444", size = 62017, upload-time = "2026-02-17T16:11:55.748Z" }, - { url = "https://files.pythonhosted.org/packages/c7/7c/c614252f9acda59b01a66e2ddfd243ed1c7e1deab0293332dfbccf862808/librt-0.8.1-cp312-cp312-win_arm64.whl", hash = "sha256:0f2ae3725904f7377e11cc37722d5d401e8b3d5851fb9273d7f4fe04f6b3d37d", size = 52441, upload-time = "2026-02-17T16:11:56.801Z" }, + { url = "https://files.pythonhosted.org/packages/ba/39/99c25030e782bdfb7a21be8c05254806a2e4bbb05c8d50c2a2130acbfa05/librt-0.15.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e87bc679f86a99aa3b26e3c78eeb821a247c9a28eae48eaafcc32c3bf4c3bb9e", size = 151021, upload-time = "2026-08-07T10:47:00.057Z" }, + { url = "https://files.pythonhosted.org/packages/14/43/f4b1bd1b2888798a1409808889a25ea1ba49eaabce7d681ed27734c2df9d/librt-0.15.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:71599e011ac880e8e45d46047d714871894c7d4ab6f25626f8d4f89da21f368d", size = 155267, upload-time = "2026-08-07T10:47:01.311Z" }, + { url = "https://files.pythonhosted.org/packages/0c/db/3ad9c965c72f1e1d6beeec44ec10a54e17be8ae042fbb4baade16cbadced/librt-0.15.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c802434092b769b1d613ed2e13fac15fbfce1934a74bd10283b03c0fae231cd1", size = 503136, upload-time = "2026-08-07T10:47:02.45Z" }, + { url = "https://files.pythonhosted.org/packages/4b/07/5888a6d76acd62ebce66c61b74d94e9370b9c32929f111e487bb6546f8ed/librt-0.15.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5500eeae393a184d14e1f35645962c27129d20c81afa4069e6ef826ebc2b3aaa", size = 496670, upload-time = "2026-08-07T10:47:03.675Z" }, + { url = "https://files.pythonhosted.org/packages/29/39/ab57cc2f5b276156da02bb7f5a8921bada1cb1993ffec99acf811c602c23/librt-0.15.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6ecfc32dfb46fb7b565bcd6abf9412acf978775a998273d22888a6d7953730dd", size = 513688, upload-time = "2026-08-07T10:47:04.981Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b9/bdbb0b648b5c2befb031f4c6f3b1dd857415e8fb492a25a3c764a6681e6c/librt-0.15.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cc46cfd15022e35084355478c9ac809d90b1152222706ac9a7655ec21df6fa", size = 531904, upload-time = "2026-08-07T10:47:06.211Z" }, + { url = "https://files.pythonhosted.org/packages/93/26/473c2e4b6c104e9e58e27ce95fc8005c8bd4fc36cae4f254371125a92db8/librt-0.15.0-cp312-cp312-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d5f51401d102c885b9ca509e62c79b1dbff286e1b9b047fde6f763780789356d", size = 524427, upload-time = "2026-08-07T10:47:07.592Z" }, + { url = "https://files.pythonhosted.org/packages/26/60/03b3abb82b41714671b907bf6989b228e31e6a8af52dec82b5b0728dc250/librt-0.15.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cc30523e3f1a23fb7511cc659834a0d01a1042bb9de359bc1c131cc4ec6c9656", size = 543155, upload-time = "2026-08-07T10:47:08.866Z" }, + { url = "https://files.pythonhosted.org/packages/f2/0e/9bb1f0a4affbd0a1888f4f79dc03ed2a299d9a2c26c59ab2a97dcbf11903/librt-0.15.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:59fe030d8ae4a57e3fb7756bf35a858de74e04066fc8555c53d0af979132af81", size = 546890, upload-time = "2026-08-07T10:47:10.327Z" }, + { url = "https://files.pythonhosted.org/packages/dc/84/6937a280d461f7de6e031ffb02edc2b7c3c90d49d630565ce8ff27cbc5f2/librt-0.15.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5a6526a2a956bbb1e4ae3568c82e650fc99119c66bb011ea60715744955a2b4d", size = 555163, upload-time = "2026-08-07T10:47:11.798Z" }, + { url = "https://files.pythonhosted.org/packages/bc/95/2a2853c1ee014bf102116e7f897a04beeaeb2461b45b79af98bdfb95f1ef/librt-0.15.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:85ea21ec6730194d67156b0e0b5430ccb1d61f8b8b907e39b37f9812b74a13f0", size = 535812, upload-time = "2026-08-07T10:47:13.279Z" }, + { url = "https://files.pythonhosted.org/packages/c9/4c/cf9601c1b4c5f09280acd5d83abdb2e68527a2be8257136eb42304218622/librt-0.15.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1e47b8ba865d7ede071a91a7163073bbaeb72541f1ef8a07d512c45c7b5007f2", size = 573688, upload-time = "2026-08-07T10:47:14.727Z" }, + { url = "https://files.pythonhosted.org/packages/47/6d/9ac7cbec46189a7625af4b5acbd25f10d827f4141b2002181848c8418923/librt-0.15.0-cp312-cp312-win32.whl", hash = "sha256:a5207ec414d1c4a2a7231b2086970dc036f94293cdf338190984958a013a42f1", size = 106138, upload-time = "2026-08-07T10:47:15.973Z" }, + { url = "https://files.pythonhosted.org/packages/38/d0/2ae99c83be86ce23f925ac1aeeedc777e97f427c4a8d190c70d0a16e9a87/librt-0.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:73b30cfa976659b3917c8f6153bdb0591c6a9ec6583599fd24a689b690622022", size = 126974, upload-time = "2026-08-07T10:47:17.049Z" }, + { url = "https://files.pythonhosted.org/packages/5d/ef/dd24f9635c730b86b87587967dda7516b1845e8b17684603d31607fed598/librt-0.15.0-cp312-cp312-win_arm64.whl", hash = "sha256:a54cf9e0ef47b96af580849db5471142200568ce1e02cbf416addab551369570", size = 112292, upload-time = "2026-08-07T10:47:18.222Z" }, ] [[package]] @@ -4072,24 +4156,24 @@ wheels = [ [[package]] name = "mypy" -version = "1.20.2" +version = "2.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "ast-serialize" }, { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, { name = "mypy-extensions" }, { name = "pathspec" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/04/af/e3d4b3e9ec91a0ff9aabfdb38692952acf49bbb899c2e4c29acb3a6da3ae/mypy-1.20.2.tar.gz", hash = "sha256:e8222c26daaafd9e8626dec58ae36029f82585890589576f769a650dd20fd665", size = 3817349, upload-time = "2026-04-21T17:12:28.473Z" } +sdist = { url = "https://files.pythonhosted.org/packages/82/6a/878cc1097d4035f82bd516658d0c528d2a9955bc7b363afcbd0b07fea11b/mypy-2.3.1.tar.gz", hash = "sha256:47c1b1207258513a9d93495f69c8be9de73916186f0e52703e8c461b7a623419", size = 3992554, upload-time = "2026-08-15T03:03:38.549Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/71/4e/7560e4528db9e9b147e4c0f22660466bf30a0a1fe3d63d1b9d3b0fd354ee/mypy-1.20.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4dbfcf869f6b0517f70cf0030ba6ea1d6645e132337a7d5204a18d8d5636c02b", size = 14539393, upload-time = "2026-04-21T17:07:12.52Z" }, - { url = "https://files.pythonhosted.org/packages/32/d9/34a5efed8124f5a9234f55ac6a4ced4201e2c5b81e1109c49ad23190ec8c/mypy-1.20.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b6481b228d072315b053210b01ac320e1be243dc17f9e5887ef167f23f5fae4", size = 13361642, upload-time = "2026-04-21T17:06:53.742Z" }, - { url = "https://files.pythonhosted.org/packages/d1/14/eb377acf78c03c92d566a1510cda8137348215b5335085ef662ab82ecd3a/mypy-1.20.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34397cdced6b90b836e38182076049fdb41424322e0b0728c946b0939ebdf9f6", size = 13740347, upload-time = "2026-04-21T17:12:04.73Z" }, - { url = "https://files.pythonhosted.org/packages/b9/94/7e4634a32b641aa1c112422eed1bbece61ee16205f674190e8b536f884de/mypy-1.20.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5da6976f20cae27059ea8d0c86e7cef3de720e04c4bb9ee18e3690fdb792066", size = 14734042, upload-time = "2026-04-21T17:07:43.16Z" }, - { url = "https://files.pythonhosted.org/packages/7a/f3/f7e62395cb7f434541b4491a01149a4439e28ace4c0c632bbf5431e92d1f/mypy-1.20.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:56908d7e08318d39f85b1f0c6cfd47b0cac1a130da677630dac0de3e0623e102", size = 14964958, upload-time = "2026-04-21T17:11:00.665Z" }, - { url = "https://files.pythonhosted.org/packages/3e/0d/47e3c3a0ec2a876e35aeac365df3cac7776c36bbd4ed18cc521e1b9d255b/mypy-1.20.2-cp312-cp312-win_amd64.whl", hash = "sha256:d52ad8d78522da1d308789df651ee5379088e77c76cb1994858d40a426b343b9", size = 10911340, upload-time = "2026-04-21T17:10:49.179Z" }, - { url = "https://files.pythonhosted.org/packages/d6/b2/6c852d72e0ea8b01f49da817fb52539993cde327e7d010e0103dc12d0dac/mypy-1.20.2-cp312-cp312-win_arm64.whl", hash = "sha256:785b08db19c9f214dc37d65f7c165d19a30fcecb48abfa30f31b01b5acaabb58", size = 9833947, upload-time = "2026-04-21T17:09:05.267Z" }, - { url = "https://files.pythonhosted.org/packages/28/9a/f23c163e25b11074188251b0b5a0342625fc1cdb6af604757174fa9acc9b/mypy-1.20.2-py3-none-any.whl", hash = "sha256:a94c5a76ab46c5e6257c7972b6c8cff0574201ca7dc05647e33e795d78680563", size = 2637314, upload-time = "2026-04-21T17:05:54.5Z" }, + { url = "https://files.pythonhosted.org/packages/85/da/d6effc4f808a842d91edc22535dc9e799d2ff6e91449168b7f47a0771f54/mypy-2.3.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a32bbbb940af990d3be0b8af321c7b6815bb1b3b48142fe7459b9cc5f58959ff", size = 14047547, upload-time = "2026-08-15T03:02:57.707Z" }, + { url = "https://files.pythonhosted.org/packages/e4/e6/478229701dab76f26485fc8ff5d6f241f393da22447400bbc56f6946aebe/mypy-2.3.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff715e45b2231a8e85de1d163d1b42791e4d7aab8f5145f85fee1b710b735aff", size = 14216515, upload-time = "2026-08-15T03:01:26.496Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fe/7c42327a3b21e84681f691982cbfe43f334a3685f3b683b72c376476c4fa/mypy-2.3.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:858fc57d3d91fa728e33e7ad71def60fc6272694607b306cd3292db53ae39080", size = 15307789, upload-time = "2026-08-15T03:03:31.62Z" }, + { url = "https://files.pythonhosted.org/packages/59/f4/7e597edbe01b5a56fa958ce541302dcaabfed979966f1dffedbea0ea0fc2/mypy-2.3.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:851833db876e7b650f93719c74b7879a08e338979c96054fdfc3bfd90a486355", size = 15548831, upload-time = "2026-08-15T03:03:15.55Z" }, + { url = "https://files.pythonhosted.org/packages/a3/52/cb31e084bc0314a1e384bdd677a4b80e55af04ccac077545e2238b9d320a/mypy-2.3.1-cp312-cp312-win_amd64.whl", hash = "sha256:4c5095a327483591c94e0c8d3ef9e50d4ab1369b541eae007c1f23bc2a41f6bb", size = 11226359, upload-time = "2026-08-15T03:03:29.002Z" }, + { url = "https://files.pythonhosted.org/packages/7a/47/88fcf6217b43fa2da81a8c2611370af18141536a4f0294bbf98b457d456d/mypy-2.3.1-cp312-cp312-win_arm64.whl", hash = "sha256:bbfe022634a2a195406bd469e888d2eaf193b02ba7e607391cd7640374aaae3b", size = 10214707, upload-time = "2026-08-15T03:02:48.807Z" }, + { url = "https://files.pythonhosted.org/packages/8e/41/9675c7a1e78edecfba0b79e587a52594c56e189368261dc7b3a7fffb9527/mypy-2.3.1-py3-none-any.whl", hash = "sha256:6ed5c7e3419083268e5c9258bd1c1ef91af44a9e89374dbcaf37b775716e72eb", size = 2754338, upload-time = "2026-08-15T03:02:53.4Z" }, ] [[package]] @@ -4783,14 +4867,14 @@ excel = [ [[package]] name = "pandas-stubs" -version = "3.0.0.260204" +version = "3.0.5.260730" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/27/1d/297ff2c7ea50a768a2247621d6451abb2a07c0e9be7ca6d36ebe371658e5/pandas_stubs-3.0.0.260204.tar.gz", hash = "sha256:bf9294b76352effcffa9cb85edf0bed1339a7ec0c30b8e1ac3d66b4228f1fbc3", size = 109383, upload-time = "2026-02-04T15:17:17.247Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c2/d2/dea4a3a56b7b5f69c5fbca9f14625fcf28e1a39a657e9833d4a10bcac593/pandas_stubs-3.0.5.260730.tar.gz", hash = "sha256:f70a232c57d93a5a2c81f8a53953e10891a5374bc92652277deb325e2e4d0ff3", size = 114631, upload-time = "2026-07-30T14:31:42.271Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7c/2f/f91e4eee21585ff548e83358332d5632ee49f6b2dcd96cb5dca4e0468951/pandas_stubs-3.0.0.260204-py3-none-any.whl", hash = "sha256:5ab9e4d55a6e2752e9720828564af40d48c4f709e6a2c69b743014a6fcb6c241", size = 168540, upload-time = "2026-02-04T15:17:15.615Z" }, + { url = "https://files.pythonhosted.org/packages/60/c2/959caec5c46f484b5f8bb6def4b0cf7a45ba6acda26f12b75142d98cc5ae/pandas_stubs-3.0.5.260730-py3-none-any.whl", hash = "sha256:60e90e3e1eda6937e337e243cbe6217e151c11137cd7eddf832af537c7310bfd", size = 174807, upload-time = "2026-07-30T14:31:41.17Z" }, ] [[package]] @@ -5115,12 +5199,12 @@ wheels = [ ] [[package]] -name = "py-cpuinfo" -version = "9.0.0" +name = "py-cpuinfo2" +version = "10.1.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/37/a8/d832f7293ebb21690860d2e01d8115e5ff6f2ae8bbdc953f0eb0fa4bd2c7/py-cpuinfo-9.0.0.tar.gz", hash = "sha256:3cdbbf3fac90dc6f118bfd64384f309edeadd902d7c8fb17f02ffa1fc3f49690", size = 104716, upload-time = "2022-10-25T20:38:06.303Z" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/97/a8b1ddada14c8280a047c0746f95cb05d94a31b1a331cea22bcdc2b2a82d/py_cpuinfo2-10.1.1.tar.gz", hash = "sha256:7861133863663f16e06eca63b12904ef100b5760415e92372dac0162799a4771", size = 100840, upload-time = "2026-03-25T21:49:40.797Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e0/a9/023730ba63db1e494a271cb018dcd361bd2c917ba7004c3e49d5daf795a2/py_cpuinfo-9.0.0-py3-none-any.whl", hash = "sha256:859625bc251f64e21f077d099d4162689c762b5d6a4c3c97553d56241c9674d5", size = 22335, upload-time = "2022-10-25T20:38:27.636Z" }, + { url = "https://files.pythonhosted.org/packages/23/0a/ba69d2dde1ae12ef1d389ea5a216384c5ff6ef7a1e7a48d1e9b6686f6790/py_cpuinfo2-10.1.1-py3-none-any.whl", hash = "sha256:adc53396bfb206e6498d078ec2ab407f85799ecd819584ac36a8f80a2d4d762d", size = 23791, upload-time = "2026-03-25T21:49:39.574Z" }, ] [[package]] @@ -5504,7 +5588,7 @@ wheels = [ [[package]] name = "pytest" -version = "9.0.3" +version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, @@ -5513,22 +5597,22 @@ dependencies = [ { name = "pluggy" }, { name = "pygments" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165, upload-time = "2026-04-07T17:16:18.027Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" }, + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] [[package]] name = "pytest-benchmark" -version = "5.2.3" +version = "5.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "py-cpuinfo" }, + { name = "py-cpuinfo2" }, { name = "pytest" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/24/34/9f732b76456d64faffbef6232f1f9dbec7a7c4999ff46282fa418bd1af66/pytest_benchmark-5.2.3.tar.gz", hash = "sha256:deb7317998a23c650fd4ff76e1230066a76cb45dcece0aca5607143c619e7779", size = 341340, upload-time = "2025-11-09T18:48:43.215Z" } +sdist = { url = "https://files.pythonhosted.org/packages/63/8f/83a15e40dbc34a580ee56eb56983cae5394c6e94d50cf28fe268e457be25/pytest_benchmark-5.3.0.tar.gz", hash = "sha256:358444d4e89be901ee2b6404fb043ac3d7684002ad7f3563cc153fca6339c965", size = 375410, upload-time = "2026-08-23T17:45:08.891Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/33/29/e756e715a48959f1c0045342088d7ca9762a2f509b945f362a316e9412b7/pytest_benchmark-5.2.3-py3-none-any.whl", hash = "sha256:bc839726ad20e99aaa0d11a127445457b4219bdb9e80a1afc4b51da7f96b0803", size = 45255, upload-time = "2025-11-09T18:48:39.765Z" }, + { url = "https://files.pythonhosted.org/packages/eb/42/7e80f7cfa191e0a766d1de99b4661847415ad5db34f8209d81fd42175b59/pytest_benchmark-5.3.0-py3-none-any.whl", hash = "sha256:920ab1dfcffa718d49aa15ba144c7e357bda59216a0dc308016cc1c7236f719d", size = 48401, upload-time = "2026-08-23T17:45:07.094Z" }, ] [[package]] @@ -5547,15 +5631,15 @@ wheels = [ [[package]] name = "pytest-env" -version = "1.6.0" +version = "1.7.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pytest" }, { name = "python-dotenv" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ff/69/4db1c30625af0621df8dbe73797b38b6d1b04e15d021dd5d26a6d297f78c/pytest_env-1.6.0.tar.gz", hash = "sha256:ac02d6fba16af54d61e311dd70a3c61024a4e966881ea844affc3c8f0bf207d3", size = 16163, upload-time = "2026-03-12T22:39:43.78Z" } +sdist = { url = "https://files.pythonhosted.org/packages/65/49/08ee056f9cc655e437abcf2ae399884844b623223476ae6a77244131db03/pytest_env-1.7.0.tar.gz", hash = "sha256:0c1dc1101fb8d3ab3611e8f8d657ba06c3c0c167fc85c90457e5b27f2508f43e", size = 16408, upload-time = "2026-07-21T13:09:21.834Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/27/16/ad52f56b96d851a2bcfdc1e754c3531341885bd7177a128c13ff2ca72ab4/pytest_env-1.6.0-py3-none-any.whl", hash = "sha256:1e7f8a62215e5885835daaed694de8657c908505b964ec8097a7ce77b403d9a3", size = 10400, upload-time = "2026-03-12T22:39:41.887Z" }, + { url = "https://files.pythonhosted.org/packages/3e/fc/9f2975c41d41bf5bd9a7d0fc03085ec20052b456b079df53828ae4a1b100/pytest_env-1.7.0-py3-none-any.whl", hash = "sha256:9ee0f1fe859d23fcdb533fe2909a404b3b133d02674a56df275bbe4df4eb104b", size = 10263, upload-time = "2026-07-21T13:09:20.677Z" }, ] [[package]] @@ -5896,7 +5980,7 @@ wheels = [ [[package]] name = "requests" -version = "2.33.0" +version = "2.34.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, @@ -5904,9 +5988,9 @@ dependencies = [ { name = "idna" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/34/64/8860370b167a9721e8956ae116825caff829224fbca0ca6e7bf8ddef8430/requests-2.33.0.tar.gz", hash = "sha256:c7ebc5e8b0f21837386ad0e1c8fe8b829fa5f544d8df3b2253bff14ef29d7652", size = 134232, upload-time = "2026-03-25T15:10:41.586Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/56/5d/c814546c2333ceea4ba42262d8c4d55763003e767fa169adc693bd524478/requests-2.33.0-py3-none-any.whl", hash = "sha256:3324635456fa185245e24865e810cecec7b4caf933d7eb133dcde67d48cee69b", size = 65017, upload-time = "2026-03-25T15:10:40.382Z" }, + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] [[package]] @@ -5998,27 +6082,27 @@ wheels = [ [[package]] name = "ruff" -version = "0.15.12" +version = "0.16.6" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/99/43/3291f1cc9106f4c63bdce7a8d0df5047fe8422a75b091c16b5e9355e0b11/ruff-0.15.12.tar.gz", hash = "sha256:ecea26adb26b4232c0c2ca19ccbc0083a68344180bba2a600605538ce51a40a6", size = 4643852, upload-time = "2026-04-24T18:17:14.305Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a4/7c/6adb35d70e7c027e308274557901c7e00fb3407750faf3620c184ae058cb/ruff-0.16.6.tar.gz", hash = "sha256:dcf8a73d2ff77e99dde91244b4da16feba7f14e6beeb4015dee7c5a909e99050", size = 4921251, upload-time = "2026-09-03T16:57:29.037Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c3/6e/e78ffb61d4686f3d96ba3df2c801161843746dcbcbb17a1e927d4829312b/ruff-0.15.12-py3-none-linux_armv6l.whl", hash = "sha256:f86f176e188e94d6bdbc09f09bfd9dc729059ad93d0e7390b5a73efe19f8861c", size = 10640713, upload-time = "2026-04-24T18:17:22.841Z" }, - { url = "https://files.pythonhosted.org/packages/ae/08/a317bc231fb9e7b93e4ef3089501e51922ff88d6936ce5cf870c4fe55419/ruff-0.15.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e3bcd123364c3770b8e1b7baaf343cc99a35f197c5c6e8af79015c666c423a6c", size = 11069267, upload-time = "2026-04-24T18:17:30.105Z" }, - { url = "https://files.pythonhosted.org/packages/aa/a4/f828e9718d3dce1f5f11c39c4f65afd32783c8b2aebb2e3d259e492c47bd/ruff-0.15.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:fe87510d000220aa1ed530d4448a7c696a0cae1213e5ec30e5874287b66557b5", size = 10397182, upload-time = "2026-04-24T18:17:07.177Z" }, - { url = "https://files.pythonhosted.org/packages/71/e0/3310fc6d1b5e1fdea22bf3b1b807c7e187b581021b0d7d4514cccdb5fb71/ruff-0.15.12-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:84a1630093121375a3e2a95b4a6dc7b59e2b4ee76216e32d81aae550a832d002", size = 10758012, upload-time = "2026-04-24T18:16:55.759Z" }, - { url = "https://files.pythonhosted.org/packages/11/c1/a606911aee04c324ddaa883ae418f3569792fd3c4a10c50e0dd0a2311e1e/ruff-0.15.12-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fb129f40f114f089ebe0ca56c0d251cf2061b17651d464bb6478dc01e69f11f5", size = 10447479, upload-time = "2026-04-24T18:16:51.677Z" }, - { url = "https://files.pythonhosted.org/packages/9d/68/4201e8444f0894f21ab4aeeaee68aa4f10b51613514a20d80bd628d57e88/ruff-0.15.12-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0c862b172d695db7598426b8af465e7e9ac00a3ea2a3630ee67eb82e366aaa6", size = 11234040, upload-time = "2026-04-24T18:17:16.529Z" }, - { url = "https://files.pythonhosted.org/packages/34/ff/8a6d6cf4ccc23fd67060874e832c18919d1557a0611ebef03fdb01fff11e/ruff-0.15.12-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2849ea9f3484c3aca43a82f484210370319e7170df4dfe4843395ddf6c57bc33", size = 12087377, upload-time = "2026-04-24T18:17:04.944Z" }, - { url = "https://files.pythonhosted.org/packages/85/f6/c669cf73f5152f623d34e69866a46d5e6185816b19fcd5b6dd8a2d299922/ruff-0.15.12-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9e77c7e51c07fe396826d5969a5b846d9cd4c402535835fb6e21ce8b28fef847", size = 11367784, upload-time = "2026-04-24T18:17:25.409Z" }, - { url = "https://files.pythonhosted.org/packages/e8/39/c61d193b8a1daaa8977f7dea9e8d8ba866e02ea7b65d32f6861693aa4c12/ruff-0.15.12-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:83b2f4f2f3b1026b5fb449b467d9264bf22067b600f7b6f41fc5958909f449d0", size = 11344088, upload-time = "2026-04-24T18:17:12.258Z" }, - { url = "https://files.pythonhosted.org/packages/c2/8d/49afab3645e31e12c590acb6d3b5b69d7aab5b81926dbaf7461f9441f37a/ruff-0.15.12-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:9ba3b8f1afd7e2e43d8943e55f249e13f9682fde09711644a6e7290eb4f3e339", size = 11271770, upload-time = "2026-04-24T18:17:02.457Z" }, - { url = "https://files.pythonhosted.org/packages/46/06/33f41fe94403e2b755481cdfb9b7ef3e4e0ed031c4581124658d935d52b4/ruff-0.15.12-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e852ba9fdc890655e1d78f2df1499efbe0e54126bd405362154a75e2bde159c5", size = 10719355, upload-time = "2026-04-24T18:17:27.648Z" }, - { url = "https://files.pythonhosted.org/packages/0d/59/18aa4e014debbf559670e4048e39260a85c7fcee84acfd761ac01e7b8d35/ruff-0.15.12-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:dd8aed930da53780d22fc70bdf84452c843cf64f8cb4eb38984319c24c5cd5fd", size = 10462758, upload-time = "2026-04-24T18:17:32.347Z" }, - { url = "https://files.pythonhosted.org/packages/25/e7/cc9f16fd0f3b5fddcbd7ec3d6ae30c8f3fde1047f32a4093a98d633c6570/ruff-0.15.12-py3-none-musllinux_1_2_i686.whl", hash = "sha256:01da3988d225628b709493d7dc67c3b9b12c0210016b08690ef9bd27970b262b", size = 10953498, upload-time = "2026-04-24T18:17:20.674Z" }, - { url = "https://files.pythonhosted.org/packages/72/7a/a9ba7f98c7a575978698f4230c5e8cc54bbc761af34f560818f933dafa0c/ruff-0.15.12-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:9cae0f92bd5700d1213188b31cd3bdd2b315361296d10b96b8e2337d3d11f53e", size = 11447765, upload-time = "2026-04-24T18:17:09.755Z" }, - { url = "https://files.pythonhosted.org/packages/ea/f9/0ae446942c846b8266059ad8a30702a35afae55f5cdc54c5adf8d7afdc27/ruff-0.15.12-py3-none-win32.whl", hash = "sha256:d0185894e038d7043ba8fd6aee7499ece6462dc0ea9f1e260c7451807c714c20", size = 10657277, upload-time = "2026-04-24T18:17:18.591Z" }, - { url = "https://files.pythonhosted.org/packages/33/f1/9614e03e1cdcbf9437570b5400ced8a720b5db22b28d8e0f1bda429f660d/ruff-0.15.12-py3-none-win_amd64.whl", hash = "sha256:c87a162d61ab3adca47c03f7f717c68672edec7d1b5499e652331780fe74950d", size = 11837758, upload-time = "2026-04-24T18:17:00.113Z" }, - { url = "https://files.pythonhosted.org/packages/c0/98/6beb4b351e472e5f4c4613f7c35a5290b8be2497e183825310c4c3a3984b/ruff-0.15.12-py3-none-win_arm64.whl", hash = "sha256:a538f7a82d061cee7be55542aca1d86d1393d55d81d4fcc314370f4340930d4f", size = 11120821, upload-time = "2026-04-24T18:16:57.979Z" }, + { url = "https://files.pythonhosted.org/packages/a4/28/9cc1b79639e284ec103f43c88c644db4eb58cbd0ea1ca11f1193435369ac/ruff-0.16.6-py3-none-linux_armv6l.whl", hash = "sha256:61c368c26bf8e973e5ab14a2772de587bc068ea3f9a277f673380749b4898fb8", size = 10015638, upload-time = "2026-09-03T16:56:40.986Z" }, + { url = "https://files.pythonhosted.org/packages/71/11/627d342ef727ea7794edf74fe23d60a074b02c3acc2e9436684e782286ca/ruff-0.16.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:ecf4f068e2e123e43a26e9db4e19524cc56563912404e83bbfca375757e45a32", size = 10220762, upload-time = "2026-09-03T16:56:44.681Z" }, + { url = "https://files.pythonhosted.org/packages/43/d9/b75668ce41e4c8d073d18d6d08672ba6906ce45d5c06ea4fdb2e84ce3853/ruff-0.16.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:99b62ea33baf130f50368798d841f0d95527b6d817bf31817b65dd058f1d314c", size = 9835082, upload-time = "2026-09-03T16:56:47.142Z" }, + { url = "https://files.pythonhosted.org/packages/99/97/123ab10b05cde889c107c20f5a9774955104b5552796a2a8584b089ae8eb/ruff-0.16.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7fbf89013f2bb3f6835a6038ff658dc8a1b38c98dc8e724b964168ad4e881876", size = 9949304, upload-time = "2026-09-03T16:56:49.813Z" }, + { url = "https://files.pythonhosted.org/packages/3e/58/a4a2c59dd2e5b85929c912d9cac3056eb9ee8c7e75e9b9fe3e109174966b/ruff-0.16.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:56a67065e22efa6bc4d498299d3bb06c0c90aace8fac2068b5a12f9dc4d8d51d", size = 9840612, upload-time = "2026-09-03T16:56:52.368Z" }, + { url = "https://files.pythonhosted.org/packages/61/6a/ff8c8626a786c4f49d48ced4a752dadbca65f5263005f9c2416578194694/ruff-0.16.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e25cc89174874b176a157e4428d66761c2c0c006654419bf384f967f361ff1b1", size = 10543465, upload-time = "2026-09-03T16:56:55.089Z" }, + { url = "https://files.pythonhosted.org/packages/ad/bb/c47535923365f337b82e28192e4e9eef2176511007cfd99a62fc22df5dad/ruff-0.16.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0700580ed5303723cb3c11c2f1d2a8913ce77b7ea86646dddb887f5417a9ba70", size = 11267576, upload-time = "2026-09-03T16:56:57.791Z" }, + { url = "https://files.pythonhosted.org/packages/ba/50/e5119a5212b5cd63b51e1f4b25e7bd636a6668fc069a3160b108ad7e3c16/ruff-0.16.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:15f1d0b6e165a6e56567befb6629f8209271311d990bae0f37e6d065035ef5f3", size = 10781993, upload-time = "2026-09-03T16:57:00.666Z" }, + { url = "https://files.pythonhosted.org/packages/8b/98/083d8b4ef3c51a0d19db84367791cbe9f44e4b53343d19dfa83556e1cd9a/ruff-0.16.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d72c591a96986ee4268860e2b7235082129ca5e4cb9cbba653a4b57c11893757", size = 10317748, upload-time = "2026-09-03T16:57:03.428Z" }, + { url = "https://files.pythonhosted.org/packages/9a/29/68f7ff2c5ad95f19f00627ac2de95644e25fe47371ea60b2db1fd952315e/ruff-0.16.6-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:65a006baa18f33324325814c864daef03541d51564b98c517610ea756ab7003e", size = 10540096, upload-time = "2026-09-03T16:57:06.182Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/79a8f6de85968641d68a7863aeec577551924ef066a990a48ff93167beab/ruff-0.16.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:cd02a7bf1a21a8735228a3e8c95a9dc5cf86bd2a52194f4aaae2a5755b4de0f4", size = 10100494, upload-time = "2026-09-03T16:57:09.194Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e8/b81a22d9b90c00b892ccf2fa2ac36fa95de4c13ab85aea3e73795cfe4651/ruff-0.16.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:31b36f1e5ad85e0737f09d2be4e512e2e283583c14015da3b9dc07359ac0fc88", size = 9843663, upload-time = "2026-09-03T16:57:12.168Z" }, + { url = "https://files.pythonhosted.org/packages/39/aa/54f516ec5e5a11c4afdceb1c454ebb054ffb96e4f4a1705580b4346abd35/ruff-0.16.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:61029b4ab4aa723fd3064fab96b1d814492596bf0c792679fffcbde1e1679953", size = 10282461, upload-time = "2026-09-03T16:57:15.077Z" }, + { url = "https://files.pythonhosted.org/packages/52/0b/38d0aa8aa32372b96dc44f97b22e576c4147808271aab7b2cb1e353d4445/ruff-0.16.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:9ac8998457832c2061709d900856b7ad271dace0cb41f346588d540162bfa718", size = 10728808, upload-time = "2026-09-03T16:57:17.797Z" }, + { url = "https://files.pythonhosted.org/packages/5e/e5/9e274e24eeb027640ffc7442f21239f16d17f47acec15ae34f32e03a5c79/ruff-0.16.6-py3-none-win32.whl", hash = "sha256:0b87d9d16fcb63e8018423ca1d50b7260f15cb2da33e30db4baad4183a948c25", size = 10049212, upload-time = "2026-09-03T16:57:20.55Z" }, + { url = "https://files.pythonhosted.org/packages/22/31/72472449414223ed1a2da236b992adbb1a2ae59e34794574810f60ce068e/ruff-0.16.6-py3-none-win_amd64.whl", hash = "sha256:10d21c51c3495d8eaea7b703a16592117ea6eb1d649e36335aa965ff1173eb39", size = 10556402, upload-time = "2026-09-03T16:57:23.501Z" }, + { url = "https://files.pythonhosted.org/packages/fc/07/d781f8f8e1ac24bef9f3269cf62ffb1407ca24c3a8f12e5e22874f90528c/ruff-0.16.6-py3-none-win_arm64.whl", hash = "sha256:7a976c79b958f94e50a022a19f0f8c87387448020935ec14fc74331bd0a7f2c5", size = 10412850, upload-time = "2026-09-03T16:57:26.416Z" }, ] [[package]] @@ -6057,14 +6141,14 @@ wheels = [ [[package]] name = "scipy-stubs" -version = "1.17.1.4" +version = "1.18.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "optype", extra = ["numpy"] }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d1/75/d944a11fca64aa84fbb4bfcf613b758319c6103cb30a304a0e9727009d62/scipy_stubs-1.17.1.4.tar.gz", hash = "sha256:cae00c5207aa62ceb4bcadea202d9fbbf002e958f9e4de981720436b8d5c1802", size = 396980, upload-time = "2026-04-13T11:46:54.528Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fc/99/02c608a58cf99774c577f22e457427f87c8e608652c5de95178daa003e1f/scipy_stubs-1.18.1.0.tar.gz", hash = "sha256:87bec0df883cd9cd6b7dc4c74a33362cf550e9cad679643a29a886ab2b438ddc", size = 448822, upload-time = "2026-08-22T09:22:52.944Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/92/f8/334aa5a7a482ea89cb14d92f6a4d9ffa1e193e733144d4d14c7ffcb33583/scipy_stubs-1.17.1.4-py3-none-any.whl", hash = "sha256:e6e5c390fb864745bc3d5f591de81f5cb4f84403857d4f660acb5b6339956f5b", size = 604752, upload-time = "2026-04-13T11:46:53.135Z" }, + { url = "https://files.pythonhosted.org/packages/12/11/263ced30149fbede00614a11f01de792842d3636b5a9e3abfee34e764a0e/scipy_stubs-1.18.1.0-py3-none-any.whl", hash = "sha256:fc1f00da3eb6bf1adf2138774b5e6a91dcf7c77039ff199577dc47929c10793e", size = 653731, upload-time = "2026-08-22T09:22:51.43Z" }, ] [[package]] @@ -6661,11 +6745,11 @@ wheels = [ [[package]] name = "types-aiofiles" -version = "25.1.0.20260409" +version = "25.1.0.20260518" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6c/66/9e62a2692792bc96c0f423f478149f4a7b84720704c546c8960b0a047c89/types_aiofiles-25.1.0.20260409.tar.gz", hash = "sha256:49e67d72bdcf9fe406f5815758a78dc34a1249bb5aa2adba78a80aec0a775435", size = 14812, upload-time = "2026-04-09T04:22:35.308Z" } +sdist = { url = "https://files.pythonhosted.org/packages/df/42/f5b9b90162d2196f016b87228d6bf43f2c2c0c6501bfd5415001b3eb68bb/types_aiofiles-25.1.0.20260518.tar.gz", hash = "sha256:c0c95eb78755d4fa7b397d4f0332c632714dd7cd0d17f49b96e31d4d7a8d8c76", size = 14891, upload-time = "2026-05-18T06:05:27.804Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/27/d0/28236f869ba4dfb223ecdbc267eb2bdb634b81a561dd992230a4f9ec48fa/types_aiofiles-25.1.0.20260409-py3-none-any.whl", hash = "sha256:923fedb532c772cc0f62e0ce4282725afa82ca5b41cabd9857f06b55e5eee8de", size = 14372, upload-time = "2026-04-09T04:22:34.328Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3d/7a9ed9faafeae3aa3b5bc22fa5b979ff9cf3c83ecbe919b58eae07795b8c/types_aiofiles-25.1.0.20260518-py3-none-any.whl", hash = "sha256:f776bdfb4bec17f743d9ef042e61edf03bdcc7821fc08556fba9b63d873fdea9", size = 14377, upload-time = "2026-05-18T06:05:26.871Z" }, ] [[package]] @@ -6703,32 +6787,32 @@ wheels = [ [[package]] name = "types-cachetools" -version = "7.0.0.20260503" +version = "7.0.0.20260713" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ec/57/5d3b8b3e66b002911ec1274e87f904eeee1d843c8713d95476c25c29cf31/types_cachetools-7.0.0.20260503.tar.gz", hash = "sha256:dfa4dcdf453f397dfc6d69fc0a57423ac1f248393f70aa56b5d05fac2df7a96c", size = 10033, upload-time = "2026-05-03T05:19:54.128Z" } +sdist = { url = "https://files.pythonhosted.org/packages/34/64/66d7efdb36ecf6826aca5415e59fe2df96e97d24157147e53acfbe8dda11/types_cachetools-7.0.0.20260713.tar.gz", hash = "sha256:f1acf079e9c66a81e096a897ef0b261a82117cf856834e37b4bd0c9a116a076a", size = 10199, upload-time = "2026-07-13T05:22:21.845Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3d/a8/84562723d9a3572e0851d82bdea6bed5a7dc033c6bd648f492c76b8c4ac8/types_cachetools-7.0.0.20260503-py3-none-any.whl", hash = "sha256:011b4fe0e85ef05c4a2471a4fda40254a78746b501cc1727359233872bb3a4e9", size = 9493, upload-time = "2026-05-03T05:19:53.124Z" }, + { url = "https://files.pythonhosted.org/packages/0e/c7/d3525c9dbdc1be7786bad46655ef051b6e7993f656d304719ec40079c91c/types_cachetools-7.0.0.20260713-py3-none-any.whl", hash = "sha256:6db9bcc7a3840d39e91c04117d85a9d0937eacc9d14d12a873e2b01a2d24a71d", size = 9615, upload-time = "2026-07-13T05:22:20.76Z" }, ] [[package]] name = "types-cffi" -version = "2.0.0.20260429" +version = "2.1.0.20260827" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "types-setuptools" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0c/7d/56b9be8b0f9dfbffb7c73e248aacf178693ff3c6cf765b77c43a1e886e04/types_cffi-2.0.0.20260429.tar.gz", hash = "sha256:afe7d9777a2921139623af0b94647637a5bd0b938b77ec125e5e5e068a1727bd", size = 17562, upload-time = "2026-04-29T05:16:43.29Z" } +sdist = { url = "https://files.pythonhosted.org/packages/04/bb/dbb844365103e4dc6ea52cdae0946c3ca55a7b8587e6f351710d7ee5bb78/types_cffi-2.1.0.20260827.tar.gz", hash = "sha256:53d1604771ad4ff09a1a90d6f6980ab36bebb6c39476dcc5bbf4896fa510d736", size = 18150, upload-time = "2026-08-27T12:07:21.754Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b8/2c/79fa47a70d534f63a54b6d22e28cc842f8c6d9ebec93048355b0020bc7a9/types_cffi-2.0.0.20260429-py3-none-any.whl", hash = "sha256:6a4237bfdbd50e4d0726929070d8b9983bde541726a5a6fe0e8e24e78c1b3826", size = 20103, upload-time = "2026-04-29T05:16:42.155Z" }, + { url = "https://files.pythonhosted.org/packages/0c/fc/690c243ddac627901f1448f5cb29ca3b5463774a00ac932862c60d7ce5cf/types_cffi-2.1.0.20260827-py3-none-any.whl", hash = "sha256:851b6ffa5b962c577a2330b98ac0b60c56c904d086726276946388f58a0cffaf", size = 20525, upload-time = "2026-08-27T12:07:20.836Z" }, ] [[package]] name = "types-colorama" -version = "0.4.15.20260408" +version = "0.4.15.20260508" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/83/c0/1c02ed9edf3462a392f4ea4bda80fa10c538c63d1d7be255dc7dcb545007/types_colorama-0.4.15.20260408.tar.gz", hash = "sha256:9a816657927489463edec1b7b47933b73fe737d37a3616bf596b7de843441032", size = 10623, upload-time = "2026-04-08T04:28:31.763Z" } +sdist = { url = "https://files.pythonhosted.org/packages/be/d5/4870d88c6c87adf786ef33d674cbf82b3a2d5fcbe6deec29282cff80e8b3/types_colorama-0.4.15.20260508.tar.gz", hash = "sha256:3a8916039e57452bd21f57e674e1f221ca9e4f319893c5e3bbd37b845c27d8e6", size = 10638, upload-time = "2026-05-08T04:47:14.593Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/65/d03948be8ae9362ad26f36443eab051fe5524295fe008126cd65792f9833/types_colorama-0.4.15.20260408-py3-none-any.whl", hash = "sha256:7327a51c760d94f7df2e8c72c275a4468c03c3abb606d23995cb37e3d24d9132", size = 10763, upload-time = "2026-04-08T04:28:30.688Z" }, + { url = "https://files.pythonhosted.org/packages/56/33/a3449e3e93c43861b92d0a93ed4ea5505756463e507625812cfb29c91c7a/types_colorama-0.4.15.20260508-py3-none-any.whl", hash = "sha256:b0c39908a3e5171ef1f8bf3d59fae082e9eaff3a19ca49b6d640b83f78cff61c", size = 10755, upload-time = "2026-05-08T04:47:13.761Z" }, ] [[package]] @@ -6742,199 +6826,196 @@ wheels = [ [[package]] name = "types-defusedxml" -version = "0.7.0.20260408" +version = "0.7.0.20260504" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/39/af/d324da5ffbf0af40477533a09ee6c902de335c445a8dcc88c58f62af6e5f/types_defusedxml-0.7.0.20260408.tar.gz", hash = "sha256:f35377d59344f98b57f9bf319cff2107aac35f9e4d42f9ed6cfeeafacffadb00", size = 10638, upload-time = "2026-04-08T04:26:12.239Z" } +sdist = { url = "https://files.pythonhosted.org/packages/da/d2/4553c8fa9cdebfe1e84b950cf790a4d2376a97fa016e43f7c65323fa6c7d/types_defusedxml-0.7.0.20260504.tar.gz", hash = "sha256:2ab2828a3f97111ba1c16cee273ad4124a831fc9198c41bf8368ff6ea48ad300", size = 10729, upload-time = "2026-05-04T05:22:50.192Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ed/68/7570cfb818d6a5b3ff964114527e28e360eccf18329b457f057a18596e64/types_defusedxml-0.7.0.20260408-py3-none-any.whl", hash = "sha256:2d68db82412170b91b3e490b7c118a4f4e5a27756a126e2453f629c8d514b106", size = 13435, upload-time = "2026-04-08T04:26:11.347Z" }, + { url = "https://files.pythonhosted.org/packages/bf/2d/8a4b5ba1d732b8bc691f0efbb1c6f77cb5f6f473b2afe181d83d910773c5/types_defusedxml-0.7.0.20260504-py3-none-any.whl", hash = "sha256:a959e3a0a43b93e464bd625d91ec9193a2703ddc10443bdd627792485fae0b10", size = 13467, upload-time = "2026-05-04T05:22:49.319Z" }, ] [[package]] name = "types-deprecated" -version = "1.3.1.20260408" +version = "1.3.1.20260728" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1a/db/076de3e81b106d3cec17aec9640ab1b2d02f29bad441de280459c161ce65/types_deprecated-1.3.1.20260408.tar.gz", hash = "sha256:62d6a86d0cc754c14bb2de31162d069b1c6a07ce11ee65e5258f8f75308eb3a3", size = 8524, upload-time = "2026-04-08T04:26:39.894Z" } +sdist = { url = "https://files.pythonhosted.org/packages/6d/0f/a6c55e899f6a2b3519f4079ee1d99f64411299a6d882decbdf17b17319ba/types_deprecated-1.3.1.20260728.tar.gz", hash = "sha256:cab836fdcf6b57d3e277e62d9d76d8a4c556a2639fd0e90cb555fa0e8300d164", size = 8729, upload-time = "2026-07-28T04:51:30.946Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/53/d0/d3258379deb749d949c3c72313981c9d2cceec518b87dcf506f022f5d49f/types_deprecated-1.3.1.20260408-py3-none-any.whl", hash = "sha256:b64e1eab560d4fa9394a27a3099211344b0e0f2f3ac8026d825c86e70d65cdd5", size = 9079, upload-time = "2026-04-08T04:26:38.752Z" }, + { url = "https://files.pythonhosted.org/packages/fe/e6/4e4d2a7d861ac277fbdce3d9a25ce5205f366bcc4e37c021eeb2017c160c/types_deprecated-1.3.1.20260728-py3-none-any.whl", hash = "sha256:d94b3e1db08db6a63ad0e8519e2da2b2d22843f015efa7bd83baef6aa99f7403", size = 9109, upload-time = "2026-07-28T04:51:30.008Z" }, ] [[package]] name = "types-docutils" -version = "0.22.3.20260408" +version = "0.23.0.20260827" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/3c/49/48a386fe15539556de085b87a69568b028cca2fa4b92596a3d4f79ac6784/types_docutils-0.22.3.20260408.tar.gz", hash = "sha256:22d5d45e4e0d65a1bc8280987a73e28669bb1cc9d16b18d0afc91713d1be26da", size = 57383, upload-time = "2026-04-08T04:27:26.924Z" } +sdist = { url = "https://files.pythonhosted.org/packages/3c/f8/55b739a017fe34c1790a1e8cf1a63c8cf50d7e64777e9b2f12032a73515d/types_docutils-0.23.0.20260827.tar.gz", hash = "sha256:757ca7313a337f83b761d917fe71e60d723376898338105aa78505b5214f4c5c", size = 58209, upload-time = "2026-08-27T12:06:52.325Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/08/47/1667fda6e9fcb044f8fb797f6dc4367b88dc2ab40f1a035e387f5405e870/types_docutils-0.22.3.20260408-py3-none-any.whl", hash = "sha256:2545a86966022cdf1468d430b0007eba0837be77974a7f3fafa1b04a6815d531", size = 91981, upload-time = "2026-04-08T04:27:25.934Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ab/6939f1ce2b1e02e2f19e7ce85728570a27740224031fb13a9dd044731943/types_docutils-0.23.0.20260827-py3-none-any.whl", hash = "sha256:4db1342b6defed4de29cb2d65ab295e3ecc13808f2718ee2980ed18cfafef730", size = 92112, upload-time = "2026-08-27T12:06:51.31Z" }, ] [[package]] name = "types-flask-cors" -version = "6.0.0.20260408" +version = "6.0.3.20260712" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "flask" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/22/68/e58191af5b56e836a4a2e2583ecfad91bde176940edf1bfc8ea706a5f74d/types_flask_cors-6.0.0.20260408.tar.gz", hash = "sha256:8c440c158c335819bb9286870c9770687ae6d943510fdd97e4b573324f8d2178", size = 10223, upload-time = "2026-04-08T04:35:42.608Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/95/d019181bd47dc32de454ebab4ff2f1cba09d1807da7823522e92b2d8a579/types_flask_cors-6.0.3.20260712.tar.gz", hash = "sha256:05d6dd4c49e2e8e64076b84caf6389d51327e9c4f3a37d4ccf0278b5b0d8daa1", size = 10231, upload-time = "2026-07-12T05:14:23.55Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a2/8d/eb905e231aaed6c0853f002446a1fb12d5a32d79b688f2cdd4f8d6e6ce03/types_flask_cors-6.0.0.20260408-py3-none-any.whl", hash = "sha256:ccd8801862b3ebd27754734b84fc3dcfebd0f8056380ae88254c7dd799d64a39", size = 9993, upload-time = "2026-04-08T04:35:41.452Z" }, + { url = "https://files.pythonhosted.org/packages/ba/bc/88f077fde1b3139b714e99db06ed592ecf4fa1b6cbfb54eec50a966f7ecb/types_flask_cors-6.0.3.20260712-py3-none-any.whl", hash = "sha256:308ecfa65c17abc59edbed74258d24099c82f5e94cb1bc4f3016313df4e5e4f0", size = 9939, upload-time = "2026-07-12T05:14:22.64Z" }, ] [[package]] name = "types-flask-migrate" -version = "4.1.0.20260408" +version = "4.1.0.20260508" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "flask" }, { name = "flask-sqlalchemy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/31/56f5607fca2ad4e41da095b0e22ce9749d29d985df8c0229907bf662413b/types_flask_migrate-4.1.0.20260408.tar.gz", hash = "sha256:65ef927584777eac9a4591eb8320c09eb6eb8862d2ffdd6e23ad485a2869b228", size = 8773, upload-time = "2026-04-08T04:36:22.197Z" } +sdist = { url = "https://files.pythonhosted.org/packages/87/cd/31a5b4882cee1ba417cd602d5b55c263c51471cd8cbe4720e17238d9a075/types_flask_migrate-4.1.0.20260508.tar.gz", hash = "sha256:af42934032789f8b4e778c0d07ea22d670e7920894481589bfa18dcfa776376e", size = 8815, upload-time = "2026-05-08T04:52:05.782Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cd/4b/1d1b300251d33f1a97004ef8bba53139116b00872cfb85521d1412259627/types_flask_migrate-4.1.0.20260408-py3-none-any.whl", hash = "sha256:ffdacb78f6697422aa09bdebba34f4133b2443a95a59761c279fc5d368c009d9", size = 8670, upload-time = "2026-04-08T04:36:21.394Z" }, + { url = "https://files.pythonhosted.org/packages/8a/b8/fe3858bb1848047b938e75001b44442a84e8c7445788f20abf7f7df2f5a2/types_flask_migrate-4.1.0.20260508-py3-none-any.whl", hash = "sha256:f22dfd36fe2c14eb533361ad021a26fc7c89079026c3b3b0ebb2d6a48a80b8e0", size = 8661, upload-time = "2026-05-08T04:52:04.673Z" }, ] [[package]] name = "types-gevent" -version = "26.4.0.20260409" +version = "26.8.0.20260811" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "types-greenlet" }, { name = "types-psutil" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a4/ea/17fa935aa62d45cb9f67947e93c3c0c1ed97a76d579b12e1623cd348b68a/types_gevent-26.4.0.20260409.tar.gz", hash = "sha256:6b029c599fe4ec0efce8cd2bf5e5ae958d9808aa5b2f7bdfcb9b9eb42d91cc6a", size = 38333, upload-time = "2026-04-09T04:22:42.334Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b6/65/2fe306d148c8bac9944641c606bff4a6beff5719b922897695bb742c9fda/types_gevent-26.8.0.20260811.tar.gz", hash = "sha256:f4b5cd46b4baf71621fe8d3f37f9a36b8d0e7bdd90a740d8a9f37a1327d16d14", size = 39064, upload-time = "2026-08-11T03:24:20.483Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/17/04671a7e3de8c0fdd4c39dc43830b496ad68998d37cff38e0d9701f77a67/types_gevent-26.4.0.20260409-py3-none-any.whl", hash = "sha256:f5f5eb7365a9b8b738787a2dc93c509ee0ca919c6d4388504f2cd09e476d4066", size = 55491, upload-time = "2026-04-09T04:22:41.226Z" }, + { url = "https://files.pythonhosted.org/packages/6a/57/d0d281bd688942a0bef5f4d73266c51d991ccd67d1c9557540cc84bf520b/types_gevent-26.8.0.20260811-py3-none-any.whl", hash = "sha256:5f4e6087ec846dbaf7323b5268a41dac771d2fab94aced56504919347b0219e7", size = 55540, upload-time = "2026-08-11T03:24:19.437Z" }, ] [[package]] name = "types-greenlet" -version = "3.5.0.20260428" +version = "3.5.0.20260518" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/79/50/d255c0e068679d7b9441d9408424ddf9e1f35620548e121003b3660af526/types_greenlet-3.5.0.20260428.tar.gz", hash = "sha256:6c188f5e9c5775d50bd00780a3eb1fb3cde17c396cf9703e3d417936e9e7a082", size = 9003, upload-time = "2026-04-28T05:19:43.062Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/58/ec7e4d35ce36557d7599d347c51632723e5f89af551af776d25bab7c605f/types_greenlet-3.5.0.20260518.tar.gz", hash = "sha256:2abc0b31a60d10244bba4a9f9e5d19b7254749b14ea85cb2f72eef282fab39f4", size = 9084, upload-time = "2026-05-18T06:03:08.352Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/30/e5/5ff280f02392ced53cb5e866b660b492b4245b1395a61e57d2a6dc02977b/types_greenlet-3.5.0.20260428-py3-none-any.whl", hash = "sha256:7b0f23ce84ee93474d4aa8058920f0578181e11431be92ce9a4ad4123de2c41b", size = 8809, upload-time = "2026-04-28T05:19:41.976Z" }, + { url = "https://files.pythonhosted.org/packages/4e/1f/112ebbffe68c40af3bca8e948a9d2df66a53dd7b3124e031e3110fcba3e5/types_greenlet-3.5.0.20260518-py3-none-any.whl", hash = "sha256:ce8f2b59314ffd683648d8f7fc1eab7b7a36a0330adb4a054d0a2157b9624166", size = 8816, upload-time = "2026-05-18T06:03:07.06Z" }, ] [[package]] name = "types-html5lib" -version = "1.1.11.20260408" +version = "1.1.11.20260518" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "types-webencodings" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/16/59/914d00107c770e49fa57d4c4572e0371bbce14321385fd2ea3e06691b62d/types_html5lib-1.1.11.20260408.tar.gz", hash = "sha256:8a281aa367bc77dbc758358cd9bef79530f2d154eeed9b33705bb035a0dab9e4", size = 18316, upload-time = "2026-04-08T04:35:49.581Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b8/5a/0c708d1b0d35ad48b6a223c77c4a882fd016b40c25becb082a92e02a9c00/types_html5lib-1.1.11.20260518.tar.gz", hash = "sha256:4f33c087cb1119d65c4c80eca4323c2b501f9eaf8af9616b8b732ed4d8eae8fa", size = 18420, upload-time = "2026-05-18T06:07:23.662Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/61/19/12d95e98e42e120522665ec6850b38df8d2c1cca94e21c4d7f8578acb64e/types_html5lib-1.1.11.20260408-py3-none-any.whl", hash = "sha256:d18dc4b90d6d6745585790b920db13ede43e1f8ff6ee1ac0ceb0dec4223a06fa", size = 24313, upload-time = "2026-04-08T04:35:48.679Z" }, + { url = "https://files.pythonhosted.org/packages/4d/d0/b088b9f11eb69637d6826843f06caaff60247156735a25512922d3dc2c13/types_html5lib-1.1.11.20260518-py3-none-any.whl", hash = "sha256:9baa7912224ebb37027c5ccb7e3768e43ea47b1dfdd977e7ddc4b0a4a550584d", size = 24339, upload-time = "2026-05-18T06:07:22.876Z" }, ] [[package]] name = "types-jmespath" -version = "1.1.0.20260408" +version = "1.1.0.20260724" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a1/5e/33881ff525fbaa71cb6192d81fd4039607006ff48f85c40ef1e20d72d1d3/types_jmespath-1.1.0.20260408.tar.gz", hash = "sha256:42483cfc3d16bdd88c1150a7419d59ef59b8bdc4db3eec8ebf6971a0dad1a425", size = 10733, upload-time = "2026-04-08T04:29:22.923Z" } +sdist = { url = "https://files.pythonhosted.org/packages/99/e5/1645e22a7aeddc20673cd7899e91a8131fd98e5f4eaaeb96fa666af05efc/types_jmespath-1.1.0.20260724.tar.gz", hash = "sha256:cd429dab3bb2f339a5a546f444f2f96c30cb1f31395590fb1d609ed13624d919", size = 10822, upload-time = "2026-07-24T04:58:24.694Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e4/f8/4c34097ce72dc8ea533db26a0162c53837398b26d4a0645ca3c7df74370b/types_jmespath-1.1.0.20260408-py3-none-any.whl", hash = "sha256:58a29fe039e5d3f9d0d42f1b067b9efa7c3e29c7e6df9c6830cbe5fa44ffb943", size = 11512, upload-time = "2026-04-08T04:29:22.133Z" }, + { url = "https://files.pythonhosted.org/packages/c1/e4/ed44f19a906c8f249653e1f1befb5f1cc87a7826629375ae7ceb62fcd0cc/types_jmespath-1.1.0.20260724-py3-none-any.whl", hash = "sha256:ad965080d2ef25f4dc95da30819be559597c4301efc0311a9571b2ce8fc62c32", size = 11524, upload-time = "2026-07-24T04:58:23.763Z" }, ] [[package]] name = "types-markdown" -version = "3.10.2.20260408" +version = "3.10.2.20260712" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/dd/0e/a690840934c459aa50e0470e7550d7f151632eafa4a8e3c21d18009ad15c/types_markdown-3.10.2.20260408.tar.gz", hash = "sha256:d5cba15ed65a1420e80e31c17e3d4a2ad7208a3f3a4da97fd2c5f093caf523cd", size = 19784, upload-time = "2026-04-08T04:33:07.644Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/eb/9520ed01687401b47265594955c0a9202a4f547795176de61bff77c8dfda/types_markdown-3.10.2.20260712.tar.gz", hash = "sha256:25aea17282490f35ab6b17a87771abd2f479185aaff8e8f4a0035043f02f2c52", size = 20185, upload-time = "2026-07-12T05:13:53.537Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/75/7e/265a8df257c8dced6ea89295f793a19f0a49ccbfeae1ed562368b2caf7a3/types_markdown-3.10.2.20260408-py3-none-any.whl", hash = "sha256:b0bbe8b7a8174db732067b86e391262898f5f536589ea81efec6d35ceb829331", size = 25857, upload-time = "2026-04-08T04:33:06.769Z" }, + { url = "https://files.pythonhosted.org/packages/9f/ea/a8dc2c8977870d27b8b44c4ba2952d765f9d39626e42d0083c871c1c1ebf/types_markdown-3.10.2.20260712-py3-none-any.whl", hash = "sha256:a551ddedde46e0eaca7059aa3d0e42db71afe2b53d8b58f72f2de63f3284f625", size = 25842, upload-time = "2026-07-12T05:13:52.702Z" }, ] [[package]] name = "types-oauthlib" -version = "3.3.0.20260408" +version = "3.3.0.20260724" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/79/7e/4cf7b08b4c6b266d9967c02ebdba8c5390029d5750def924b23679a730a0/types_oauthlib-3.3.0.20260408.tar.gz", hash = "sha256:deaeccbc33634f5efa7ef320924bce743495f5a1520073ce4fa0fea441bf063d", size = 26066, upload-time = "2026-04-08T04:28:45.636Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9e/ed/72823bc9c60e8f5354827eec6b85aa1baec94b3ca6c62f8e104c3717c31b/types_oauthlib-3.3.0.20260724.tar.gz", hash = "sha256:00c7dab6a2f764e991180bff4bdb1ba8bddb1d546013b1c81f903192c30f2386", size = 26194, upload-time = "2026-07-24T04:58:57.564Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d7/77/6866665af7b414bbffd37028a92618d3771402ae587e9cd2d70efcb6d8f6/types_oauthlib-3.3.0.20260408-py3-none-any.whl", hash = "sha256:1c305d18a05636fac4953800aa0982e54c258562838dafeaa6a3d05b7f4669fe", size = 48987, upload-time = "2026-04-08T04:28:44.719Z" }, + { url = "https://files.pythonhosted.org/packages/2b/e8/96d1e19015c1384022a296a2e73d7843739ccc2f13afcaed5c2f797c86e4/types_oauthlib-3.3.0.20260724-py3-none-any.whl", hash = "sha256:73bc776c00ed00957bc1422a3a53696d8aa18f24c47a628e08566c0d4e0a6bbd", size = 48967, upload-time = "2026-07-24T04:58:56.634Z" }, ] [[package]] name = "types-objgraph" -version = "3.6.0.20260408" +version = "3.6.0.20260508" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/82/4b/e43381191b1d9d1a0d8b1d7da12ee28ea63f97f38bc6694231dde066b3c8/types_objgraph-3.6.0.20260408.tar.gz", hash = "sha256:9937aae5ad5bb625a2091b33e2f67e979f61e3719078d318b2261c4e7f13ac9a", size = 7606, upload-time = "2026-04-08T04:30:41.072Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/5d/9809f0c8ecab48e7d132af4b2757df5153dd1ee90e11830532cfb469330f/types_objgraph-3.6.0.20260508.tar.gz", hash = "sha256:86fa246a38022c1c1385601942e3fe69e4dd1489fb82b47c2125664e4fa88a94", size = 7656, upload-time = "2026-05-08T04:48:25.635Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/38/99/6f618e0931367814b2ab9ad2b946f0f0ca4b8b02405a3552bcb90acc1b5c/types_objgraph-3.6.0.20260408-py3-none-any.whl", hash = "sha256:fd4ae0c6c10e260a3dfdd778f3f79f081c804f9d48b5bb6c2299d8645b287c5f", size = 8059, upload-time = "2026-04-08T04:30:40.301Z" }, + { url = "https://files.pythonhosted.org/packages/47/59/d39e5ecd6e70fd261fd935ba7cdc02c6f7023580bf01cd8edd6fba7e1c44/types_objgraph-3.6.0.20260508-py3-none-any.whl", hash = "sha256:628982bfcc8cd6dcabe23cce1bd9ecdc539d1d3ca14f5dd62ac4c0d0170cbb4e", size = 8052, upload-time = "2026-05-08T04:48:24.853Z" }, ] [[package]] name = "types-olefile" -version = "0.47.0.20260408" +version = "0.47.0.20260508" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/84/d0/1c7e058666a4e5364463ad0a7bfd7a0bbc2180df427016cc7ebeeddb0b29/types_olefile-0.47.0.20260408.tar.gz", hash = "sha256:01fbcb6332152e88486634460c8d59a8c75da9a50d85e0ff6f754c02db3fc23e", size = 9037, upload-time = "2026-04-08T04:30:13.973Z" } +sdist = { url = "https://files.pythonhosted.org/packages/86/c6/7efcaba079309d7f29a238f1ffbe810c4952f9e0303aa9353b80e74ec1c9/types_olefile-0.47.0.20260508.tar.gz", hash = "sha256:02131a421b0e90d3ca61770c89c0d7ea2095a13560a87e7add26a42c10ab7a0e", size = 9089, upload-time = "2026-05-08T04:48:05.447Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/37/20/b88f8f1336fd3772813c21dd536e50d10c4416294539b8b623e769e9b4a2/types_olefile-0.47.0.20260408-py3-none-any.whl", hash = "sha256:2499f110beb659504173dcd66c069a297b210f715ad45a713e097ecd3a265992", size = 9493, upload-time = "2026-04-08T04:30:13.173Z" }, + { url = "https://files.pythonhosted.org/packages/f4/a3/1811204ac3b74f42863f8de0635d0e3663502d24f66b7f6d5f44c09e4934/types_olefile-0.47.0.20260508-py3-none-any.whl", hash = "sha256:d9d799fe07e5c8afcfcfc7437737a4d78beff9eccb712c96a61231ac1bdc1c3e", size = 9494, upload-time = "2026-05-08T04:48:04.294Z" }, ] [[package]] name = "types-openpyxl" -version = "3.1.5.20260408" +version = "3.1.5.20260827" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/74/c9/24f03f9d9fedd164de699c1418869bef9b819f59f75e7f647f5788c02d98/types_openpyxl-3.1.5.20260408.tar.gz", hash = "sha256:b49274d086fbb6e6bcd2a67d161dd1161d4d380488e4cce546d647d45eadcac2", size = 101361, upload-time = "2026-04-08T04:30:37.809Z" } +sdist = { url = "https://files.pythonhosted.org/packages/8e/6b/ce650ce7754a2bce3ca1dfbce7f7441df092e2dc6047d00e04f840c2b56e/types_openpyxl-3.1.5.20260827.tar.gz", hash = "sha256:be8b605fb99cfd7d5f5576d4a508e8ec44be2dd15b85157c559080de6384be34", size = 101985, upload-time = "2026-08-27T12:06:18.927Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5f/e8/64db0c32c6fda4b198aff84329ceeea00a93d16c28f05e9fe0404ddb8b8c/types_openpyxl-3.1.5.20260408-py3-none-any.whl", hash = "sha256:7ab7586796aed017cde50b81bd67ba024120c39b99c102320b57dd91390c317f", size = 166044, upload-time = "2026-04-08T04:30:36.449Z" }, + { url = "https://files.pythonhosted.org/packages/12/23/9708c0895d237205ab2b31c06f97d72294f69789ff9923ff7f4aa2126d6b/types_openpyxl-3.1.5.20260827-py3-none-any.whl", hash = "sha256:94e176d871d12e3cbc34f8fb03dc14db2a4245a6690791daf16fc7b08fd67869", size = 165885, upload-time = "2026-08-27T12:06:17.88Z" }, ] [[package]] name = "types-pexpect" -version = "4.9.0.20260408" +version = "4.9.0.20260518" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9a/0f/5e9aa68e4595264e968ffaa3358afb2a8d60093f460aaa7e0398c0d9bfd0/types_pexpect-4.9.0.20260408.tar.gz", hash = "sha256:faedd97fc8086b224bc1966770c486ac6ec96bef07dc47cc2724fe4ae62f8f4a", size = 13471, upload-time = "2026-04-08T04:32:30.624Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/84/c52c4841aeaf1d56551f14335ca99a40e7e04b4f8358b402115910828e8e/types_pexpect-4.9.0.20260518.tar.gz", hash = "sha256:38c373798209428dd90988b6fd4b8839c68c7e3ed79215f1ab11fa42d7ff9427", size = 13568, upload-time = "2026-05-18T06:03:35.378Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c2/13/96004a3e5dd6c6e7de4edc421d5a2926e062d22be7b006edab747ed42830/types_pexpect-4.9.0.20260408-py3-none-any.whl", hash = "sha256:ba6699609bb6593f00ef7204efc390fd10bc14a8d632f22c8dea13f263b16fcc", size = 17083, upload-time = "2026-04-08T04:32:29.75Z" }, + { url = "https://files.pythonhosted.org/packages/01/11/17b1da645d5f2a12e4db83ae38dbb732fbac96fb3bd7416635c844f7d24e/types_pexpect-4.9.0.20260518-py3-none-any.whl", hash = "sha256:bf2422e825e4efe29cc4a1b7bdc3c375ae97d9c3046ce6b2018c100fb049c262", size = 17087, upload-time = "2026-05-18T06:03:34.14Z" }, ] [[package]] name = "types-protobuf" -version = "7.34.1.20260503" +version = "7.35.1.20260827" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a0/31/87969cb3e62287bde7598b78b3c098d2873d54f5fb5a7cfbcaa73b8c965e/types_protobuf-7.34.1.20260503.tar.gz", hash = "sha256:effbc819aa17e02448dde99f089c6794662d66f4b2797e922f185ffe0b24e766", size = 68830, upload-time = "2026-05-03T05:19:50.739Z" } +sdist = { url = "https://files.pythonhosted.org/packages/44/07/541ffc94a4baee7d92ec91d91018aa684f97ece608b74619863e3cfd9cb3/types_protobuf-7.35.1.20260827.tar.gz", hash = "sha256:5a98c18177cfd968d6a0de55ecfc4221aa829ef88bcd86104298e028516b04af", size = 69646, upload-time = "2026-08-27T12:06:04.93Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f9/67/a33fb18090a927794a5ee4b1a30730b528ace0dad6b18932540d21258184/types_protobuf-7.34.1.20260503-py3-none-any.whl", hash = "sha256:75fd66121d56785c91828b8bf7b511f39ba847f11e682573e41847f01e9cd1de", size = 86019, upload-time = "2026-05-03T05:19:49.486Z" }, + { url = "https://files.pythonhosted.org/packages/01/e2/7ce7c4802bcf3732155dedc23fe3d2b506a387d6b42da61261886f42af80/types_protobuf-7.35.1.20260827-py3-none-any.whl", hash = "sha256:7cc452a012678a6a889287d4cb702ea54b9f90a6ab0f3aa4c019d21f3ae7529b", size = 86412, upload-time = "2026-08-27T12:06:03.826Z" }, ] [[package]] name = "types-psutil" -version = "7.2.2.20260408" +version = "7.2.2.20260827" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/44/14/279fd5defebbd560ede04aecd38f7651cccee7336f2264d0889d8c9a9d43/types_psutil-7.2.2.20260408.tar.gz", hash = "sha256:e8053450685965b8cd52afb62569073d00ea9967ae78bb45dff5f606847f97f2", size = 26556, upload-time = "2026-04-08T04:27:44.349Z" } +sdist = { url = "https://files.pythonhosted.org/packages/89/ea/23a949b56d3a226a142b43c5c32404fae7044400296d18e8eda63d5d03a4/types_psutil-7.2.2.20260827.tar.gz", hash = "sha256:3c6067dba47c700495ca493f07b11e866ba13de223aabb26da555f9c86ae0b1f", size = 27294, upload-time = "2026-08-27T12:06:22.279Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/af/40/2fd92a4a1ee088c4dbcc44c977908d9869838d9cd2a2fa2e001352f56694/types_psutil-7.2.2.20260408-py3-none-any.whl", hash = "sha256:0c334f6f6bc9e9c24fca5c7d1f0b6971c961a0a2e3956dc5ce704722c01f9762", size = 32861, upload-time = "2026-04-08T04:27:42.929Z" }, + { url = "https://files.pythonhosted.org/packages/4b/1b/7e0f5cfad4faa4a2e0845f69e9206eeefc6659dfa11d07da04e2fa47d08b/types_psutil-7.2.2.20260827-py3-none-any.whl", hash = "sha256:62364359cf85482aa698a62488e5420cae5c576e8acec450ce7fb3b91cdb3d96", size = 33365, upload-time = "2026-08-27T12:06:21.444Z" }, ] [[package]] name = "types-psycopg2" -version = "2.9.21.20260422" +version = "2.9.21.20260724" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b9/a2/ecb04604074a7f2e82231ab1f2d3b5a792589aa3c21a597cb3232a38ece3/types_psycopg2-2.9.21.20260422.tar.gz", hash = "sha256:ad7574fa8e25d9aa96ab96cd280c4dee20872725cd1fe6a6d3facc354f2644d4", size = 27123, upload-time = "2026-04-22T04:36:33.263Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/29/09ca8f0ad16105193deabcaf8256059e361e9e37ff24551efd9c739e240b/types_psycopg2-2.9.21.20260724.tar.gz", hash = "sha256:db31031c37de823a2b21c787cb84832174fdda2a99a8b1af648206f19cc32f8c", size = 27644, upload-time = "2026-07-24T04:57:36.61Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/61/08/82f86c2d0a7ae4d335c6fe3c4ad193c4a57f0d6bfe1a676289cf63667275/types_psycopg2-2.9.21.20260422-py3-none-any.whl", hash = "sha256:e240684ac37946c5a2a058b04ea1f2fd0e4ee2655719b8c3ec9abf37f96da5ba", size = 24918, upload-time = "2026-04-22T04:36:32.108Z" }, + { url = "https://files.pythonhosted.org/packages/cb/90/1e77eb76030bb5feb249ecb41cd7647c6ae831ec7bd2b61a61beecac4029/types_psycopg2-2.9.21.20260724-py3-none-any.whl", hash = "sha256:4f87890dd06cea99e3bb0536330ffc2a7320e69059dc1ee0e2c884ef2718f2b4", size = 24964, upload-time = "2026-07-24T04:57:35.703Z" }, ] [[package]] name = "types-pygments" -version = "2.20.0.20260408" +version = "2.21.0.20260819" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "types-docutils" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/fe/89/4b443128fa540c54a8f7ecdeec225aab4818534167c4a2d133099dc00fa6/types_pygments-2.20.0.20260408.tar.gz", hash = "sha256:e8a56a3ab1aee7f4ed8f1876d2f62c96e0f41ede52405a7d30c888f3989d8f00", size = 21115, upload-time = "2026-04-08T04:34:24.29Z" } +sdist = { url = "https://files.pythonhosted.org/packages/84/2b/b3e929c39fb056f0e44560acbe53a7c3f28f428af5362d043642d80b31ec/types_pygments-2.21.0.20260819.tar.gz", hash = "sha256:68e0cb27115b08b681c843e30a153b5d9850c048e1158623ada36ccd4cf7e89b", size = 21509, upload-time = "2026-08-19T02:47:15.827Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5e/d8/30924b38eef70caef6b05af5440c84d7673cea2a042e206f404c8100a88d/types_pygments-2.20.0.20260408-py3-none-any.whl", hash = "sha256:6d347d5967b5f0654b659a8b8461a870b207b7e60cd4d646bbc047f6a8db8e1e", size = 29055, upload-time = "2026-04-08T04:34:23.412Z" }, + { url = "https://files.pythonhosted.org/packages/d9/a5/10a2de06b53a36f4334391fcf292b51877cbc71d3f6eac353e7b87a0a17e/types_pygments-2.21.0.20260819-py3-none-any.whl", hash = "sha256:85e216770d616db6a7e96fb70c2de9d9f283b746c37edb7768ce645bdbcaddb2", size = 29099, upload-time = "2026-08-19T02:47:14.81Z" }, ] [[package]] name = "types-pymysql" -version = "1.1.0.20260408" +version = "1.2.0.20260807" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b3/04/c3570f05ebab083f28698c829dddf754ffefc30aae4e29915610848e44db/types_pymysql-1.1.0.20260408.tar.gz", hash = "sha256:b784dc37908479e3767e2d794ab507b3674adb1c686ca3d13fc9e2960dbcb9ec", size = 22344, upload-time = "2026-04-08T04:27:47.651Z" } +sdist = { url = "https://files.pythonhosted.org/packages/cf/71/f2d9cf554a59396c9dcf7cd902d1c187b6d4762dc7650e25a02c4ca2cf9c/types_pymysql-1.2.0.20260807.tar.gz", hash = "sha256:7fd4a7767925dbb0fd3e73fd488184fcd98b7612f8066cda280453b17864264f", size = 22768, upload-time = "2026-08-07T04:17:29.272Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/70/b3/15dee33878709705a4cc83bcc1bb30e00e95bbe038b472cb1207a15b50a1/types_pymysql-1.1.0.20260408-py3-none-any.whl", hash = "sha256:da630647eaaa7a926a3907794f4067f269cd245b2c202c74aa3c6a3bd660a9db", size = 23071, upload-time = "2026-04-08T04:27:46.735Z" }, + { url = "https://files.pythonhosted.org/packages/79/83/37e485e7ad3404aa018b6740d759b74665669c61c9c154f81d890b2ccd3a/types_pymysql-1.2.0.20260807-py3-none-any.whl", hash = "sha256:2a722284451649e1c2564655cba4963c0661851d04cc10195b7c002fab8e55f6", size = 23327, upload-time = "2026-08-07T04:17:28.318Z" }, ] [[package]] @@ -6952,20 +7033,20 @@ wheels = [ [[package]] name = "types-python-dateutil" -version = "2.9.0.20260408" +version = "2.9.0.20260807" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/88/f3/2427775f80cd5e19a0a71ba8e5ab7645a01a852f43a5fd0ffc24f66338e0/types_python_dateutil-2.9.0.20260408.tar.gz", hash = "sha256:8b056ec01568674235f64ecbcef928972a5fac412f5aab09c516dfa2acfbb582", size = 16981, upload-time = "2026-04-08T04:28:10.995Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c8/4e/b3fa538f9cb38dfece0d6ccf6d3d0d925bdedb144fb9c8129dfc007cd003/types_python_dateutil-2.9.0.20260807.tar.gz", hash = "sha256:e0b8a90d464c8684c66b7b8e4556d9074afdddcc56ca45323f0987134f9e7034", size = 17618, upload-time = "2026-08-07T04:17:13.491Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fd/c6/eeba37bfee282a6a97f889faef9352d6172c6a5088eb9a4daf570d9d748d/types_python_dateutil-2.9.0.20260408-py3-none-any.whl", hash = "sha256:473139d514a71c9d1fbd8bb328974bedcb1cc3dba57aad04ffa4157f483c216f", size = 18437, upload-time = "2026-04-08T04:28:10.095Z" }, + { url = "https://files.pythonhosted.org/packages/e4/5e/3715867caea2f4cea56ccb04c851cde23ed063449c3b004c7a047f20dd48/types_python_dateutil-2.9.0.20260807-py3-none-any.whl", hash = "sha256:54aa3707350ed7a9cc0776fd2f6739679d6967d11b40150985e81edcb86df4db", size = 18486, upload-time = "2026-08-07T04:17:12.504Z" }, ] [[package]] name = "types-python-http-client" -version = "3.3.7.20260408" +version = "3.3.7.20260518" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2a/30/f741f5edce6b02a838a30064360f5480510d5f2861561f44c5e33bc1dd96/types_python_http_client-3.3.7.20260408.tar.gz", hash = "sha256:ae84aadeec645ede7e602714090e6c8ebca97dbf28af509ac5eeccfc300174a2", size = 7684, upload-time = "2026-04-08T04:27:09.67Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1e/53/ae1fab16eaeb9a3a4c552a8ceb722ea79b2afb0c958a68dc4445d61a2a3c/types_python_http_client-3.3.7.20260518.tar.gz", hash = "sha256:a8f58f5957fec443f4349cf7e16d8975f32a798094412f1059c3246393e29740", size = 7737, upload-time = "2026-05-18T06:04:51.813Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f1/d8/45c6c04924086e8856e7f9a33a38ee713992d9ae9cd6d449de97badcba3c/types_python_http_client-3.3.7.20260408-py3-none-any.whl", hash = "sha256:3f310282e0fe2a18c5291f935538e1f97b9f80d2c5571aad155e66806719017c", size = 8851, upload-time = "2026-04-08T04:27:08.877Z" }, + { url = "https://files.pythonhosted.org/packages/90/0d/4e07fdf22c2dd014df29fcf20ad4860717e37c344e41b3a6d81315f456cc/types_python_http_client-3.3.7.20260518-py3-none-any.whl", hash = "sha256:40d8df1b30bd1b8facd34635b570d4ca45281e3d2d10461dddf48df797fb357a", size = 8852, upload-time = "2026-05-18T06:04:51.046Z" }, ] [[package]] @@ -6979,20 +7060,20 @@ wheels = [ [[package]] name = "types-pywin32" -version = "311.0.0.20260408" +version = "312.0.0.20260827" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/30/40/0d182fbf578f30f7ff2b07b8fe494cc42178992d0087a739c70990adca8c/types_pywin32-311.0.0.20260408.tar.gz", hash = "sha256:cb86c6beae20195165e770a65c3ee707746dc777ca8e03e4f06a66d4013a4bd0", size = 332341, upload-time = "2026-04-08T04:33:29.824Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d2/ba/de660e0aa3dcde61b2cada38c79fdaafcaaf2a7c811512fbe577d03c7245/types_pywin32-312.0.0.20260827.tar.gz", hash = "sha256:348facaabb9b3dfbeec50399ef430b660f7454529acf4c7e24874019cb721d58", size = 357427, upload-time = "2026-08-27T12:07:04.192Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0d/b5/3cc67baf622805270d84e2252dfa130daf7ccd49795f80b51350abb91bd9/types_pywin32-311.0.0.20260408-py3-none-any.whl", hash = "sha256:0b691da60aaed0ee7169a69268bad1e2051eb52f4acc10248c103aadcd1f2451", size = 395413, upload-time = "2026-04-08T04:33:28.476Z" }, + { url = "https://files.pythonhosted.org/packages/81/53/9c90587245adee3a73af4b8c5374dcfb1f3f0d710d1ab139dfe35dd7258e/types_pywin32-312.0.0.20260827-py3-none-any.whl", hash = "sha256:f22580e0d59c9cea33cf172396a7fb2f19a934c3eb82370bb74ca98f8e3db71e", size = 419299, upload-time = "2026-08-27T12:07:03.081Z" }, ] [[package]] name = "types-pyyaml" -version = "6.0.12.20260408" +version = "6.0.12.20260815" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/74/73/b759b1e413c31034cc01ecdfb96b38115d0ab4db55a752a3929f0cd449fd/types_pyyaml-6.0.12.20260408.tar.gz", hash = "sha256:92a73f2b8d7f39ef392a38131f76b970f8c66e4c42b3125ae872b7c93b556307", size = 17735, upload-time = "2026-04-08T04:30:50.974Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9f/72/b56089aeee6c496d969bac42376bedb6e3eeab4682e1018fa3137122f94b/types_pyyaml-6.0.12.20260815.tar.gz", hash = "sha256:28764110c9cf35846e733da32d8d734df7473c5dde9ef67c3b7332ec0e819858", size = 18545, upload-time = "2026-08-15T02:41:51.532Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1c/f0/c391068b86abb708882c6d75a08cd7d25b2c7227dab527b3a3685a3c635b/types_pyyaml-6.0.12.20260408-py3-none-any.whl", hash = "sha256:fbc42037d12159d9c801ebfcc79ebd28335a7c13b08a4cfbc6916df78fee9384", size = 20339, upload-time = "2026-04-08T04:30:50.113Z" }, + { url = "https://files.pythonhosted.org/packages/08/52/eefeba09be4ef2a1eb989eb92934561e8e502a6ee3c32654996e4be7e399/types_pyyaml-6.0.12.20260815-py3-none-any.whl", hash = "sha256:6f332212b7e191f3afd5016a713c510b6340593b7ebec573c7d5d20aa5386d3b", size = 21148, upload-time = "2026-08-15T02:41:50.555Z" }, ] [[package]] @@ -7010,23 +7091,11 @@ wheels = [ [[package]] name = "types-regex" -version = "2026.4.4.20260408" +version = "2026.9.3.20260903" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/92/42/d7c691fc5a8a8ecfba3f23c1c4c087a089af0767610d88c29201193d8f60/types_regex-2026.4.4.20260408.tar.gz", hash = "sha256:86b2975ff11b06e7f538839821510daea2566d9cb18bb8acde47834315409cf9", size = 13182, upload-time = "2026-04-08T04:31:11.887Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/65/7a39af8705ba0685429e8306ce7cbc6d40be0658c36bb2330aefcca13815/types_regex-2026.9.3.20260903.tar.gz", hash = "sha256:eef82a0ae08806f32609fc4829fee845f98672dd6378834c34dec33bf8c60cf0", size = 13858, upload-time = "2026-09-03T06:36:49.602Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e1/92/e109654a804d11d9b60d67c7b29d64b2beac6b2e3209ea075e268e5a1021/types_regex-2026.4.4.20260408-py3-none-any.whl", hash = "sha256:d436bcc409abf9b06747b7e038014afc6d40ef7b72329655c353a1955534068f", size = 11116, upload-time = "2026-04-08T04:31:11.01Z" }, -] - -[[package]] -name = "types-requests" -version = "2.32.4.20250913" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/36/27/489922f4505975b11de2b5ad07b4fe1dca0bca9be81a703f26c5f3acfce5/types_requests-2.32.4.20250913.tar.gz", hash = "sha256:abd6d4f9ce3a9383f269775a9835a4c24e5cd6b9f647d64f88aa4613c33def5d", size = 23113, upload-time = "2025-09-13T02:40:02.309Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/20/9a227ea57c1285986c4cf78400d0a91615d25b24e257fd9e2969606bdfae/types_requests-2.32.4.20250913-py3-none-any.whl", hash = "sha256:78c9c1fffebbe0fa487a418e0fa5252017e9c60d1a2da394077f1780f655d7e1", size = 20658, upload-time = "2025-09-13T02:40:01.115Z" }, + { url = "https://files.pythonhosted.org/packages/8e/c7/571fb5dbfee06a57651d8af664dbda43409277b6f7ccff5df8fbeee526e3/types_regex-2026.9.3.20260903-py3-none-any.whl", hash = "sha256:d12a58823ba330497c4369fc47f9de028f5fd74036d3cfabb7732c69e88a5fd0", size = 11181, upload-time = "2026-09-03T06:36:48.605Z" }, ] [[package]] @@ -7040,67 +7109,64 @@ wheels = [ [[package]] name = "types-setuptools" -version = "82.0.0.20260408" +version = "84.0.0.20260812" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c3/12/3464b410c50420dd4674fa5fe9d3880711c1dbe1a06f5fe4960ee9067b9e/types_setuptools-82.0.0.20260408.tar.gz", hash = "sha256:036c68caf7e672a699f5ebbf914708d40644c14e05298bc49f7272be91cf43d3", size = 44861, upload-time = "2026-04-08T04:29:33.292Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4f/cd/3b2a3362a526f91c33f785a291462b2ec448ae531101c62372fc30a21f53/types_setuptools-84.0.0.20260812.tar.gz", hash = "sha256:09bedc248ebbb7a232c9419dfcdca329706e61bf2aa5743e9424d027f1d956b4", size = 46545, upload-time = "2026-08-12T03:52:42.316Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3d/e1/46a4fc3ef03aabf5d18bac9df5cf37c6b02c3bddf3e05c3533f4b4588331/types_setuptools-82.0.0.20260408-py3-none-any.whl", hash = "sha256:ece0a215cdfa6463a65fd6f68bd940f39e455729300ddfe61cab1147ed1d2462", size = 68428, upload-time = "2026-04-08T04:29:32.175Z" }, + { url = "https://files.pythonhosted.org/packages/8a/e5/3a41cab4066465593facd660b2683c017f3d88d3297cdd26db0677b8e479/types_setuptools-84.0.0.20260812-py3-none-any.whl", hash = "sha256:799c08e4bc6a288e8a0b538afb5f5ff320a08927ba8dbedb30c74ee3ba5d867b", size = 70320, upload-time = "2026-08-12T03:52:41.154Z" }, ] [[package]] name = "types-shapely" -version = "2.1.0.20260408" +version = "2.1.0.20260728" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/10/8d/bf9e3eb51249601e22d797481999a06fb34998c4db5c76804394f8a3fa28/types_shapely-2.1.0.20260408.tar.gz", hash = "sha256:8552549d9429baa52ec4331e43b5db3b334fc3a7f30da48663010b7454b1451c", size = 26529, upload-time = "2026-04-08T04:34:42.111Z" } +sdist = { url = "https://files.pythonhosted.org/packages/be/cf/1ea740a3532b6e4cdeae8ba121618eb58a543eba2721016d358e4c0992e3/types_shapely-2.1.0.20260728.tar.gz", hash = "sha256:8ec23a5aa484c1ec7bbc56aa353cc230ae63e38e0f35a6e4b79a011d99bcfcc2", size = 27501, upload-time = "2026-07-28T04:51:41.724Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8e/3d/cbec691f56e71636192a07bf6809f598bed06d869b03b4e2b1ad2f7df032/types_shapely-2.1.0.20260408-py3-none-any.whl", hash = "sha256:8a31e2b074342a363f0c9d0c7d6e1e6c0dcce302a92ef94d64d0ca2a2b94a1d1", size = 37818, upload-time = "2026-04-08T04:34:41.243Z" }, + { url = "https://files.pythonhosted.org/packages/79/8d/2e6c38118cc6b20075ccd1609840314aa8a694a255a09149b185d8a608e1/types_shapely-2.1.0.20260728-py3-none-any.whl", hash = "sha256:7299a62025528b3f0cc5af37095f05fbe7d76d399bdc8d7ea9b3d395e988f547", size = 38539, upload-time = "2026-07-28T04:51:40.638Z" }, ] [[package]] name = "types-simplejson" -version = "3.20.0.20260408" +version = "4.1.0.20260724" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9f/36/e319fd0f6d906dbf7c2c03eef17db77ef461197a75b253fccd9c7c695d3e/types_simplejson-3.20.0.20260408.tar.gz", hash = "sha256:0b0e1bf61e70f81dfe6ef4c2b9c02e39403848c0652df334e7a430c3a26c06b3", size = 10693, upload-time = "2026-04-08T04:28:07.8Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1d/42/1916db531db4130e4c3dc5df35144d2cb018c9f24895743f36c5cb35da6f/types_simplejson-4.1.0.20260724.tar.gz", hash = "sha256:62045f0b81581e714641c486c9238088eacaa3310b7873e05b89999664b64934", size = 11069, upload-time = "2026-07-24T04:58:39.843Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/22/c0/01a5a4c3948c2269cf9d727e5e66a8b404e03beb4f9522680a3f71097011/types_simplejson-3.20.0.20260408-py3-none-any.whl", hash = "sha256:f9e542199cb159ed34ad54b6ceb3dc9af890c256b810ad1bd7c69c61db7d2236", size = 10415, upload-time = "2026-04-08T04:28:06.984Z" }, + { url = "https://files.pythonhosted.org/packages/c4/fc/64b8f433237ba4bb1b204f83be37b4954de187e334e36ecce78851045f60/types_simplejson-4.1.0.20260724-py3-none-any.whl", hash = "sha256:160e894bb546ccf8455d34512f5fa7edf2aa25c047a43be840dde3a7bf3e4388", size = 10583, upload-time = "2026-07-24T04:58:38.994Z" }, ] [[package]] name = "types-six" -version = "1.17.0.20260408" +version = "1.17.0.20260724" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9d/95/14bb40b2fa8f19234d60b370bfa1ff64b42509b6d2dee070132949ce4f80/types_six-1.17.0.20260408.tar.gz", hash = "sha256:b28579aedb204d07abac52e49c87e2b4c03cb6171bd764bd9b7775ba58fffaba", size = 15766, upload-time = "2026-04-08T04:26:23.54Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f8/0a/1fb3a4b570f654475a2eadb8c14cc213c25bec5ba25b51364189dcb0b753/types_six-1.17.0.20260724.tar.gz", hash = "sha256:d7abfa82d40eb7dfbb6356c5b1abb4ddc87e0854515a213512e6be98c5d6bc02", size = 15900, upload-time = "2026-07-24T04:58:28.187Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/83/04/3e9c382043579b5170c3bc38d13154d48e8ef2c89c4473748a33e3c9bccd/types_six-1.17.0.20260408-py3-none-any.whl", hash = "sha256:02208fa1099944ed0c8f8de42f065ffd63c55cd7b59f49be49802626b8d58318", size = 19937, upload-time = "2026-04-08T04:26:22.259Z" }, + { url = "https://files.pythonhosted.org/packages/f7/b5/e955d46780884ab065dd2dca5a4c240585d0ea4c851e978d669e06b71abb/types_six-1.17.0.20260724-py3-none-any.whl", hash = "sha256:5076f03667e21f77b45c029c0aba0a4f5f0f0472c27fc102c8ec7bb68206ecf4", size = 19937, upload-time = "2026-07-24T04:58:27.335Z" }, ] [[package]] name = "types-tensorflow" -version = "2.18.0.20260408" +version = "2.18.0.20260827" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, + { name = "requests" }, { name = "types-protobuf" }, - { name = "types-requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/cb/15/d9f1a54e75008fde3dc48f333b4d3c86f0d27b822e3a9c109214f8957ae6/types_tensorflow-2.18.0.20260408.tar.gz", hash = "sha256:68bfbcc76dd9e314eae0a91964edf463c52fc0e3d60189542efbf67006e71015", size = 259103, upload-time = "2026-04-08T04:36:45.263Z" } +sdist = { url = "https://files.pythonhosted.org/packages/48/13/73880d3cc2051f33552423032832da0933ee21d818c5aecb2bcef624c488/types_tensorflow-2.18.0.20260827.tar.gz", hash = "sha256:c520bca32249a59ed0259987a95bb6ab4cb9a0d492b1a9604437630edc433398", size = 260668, upload-time = "2026-08-27T12:07:29.206Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/11/64/4005df91e916f586d9f80c3f052f2ae41afbcd9c9a54d33005fabeefcaab/types_tensorflow-2.18.0.20260408-py3-none-any.whl", hash = "sha256:01cff182dd6c38c300b27b9d1a26791f04607d914fa9429e5f85766c3bc0d71d", size = 329775, upload-time = "2026-04-08T04:36:43.863Z" }, + { url = "https://files.pythonhosted.org/packages/03/c6/21ae388b27968b7b8adef052b82a9bcbf6ca44c417eaa6991edb45dde1c9/types_tensorflow-2.18.0.20260827-py3-none-any.whl", hash = "sha256:3cdd6b57feafca966f4c839edfe29602772c8301c4aa493c379eef38e3b7f0da", size = 330854, upload-time = "2026-08-27T12:07:28.166Z" }, ] [[package]] name = "types-tqdm" -version = "4.67.3.20260408" +version = "4.70.0.20260827" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "types-requests" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/43/42/2e2968e68a694d3dac3a47aa0df06e46be1a6eef498e5bd15f4c54674eb9/types_tqdm-4.67.3.20260408.tar.gz", hash = "sha256:fd849a79891ae7136ed47541aface15c35bd9a13160fa8a93e42e10f60cf4c8d", size = 18119, upload-time = "2026-04-08T04:36:52.488Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fa/66/f4a8d5483513ed883e8f01c607b5d47815ca0eb796d376349fdfe85a125c/types_tqdm-4.70.0.20260827.tar.gz", hash = "sha256:d3efd69243ac9093c552f1c0d081b77286d61ace96b6899a142542555bdad2dc", size = 19251, upload-time = "2026-08-27T12:06:55.911Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/14/5d/7dedddc32ab7bc2344ece772b5e0f03ec63a1d47ad259696689713c1cf50/types_tqdm-4.67.3.20260408-py3-none-any.whl", hash = "sha256:3b9ed74ebef04df8f53d470ffdc84348e93496d8acafa08bf79fafce0f2f5b5d", size = 24561, upload-time = "2026-04-08T04:36:51.538Z" }, + { url = "https://files.pythonhosted.org/packages/7a/f0/b0e2a33c0367e79806054f556159f0b43e6a98d7e728aea1b07028a56ee4/types_tqdm-4.70.0.20260827-py3-none-any.whl", hash = "sha256:d6e02da8ec2bc11124e02d4bc84bd8b67a444f4c5decf544846897c8272c7023", size = 25163, upload-time = "2026-08-27T12:06:54.898Z" }, ] [[package]] diff --git a/dify-agent/docs/dify-agent/guide/index.md b/dify-agent/docs/dify-agent/guide/index.md index 99ff7b0ac28..bc6eacee02f 100644 --- a/dify-agent/docs/dify-agent/guide/index.md +++ b/dify-agent/docs/dify-agent/guide/index.md @@ -359,6 +359,49 @@ whose Agenton layers provide user input. With the MVP provider set, use effective prompts are rejected during create-run validation before the run is persisted or scheduled. +Agent App callers can use the `dify.user_prompt` layer to send text and images +in the same model turn. Each image must provide exactly one transport: an +HTTP(S) `url` or unprefixed Base64 data in `base64_data`. The image is passed as +structured multimodal content; it is not interpolated into `config.text`. + +```json +{ + "name": "agent_app_user_prompt", + "type": "dify.user_prompt", + "config": { + "text": "Describe this image.", + "files": [ + { + "delivery": "multimodal", + "type": "image", + "filename": "earth.png", + "mime_type": "image/png", + "format": "png", + "url": "https://files.example.com/earth.png", + "base64_data": null, + "detail": "high" + } + ] + } +} +``` + +All attachments use `config.files`. The `delivery` field selects how an attachment +is presented, independently of its file `type` (`image`, `document`, `audio`, +`video`, or `custom`): + +- `delivery: "multimodal"` currently supports `type: "image"` only. Dify API + chooses URL or Base64 transport according to `MULTIMODAL_SEND_FORMAT`. +- `delivery: "download"` preserves the original file `type`, including `image` + when the selected model has no Vision feature. It contains either + `transfer_method: "remote_url"` with `url`, or a `local_file`, `tool_file`, or + `datasource_file` transfer method with a canonical `reference`. + +The layer appends sandbox file-download instructions for download attachments +and adds multimodal attachments as structured model content. Callers keep +`config.text` as the original user text. Omitting `config.files` is equivalent +to an empty list. + The optional Pydantic AI history layer uses the reserved name `history` and persists captured messages in session snapshots for later resume. Resume from a terminal event's `session_snapshot` using the same layer composition, names, and diff --git a/dify-agent/src/dify_agent/layers/user_prompt/__init__.py b/dify-agent/src/dify_agent/layers/user_prompt/__init__.py new file mode 100644 index 00000000000..f675b1c0140 --- /dev/null +++ b/dify-agent/src/dify_agent/layers/user_prompt/__init__.py @@ -0,0 +1,19 @@ +"""Client-safe exports for the Agent App multimodal user prompt layer.""" + +from dify_agent.layers.user_prompt.configs import ( + DIFY_USER_PROMPT_LAYER_TYPE_ID, + DifyUserPromptDownloadConfig, + DifyUserPromptFileConfig, + DifyUserPromptFileType, + DifyUserPromptImageConfig, + DifyUserPromptLayerConfig, +) + +__all__ = [ + "DIFY_USER_PROMPT_LAYER_TYPE_ID", + "DifyUserPromptDownloadConfig", + "DifyUserPromptFileConfig", + "DifyUserPromptFileType", + "DifyUserPromptImageConfig", + "DifyUserPromptLayerConfig", +] diff --git a/dify-agent/src/dify_agent/layers/user_prompt/configs.py b/dify-agent/src/dify_agent/layers/user_prompt/configs.py new file mode 100644 index 00000000000..fc9fa273e7d --- /dev/null +++ b/dify-agent/src/dify_agent/layers/user_prompt/configs.py @@ -0,0 +1,90 @@ +"""Serializable DTOs for one Agent App multimodal user prompt.""" + +from __future__ import annotations + +import base64 +import binascii +from typing import Annotated, ClassVar, Final, Literal, Self + +from pydantic import ConfigDict, Field, model_validator + +from agenton.layers import LayerConfig + + +DIFY_USER_PROMPT_LAYER_TYPE_ID: Final[str] = "dify.user_prompt" +type DifyUserPromptFileType = Literal["image", "document", "audio", "video", "custom"] + + +class DifyUserPromptImageConfig(LayerConfig): + """One image delivered directly to the configured vision model. + + Callers provide either an HTTP(S) URL or base64 bytes. Opaque Dify file + references belong to the sandbox download flow and are not accepted here. + """ + + delivery: Literal["multimodal"] = "multimodal" + type: Literal["image"] = "image" + filename: str = Field(min_length=1) + mime_type: str = Field(pattern=r"^image/[A-Za-z0-9.+-]+$") + format: str = Field(min_length=1) + url: str | None = None + base64_data: str | None = None + detail: Literal["low", "high"] | None = None + + model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid") + + @model_validator(mode="after") + def _validate_transport(self) -> Self: + if (self.url is None) == (self.base64_data is None): + raise ValueError("exactly one of url or base64_data must be provided") + if self.url is not None and not self.url.startswith(("http://", "https://")): + raise ValueError("url must use http or https") + if self.base64_data is not None: + try: + base64.b64decode(self.base64_data, validate=True) + except (ValueError, binascii.Error) as exc: + raise ValueError("base64_data must be valid base64") from exc + return self + + +class DifyUserPromptDownloadConfig(LayerConfig): + delivery: Literal["download"] = "download" + type: DifyUserPromptFileType + transfer_method: Literal["remote_url", "local_file", "tool_file", "datasource_file"] + url: str | None = Field(default=None, min_length=1) + reference: str | None = Field(default=None, min_length=1) + + model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid") + + @model_validator(mode="after") + def _validate_locator(self) -> Self: + if self.transfer_method == "remote_url": + if self.url is None or self.reference is not None: + raise ValueError("remote_url requires url and must not include reference") + elif self.reference is None or self.url is not None: + raise ValueError("reference is required and url must not be provided") + return self + + +type DifyUserPromptFileConfig = Annotated[ + DifyUserPromptImageConfig | DifyUserPromptDownloadConfig, Field(discriminator="delivery") +] + + +class DifyUserPromptLayerConfig(LayerConfig): + """User text plus images that should be sent in the same model turn.""" + + text: str = Field(min_length=1) + files: list[DifyUserPromptFileConfig] = Field(default_factory=list) + + model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid") + + +__all__ = [ + "DIFY_USER_PROMPT_LAYER_TYPE_ID", + "DifyUserPromptDownloadConfig", + "DifyUserPromptFileConfig", + "DifyUserPromptFileType", + "DifyUserPromptImageConfig", + "DifyUserPromptLayerConfig", +] diff --git a/dify-agent/src/dify_agent/layers/user_prompt/layer.py b/dify-agent/src/dify_agent/layers/user_prompt/layer.py new file mode 100644 index 00000000000..edcdf0a45bc --- /dev/null +++ b/dify-agent/src/dify_agent/layers/user_prompt/layer.py @@ -0,0 +1,91 @@ +"""Turn serialized Agent App images into pydantic-ai user content.""" + +from __future__ import annotations + +import base64 +import json +from dataclasses import dataclass +from typing import ClassVar, assert_never + +from pydantic_ai.messages import BinaryContent, ImageUrl, UserContent +from typing_extensions import Self, override + +from agenton.layers import EmptyRuntimeState, NoLayerDeps, PydanticAILayer +from dify_agent.layers.user_prompt.configs import ( + DIFY_USER_PROMPT_LAYER_TYPE_ID, + DifyUserPromptDownloadConfig, + DifyUserPromptImageConfig, + DifyUserPromptLayerConfig, +) + + +@dataclass(slots=True) +class DifyUserPromptLayer(PydanticAILayer[NoLayerDeps, object, DifyUserPromptLayerConfig, EmptyRuntimeState]): + """State-free layer for a text prompt and directly attached images.""" + + type_id: ClassVar[str | None] = DIFY_USER_PROMPT_LAYER_TYPE_ID + config: DifyUserPromptLayerConfig + + @classmethod + @override + def from_config(cls, config: DifyUserPromptLayerConfig) -> Self: + return cls(config=DifyUserPromptLayerConfig.model_validate(config)) + + @property + @override + def user_prompts(self) -> list[UserContent]: + images: list[UserContent] = [] + downloads: list[DifyUserPromptDownloadConfig] = [] + for file in self.config.files: + match file.delivery: + case "multimodal": + images.append(_to_image_content(file)) + case "download": + downloads.append(file) + case _: + assert_never(file) + return [_append_file_downloads(self.config.text, downloads), *images] + + +def _append_file_downloads(text: str, files: list[DifyUserPromptDownloadConfig]) -> str: + if not files: + return text + locators = [file.model_dump(mode="json", exclude={"delivery", "type"}, exclude_none=True) for file in files] + payload = json.dumps(locators, ensure_ascii=False, separators=(",", ":")) + return ( + f"{text}\n" + "User provided files: use dify-agent file download with the listed transfer_method and reference/url " + "to get the files and investigate them\n" + f"{payload}" + ) + + +def _to_image_content(file: DifyUserPromptImageConfig) -> ImageUrl | BinaryContent: + vendor_metadata: dict[str, str] = {"filename": file.filename} + if file.detail is not None: + vendor_metadata["detail"] = file.detail + identifier = _identifier_from_filename(file.filename, file.format) + if file.url is not None: + return ImageUrl( + url=file.url, + media_type=file.mime_type, + identifier=identifier, + vendor_metadata=vendor_metadata, + ) + assert file.base64_data is not None + return BinaryContent( + data=base64.b64decode(file.base64_data, validate=True), + media_type=file.mime_type, + identifier=identifier, + vendor_metadata=vendor_metadata, + ) + + +def _identifier_from_filename(filename: str, file_format: str) -> str: + suffix = f".{file_format}" + if filename.lower().endswith(suffix.lower()): + return filename[: -len(suffix)] or "image" + return filename + + +__all__ = ["DifyUserPromptLayer"] diff --git a/dify-agent/src/dify_agent/runtime/compositor_factory.py b/dify-agent/src/dify_agent/runtime/compositor_factory.py index f56b37e3c17..a22df749ea6 100644 --- a/dify-agent/src/dify_agent/runtime/compositor_factory.py +++ b/dify-agent/src/dify_agent/runtime/compositor_factory.py @@ -10,6 +10,7 @@ layer, and the Dify plugin/knowledge business-layer family: - ``dify.execution_context`` for shared tenant/user/run daemon context, - ``dify.runtime`` for operation-scoped RuntimeLease acquisition, - ``dify.shell`` for command/file capabilities from the active RuntimeLease, +- ``dify.user_prompt`` for structured text-plus-image user turns, - ``dify.plugin.llm`` for plugin-backed model selection, - ``dify.plugin.tools`` for prepared plugin tool exposure, and - ``dify.core.tools`` for API-routed Dify tool exposure, and @@ -55,6 +56,7 @@ from dify_agent.layers.runtime.configs import DifyRuntimeLayerConfig from dify_agent.layers.runtime.layer import DifyRuntimeLayer from dify_agent.layers.shell.configs import DifyShellLayerConfig from dify_agent.layers.shell.layer import DifyShellLayer +from dify_agent.layers.user_prompt.layer import DifyUserPromptLayer from dify_agent.runtime_backend import RuntimeBackendProfile type DifyAgentLayerProvider = LayerProvider[Any] @@ -74,6 +76,7 @@ def create_default_layer_providers( """Return the server provider set of safe config-constructible layers.""" providers: list[DifyAgentLayerProvider] = [ LayerProvider.from_layer_type(PromptLayer), + LayerProvider.from_layer_type(DifyUserPromptLayer), LayerProvider.from_layer_type(PydanticAIHistoryLayer), LayerProvider.from_layer_type(DifyOutputLayer), LayerProvider.from_layer_type(DifyAskHumanLayer), diff --git a/dify-agent/tests/local/dify_agent/layers/user_prompt/test_layer.py b/dify-agent/tests/local/dify_agent/layers/user_prompt/test_layer.py new file mode 100644 index 00000000000..3c8927bd732 --- /dev/null +++ b/dify-agent/tests/local/dify_agent/layers/user_prompt/test_layer.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import base64 + +import pytest +from pydantic import ValidationError +from pydantic_ai.messages import BinaryContent, ImageUrl + +from dify_agent.layers.user_prompt import DifyUserPromptLayerConfig +from dify_agent.layers.user_prompt.layer import DifyUserPromptLayer +from dify_agent.runtime.compositor_factory import create_default_layer_providers + + +@pytest.mark.parametrize("include_image", [False, True]) +@pytest.mark.parametrize("download_type", ["image", "document"]) +def test_user_prompt_layer_injects_file_locators(include_image: bool, download_type: str) -> None: + config = DifyUserPromptLayerConfig.model_validate( + { + "text": "Inspect these files.", + "files": [ + { + "delivery": "download", + "type": download_type, + "transfer_method": "local_file", + "reference": "dify-file-ref:upload-file-1", + }, + { + "delivery": "download", + "type": "document", + "transfer_method": "remote_url", + "url": "https://example.com/说明.pdf", + }, + { + "delivery": "download", + "type": "document", + "transfer_method": "tool_file", + "reference": "dify-file-ref:tool-file-1", + }, + { + "delivery": "download", + "type": "document", + "transfer_method": "datasource_file", + "reference": "dify-file-ref:datasource-file-1", + }, + *( + [ + { + "delivery": "multimodal", + "type": "image", + "filename": "earth.png", + "mime_type": "image/png", + "format": "png", + "url": "https://files.example.com/earth.png", + } + ] + if include_image + else [] + ), + ], + } + ) + layer = DifyUserPromptLayer.from_config(DifyUserPromptLayerConfig.model_validate_json(config.model_dump_json())) + + prompts = layer.user_prompts + + assert prompts[0] == ( + "Inspect these files.\n" + "User provided files: use dify-agent file download with the listed transfer_method and reference/url " + "to get the files and investigate them\n" + '[{"transfer_method":"local_file","reference":"dify-file-ref:upload-file-1"},' + '{"transfer_method":"remote_url","url":"https://example.com/说明.pdf"},' + '{"transfer_method":"tool_file","reference":"dify-file-ref:tool-file-1"},' + '{"transfer_method":"datasource_file","reference":"dify-file-ref:datasource-file-1"}]' + ) + assert layer.config.text == "Inspect these files." + assert "locators" not in layer.config.model_dump() + assert layer.user_prompts == prompts + assert len(prompts) == (2 if include_image else 1) + if include_image: + assert isinstance(prompts[1], ImageUrl) + assert prompts[1].url == "https://files.example.com/earth.png" + + +@pytest.mark.parametrize( + "locator", + [ + {"transfer_method": "remote_url", "reference": "file-1"}, + {"transfer_method": "local_file", "url": "https://example.com/file.pdf"}, + {"transfer_method": "unsupported", "reference": "file-1"}, + {"transfer_method": "local_file"}, + {"transfer_method": "remote_url"}, + {"transfer_method": "local_file", "reference": ""}, + {"transfer_method": "remote_url", "url": ""}, + {"transfer_method": "remote_url", "url": "https://example.com/file.pdf", "reference": "file-1"}, + {"transfer_method": "tool_file", "url": "https://example.com/file.pdf", "reference": "file-1"}, + ], +) +def test_user_prompt_layer_rejects_invalid_locators(locator: dict[str, str]) -> None: + with pytest.raises(ValidationError): + DifyUserPromptLayerConfig.model_validate( + {"text": "Inspect it.", "files": [{"delivery": "download", "type": "document", **locator}]} + ) + + +def test_user_prompt_layer_preserves_text_without_locators() -> None: + layer = DifyUserPromptLayer.from_config(DifyUserPromptLayerConfig(text=" Original prompt.\n")) + + assert layer.user_prompts == [" Original prompt.\n"] + + +def test_user_prompt_layer_restores_image_url_content() -> None: + layer = DifyUserPromptLayer.from_config( + DifyUserPromptLayerConfig.model_validate( + { + "text": "What is in this image?", + "files": [ + { + "delivery": "multimodal", + "type": "image", + "filename": "earth.png", + "mime_type": "image/png", + "format": "png", + "url": "https://files.example.com/earth.png?sign=secret", + "detail": "high", + } + ], + } + ) + ) + + prompts = layer.user_prompts + + assert prompts[0] == "What is in this image?" + assert isinstance(prompts[1], ImageUrl) + assert prompts[1].url == "https://files.example.com/earth.png?sign=secret" + assert prompts[1].media_type == "image/png" + assert prompts[1].vendor_metadata == {"filename": "earth.png", "detail": "high"} + + +def test_user_prompt_layer_restores_inline_binary_content() -> None: + payload = base64.b64encode(b"image-bytes").decode() + layer = DifyUserPromptLayer.from_config( + DifyUserPromptLayerConfig.model_validate( + { + "text": "Describe it.", + "files": [ + { + "delivery": "multimodal", + "type": "image", + "filename": "inline.png", + "mime_type": "image/png", + "format": "png", + "base64_data": payload, + } + ], + } + ) + ) + + content = layer.user_prompts[1] + + assert isinstance(content, BinaryContent) + assert content.data == b"image-bytes" + assert content.media_type == "image/png" + + +@pytest.mark.parametrize( + "file_payload", + [ + { + "delivery": "multimodal", + "type": "image", + "filename": "missing.png", + "mime_type": "image/png", + "format": "png", + }, + { + "delivery": "multimodal", + "type": "image", + "filename": "ambiguous.png", + "mime_type": "image/png", + "format": "png", + "url": "https://files.example.com/ambiguous.png", + "base64_data": "aW1hZ2U=", + }, + ], +) +def test_user_prompt_file_requires_exactly_one_transport(file_payload: dict[str, str]) -> None: + with pytest.raises(ValidationError, match="exactly one"): + DifyUserPromptLayerConfig.model_validate({"text": "Describe it.", "files": [file_payload]}) + + +def test_default_compositor_registers_user_prompt_layer() -> None: + provider = next(provider for provider in create_default_layer_providers() if provider.type_id == "dify.user_prompt") + + layer = provider.create_layer({"text": "Describe it."}) + + assert isinstance(layer, DifyUserPromptLayer) diff --git a/dify-agent/tests/local/dify_agent/test_client_safe_exports.py b/dify-agent/tests/local/dify_agent/test_client_safe_exports.py index ba1493701fb..ec4ca696882 100644 --- a/dify-agent/tests/local/dify_agent/test_client_safe_exports.py +++ b/dify-agent/tests/local/dify_agent/test_client_safe_exports.py @@ -72,6 +72,7 @@ def test_client_public_exports_work_with_default_dependencies_only(tmp_path: Pat plugin_module = importlib.import_module("dify_agent.layers.dify_plugin") ask_human_module = importlib.import_module("dify_agent.layers.ask_human") output_module = importlib.import_module("dify_agent.layers.output") + user_prompt_module = importlib.import_module("dify_agent.layers.user_prompt") assert agenton_layers.ExitIntent is not None assert agenton_layers.LayerConfig is not None @@ -93,6 +94,17 @@ def test_client_public_exports_work_with_default_dependencies_only(tmp_path: Pat assert plugin_module.DifyPluginLLMLayerConfig is not None assert ask_human_module.DifyAskHumanLayerConfig is not None assert output_module.DifyOutputLayerConfig is not None + assert user_prompt_module.DifyUserPromptLayerConfig is not None + assert user_prompt_module.DifyUserPromptFileConfig is not None + download = user_prompt_module.DifyUserPromptDownloadConfig( + type="image", transfer_method="local_file", reference="file-1" + ) + image = user_prompt_module.DifyUserPromptImageConfig( + filename="image.png", mime_type="image/png", format="png", url="https://example.com/image.png" + ) + config = user_prompt_module.DifyUserPromptLayerConfig(text="Inspect it.", files=[download, image]) + assert user_prompt_module.DifyUserPromptLayerConfig.model_validate_json(config.model_dump_json()) == config + assert [file.delivery for file in config.files] == ["download", "multimodal"] unexpectedly_installed = [] for dependency_name in sorted(server_only_dependency_names): diff --git a/docker/docker-compose-template.yaml b/docker/docker-compose-template.yaml index 04a0c9b9fa1..3ce3358c569 100644 --- a/docker/docker-compose-template.yaml +++ b/docker/docker-compose-template.yaml @@ -706,6 +706,8 @@ services: environment: HTTP_PORT: ${SSRF_HTTP_PORT:-3128} COREDUMP_DIR: ${SSRF_COREDUMP_DIR:-/var/spool/squid} + SSRF_PROXY_ALLOW_PRIVATE_IPS: ${SSRF_PROXY_ALLOW_PRIVATE_IPS:-} + SSRF_PROXY_ALLOW_PRIVATE_DOMAINS: ${SSRF_PROXY_ALLOW_PRIVATE_DOMAINS:-} networks: # Needs to reach api and agent_backend as forward-proxy destinations. - default diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml index 0ad2271b29d..fd59abaa3f9 100644 --- a/docker/docker-compose.yaml +++ b/docker/docker-compose.yaml @@ -712,6 +712,8 @@ services: environment: HTTP_PORT: ${SSRF_HTTP_PORT:-3128} COREDUMP_DIR: ${SSRF_COREDUMP_DIR:-/var/spool/squid} + SSRF_PROXY_ALLOW_PRIVATE_IPS: ${SSRF_PROXY_ALLOW_PRIVATE_IPS:-} + SSRF_PROXY_ALLOW_PRIVATE_DOMAINS: ${SSRF_PROXY_ALLOW_PRIVATE_DOMAINS:-} networks: # Needs to reach api and agent_backend as forward-proxy destinations. - default diff --git a/docker/envs/core-services/web.env.example b/docker/envs/core-services/web.env.example index bafb965778a..342e7f08e7f 100644 --- a/docker/envs/core-services/web.env.example +++ b/docker/envs/core-services/web.env.example @@ -32,6 +32,7 @@ ENABLE_WEBSITE_WATERCRAWL=true NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX=false NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW=true NEXT_PUBLIC_ENABLE_AGENT_V2=true +NEXT_PUBLIC_ENABLE_AGENT_V2_IN_CHATFLOW=false NEXT_PUBLIC_COOKIE_DOMAIN= NEXT_PUBLIC_BATCH_CONCURRENCY=5 CSP_WHITELIST= diff --git a/docker/ssrf_proxy/docker-agent-entrypoint.sh b/docker/ssrf_proxy/docker-agent-entrypoint.sh old mode 100644 new mode 100755 index 29dee3c48e3..0ea6adbfec9 --- a/docker/ssrf_proxy/docker-agent-entrypoint.sh +++ b/docker/ssrf_proxy/docker-agent-entrypoint.sh @@ -5,6 +5,40 @@ tail -F /var/log/squid/error.log 2>/dev/null & tail -F /var/log/squid/store.log 2>/dev/null & tail -F /var/log/squid/cache.log 2>/dev/null & +ALLOW_PRIVATE_CONF=/etc/squid/dify_allow_private.conf + +write_optional_private_allowlist() { + local env_name="$1" + local acl_name="$2" + local acl_type="$3" + local raw_values="${!env_name:-}" + local -a tokens=() + + raw_values="${raw_values//,/ }" + raw_values="${raw_values//$'\n'/ }" + raw_values="${raw_values//$'\r'/ }" + + if [ -z "${raw_values//[[:space:]]/}" ]; then + return + fi + + read -r -a tokens <<< "$raw_values" + + printf 'acl %s %s' "$acl_name" "$acl_type" >> "$ALLOW_PRIVATE_CONF" + for value in "${tokens[@]}"; do + [ -z "${value//[[:space:]]/}" ] && continue + printf ' %s' "$value" >> "$ALLOW_PRIVATE_CONF" + done + printf '\nhttp_access allow client_localnet %s\n' "$acl_name" >> "$ALLOW_PRIVATE_CONF" +} + +{ + echo "# Generated by docker-agent-entrypoint.sh." + echo "# Allows selected private targets before the default private-network deny rule." +} > "$ALLOW_PRIVATE_CONF" +write_optional_private_allowlist "SSRF_PROXY_ALLOW_PRIVATE_IPS" "dify_allowed_private_networks" "dst" +write_optional_private_allowlist "SSRF_PROXY_ALLOW_PRIVATE_DOMAINS" "dify_allowed_private_domains" "dstdomain" + expand_env() { awk '{ while(match($0, /\${[A-Za-z_][A-Za-z_0-9]*}/)) { diff --git a/docker/ssrf_proxy/squid-agent.conf.template b/docker/ssrf_proxy/squid-agent.conf.template index 3a00d73dc85..ef78ef07aab 100644 --- a/docker/ssrf_proxy/squid-agent.conf.template +++ b/docker/ssrf_proxy/squid-agent.conf.template @@ -17,5 +17,6 @@ http_access deny !Safe_ports http_access deny CONNECT !SSL_ports http_access allow dst_agent_backend path_agent_stub http_access allow dst_dify_api path_files +include /etc/squid/dify_allow_private.conf http_access deny to_private_networks http_access allow all diff --git a/docker/ssrf_proxy/test_agent_ssrf_allowlist_unit.sh b/docker/ssrf_proxy/test_agent_ssrf_allowlist_unit.sh new file mode 100755 index 00000000000..6980ffa1690 --- /dev/null +++ b/docker/ssrf_proxy/test_agent_ssrf_allowlist_unit.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +ALLOW_PRIVATE_CONF="$WORK_DIR/dify_allow_private.conf" +export ALLOW_PRIVATE_CONF + +write_optional_private_allowlist() { + local env_name="$1" + local acl_name="$2" + local acl_type="$3" + local raw_values="${!env_name:-}" + local -a tokens=() + + raw_values="${raw_values//,/ }" + raw_values="${raw_values//$'\n'/ }" + raw_values="${raw_values//$'\r'/ }" + + if [ -z "${raw_values//[[:space:]]/}" ]; then + return + fi + + read -r -a tokens <<< "$raw_values" + + printf 'acl %s %s' "$acl_name" "$acl_type" >> "$ALLOW_PRIVATE_CONF" + for value in "${tokens[@]}"; do + [ -z "${value//[[:space:]]/}" ] && continue + printf ' %s' "$value" >> "$ALLOW_PRIVATE_CONF" + done + printf '\nhttp_access allow client_localnet %s\n' "$acl_name" >> "$ALLOW_PRIVATE_CONF" +} + +generate_allowlist_config() { + { + echo "# Generated by docker-agent-entrypoint.sh." + echo "# Allows selected private targets before the default private-network deny rule." + } > "$ALLOW_PRIVATE_CONF" + write_optional_private_allowlist "SSRF_PROXY_ALLOW_PRIVATE_IPS" "dify_allowed_private_networks" "dst" + write_optional_private_allowlist "SSRF_PROXY_ALLOW_PRIVATE_DOMAINS" "dify_allowed_private_domains" "dstdomain" +} + +assert_contains() { + local file="$1" + local expected="$2" + if ! grep -Fq "$expected" "$file"; then + echo "Expected generated config to contain: $expected" + cat "$file" >&2 || true + exit 1 + fi +} + +assert_not_contains() { + local file="$1" + local unexpected="$2" + if grep -Fq "$unexpected" "$file"; then + echo "Expected generated config NOT to contain: $unexpected" + cat "$file" >&2 || true + exit 1 + fi +} + +# Empty env vars should produce only the header comments. +unset SSRF_PROXY_ALLOW_PRIVATE_IPS SSRF_PROXY_ALLOW_PRIVATE_DOMAINS +generate_allowlist_config +assert_not_contains "$ALLOW_PRIVATE_CONF" "dify_allowed_private_networks" +assert_not_contains "$ALLOW_PRIVATE_CONF" "dify_allowed_private_domains" + +# IP and domain allowlists should match the workflow ssrf_proxy entrypoint format. +export SSRF_PROXY_ALLOW_PRIVATE_IPS="172.21.0.0/16,10.0.0.1" +export SSRF_PROXY_ALLOW_PRIVATE_DOMAINS="internal_api,.corp.local" +generate_allowlist_config +assert_contains "$ALLOW_PRIVATE_CONF" "acl dify_allowed_private_networks dst 172.21.0.0/16 10.0.0.1" +assert_contains "$ALLOW_PRIVATE_CONF" "http_access allow client_localnet dify_allowed_private_networks" +assert_contains "$ALLOW_PRIVATE_CONF" "acl dify_allowed_private_domains dstdomain internal_api .corp.local" +assert_contains "$ALLOW_PRIVATE_CONF" "http_access allow client_localnet dify_allowed_private_domains" + +# Glob-like tokens and newline separators must not be expanded or split by the shell. +export SSRF_PROXY_ALLOW_PRIVATE_IPS=$'172.21.0.0/16\n10.0.0.1' +export SSRF_PROXY_ALLOW_PRIVATE_DOMAINS='*.corp.local,?internal.example' +generate_allowlist_config +assert_contains "$ALLOW_PRIVATE_CONF" "acl dify_allowed_private_networks dst 172.21.0.0/16 10.0.0.1" +assert_contains "$ALLOW_PRIVATE_CONF" "acl dify_allowed_private_domains dstdomain *.corp.local ?internal.example" + +if ! grep -Fq "include /etc/squid/dify_allow_private.conf" "$ROOT_DIR/squid-agent.conf.template"; then + echo "squid-agent.conf.template must include dify_allow_private.conf before the private-network deny rule." + exit 1 +fi + +if ! grep -A1 "include /etc/squid/dify_allow_private.conf" "$ROOT_DIR/squid-agent.conf.template" | grep -Fq "http_access deny to_private_networks"; then + echo "dify_allow_private.conf must be included before http_access deny to_private_networks." + exit 1 +fi + +echo "Agent SSRF allowlist unit tests passed." diff --git a/docker/ssrf_proxy/test_ssrf_proxy_config.sh b/docker/ssrf_proxy/test_ssrf_proxy_config.sh index e2e6f435b49..1c031e45c0d 100755 --- a/docker/ssrf_proxy/test_ssrf_proxy_config.sh +++ b/docker/ssrf_proxy/test_ssrf_proxy_config.sh @@ -9,6 +9,7 @@ SANDBOX_CONTAINER_NAME="${CONTAINER_NAME}-sandbox" AGENT_PROXY_CONTAINER_NAME="${CONTAINER_NAME}-agent-proxy" API_CONTAINER_NAME="${CONTAINER_NAME}-api" AGENT_BACKEND_CONTAINER_NAME="${CONTAINER_NAME}-agent-backend" +INTERNAL_SERVICE_CONTAINER_NAME="${CONTAINER_NAME}-internal-service" NETWORK_NAME="${SSRF_PROXY_TEST_NETWORK:-dify-ssrf-proxy-test-$$}" RUN_PUBLIC_CHECK="${SSRF_PROXY_TEST_PUBLIC_CHECK:-true}" @@ -18,6 +19,7 @@ cleanup() { docker rm -f "$AGENT_PROXY_CONTAINER_NAME" >/dev/null 2>&1 || true docker rm -f "$API_CONTAINER_NAME" >/dev/null 2>&1 || true docker rm -f "$AGENT_BACKEND_CONTAINER_NAME" >/dev/null 2>&1 || true + docker rm -f "$INTERNAL_SERVICE_CONTAINER_NAME" >/dev/null 2>&1 || true docker network rm "$NETWORK_NAME" >/dev/null 2>&1 || true } @@ -204,6 +206,16 @@ docker run \ sh -c "mkdir -p /www/agent-stub && echo stub-ok > /www/agent-stub/config && echo denied > /www/index.html && httpd -f -p 5050 -h /www" \ >/dev/null +# Mock internal service reachable only on the private Docker network. +docker run \ + --detach \ + --name "$INTERNAL_SERVICE_CONTAINER_NAME" \ + --network "$NETWORK_NAME" \ + --network-alias internal_api \ + "$CLIENT_IMAGE" \ + sh -c "mkdir -p /www && echo internal-ok > /www/health && httpd -f -p 8080 -h /www" \ + >/dev/null + docker run \ --detach \ --name "$AGENT_PROXY_CONTAINER_NAME" \ @@ -214,6 +226,8 @@ docker run \ --volume "$ROOT_DIR/docker/ssrf_proxy/docker-agent-entrypoint.sh:/docker-entrypoint-mount.sh:ro" \ --env HTTP_PORT=3128 \ --env COREDUMP_DIR=/var/spool/squid \ + --env "SSRF_PROXY_ALLOW_PRIVATE_IPS=${SSRF_PROXY_ALLOW_PRIVATE_IPS:-}" \ + --env "SSRF_PROXY_ALLOW_PRIVATE_DOMAINS=${SSRF_PROXY_ALLOW_PRIVATE_DOMAINS:-internal_api}" \ "$IMAGE" \ -c "cp /docker-entrypoint-mount.sh /docker-entrypoint.sh && sed -i 's/\r$//' /docker-entrypoint.sh && chmod +x /docker-entrypoint.sh && /docker-entrypoint.sh" \ >/dev/null @@ -237,6 +251,9 @@ fi assert_private_target_blocked "$agent_proxy_url" "http://127.0.0.1:80/" assert_private_target_blocked "$agent_proxy_url" "http://169.254.169.254/latest/meta-data/" +# Allowlisted private domains must be reachable for agent skills. +assert_public_target_allowed "$agent_proxy_url" "http://internal_api:8080/health" + # agent_backend /agent-stub/* must be allowed. assert_public_target_allowed "$agent_proxy_url" "http://agent_backend:5050/agent-stub/config" diff --git a/knip.config.ts b/knip.config.ts index 3931cfd7a2f..939a3143ac2 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -32,11 +32,7 @@ const config: KnipConfig = { '!vitest.setup.ts!', ], ignore: ['public/**'], - ignoreFiles: [ - 'features/agent-v2/agent-detail/configure/components/orchestrate/memory.tsx', - 'features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/option-menu.tsx', - 'i18n-config/locale-resources/*.ts', - ], + ignoreFiles: ['i18n-config/locale-resources/*.ts'], ignoreDependencies: ['@iconify-json/*', '@storybook/addon-onboarding'], }, }, diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index fc508e12a38..b5ed66f3872 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -2294,7 +2294,7 @@ }, "web/app/components/header/account-setting/model-provider-page/hooks.ts": { "@tanstack/query/prefer-query-options": { - "count": 2 + "count": 1 } }, "web/app/components/header/account-setting/model-provider-page/model-auth/add-custom-model.tsx": { @@ -3260,14 +3260,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/_base/components/error-handle/default-value.tsx": { - "no-restricted-imports": { - "count": 1 - }, - "typescript/no-explicit-any": { - "count": 1 - } - }, "web/app/components/workflow/nodes/_base/components/error-handle/types.ts": { "erasable-syntax-only/enums": { "count": 1 @@ -4009,11 +4001,8 @@ } }, "web/app/components/workflow/nodes/loop/components/loop-variables/form-item.tsx": { - "no-restricted-imports": { - "count": 1 - }, "typescript/no-explicit-any": { - "count": 3 + "count": 2 } }, "web/app/components/workflow/nodes/loop/components/loop-variables/item.tsx": { @@ -4801,7 +4790,7 @@ }, "web/context/hooks/use-trigger-events-limit-modal.ts": { "eslint-react/set-state-in-effect": { - "count": 3 + "count": 1 }, "no-restricted-globals": { "count": 2 @@ -5138,7 +5127,7 @@ }, "web/service/use-common.ts": { "@tanstack/query/prefer-query-options": { - "count": 12 + "count": 10 } }, "web/service/use-datasource.ts": { diff --git a/package.json b/package.json index 68ec273fbba..219ee4f6fc7 100644 --- a/package.json +++ b/package.json @@ -3,8 +3,8 @@ "private": true, "type": "module", "scripts": { - "check": "vp check && pnpm lint:eslint", - "check:fix": "pnpm lint:eslint:fix && vp check --fix", + "check": "vp check && vp run lint:eslint", + "check:fix": "vp run lint:eslint:fix && vp check --fix", "dev": "concurrently -k -n vinext,proxy \"vp run dify-web#dev:vinext\" \"vp run dify-web#dev:proxy\"", "knip": "knip --workspace web", "knip:production": "knip --workspace web --production --include files", diff --git a/packages/contracts/generated/api/console/apps/orpc.gen.ts b/packages/contracts/generated/api/console/apps/orpc.gen.ts index f9dd6e0c582..d2f3910cd36 100644 --- a/packages/contracts/generated/api/console/apps/orpc.gen.ts +++ b/packages/contracts/generated/api/console/apps/orpc.gen.ts @@ -1358,7 +1358,6 @@ export const delete3 = oc method: 'DELETE', operationId: 'deleteAppsByAppIdAnnotationsByAnnotationId', path: '/apps/{app_id}/annotations/{annotation_id}', - successStatus: 204, tags: ['console'], }) .input(z.object({ params: zDeleteAppsByAppIdAnnotationsByAnnotationIdPath })) @@ -1396,7 +1395,6 @@ export const delete4 = oc method: 'DELETE', operationId: 'deleteAppsByAppIdAnnotations', path: '/apps/{app_id}/annotations', - successStatus: 204, tags: ['console'], }) .input(z.object({ params: zDeleteAppsByAppIdAnnotationsPath })) @@ -4334,7 +4332,6 @@ export const delete14 = oc method: 'DELETE', operationId: 'deleteAppsByAppIdWorkflowsByWorkflowId', path: '/apps/{app_id}/workflows/{workflow_id}', - successStatus: 204, summary: 'Delete workflow', tags: ['console'], }) diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts index 1098bb2809e..5899611953a 100644 --- a/packages/contracts/generated/api/console/apps/types.gen.ts +++ b/packages/contracts/generated/api/console/apps/types.gen.ts @@ -729,18 +729,6 @@ export type ParserEnable = { trigger_id: string } -export type WorkflowTriggerResponse = { - created_at?: string | null - icon: string - id: string - node_id: string - provider_name: string - status: string - title: string - trigger_type: string - updated_at?: string | null -} - export type WorkflowTriggerListResponse = { data: Array } @@ -1667,6 +1655,18 @@ export type TextToSpeechVoiceResponse = { value: string } +export type WorkflowTriggerResponse = { + created_at?: string | null + icon: string + id: string + node_id: string + provider_name: string + status: string + title: string + trigger_type: string + updated_at?: string | null +} + export type WorkflowAppLogPartialResponse = { created_at?: number | null created_by_account?: SimpleAccountResponse | null @@ -3870,7 +3870,9 @@ export type DeleteAppsByAppIdAnnotationsData = { } export type DeleteAppsByAppIdAnnotationsResponses = { - 204: void + 200: { + [key: string]: unknown + } } export type DeleteAppsByAppIdAnnotationsResponse = @@ -4011,7 +4013,9 @@ export type DeleteAppsByAppIdAnnotationsByAnnotationIdData = { } export type DeleteAppsByAppIdAnnotationsByAnnotationIdResponses = { - 204: void + 200: { + [key: string]: unknown + } } export type DeleteAppsByAppIdAnnotationsByAnnotationIdResponse = @@ -5095,7 +5099,9 @@ export type PostAppsByAppIdTriggerEnableData = { } export type PostAppsByAppIdTriggerEnableResponses = { - 200: WorkflowTriggerResponse + 200: { + [key: string]: unknown + } } export type PostAppsByAppIdTriggerEnableResponse = @@ -6503,7 +6509,9 @@ export type DeleteAppsByAppIdWorkflowsByWorkflowIdData = { } export type DeleteAppsByAppIdWorkflowsByWorkflowIdResponses = { - 204: void + 200: { + [key: string]: unknown + } } export type DeleteAppsByAppIdWorkflowsByWorkflowIdResponse = diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts index ef20a64815b..3f556df7381 100644 --- a/packages/contracts/generated/api/console/apps/zod.gen.ts +++ b/packages/contracts/generated/api/console/apps/zod.gen.ts @@ -481,28 +481,6 @@ export const zParserEnable = z.object({ trigger_id: z.string(), }) -/** - * WorkflowTriggerResponse - */ -export const zWorkflowTriggerResponse = z.object({ - created_at: z.iso.datetime().nullish(), - icon: z.string(), - id: z.string(), - node_id: z.string(), - provider_name: z.string(), - status: z.string(), - title: z.string(), - trigger_type: z.string(), - updated_at: z.iso.datetime().nullish(), -}) - -/** - * WorkflowTriggerListResponse - */ -export const zWorkflowTriggerListResponse = z.object({ - data: z.array(zWorkflowTriggerResponse), -}) - /** * WorkflowAgentSandboxDownloadPayload */ @@ -1479,6 +1457,28 @@ export const zTextToSpeechVoiceResponse = z.object({ */ export const zTextToSpeechVoiceListResponse = z.array(zTextToSpeechVoiceResponse) +/** + * WorkflowTriggerResponse + */ +export const zWorkflowTriggerResponse = z.object({ + created_at: z.iso.datetime().nullish(), + icon: z.string(), + id: z.string(), + node_id: z.string(), + provider_name: z.string(), + status: z.string(), + title: z.string(), + trigger_type: z.string(), + updated_at: z.iso.datetime().nullish(), +}) + +/** + * WorkflowTriggerListResponse + */ +export const zWorkflowTriggerListResponse = z.object({ + data: z.array(zWorkflowTriggerResponse), +}) + /** * SimpleAccountResponse */ @@ -4723,9 +4723,9 @@ export const zDeleteAppsByAppIdAnnotationsPath = z.object({ }) /** - * Annotations deleted successfully + * Success */ -export const zDeleteAppsByAppIdAnnotationsResponse = z.void() +export const zDeleteAppsByAppIdAnnotationsResponse = z.record(z.string(), z.unknown()) export const zGetAppsByAppIdAnnotationsPath = z.object({ app_id: z.uuid(), @@ -4797,9 +4797,9 @@ export const zDeleteAppsByAppIdAnnotationsByAnnotationIdPath = z.object({ }) /** - * Annotation deleted successfully + * Success */ -export const zDeleteAppsByAppIdAnnotationsByAnnotationIdResponse = z.void() +export const zDeleteAppsByAppIdAnnotationsByAnnotationIdResponse = z.record(z.string(), z.unknown()) export const zPostAppsByAppIdAnnotationsByAnnotationIdBody = zUpdateAnnotationPayload @@ -5421,7 +5421,7 @@ export const zPostAppsByAppIdTriggerEnablePath = z.object({ /** * Success */ -export const zPostAppsByAppIdTriggerEnableResponse = zWorkflowTriggerResponse +export const zPostAppsByAppIdTriggerEnableResponse = z.record(z.string(), z.unknown()) export const zGetAppsByAppIdTriggersPath = z.object({ app_id: z.uuid(), @@ -6314,9 +6314,9 @@ export const zDeleteAppsByAppIdWorkflowsByWorkflowIdPath = z.object({ }) /** - * Workflow deleted successfully + * Success */ -export const zDeleteAppsByAppIdWorkflowsByWorkflowIdResponse = z.void() +export const zDeleteAppsByAppIdWorkflowsByWorkflowIdResponse = z.record(z.string(), z.unknown()) export const zPatchAppsByAppIdWorkflowsByWorkflowIdBody = zWorkflowUpdatePayload diff --git a/packages/contracts/generated/api/console/auth/types.gen.ts b/packages/contracts/generated/api/console/auth/types.gen.ts index 7b9404d5bfb..3f83a36fb2a 100644 --- a/packages/contracts/generated/api/console/auth/types.gen.ts +++ b/packages/contracts/generated/api/console/auth/types.gen.ts @@ -205,7 +205,9 @@ export type DeleteAuthPluginDatasourceByProviderIdCustomClientData = { } export type DeleteAuthPluginDatasourceByProviderIdCustomClientResponses = { - 200: SimpleResultResponse + 200: { + [key: string]: unknown + } } export type DeleteAuthPluginDatasourceByProviderIdCustomClientResponse = diff --git a/packages/contracts/generated/api/console/auth/zod.gen.ts b/packages/contracts/generated/api/console/auth/zod.gen.ts index b52a8f4f63a..cedba982045 100644 --- a/packages/contracts/generated/api/console/auth/zod.gen.ts +++ b/packages/contracts/generated/api/console/auth/zod.gen.ts @@ -223,7 +223,10 @@ export const zDeleteAuthPluginDatasourceByProviderIdCustomClientPath = z.object( /** * Success */ -export const zDeleteAuthPluginDatasourceByProviderIdCustomClientResponse = zSimpleResultResponse +export const zDeleteAuthPluginDatasourceByProviderIdCustomClientResponse = z.record( + z.string(), + z.unknown(), +) export const zPostAuthPluginDatasourceByProviderIdCustomClientBody = zDatasourceCustomClientPayload diff --git a/packages/contracts/generated/api/console/data-source/types.gen.ts b/packages/contracts/generated/api/console/data-source/types.gen.ts index 1c074190df0..1c1051369c4 100644 --- a/packages/contracts/generated/api/console/data-source/types.gen.ts +++ b/packages/contracts/generated/api/console/data-source/types.gen.ts @@ -4,46 +4,6 @@ export type ClientOptions = { baseUrl: `${string}://${string}/console/api` | (string & {}) } -export type DataSourceIntegrateListResponse = { - data: Array -} - -export type SimpleResultResponse = { - result: string -} - -export type DataSourceIntegrateResponse = { - created_at: number | null - disabled: boolean | null - id: string | null - is_bound: boolean - link: string - provider: string - source_info: DataSourceIntegrateWorkspaceResponse | null -} - -export type DataSourceIntegrateWorkspaceResponse = { - pages: Array - total: number - workspace_icon: string | null - workspace_id: string | null - workspace_name: string | null -} - -export type DataSourceIntegratePageResponse = { - page_icon: DataSourceIntegrateIconResponse | null - page_id: string - page_name: string - parent_id: string - type: string -} - -export type DataSourceIntegrateIconResponse = { - emoji?: string | null - type?: string | null - url?: string | null -} - export type GetDataSourceIntegratesData = { body?: never path?: never @@ -52,7 +12,9 @@ export type GetDataSourceIntegratesData = { } export type GetDataSourceIntegratesResponses = { - 200: DataSourceIntegrateListResponse + 200: { + [key: string]: unknown + } } export type GetDataSourceIntegratesResponse = @@ -66,7 +28,9 @@ export type PatchDataSourceIntegratesData = { } export type PatchDataSourceIntegratesResponses = { - 200: SimpleResultResponse + 200: { + [key: string]: unknown + } } export type PatchDataSourceIntegratesResponse = @@ -83,7 +47,9 @@ export type GetDataSourceIntegratesByBindingIdByActionData = { } export type GetDataSourceIntegratesByBindingIdByActionResponses = { - 200: DataSourceIntegrateListResponse + 200: { + [key: string]: unknown + } } export type GetDataSourceIntegratesByBindingIdByActionResponse = @@ -100,7 +66,9 @@ export type PatchDataSourceIntegratesByBindingIdByActionData = { } export type PatchDataSourceIntegratesByBindingIdByActionResponses = { - 200: SimpleResultResponse + 200: { + [key: string]: unknown + } } export type PatchDataSourceIntegratesByBindingIdByActionResponse = diff --git a/packages/contracts/generated/api/console/data-source/zod.gen.ts b/packages/contracts/generated/api/console/data-source/zod.gen.ts index e2774d10f42..8236a06d2e4 100644 --- a/packages/contracts/generated/api/console/data-source/zod.gen.ts +++ b/packages/contracts/generated/api/console/data-source/zod.gen.ts @@ -3,72 +3,14 @@ import * as z from 'zod' /** - * SimpleResultResponse + * Success */ -export const zSimpleResultResponse = z.object({ - result: z.string(), -}) - -/** - * DataSourceIntegrateIconResponse - */ -export const zDataSourceIntegrateIconResponse = z.object({ - emoji: z.string().nullish(), - type: z.string().nullish(), - url: z.string().nullish(), -}) - -/** - * DataSourceIntegratePageResponse - */ -export const zDataSourceIntegratePageResponse = z.object({ - page_icon: zDataSourceIntegrateIconResponse.nullable(), - page_id: z.string(), - page_name: z.string(), - parent_id: z.string(), - type: z.string(), -}) - -/** - * DataSourceIntegrateWorkspaceResponse - */ -export const zDataSourceIntegrateWorkspaceResponse = z.object({ - pages: z.array(zDataSourceIntegratePageResponse), - total: z.int(), - workspace_icon: z.string().nullable(), - workspace_id: z.string().nullable(), - workspace_name: z.string().nullable(), -}) - -/** - * DataSourceIntegrateResponse - */ -export const zDataSourceIntegrateResponse = z.object({ - created_at: z.int().nullable(), - disabled: z.boolean().nullable(), - id: z.string().nullable(), - is_bound: z.boolean(), - link: z.string(), - provider: z.string(), - source_info: zDataSourceIntegrateWorkspaceResponse.nullable(), -}) - -/** - * DataSourceIntegrateListResponse - */ -export const zDataSourceIntegrateListResponse = z.object({ - data: z.array(zDataSourceIntegrateResponse), -}) +export const zGetDataSourceIntegratesResponse = z.record(z.string(), z.unknown()) /** * Success */ -export const zGetDataSourceIntegratesResponse = zDataSourceIntegrateListResponse - -/** - * Success - */ -export const zPatchDataSourceIntegratesResponse = zSimpleResultResponse +export const zPatchDataSourceIntegratesResponse = z.record(z.string(), z.unknown()) export const zGetDataSourceIntegratesByBindingIdByActionPath = z.object({ action: z.string(), @@ -78,7 +20,7 @@ export const zGetDataSourceIntegratesByBindingIdByActionPath = z.object({ /** * Success */ -export const zGetDataSourceIntegratesByBindingIdByActionResponse = zDataSourceIntegrateListResponse +export const zGetDataSourceIntegratesByBindingIdByActionResponse = z.record(z.string(), z.unknown()) export const zPatchDataSourceIntegratesByBindingIdByActionPath = z.object({ action: z.string(), @@ -88,4 +30,7 @@ export const zPatchDataSourceIntegratesByBindingIdByActionPath = z.object({ /** * Success */ -export const zPatchDataSourceIntegratesByBindingIdByActionResponse = zSimpleResultResponse +export const zPatchDataSourceIntegratesByBindingIdByActionResponse = z.record( + z.string(), + z.unknown(), +) diff --git a/packages/contracts/generated/api/console/features/orpc.gen.ts b/packages/contracts/generated/api/console/features/orpc.gen.ts index f59b841fcd2..cdde66b21ad 100644 --- a/packages/contracts/generated/api/console/features/orpc.gen.ts +++ b/packages/contracts/generated/api/console/features/orpc.gen.ts @@ -25,18 +25,18 @@ export const vectorSpace = { } /** - * Get feature configuration for current tenant + * Get current workspace features * - * Get feature configuration for current tenant + * Get feature availability and limits for the current workspace */ export const get2 = oc .route({ - description: 'Get feature configuration for current tenant', + description: 'Get feature availability and limits for the current workspace', inputStructure: 'detailed', method: 'GET', operationId: 'getFeatures', path: '/features', - summary: 'Get feature configuration for current tenant', + summary: 'Get current workspace features', tags: ['console'], }) .output(zGetFeaturesResponse) diff --git a/packages/contracts/generated/api/console/features/types.gen.ts b/packages/contracts/generated/api/console/features/types.gen.ts index 227ba487b51..b110f50a282 100644 --- a/packages/contracts/generated/api/console/features/types.gen.ts +++ b/packages/contracts/generated/api/console/features/types.gen.ts @@ -10,22 +10,16 @@ export type FeatureModel = { apps: LimitationModel billing: BillingModel can_replace_logo: boolean - dataset_operator_enabled: boolean dify_builder_enabled: boolean - docs_processing: string documents_upload_quota: LimitationModel education: EducationModel enable_skill: boolean human_input_email_delivery_enabled: boolean is_allow_transfer_workspace: boolean knowledge_pipeline: KnowledgePipeline - knowledge_rate_limit: number members: LimitationModel model_load_balancing_enabled: boolean - next_credit_reset_date: number - skill_learning_policy: string trigger_event: Quota - vector_space: LimitationModel | null webapp_copyright_enabled: boolean workspace_members: LicenseLimitationModel } @@ -48,7 +42,6 @@ export type Quota = { } export type BillingModel = { - enabled: boolean subscription: SubscriptionModel } diff --git a/packages/contracts/generated/api/console/features/zod.gen.ts b/packages/contracts/generated/api/console/features/zod.gen.ts index bc28b5c706c..f9fe1c3db73 100644 --- a/packages/contracts/generated/api/console/features/zod.gen.ts +++ b/packages/contracts/generated/api/console/features/zod.gen.ts @@ -79,12 +79,13 @@ export const zSubscriptionModel = z.object({ * BillingModel */ export const zBillingModel = z.object({ - enabled: z.boolean().default(false), subscription: zSubscriptionModel.default({ interval: '', plan: 'sandbox' }), }) /** * FeatureModel + * + * Effective feature availability and limits for the current workspace. */ export const zFeatureModel = z.object({ annotation_quota_limit: zLimitationModel.default({ limit: 10, size: 0 }), @@ -94,31 +95,22 @@ export const zFeatureModel = z.object({ usage: 0, }), apps: zLimitationModel.default({ limit: 10, size: 0 }), - billing: zBillingModel.default({ - enabled: false, - subscription: { interval: '', plan: 'sandbox' }, - }), + billing: zBillingModel.default({ subscription: { interval: '', plan: 'sandbox' } }), can_replace_logo: z.boolean().default(false), - dataset_operator_enabled: z.boolean().default(false), dify_builder_enabled: z.boolean().default(false), - docs_processing: z.string().default('standard'), documents_upload_quota: zLimitationModel.default({ limit: 50, size: 0 }), education: zEducationModel.default({ activated: false, enabled: false }), enable_skill: z.boolean().default(true), human_input_email_delivery_enabled: z.boolean().default(false), is_allow_transfer_workspace: z.boolean().default(true), knowledge_pipeline: zKnowledgePipeline.default({ publish_enabled: false }), - knowledge_rate_limit: z.int().default(10), members: zLimitationModel.default({ limit: 1, size: 0 }), model_load_balancing_enabled: z.boolean().default(false), - next_credit_reset_date: z.int().default(0), - skill_learning_policy: z.string().default('ask'), trigger_event: zQuota.default({ limit: 3000, reset_date: 0, usage: 0, }), - vector_space: zLimitationModel.nullable().default({ limit: 5, size: 0 }), webapp_copyright_enabled: z.boolean().default(false), workspace_members: zLicenseLimitationModel.default({ enabled: false, diff --git a/packages/contracts/generated/api/console/rag/orpc.gen.ts b/packages/contracts/generated/api/console/rag/orpc.gen.ts index 848cfd1d15b..3609fc31511 100644 --- a/packages/contracts/generated/api/console/rag/orpc.gen.ts +++ b/packages/contracts/generated/api/console/rag/orpc.gen.ts @@ -73,10 +73,8 @@ import { zPatchRagPipelineCustomizedTemplatesByTemplateIdBody, zPatchRagPipelineCustomizedTemplatesByTemplateIdPath, zPatchRagPipelineCustomizedTemplatesByTemplateIdResponse, - zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdBody, zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdPath, zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdResponse, - zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdBody, zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdPath, zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdResponse, zPostRagPipelineCustomizedTemplatesByTemplateIdPath, @@ -91,7 +89,6 @@ import { zPostRagPipelinesByPipelineIdWorkflowRunsTasksByTaskIdStopResponse, zPostRagPipelinesByPipelineIdWorkflowsByWorkflowIdRestorePath, zPostRagPipelinesByPipelineIdWorkflowsByWorkflowIdRestoreResponse, - zPostRagPipelinesByPipelineIdWorkflowsDraftBody, zPostRagPipelinesByPipelineIdWorkflowsDraftDatasourceNodesByNodeIdRunBody, zPostRagPipelinesByPipelineIdWorkflowsDraftDatasourceNodesByNodeIdRunPath, zPostRagPipelinesByPipelineIdWorkflowsDraftDatasourceNodesByNodeIdRunResponse, @@ -927,10 +924,7 @@ export const patch2 = oc tags: ['console'], }) .input( - z.object({ - body: zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdBody, - params: zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdPath, - }), + z.object({ params: zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdPath }), ) .output(zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdResponse) @@ -1006,12 +1000,7 @@ export const post15 = oc summary: 'Sync draft workflow', tags: ['console'], }) - .input( - z.object({ - body: zPostRagPipelinesByPipelineIdWorkflowsDraftBody, - params: zPostRagPipelinesByPipelineIdWorkflowsDraftPath, - }), - ) + .input(z.object({ params: zPostRagPipelinesByPipelineIdWorkflowsDraftPath })) .output(zPostRagPipelinesByPipelineIdWorkflowsDraftResponse) export const draft = { @@ -1255,12 +1244,7 @@ export const patch3 = oc summary: 'Update workflow attributes', tags: ['console'], }) - .input( - z.object({ - body: zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdBody, - params: zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdPath, - }), - ) + .input(z.object({ params: zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdPath })) .output(zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdResponse) export const byWorkflowId = { diff --git a/packages/contracts/generated/api/console/rag/types.gen.ts b/packages/contracts/generated/api/console/rag/types.gen.ts index dedbd4ec55e..c5ea18e56b1 100644 --- a/packages/contracts/generated/api/console/rag/types.gen.ts +++ b/packages/contracts/generated/api/console/rag/types.gen.ts @@ -178,31 +178,6 @@ export type WorkflowResponse = { version_number?: number | null } -export type DraftWorkflowSyncPayload = { - conversation_variables?: Array<{ - [key: string]: unknown - }> | null - environment_variables?: Array<{ - [key: string]: unknown - }> | null - features?: { - [key: string]: unknown - } | null - graph: { - [key: string]: unknown - } - hash?: string | null - rag_pipeline_variables?: Array<{ - [key: string]: unknown - }> | null -} - -export type RagPipelineWorkflowSyncResponse = { - hash: string - result: string - updated_at: number -} - export type DatasourceNodeRunPayload = { credential_id?: string | null datasource_type: string @@ -311,11 +286,6 @@ export type WorkflowDraftVariable = { visible?: boolean } -export type WorkflowDraftVariablePatchPayload = { - name?: string | null - value?: unknown | null -} - export type RagPipelineWorkflowPublishResponse = { created_at: number result: string @@ -343,9 +313,10 @@ export type PublishedWorkflowRunPayload = { start_node_id: string } -export type WorkflowUpdatePayload = { - marked_comment?: string | null - marked_name?: string | null +export type RagPipelineWorkflowSyncResponse = { + hash: string + result: string + updated_at: number } export type ImportStatus = 'completed' | 'completed-with-warnings' | 'failed' | 'pending' @@ -963,7 +934,7 @@ export type GetRagPipelinesByPipelineIdWorkflowsDraftResponse = GetRagPipelinesByPipelineIdWorkflowsDraftResponses[keyof GetRagPipelinesByPipelineIdWorkflowsDraftResponses] export type PostRagPipelinesByPipelineIdWorkflowsDraftData = { - body: DraftWorkflowSyncPayload + body?: never path: { pipeline_id: string } @@ -972,7 +943,9 @@ export type PostRagPipelinesByPipelineIdWorkflowsDraftData = { } export type PostRagPipelinesByPipelineIdWorkflowsDraftResponses = { - 200: RagPipelineWorkflowSyncResponse + 200: { + [key: string]: unknown + } } export type PostRagPipelinesByPipelineIdWorkflowsDraftResponse = @@ -1267,7 +1240,7 @@ export type GetRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdRespon GetRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdResponses[keyof GetRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdResponses] export type PatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdData = { - body: WorkflowDraftVariablePatchPayload + body?: never path: { pipeline_id: string variable_id: string @@ -1440,7 +1413,7 @@ export type DeleteRagPipelinesByPipelineIdWorkflowsByWorkflowIdResponse = DeleteRagPipelinesByPipelineIdWorkflowsByWorkflowIdResponses[keyof DeleteRagPipelinesByPipelineIdWorkflowsByWorkflowIdResponses] export type PatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdData = { - body: WorkflowUpdatePayload + body?: never path: { pipeline_id: string workflow_id: string diff --git a/packages/contracts/generated/api/console/rag/zod.gen.ts b/packages/contracts/generated/api/console/rag/zod.gen.ts index 7ff07aabc10..36e185707f8 100644 --- a/packages/contracts/generated/api/console/rag/zod.gen.ts +++ b/packages/contracts/generated/api/console/rag/zod.gen.ts @@ -76,27 +76,6 @@ export const zDefaultBlockConfigsResponse = z.array(z.record(z.string(), z.unkno */ export const zDefaultBlockConfigResponse = z.record(z.string(), z.unknown()) -/** - * DraftWorkflowSyncPayload - */ -export const zDraftWorkflowSyncPayload = z.object({ - conversation_variables: z.array(z.record(z.string(), z.unknown())).nullish(), - environment_variables: z.array(z.record(z.string(), z.unknown())).nullish(), - features: z.record(z.string(), z.unknown()).nullish(), - graph: z.record(z.string(), z.unknown()), - hash: z.string().nullish(), - rag_pipeline_variables: z.array(z.record(z.string(), z.unknown())).nullish(), -}) - -/** - * RagPipelineWorkflowSyncResponse - */ -export const zRagPipelineWorkflowSyncResponse = z.object({ - hash: z.string(), - result: z.string(), - updated_at: z.int(), -}) - /** * DatasourceNodeRunPayload */ @@ -174,14 +153,6 @@ export const zWorkflowDraftVariableList = z.object({ items: z.array(zWorkflowDraftVariable).optional(), }) -/** - * WorkflowDraftVariablePatchPayload - */ -export const zWorkflowDraftVariablePatchPayload = z.object({ - name: z.string().nullish(), - value: z.unknown().nullish(), -}) - /** * RagPipelineWorkflowPublishResponse */ @@ -213,11 +184,12 @@ export const zPublishedWorkflowRunPayload = z.object({ }) /** - * WorkflowUpdatePayload + * RagPipelineWorkflowSyncResponse */ -export const zWorkflowUpdatePayload = z.object({ - marked_comment: z.string().max(100).nullish(), - marked_name: z.string().max(20).nullish(), +export const zRagPipelineWorkflowSyncResponse = z.object({ + hash: z.string(), + result: z.string(), + updated_at: z.int(), }) /** @@ -906,8 +878,6 @@ export const zGetRagPipelinesByPipelineIdWorkflowsDraftPath = z.object({ */ export const zGetRagPipelinesByPipelineIdWorkflowsDraftResponse = zWorkflowResponse -export const zPostRagPipelinesByPipelineIdWorkflowsDraftBody = zDraftWorkflowSyncPayload - export const zPostRagPipelinesByPipelineIdWorkflowsDraftPath = z.object({ pipeline_id: z.uuid(), }) @@ -915,7 +885,7 @@ export const zPostRagPipelinesByPipelineIdWorkflowsDraftPath = z.object({ /** * Success */ -export const zPostRagPipelinesByPipelineIdWorkflowsDraftResponse = zRagPipelineWorkflowSyncResponse +export const zPostRagPipelinesByPipelineIdWorkflowsDraftResponse = z.record(z.string(), z.unknown()) export const zPostRagPipelinesByPipelineIdWorkflowsDraftDatasourceNodesByNodeIdRunBody = zDatasourceNodeRunPayload @@ -1121,9 +1091,6 @@ export const zGetRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdPath export const zGetRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdResponse = zWorkflowDraftVariable -export const zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdBody = - zWorkflowDraftVariablePatchPayload - export const zPatchRagPipelinesByPipelineIdWorkflowsDraftVariablesByVariableIdPath = z.object({ pipeline_id: z.uuid(), variable_id: z.uuid(), @@ -1242,8 +1209,6 @@ export const zDeleteRagPipelinesByPipelineIdWorkflowsByWorkflowIdPath = z.object */ export const zDeleteRagPipelinesByPipelineIdWorkflowsByWorkflowIdResponse = z.void() -export const zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdBody = zWorkflowUpdatePayload - export const zPatchRagPipelinesByPipelineIdWorkflowsByWorkflowIdPath = z.object({ pipeline_id: z.uuid(), workflow_id: z.string(), diff --git a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts index 69a7e3a9d64..0ff9cd3c520 100644 --- a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts +++ b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts @@ -20,6 +20,9 @@ import { zDeleteWorkspacesCurrentModelProvidersByProviderModelsResponse, zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath, zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse, + zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsBody, + zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsPath, + zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse, zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsBody, zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath, zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse, @@ -113,6 +116,20 @@ import { zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath, zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse, zGetWorkspacesCurrentRbacAccessPoliciesResponse, + zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsPath, + zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse, + zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsPath, + zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsResponse, + zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyPath, + zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyQuery, + zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyResponse, + zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesPath, + zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesQuery, + zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesResponse, + zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigPath, + zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigResponse, + zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistPath, + zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse, zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath, zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse, zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsPath, @@ -144,6 +161,7 @@ import { zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath, zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse, zGetWorkspacesCurrentRbacMyPermissionsResponse, + zGetWorkspacesCurrentRbacRolePermissionsCatalogAgentResponse, zGetWorkspacesCurrentRbacRolePermissionsCatalogAppResponse, zGetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponse, zGetWorkspacesCurrentRbacRolePermissionsCatalogResponse, @@ -152,6 +170,11 @@ import { zGetWorkspacesCurrentRbacRolesByRoleIdPath, zGetWorkspacesCurrentRbacRolesByRoleIdResponse, zGetWorkspacesCurrentRbacRolesResponse, + zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsPath, + zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsResponse, + zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsPath, + zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsResponse, + zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyResponse, zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsPath, zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponse, zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsPath, @@ -463,6 +486,12 @@ import { zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse, zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockPath, zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse, + zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesBody, + zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesPath, + zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesResponse, + zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistBody, + zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistPath, + zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse, zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesBody, zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesPath, zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponse, @@ -480,6 +509,9 @@ import { zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse, zPutWorkspacesCurrentRbacRolesByRoleIdPath, zPutWorkspacesCurrentRbacRolesByRoleIdResponse, + zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsBody, + zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsPath, + zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsResponse, zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsBody, zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsPath, zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponse, @@ -2277,7 +2309,6 @@ export const post44 = oc method: 'POST', operationId: 'postWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopy', path: '/workspaces/current/rbac/access-policies/{policy_id}/copy', - successStatus: 201, tags: ['console'], }) .input(z.object({ params: zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyPath })) @@ -2343,7 +2374,6 @@ export const post45 = oc method: 'POST', operationId: 'postWorkspacesCurrentRbacAccessPolicies', path: '/workspaces/current/rbac/access-policies', - successStatus: 201, tags: ['console'], }) .output(zPostWorkspacesCurrentRbacAccessPoliciesResponse) @@ -2397,32 +2427,32 @@ export const delete10 = oc .route({ inputStructure: 'detailed', method: 'DELETE', - operationId: 'deleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindings', - path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings', + operationId: 'deleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindings', + path: '/workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/member-bindings', tags: ['console'], }) .input( z.object({ - body: zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsBody, - params: zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath, + body: zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsBody, + params: zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsPath, }), ) - .output(zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse) + .output(zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse) export const get39 = oc .route({ inputStructure: 'detailed', method: 'GET', - operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindings', - path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings', + operationId: 'getWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindings', + path: '/workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/member-bindings', tags: ['console'], }) .input( z.object({ - params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath, + params: zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsPath, }), ) - .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse) + .output(zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse) export const memberBindings = { delete: delete10, @@ -2433,16 +2463,16 @@ export const get40 = oc .route({ inputStructure: 'detailed', method: 'GET', - operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindings', - path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/role-bindings', + operationId: 'getWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindings', + path: '/workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/role-bindings', tags: ['console'], }) .input( z.object({ - params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsPath, + params: zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsPath, }), ) - .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponse) + .output(zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsResponse) export const roleBindings = { get: get40, @@ -2461,17 +2491,17 @@ export const get41 = oc .route({ inputStructure: 'detailed', method: 'GET', - operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPolicy', - path: '/workspaces/current/rbac/apps/{app_id}/access-policy', + operationId: 'getWorkspacesCurrentRbacAgentsByAgentIdAccessPolicy', + path: '/workspaces/current/rbac/agents/{agent_id}/access-policy', tags: ['console'], }) .input( z.object({ - params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyPath, - query: zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyQuery.optional(), + params: zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyPath, + query: zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyQuery.optional(), }), ) - .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponse) + .output(zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyResponse) export const accessPolicy = { get: get41, @@ -2481,17 +2511,17 @@ export const get42 = oc .route({ inputStructure: 'detailed', method: 'GET', - operationId: 'getWorkspacesCurrentRbacAppsByAppIdUserAccessPolicies', - path: '/workspaces/current/rbac/apps/{app_id}/user-access-policies', + operationId: 'getWorkspacesCurrentRbacAgentsByAgentIdUserAccessPolicies', + path: '/workspaces/current/rbac/agents/{agent_id}/user-access-policies', tags: ['console'], }) .input( z.object({ - params: zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesPath, - query: zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesQuery.optional(), + params: zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesPath, + query: zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesQuery.optional(), }), ) - .output(zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponse) + .output(zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesResponse) export const userAccessPolicies = { get: get42, @@ -2501,17 +2531,17 @@ export const put8 = oc .route({ inputStructure: 'detailed', method: 'PUT', - operationId: 'putWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPolicies', - path: '/workspaces/current/rbac/apps/{app_id}/users/{target_account_id}/access-policies', + operationId: 'putWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPolicies', + path: '/workspaces/current/rbac/agents/{agent_id}/users/{target_account_id}/access-policies', tags: ['console'], }) .input( z.object({ - body: zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesBody, - params: zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesPath, + body: zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesBody, + params: zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesPath, }), ) - .output(zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponse) + .output(zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesResponse) export const accessPolicies3 = { put: put8, @@ -2526,6 +2556,198 @@ export const users = { } export const get43 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacAgentsByAgentIdWhitelist', + path: '/workspaces/current/rbac/agents/{agent_id}/whitelist', + tags: ['console'], + }) + .input(z.object({ params: zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistPath })) + .output(zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse) + +export const put9 = oc + .route({ + inputStructure: 'detailed', + method: 'PUT', + operationId: 'putWorkspacesCurrentRbacAgentsByAgentIdWhitelist', + path: '/workspaces/current/rbac/agents/{agent_id}/whitelist', + tags: ['console'], + }) + .input( + z.object({ + body: zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistBody, + params: zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistPath, + }), + ) + .output(zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse) + +export const whitelist = { + get: get43, + put: put9, +} + +export const get44 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfig', + path: '/workspaces/current/rbac/agents/{agent_id}/whitelist_config', + tags: ['console'], + }) + .input(z.object({ params: zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigPath })) + .output(zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigResponse) + +export const whitelistConfig = { + get: get44, +} + +export const byAgentId2 = { + accessPolicies: accessPolicies2, + accessPolicy, + userAccessPolicies, + users, + whitelist, + whitelistConfig, +} + +export const agents2 = { + byAgentId: byAgentId2, +} + +export const delete11 = oc + .route({ + inputStructure: 'detailed', + method: 'DELETE', + operationId: 'deleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindings', + path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings', + tags: ['console'], + }) + .input( + z.object({ + body: zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsBody, + params: zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath, + }), + ) + .output(zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse) + +export const get45 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindings', + path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings', + tags: ['console'], + }) + .input( + z.object({ + params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsPath, + }), + ) + .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsResponse) + +export const memberBindings2 = { + delete: delete11, + get: get45, +} + +export const get46 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindings', + path: '/workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/role-bindings', + tags: ['console'], + }) + .input( + z.object({ + params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsPath, + }), + ) + .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdRoleBindingsResponse) + +export const roleBindings2 = { + get: get46, +} + +export const byPolicyId3 = { + memberBindings: memberBindings2, + roleBindings: roleBindings2, +} + +export const accessPolicies4 = { + byPolicyId: byPolicyId3, +} + +export const get47 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacAppsByAppIdAccessPolicy', + path: '/workspaces/current/rbac/apps/{app_id}/access-policy', + tags: ['console'], + }) + .input( + z.object({ + params: zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyPath, + query: zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyQuery.optional(), + }), + ) + .output(zGetWorkspacesCurrentRbacAppsByAppIdAccessPolicyResponse) + +export const accessPolicy2 = { + get: get47, +} + +export const get48 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacAppsByAppIdUserAccessPolicies', + path: '/workspaces/current/rbac/apps/{app_id}/user-access-policies', + tags: ['console'], + }) + .input( + z.object({ + params: zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesPath, + query: zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesQuery.optional(), + }), + ) + .output(zGetWorkspacesCurrentRbacAppsByAppIdUserAccessPoliciesResponse) + +export const userAccessPolicies2 = { + get: get48, +} + +export const put10 = oc + .route({ + inputStructure: 'detailed', + method: 'PUT', + operationId: 'putWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPolicies', + path: '/workspaces/current/rbac/apps/{app_id}/users/{target_account_id}/access-policies', + tags: ['console'], + }) + .input( + z.object({ + body: zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesBody, + params: zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesPath, + }), + ) + .output(zPutWorkspacesCurrentRbacAppsByAppIdUsersByTargetAccountIdAccessPoliciesResponse) + +export const accessPolicies5 = { + put: put10, +} + +export const byTargetAccountId2 = { + accessPolicies: accessPolicies5, +} + +export const users2 = { + byTargetAccountId: byTargetAccountId2, +} + +export const get49 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2536,7 +2758,7 @@ export const get43 = oc .input(z.object({ params: zGetWorkspacesCurrentRbacAppsByAppIdWhitelistPath })) .output(zGetWorkspacesCurrentRbacAppsByAppIdWhitelistResponse) -export const put9 = oc +export const put11 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -2552,12 +2774,12 @@ export const put9 = oc ) .output(zPutWorkspacesCurrentRbacAppsByAppIdWhitelistResponse) -export const whitelist = { - get: get43, - put: put9, +export const whitelist2 = { + get: get49, + put: put11, } -export const get44 = oc +export const get50 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2568,24 +2790,24 @@ export const get44 = oc .input(z.object({ params: zGetWorkspacesCurrentRbacAppsByAppIdWhitelistConfigPath })) .output(zGetWorkspacesCurrentRbacAppsByAppIdWhitelistConfigResponse) -export const whitelistConfig = { - get: get44, +export const whitelistConfig2 = { + get: get50, } export const byAppId = { - accessPolicies: accessPolicies2, - accessPolicy, - userAccessPolicies, - users, - whitelist, - whitelistConfig, + accessPolicies: accessPolicies4, + accessPolicy: accessPolicy2, + userAccessPolicies: userAccessPolicies2, + users: users2, + whitelist: whitelist2, + whitelistConfig: whitelistConfig2, } export const apps = { byAppId, } -export const delete11 = oc +export const delete12 = oc .route({ inputStructure: 'detailed', method: 'DELETE', @@ -2605,7 +2827,7 @@ export const delete11 = oc zDeleteWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse, ) -export const get45 = oc +export const get51 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2624,12 +2846,12 @@ export const get45 = oc zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdMemberBindingsResponse, ) -export const memberBindings2 = { - delete: delete11, - get: get45, +export const memberBindings3 = { + delete: delete12, + get: get51, } -export const get46 = oc +export const get52 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2644,20 +2866,20 @@ export const get46 = oc ) .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPoliciesByPolicyIdRoleBindingsResponse) -export const roleBindings2 = { - get: get46, +export const roleBindings3 = { + get: get52, } -export const byPolicyId3 = { - memberBindings: memberBindings2, - roleBindings: roleBindings2, +export const byPolicyId4 = { + memberBindings: memberBindings3, + roleBindings: roleBindings3, } -export const accessPolicies4 = { - byPolicyId: byPolicyId3, +export const accessPolicies6 = { + byPolicyId: byPolicyId4, } -export const get47 = oc +export const get53 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2673,11 +2895,11 @@ export const get47 = oc ) .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdAccessPolicyResponse) -export const accessPolicy2 = { - get: get47, +export const accessPolicy3 = { + get: get53, } -export const get48 = oc +export const get54 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2693,11 +2915,11 @@ export const get48 = oc ) .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdUserAccessPoliciesResponse) -export const userAccessPolicies2 = { - get: get48, +export const userAccessPolicies3 = { + get: get54, } -export const put10 = oc +export const put12 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -2713,19 +2935,19 @@ export const put10 = oc ) .output(zPutWorkspacesCurrentRbacDatasetsByDatasetIdUsersByTargetAccountIdAccessPoliciesResponse) -export const accessPolicies5 = { - put: put10, +export const accessPolicies7 = { + put: put12, } -export const byTargetAccountId2 = { - accessPolicies: accessPolicies5, +export const byTargetAccountId3 = { + accessPolicies: accessPolicies7, } -export const users2 = { - byTargetAccountId: byTargetAccountId2, +export const users3 = { + byTargetAccountId: byTargetAccountId3, } -export const get49 = oc +export const get55 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2736,7 +2958,7 @@ export const get49 = oc .input(z.object({ params: zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistPath })) .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse) -export const put11 = oc +export const put13 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -2752,12 +2974,12 @@ export const put11 = oc ) .output(zPutWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistResponse) -export const whitelist2 = { - get: get49, - put: put11, +export const whitelist3 = { + get: get55, + put: put13, } -export const get50 = oc +export const get56 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2768,24 +2990,24 @@ export const get50 = oc .input(z.object({ params: zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistConfigPath })) .output(zGetWorkspacesCurrentRbacDatasetsByDatasetIdWhitelistConfigResponse) -export const whitelistConfig2 = { - get: get50, +export const whitelistConfig3 = { + get: get56, } export const byDatasetId = { - accessPolicies: accessPolicies4, - accessPolicy: accessPolicy2, - userAccessPolicies: userAccessPolicies2, - users: users2, - whitelist: whitelist2, - whitelistConfig: whitelistConfig2, + accessPolicies: accessPolicies6, + accessPolicy: accessPolicy3, + userAccessPolicies: userAccessPolicies3, + users: users3, + whitelist: whitelist3, + whitelistConfig: whitelistConfig3, } export const datasets = { byDatasetId, } -export const get51 = oc +export const get57 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2796,7 +3018,7 @@ export const get51 = oc .input(z.object({ params: zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesPath })) .output(zGetWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse) -export const put12 = oc +export const put14 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -2813,8 +3035,8 @@ export const put12 = oc .output(zPutWorkspacesCurrentRbacMembersByMemberIdRbacRolesResponse) export const rbacRoles = { - get: get51, - put: put12, + get: get57, + put: put14, } export const byMemberId2 = { @@ -2825,7 +3047,7 @@ export const members2 = { byMemberId: byMemberId2, } -export const get52 = oc +export const get58 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2836,10 +3058,24 @@ export const get52 = oc .output(zGetWorkspacesCurrentRbacMyPermissionsResponse) export const myPermissions = { - get: get52, + get: get58, } -export const get53 = oc +export const get59 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacRolePermissionsCatalogAgent', + path: '/workspaces/current/rbac/role-permissions/catalog/agent', + tags: ['console'], + }) + .output(zGetWorkspacesCurrentRbacRolePermissionsCatalogAgentResponse) + +export const agent = { + get: get59, +} + +export const get60 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2850,10 +3086,10 @@ export const get53 = oc .output(zGetWorkspacesCurrentRbacRolePermissionsCatalogAppResponse) export const app = { - get: get53, + get: get60, } -export const get54 = oc +export const get61 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2864,10 +3100,10 @@ export const get54 = oc .output(zGetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponse) export const dataset = { - get: get54, + get: get61, } -export const get55 = oc +export const get62 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2878,7 +3114,8 @@ export const get55 = oc .output(zGetWorkspacesCurrentRbacRolePermissionsCatalogResponse) export const catalog = { - get: get55, + get: get62, + agent, app, dataset, } @@ -2893,7 +3130,6 @@ export const post46 = oc method: 'POST', operationId: 'postWorkspacesCurrentRbacRolesByRoleIdCopy', path: '/workspaces/current/rbac/roles/{role_id}/copy', - successStatus: 201, tags: ['console'], }) .input(z.object({ params: zPostWorkspacesCurrentRbacRolesByRoleIdCopyPath })) @@ -2903,7 +3139,7 @@ export const copy2 = { post: post46, } -export const get56 = oc +export const get63 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2915,10 +3151,10 @@ export const get56 = oc .output(zGetWorkspacesCurrentRbacRolesByRoleIdMembersResponse) export const members3 = { - get: get56, + get: get63, } -export const delete12 = oc +export const delete13 = oc .route({ inputStructure: 'detailed', method: 'DELETE', @@ -2929,7 +3165,7 @@ export const delete12 = oc .input(z.object({ params: zDeleteWorkspacesCurrentRbacRolesByRoleIdPath })) .output(zDeleteWorkspacesCurrentRbacRolesByRoleIdResponse) -export const get57 = oc +export const get64 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2940,7 +3176,7 @@ export const get57 = oc .input(z.object({ params: zGetWorkspacesCurrentRbacRolesByRoleIdPath })) .output(zGetWorkspacesCurrentRbacRolesByRoleIdResponse) -export const put13 = oc +export const put15 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -2952,14 +3188,14 @@ export const put13 = oc .output(zPutWorkspacesCurrentRbacRolesByRoleIdResponse) export const byRoleId = { - delete: delete12, - get: get57, - put: put13, + delete: delete13, + get: get64, + put: put15, copy: copy2, members: members3, } -export const get58 = oc +export const get65 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -2975,18 +3211,104 @@ export const post47 = oc method: 'POST', operationId: 'postWorkspacesCurrentRbacRoles', path: '/workspaces/current/rbac/roles', - successStatus: 201, tags: ['console'], }) .output(zPostWorkspacesCurrentRbacRolesResponse) export const roles = { - get: get58, + get: get65, post: post47, byRoleId, } -export const put14 = oc +export const put16 = oc + .route({ + inputStructure: 'detailed', + method: 'PUT', + operationId: 'putWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindings', + path: '/workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/bindings', + tags: ['console'], + }) + .input( + z.object({ + body: zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsBody, + params: zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsPath, + }), + ) + .output(zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsResponse) + +export const bindings = { + put: put16, +} + +export const get66 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindings', + path: '/workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/member-bindings', + tags: ['console'], + }) + .input( + z.object({ + params: zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsPath, + }), + ) + .output(zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsResponse) + +export const memberBindings4 = { + get: get66, +} + +export const get67 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindings', + path: '/workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/role-bindings', + tags: ['console'], + }) + .input( + z.object({ + params: zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsPath, + }), + ) + .output(zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsResponse) + +export const roleBindings4 = { + get: get67, +} + +export const byPolicyId5 = { + bindings, + memberBindings: memberBindings4, + roleBindings: roleBindings4, +} + +export const accessPolicies8 = { + byPolicyId: byPolicyId5, +} + +export const get68 = oc + .route({ + inputStructure: 'detailed', + method: 'GET', + operationId: 'getWorkspacesCurrentRbacWorkspaceAgentsAccessPolicy', + path: '/workspaces/current/rbac/workspace/agents/access-policy', + tags: ['console'], + }) + .output(zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyResponse) + +export const accessPolicy4 = { + get: get68, +} + +export const agents3 = { + accessPolicies: accessPolicies8, + accessPolicy: accessPolicy4, +} + +export const put17 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -3002,11 +3324,11 @@ export const put14 = oc ) .output(zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsResponse) -export const bindings = { - put: put14, +export const bindings2 = { + put: put17, } -export const get59 = oc +export const get69 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3021,11 +3343,11 @@ export const get59 = oc ) .output(zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdMemberBindingsResponse) -export const memberBindings3 = { - get: get59, +export const memberBindings5 = { + get: get69, } -export const get60 = oc +export const get70 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3040,21 +3362,21 @@ export const get60 = oc ) .output(zGetWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdRoleBindingsResponse) -export const roleBindings3 = { - get: get60, +export const roleBindings5 = { + get: get70, } -export const byPolicyId4 = { - bindings, - memberBindings: memberBindings3, - roleBindings: roleBindings3, +export const byPolicyId6 = { + bindings: bindings2, + memberBindings: memberBindings5, + roleBindings: roleBindings5, } -export const accessPolicies6 = { - byPolicyId: byPolicyId4, +export const accessPolicies9 = { + byPolicyId: byPolicyId6, } -export const get61 = oc +export const get71 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3064,16 +3386,16 @@ export const get61 = oc }) .output(zGetWorkspacesCurrentRbacWorkspaceAppsAccessPolicyResponse) -export const accessPolicy3 = { - get: get61, +export const accessPolicy5 = { + get: get71, } export const apps2 = { - accessPolicies: accessPolicies6, - accessPolicy: accessPolicy3, + accessPolicies: accessPolicies9, + accessPolicy: accessPolicy5, } -export const put15 = oc +export const put18 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -3089,11 +3411,11 @@ export const put15 = oc ) .output(zPutWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdBindingsResponse) -export const bindings2 = { - put: put15, +export const bindings3 = { + put: put18, } -export const get62 = oc +export const get72 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3108,11 +3430,11 @@ export const get62 = oc ) .output(zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdMemberBindingsResponse) -export const memberBindings4 = { - get: get62, +export const memberBindings6 = { + get: get72, } -export const get63 = oc +export const get73 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3127,21 +3449,21 @@ export const get63 = oc ) .output(zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPoliciesByPolicyIdRoleBindingsResponse) -export const roleBindings4 = { - get: get63, +export const roleBindings6 = { + get: get73, } -export const byPolicyId5 = { - bindings: bindings2, - memberBindings: memberBindings4, - roleBindings: roleBindings4, +export const byPolicyId7 = { + bindings: bindings3, + memberBindings: memberBindings6, + roleBindings: roleBindings6, } -export const accessPolicies7 = { - byPolicyId: byPolicyId5, +export const accessPolicies10 = { + byPolicyId: byPolicyId7, } -export const get64 = oc +export const get74 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3151,16 +3473,17 @@ export const get64 = oc }) .output(zGetWorkspacesCurrentRbacWorkspaceDatasetsAccessPolicyResponse) -export const accessPolicy4 = { - get: get64, +export const accessPolicy6 = { + get: get74, } export const datasets2 = { - accessPolicies: accessPolicies7, - accessPolicy: accessPolicy4, + accessPolicies: accessPolicies10, + accessPolicy: accessPolicy6, } export const workspace = { + agents: agents3, apps: apps2, datasets: datasets2, } @@ -3168,6 +3491,7 @@ export const workspace = { export const rbac = { accessPolicies, accessPolicyBindings, + agents: agents2, apps, datasets, members: members2, @@ -3216,7 +3540,7 @@ export const import_ = { post: post49, } -export const get65 = oc +export const get75 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3227,7 +3551,7 @@ export const get65 = oc .output(zGetWorkspacesCurrentSkillsTagsResponse) export const tags = { - get: get65, + get: get75, } export const post50 = oc @@ -3270,7 +3594,7 @@ export const duplicate = { post: post51, } -export const get66 = oc +export const get76 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3282,7 +3606,7 @@ export const get66 = oc .output(zGetWorkspacesCurrentSkillsBySkillIdExportResponse) export const export2 = { - get: get66, + get: get76, } export const post52 = oc @@ -3305,7 +3629,7 @@ export const check = { post: post52, } -export const get67 = oc +export const get77 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3322,10 +3646,10 @@ export const get67 = oc .output(zGetWorkspacesCurrentSkillsBySkillIdFilesContentResponse) export const content = { - get: get67, + get: get77, } -export const get68 = oc +export const get78 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3342,7 +3666,7 @@ export const get68 = oc .output(zGetWorkspacesCurrentSkillsBySkillIdFilesPreviewResponse) export const preview = { - get: get68, + get: get78, } export const patch5 = oc @@ -3361,7 +3685,7 @@ export const patch5 = oc ) .output(zPatchWorkspacesCurrentSkillsBySkillIdFilesResponse) -export const put16 = oc +export const put19 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -3379,7 +3703,7 @@ export const put16 = oc export const files2 = { patch: patch5, - put: put16, + put: put19, check, content, preview, @@ -3405,7 +3729,7 @@ export const publish = { post: post53, } -export const get69 = oc +export const get79 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3417,7 +3741,7 @@ export const get69 = oc .output(zGetWorkspacesCurrentSkillsBySkillIdReferencesResponse) export const references = { - get: get69, + get: get79, } export const post54 = oc @@ -3440,7 +3764,7 @@ export const restore = { post: post54, } -export const delete13 = oc +export const delete14 = oc .route({ inputStructure: 'detailed', method: 'DELETE', @@ -3451,7 +3775,7 @@ export const delete13 = oc .input(z.object({ params: zDeleteWorkspacesCurrentSkillsBySkillIdVersionsByVersionIdPath })) .output(zDeleteWorkspacesCurrentSkillsBySkillIdVersionsByVersionIdResponse) -export const get70 = oc +export const get80 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3479,12 +3803,12 @@ export const patch6 = oc .output(zPatchWorkspacesCurrentSkillsBySkillIdVersionsByVersionIdResponse) export const byVersionId = { - delete: delete13, - get: get70, + delete: delete14, + get: get80, patch: patch6, } -export const get71 = oc +export const get81 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3496,11 +3820,11 @@ export const get71 = oc .output(zGetWorkspacesCurrentSkillsBySkillIdVersionsResponse) export const versions = { - get: get71, + get: get81, byVersionId, } -export const delete14 = oc +export const delete15 = oc .route({ inputStructure: 'detailed', method: 'DELETE', @@ -3516,7 +3840,7 @@ export const delete14 = oc ) .output(zDeleteWorkspacesCurrentSkillsBySkillIdResponse) -export const get72 = oc +export const get82 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3544,8 +3868,8 @@ export const patch7 = oc .output(zPatchWorkspacesCurrentSkillsBySkillIdResponse) export const bySkillId = { - delete: delete14, - get: get72, + delete: delete15, + get: get82, patch: patch7, assist, duplicate, @@ -3557,7 +3881,7 @@ export const bySkillId = { versions, } -export const get73 = oc +export const get83 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3581,7 +3905,7 @@ export const post55 = oc .output(zPostWorkspacesCurrentSkillsResponse) export const skills2 = { - get: get73, + get: get83, post: post55, files, import: import_, @@ -3589,7 +3913,7 @@ export const skills2 = { bySkillId, } -export const get74 = oc +export const get84 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3600,10 +3924,10 @@ export const get74 = oc .output(zGetWorkspacesCurrentSummaryResponse) export const summary2 = { - get: get74, + get: get84, } -export const get75 = oc +export const get85 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3614,7 +3938,7 @@ export const get75 = oc .output(zGetWorkspacesCurrentToolLabelsResponse) export const toolLabels = { - get: get75, + get: get85, } export const post56 = oc @@ -3643,11 +3967,11 @@ export const post57 = oc .input(z.object({ body: zPostWorkspacesCurrentToolProviderApiDeleteBody })) .output(zPostWorkspacesCurrentToolProviderApiDeleteResponse) -export const delete15 = { +export const delete16 = { post: post57, } -export const get76 = oc +export const get86 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3658,11 +3982,11 @@ export const get76 = oc .input(z.object({ query: zGetWorkspacesCurrentToolProviderApiGetQuery })) .output(zGetWorkspacesCurrentToolProviderApiGetResponse) -export const get77 = { - get: get76, +export const get87 = { + get: get86, } -export const get78 = oc +export const get88 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3674,7 +3998,7 @@ export const get78 = oc .output(zGetWorkspacesCurrentToolProviderApiRemoteResponse) export const remote = { - get: get78, + get: get88, } export const post58 = oc @@ -3711,7 +4035,7 @@ export const test = { pre, } -export const get79 = oc +export const get89 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3723,7 +4047,7 @@ export const get79 = oc .output(zGetWorkspacesCurrentToolProviderApiToolsResponse) export const tools = { - get: get79, + get: get89, } export const post60 = oc @@ -3743,8 +4067,8 @@ export const update2 = { export const api = { add, - delete: delete15, - get: get77, + delete: delete16, + get: get87, remote, schema, test, @@ -3772,7 +4096,7 @@ export const add2 = { post: post61, } -export const get80 = oc +export const get90 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3789,10 +4113,10 @@ export const get80 = oc .output(zGetWorkspacesCurrentToolProviderBuiltinByProviderCredentialInfoResponse) export const info = { - get: get80, + get: get90, } -export const get81 = oc +export const get91 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3812,7 +4136,7 @@ export const get81 = oc ) export const byCredentialType = { - get: get81, + get: get91, } export const schema2 = { @@ -3824,7 +4148,7 @@ export const credential = { schema: schema2, } -export const get82 = oc +export const get92 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3841,7 +4165,7 @@ export const get82 = oc .output(zGetWorkspacesCurrentToolProviderBuiltinByProviderCredentialsResponse) export const credentials3 = { - get: get82, + get: get92, } export const post62 = oc @@ -3880,11 +4204,11 @@ export const post63 = oc ) .output(zPostWorkspacesCurrentToolProviderBuiltinByProviderDeleteResponse) -export const delete16 = { +export const delete17 = { post: post63, } -export const get83 = oc +export const get93 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3896,10 +4220,10 @@ export const get83 = oc .output(zGetWorkspacesCurrentToolProviderBuiltinByProviderIconResponse) export const icon2 = { - get: get83, + get: get93, } -export const get84 = oc +export const get94 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3911,10 +4235,10 @@ export const get84 = oc .output(zGetWorkspacesCurrentToolProviderBuiltinByProviderInfoResponse) export const info2 = { - get: get84, + get: get94, } -export const get85 = oc +export const get95 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3928,10 +4252,10 @@ export const get85 = oc .output(zGetWorkspacesCurrentToolProviderBuiltinByProviderOauthClientSchemaResponse) export const clientSchema = { - get: get85, + get: get95, } -export const delete17 = oc +export const delete18 = oc .route({ inputStructure: 'detailed', method: 'DELETE', @@ -3946,7 +4270,7 @@ export const delete17 = oc ) .output(zDeleteWorkspacesCurrentToolProviderBuiltinByProviderOauthCustomClientResponse) -export const get86 = oc +export const get96 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3976,8 +4300,8 @@ export const post64 = oc .output(zPostWorkspacesCurrentToolProviderBuiltinByProviderOauthCustomClientResponse) export const customClient = { - delete: delete17, - get: get86, + delete: delete18, + get: get96, post: post64, } @@ -3986,7 +4310,7 @@ export const oauth = { customClient, } -export const get87 = oc +export const get97 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -3998,7 +4322,7 @@ export const get87 = oc .output(zGetWorkspacesCurrentToolProviderBuiltinByProviderToolsResponse) export const tools2 = { - get: get87, + get: get97, } export const post65 = oc @@ -4026,7 +4350,7 @@ export const byProvider2 = { credential, credentials: credentials3, defaultCredential, - delete: delete16, + delete: delete17, icon: icon2, info: info2, oauth, @@ -4053,7 +4377,7 @@ export const auth = { post: post66, } -export const get88 = oc +export const get98 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4065,14 +4389,14 @@ export const get88 = oc .output(zGetWorkspacesCurrentToolProviderMcpToolsByProviderIdResponse) export const byProviderId = { - get: get88, + get: get98, } export const tools3 = { byProviderId, } -export const get89 = oc +export const get99 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4084,14 +4408,14 @@ export const get89 = oc .output(zGetWorkspacesCurrentToolProviderMcpUpdateByProviderIdResponse) export const byProviderId2 = { - get: get89, + get: get99, } export const update4 = { byProviderId: byProviderId2, } -export const delete18 = oc +export const delete19 = oc .route({ inputStructure: 'detailed', method: 'DELETE', @@ -4113,7 +4437,7 @@ export const post67 = oc .input(z.object({ body: zPostWorkspacesCurrentToolProviderMcpBody })) .output(zPostWorkspacesCurrentToolProviderMcpResponse) -export const put17 = oc +export const put20 = oc .route({ inputStructure: 'detailed', method: 'PUT', @@ -4125,9 +4449,9 @@ export const put17 = oc .output(zPutWorkspacesCurrentToolProviderMcpResponse) export const mcp = { - delete: delete18, + delete: delete19, post: post67, - put: put17, + put: put20, auth, tools: tools3, update: update4, @@ -4159,11 +4483,11 @@ export const post69 = oc .input(z.object({ body: zPostWorkspacesCurrentToolProviderWorkflowDeleteBody })) .output(zPostWorkspacesCurrentToolProviderWorkflowDeleteResponse) -export const delete19 = { +export const delete20 = { post: post69, } -export const get90 = oc +export const get100 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4174,11 +4498,11 @@ export const get90 = oc .input(z.object({ query: zGetWorkspacesCurrentToolProviderWorkflowGetQuery.optional() })) .output(zGetWorkspacesCurrentToolProviderWorkflowGetResponse) -export const get91 = { - get: get90, +export const get101 = { + get: get100, } -export const get92 = oc +export const get102 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4190,7 +4514,7 @@ export const get92 = oc .output(zGetWorkspacesCurrentToolProviderWorkflowToolsResponse) export const tools4 = { - get: get92, + get: get102, } export const post70 = oc @@ -4210,8 +4534,8 @@ export const update5 = { export const workflow = { create: create2, - delete: delete19, - get: get91, + delete: delete20, + get: get101, tools: tools4, update: update5, } @@ -4223,7 +4547,7 @@ export const toolProvider = { workflow, } -export const get93 = oc +export const get103 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4235,10 +4559,10 @@ export const get93 = oc .output(zGetWorkspacesCurrentToolProvidersResponse) export const toolProviders = { - get: get93, + get: get103, } -export const get94 = oc +export const get104 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4249,10 +4573,10 @@ export const get94 = oc .output(zGetWorkspacesCurrentToolsApiResponse) export const api2 = { - get: get94, + get: get104, } -export const get95 = oc +export const get105 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4263,10 +4587,10 @@ export const get95 = oc .output(zGetWorkspacesCurrentToolsBuiltinResponse) export const builtin2 = { - get: get95, + get: get105, } -export const get96 = oc +export const get106 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4277,10 +4601,10 @@ export const get96 = oc .output(zGetWorkspacesCurrentToolsMcpResponse) export const mcp2 = { - get: get96, + get: get106, } -export const get97 = oc +export const get107 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4291,7 +4615,7 @@ export const get97 = oc .output(zGetWorkspacesCurrentToolsWorkflowResponse) export const workflow2 = { - get: get97, + get: get107, } export const tools5 = { @@ -4301,7 +4625,7 @@ export const tools5 = { workflow: workflow2, } -export const get98 = oc +export const get108 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4313,13 +4637,13 @@ export const get98 = oc .output(zGetWorkspacesCurrentTriggerProviderByProviderIconResponse) export const icon3 = { - get: get98, + get: get108, } /** * Get info for a trigger provider */ -export const get99 = oc +export const get109 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4332,13 +4656,13 @@ export const get99 = oc .output(zGetWorkspacesCurrentTriggerProviderByProviderInfoResponse) export const info3 = { - get: get99, + get: get109, } /** * Remove custom OAuth client configuration */ -export const delete20 = oc +export const delete21 = oc .route({ inputStructure: 'detailed', method: 'DELETE', @@ -4353,7 +4677,7 @@ export const delete20 = oc /** * Get OAuth client configuration for a provider */ -export const get100 = oc +export const get110 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4386,8 +4710,8 @@ export const post71 = oc .output(zPostWorkspacesCurrentTriggerProviderByProviderOauthClientResponse) export const client = { - delete: delete20, - get: get100, + delete: delete21, + get: get110, post: post71, } @@ -4454,7 +4778,7 @@ export const create3 = { /** * Get the request logs for a subscription instance for a trigger provider */ -export const get101 = oc +export const get111 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4475,7 +4799,7 @@ export const get101 = oc ) export const bySubscriptionBuilderId2 = { - get: get101, + get: get111, } export const logs = { @@ -4549,7 +4873,7 @@ export const verifyAndUpdate = { /** * Get a subscription instance for a trigger provider */ -export const get102 = oc +export const get112 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4570,7 +4894,7 @@ export const get102 = oc ) export const bySubscriptionBuilderId5 = { - get: get102, + get: get112, } export const builder = { @@ -4585,7 +4909,7 @@ export const builder = { /** * List all trigger subscriptions for the current tenant's provider */ -export const get103 = oc +export const get113 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4598,13 +4922,13 @@ export const get103 = oc .output(zGetWorkspacesCurrentTriggerProviderByProviderSubscriptionsListResponse) export const list4 = { - get: get103, + get: get113, } /** * Initiate OAuth authorization flow for a trigger provider */ -export const get104 = oc +export const get114 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4621,7 +4945,7 @@ export const get104 = oc .output(zGetWorkspacesCurrentTriggerProviderByProviderSubscriptionsOauthAuthorizeResponse) export const authorize = { - get: get104, + get: get114, } export const oauth3 = { @@ -4693,7 +5017,7 @@ export const post77 = oc ) .output(zPostWorkspacesCurrentTriggerProviderBySubscriptionIdSubscriptionsDeleteResponse) -export const delete21 = { +export const delete22 = { post: post77, } @@ -4722,7 +5046,7 @@ export const update7 = { } export const subscriptions2 = { - delete: delete21, + delete: delete22, update: update7, } @@ -4738,7 +5062,7 @@ export const triggerProvider = { /** * List all trigger providers for the current tenant */ -export const get105 = oc +export const get115 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4750,7 +5074,7 @@ export const get105 = oc .output(zGetWorkspacesCurrentTriggersResponse) export const triggers = { - get: get105, + get: get115, } export const current = { @@ -4797,7 +5121,7 @@ export const webappLogo = { upload: upload3, } -export const get106 = oc +export const get116 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4819,7 +5143,7 @@ export const post80 = oc .output(zPostWorkspacesCustomConfigResponse) export const customConfig = { - get: get106, + get: get116, post: post80, webappLogo, } @@ -4854,7 +5178,7 @@ export const switch3 = { post: post82, } -export const get107 = oc +export const get117 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4866,7 +5190,7 @@ export const get107 = oc .output(zGetWorkspacesByTenantIdModelProvidersByProviderByIconTypeByLangResponse) export const byLang = { - get: get107, + get: get117, } export const byIconType = { @@ -4885,7 +5209,7 @@ export const byTenantId = { modelProviders: modelProviders2, } -export const get108 = oc +export const get118 = oc .route({ inputStructure: 'detailed', method: 'GET', @@ -4896,7 +5220,7 @@ export const get108 = oc .output(zGetWorkspacesResponse) export const workspaces = { - get: get108, + get: get118, current, customConfig, info: info4, diff --git a/packages/contracts/generated/api/console/workspaces/types.gen.ts b/packages/contracts/generated/api/console/workspaces/types.gen.ts index 58b995b4c08..4b3373e7bf1 100644 --- a/packages/contracts/generated/api/console/workspaces/types.gen.ts +++ b/packages/contracts/generated/api/console/workspaces/types.gen.ts @@ -527,30 +527,6 @@ export type PluginCategoryListResponse = { plugins: Array } -export type AccessPolicyList = { - data?: Array - pagination?: Pagination | null -} - -export type AccessPolicy = { - category?: string - created_at?: number - description?: string - id: string - is_builtin?: boolean - name: string - permission_keys?: Array - policy_key?: string - resource_type: string - tenant_id?: string - updated_at?: number -} - -export type AccessPolicyBindingState = { - binding_id: string - is_locked?: boolean -} - export type DeleteMemberBindingsRequest = { account_ids?: Array } @@ -563,8 +539,8 @@ export type RoleBindingsResponse = { data?: Array } -export type AppAccessMatrix = { - app_id?: string +export type AgentAccessMatrix = { + agent_id?: string items?: Array } @@ -594,6 +570,11 @@ export type ResourceWhitelistConfig = { automatic_include_workspace_members: boolean } +export type AppAccessMatrix = { + app_id?: string + items?: Array +} + export type DatasetAccessMatrix = { dataset_id?: string items?: Array @@ -609,6 +590,7 @@ export type ReplaceMemberRolesRequest = { } export type MyPermissionsResponse = { + agent?: ResourcePermissionSnapshot app?: ResourcePermissionSnapshot dataset?: ResourcePermissionSnapshot workspace?: WorkspacePermissionSnapshot @@ -618,23 +600,6 @@ export type PermissionCatalogResponse = { groups?: Array } -export type RbacRoleList = { - data?: Array - pagination?: Pagination | null -} - -export type RbacRole = { - category?: string - description?: string - id: string - is_builtin?: boolean - name: string - permission_keys?: Array - role_tag?: string - tenant_id?: string | null - type: string -} - export type MembersInRoleList = { data?: Array pagination?: Pagination | null @@ -1690,13 +1655,6 @@ export type PluginCategoryInstalledPluginResponse = { version: string } -export type Pagination = { - current_page?: number - per_page?: number - total_count?: number - total_pages?: number -} - export type AccessPolicyMemberBinding = { access_policy_id: string account_id: string @@ -1725,6 +1683,39 @@ export type ResourceUserAccessPolicies = { roles?: Array } +export type Pagination = { + current_page?: number + per_page?: number + total_count?: number + total_pages?: number +} + +export type AccessPolicy = { + category?: string + created_at?: number + description?: string + id: string + is_builtin?: boolean + name: string + permission_keys?: Array + policy_key?: string + resource_type: string + tenant_id?: string + updated_at?: number +} + +export type RbacRole = { + category?: string + description?: string + id: string + is_builtin?: boolean + name: string + permission_keys?: Array + role_tag?: string + tenant_id?: string | null + type: string +} + export type ResourcePermissionSnapshot = { default_permission_keys?: Array overrides?: Array @@ -4372,7 +4363,9 @@ export type GetWorkspacesCurrentRbacAccessPoliciesData = { } export type GetWorkspacesCurrentRbacAccessPoliciesResponses = { - 200: AccessPolicyList + 200: { + [key: string]: unknown + } } export type GetWorkspacesCurrentRbacAccessPoliciesResponse = @@ -4386,7 +4379,9 @@ export type PostWorkspacesCurrentRbacAccessPoliciesData = { } export type PostWorkspacesCurrentRbacAccessPoliciesResponses = { - 201: AccessPolicy + 200: { + [key: string]: unknown + } } export type PostWorkspacesCurrentRbacAccessPoliciesResponse = @@ -4402,7 +4397,9 @@ export type DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = { } export type DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses = { - 200: AccessPolicy + 200: { + [key: string]: unknown + } } export type DeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = @@ -4418,7 +4415,9 @@ export type GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = { } export type GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses = { - 200: AccessPolicy + 200: { + [key: string]: unknown + } } export type GetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = @@ -4434,7 +4433,9 @@ export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdData = { } export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponses = { - 200: AccessPolicy + 200: { + [key: string]: unknown + } } export type PutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = @@ -4450,7 +4451,9 @@ export type PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyData = { } export type PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponses = { - 201: AccessPolicy + 200: { + [key: string]: unknown + } } export type PostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse = @@ -4466,7 +4469,9 @@ export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockData = { } export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponses = { - 200: AccessPolicyBindingState + 200: { + [key: string]: unknown + } } export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse = @@ -4482,12 +4487,171 @@ export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockData = } export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponses = { - 200: AccessPolicyBindingState + 200: { + [key: string]: unknown + } } export type PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse = PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponses[keyof PutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponses] +export type DeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsData = { + body: DeleteMemberBindingsRequest + path: { + agent_id: string + policy_id: string + } + query?: never + url: '/workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/member-bindings' +} + +export type DeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponses = + { + 200: MemberBindingsResponse + } + +export type DeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse = + DeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponses[keyof DeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponses] + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsData = { + body?: never + path: { + agent_id: string + policy_id: string + } + query?: never + url: '/workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/member-bindings' +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponses = + { + 200: MemberBindingsResponse + } + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse = + GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponses[keyof GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponses] + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsData = { + body?: never + path: { + agent_id: string + policy_id: string + } + query?: never + url: '/workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/role-bindings' +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsResponses = { + 200: RoleBindingsResponse +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsResponse = + GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsResponses[keyof GetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsResponses] + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyData = { + body?: never + path: { + agent_id: string + } + query?: { + language?: 'en' | 'ja' | 'zh' + } + url: '/workspaces/current/rbac/agents/{agent_id}/access-policy' +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyResponses = { + 200: AgentAccessMatrix +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyResponse = + GetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyResponses[keyof GetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyResponses] + +export type GetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesData = { + body?: never + path: { + agent_id: string + } + query?: { + language?: 'en' | 'ja' | 'zh' + limit?: number + page?: number + reverse?: boolean + } + url: '/workspaces/current/rbac/agents/{agent_id}/user-access-policies' +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesResponses = { + 200: ResourceUserAccessPoliciesResponse +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesResponse = + GetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesResponses[keyof GetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesResponses] + +export type PutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesData = { + body: ReplaceUserAccessPolicies + path: { + agent_id: string + target_account_id: string + } + query?: never + url: '/workspaces/current/rbac/agents/{agent_id}/users/{target_account_id}/access-policies' +} + +export type PutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesResponses = { + 200: ReplaceUserAccessPoliciesResponse +} + +export type PutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesResponse = + PutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesResponses[keyof PutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesResponses] + +export type GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistData = { + body?: never + path: { + agent_id: string + } + query?: never + url: '/workspaces/current/rbac/agents/{agent_id}/whitelist' +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponses = { + 200: ResourceWhitelist +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse = + GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponses[keyof GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponses] + +export type PutWorkspacesCurrentRbacAgentsByAgentIdWhitelistData = { + body: ResourceAccessScopeRequest + path: { + agent_id: string + } + query?: never + url: '/workspaces/current/rbac/agents/{agent_id}/whitelist' +} + +export type PutWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponses = { + 200: ResourceWhitelist +} + +export type PutWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse = + PutWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponses[keyof PutWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponses] + +export type GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigData = { + body?: never + path: { + agent_id: string + } + query?: never + url: '/workspaces/current/rbac/agents/{agent_id}/whitelist_config' +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigResponses = { + 200: ResourceWhitelistConfig +} + +export type GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigResponse = + GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigResponses[keyof GetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigResponses] + export type DeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsData = { body: DeleteMemberBindingsRequest path: { @@ -4865,6 +5029,20 @@ export type GetWorkspacesCurrentRbacRolePermissionsCatalogResponses = { export type GetWorkspacesCurrentRbacRolePermissionsCatalogResponse = GetWorkspacesCurrentRbacRolePermissionsCatalogResponses[keyof GetWorkspacesCurrentRbacRolePermissionsCatalogResponses] +export type GetWorkspacesCurrentRbacRolePermissionsCatalogAgentData = { + body?: never + path?: never + query?: never + url: '/workspaces/current/rbac/role-permissions/catalog/agent' +} + +export type GetWorkspacesCurrentRbacRolePermissionsCatalogAgentResponses = { + 200: PermissionCatalogResponse +} + +export type GetWorkspacesCurrentRbacRolePermissionsCatalogAgentResponse = + GetWorkspacesCurrentRbacRolePermissionsCatalogAgentResponses[keyof GetWorkspacesCurrentRbacRolePermissionsCatalogAgentResponses] + export type GetWorkspacesCurrentRbacRolePermissionsCatalogAppData = { body?: never path?: never @@ -4901,7 +5079,9 @@ export type GetWorkspacesCurrentRbacRolesData = { } export type GetWorkspacesCurrentRbacRolesResponses = { - 200: RbacRoleList + 200: { + [key: string]: unknown + } } export type GetWorkspacesCurrentRbacRolesResponse = @@ -4915,7 +5095,9 @@ export type PostWorkspacesCurrentRbacRolesData = { } export type PostWorkspacesCurrentRbacRolesResponses = { - 201: RbacRole + 200: { + [key: string]: unknown + } } export type PostWorkspacesCurrentRbacRolesResponse = @@ -4931,7 +5113,9 @@ export type DeleteWorkspacesCurrentRbacRolesByRoleIdData = { } export type DeleteWorkspacesCurrentRbacRolesByRoleIdResponses = { - 200: RbacRole + 200: { + [key: string]: unknown + } } export type DeleteWorkspacesCurrentRbacRolesByRoleIdResponse = @@ -4947,7 +5131,9 @@ export type GetWorkspacesCurrentRbacRolesByRoleIdData = { } export type GetWorkspacesCurrentRbacRolesByRoleIdResponses = { - 200: RbacRole + 200: { + [key: string]: unknown + } } export type GetWorkspacesCurrentRbacRolesByRoleIdResponse = @@ -4963,7 +5149,9 @@ export type PutWorkspacesCurrentRbacRolesByRoleIdData = { } export type PutWorkspacesCurrentRbacRolesByRoleIdResponses = { - 200: RbacRole + 200: { + [key: string]: unknown + } } export type PutWorkspacesCurrentRbacRolesByRoleIdResponse = @@ -4979,7 +5167,9 @@ export type PostWorkspacesCurrentRbacRolesByRoleIdCopyData = { } export type PostWorkspacesCurrentRbacRolesByRoleIdCopyResponses = { - 201: RbacRole + 200: { + [key: string]: unknown + } } export type PostWorkspacesCurrentRbacRolesByRoleIdCopyResponse = @@ -5001,6 +5191,69 @@ export type GetWorkspacesCurrentRbacRolesByRoleIdMembersResponses = { export type GetWorkspacesCurrentRbacRolesByRoleIdMembersResponse = GetWorkspacesCurrentRbacRolesByRoleIdMembersResponses[keyof GetWorkspacesCurrentRbacRolesByRoleIdMembersResponses] +export type PutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsData = { + body: ReplaceBindingsRequest + path: { + policy_id: string + } + query?: never + url: '/workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/bindings' +} + +export type PutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsResponses = { + 200: AccessMatrixItem +} + +export type PutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsResponse = + PutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsResponses[keyof PutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsResponses] + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsData = { + body?: never + path: { + policy_id: string + } + query?: never + url: '/workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/member-bindings' +} + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsResponses = + { + 200: MemberBindingsResponse + } + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsResponse = + GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsResponses[keyof GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsResponses] + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsData = { + body?: never + path: { + policy_id: string + } + query?: never + url: '/workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/role-bindings' +} + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsResponses = { + 200: RoleBindingsResponse +} + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsResponse = + GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsResponses[keyof GetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsResponses] + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyData = { + body?: never + path?: never + query?: never + url: '/workspaces/current/rbac/workspace/agents/access-policy' +} + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyResponses = { + 200: WorkspaceAccessMatrix +} + +export type GetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyResponse = + GetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyResponses[keyof GetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyResponses] + export type PutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsData = { body: ReplaceBindingsRequest path: { diff --git a/packages/contracts/generated/api/console/workspaces/zod.gen.ts b/packages/contracts/generated/api/console/workspaces/zod.gen.ts index fa7e8ee27c4..efec8abd342 100644 --- a/packages/contracts/generated/api/console/workspaces/zod.gen.ts +++ b/packages/contracts/generated/api/console/workspaces/zod.gen.ts @@ -373,31 +373,6 @@ export const zParserGithubUpload = z.object({ version: z.string(), }) -/** - * AccessPolicy - */ -export const zAccessPolicy = z.object({ - category: z.string().optional().default(''), - created_at: z.int().optional().default(0), - description: z.string().optional().default(''), - id: z.string(), - is_builtin: z.boolean().optional().default(false), - name: z.string(), - permission_keys: z.array(z.string()).optional(), - policy_key: z.string().optional().default(''), - resource_type: z.string(), - tenant_id: z.string().optional().default(''), - updated_at: z.int().optional().default(0), -}) - -/** - * AccessPolicyBindingState - */ -export const zAccessPolicyBindingState = z.object({ - binding_id: z.string(), - is_locked: z.boolean().optional().default(false), -}) - /** * _DeleteMemberBindingsRequest */ @@ -413,13 +388,6 @@ 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 */ @@ -448,29 +416,6 @@ export const zReplaceMemberRolesRequest = z.object({ role_ids: z.array(z.string()).optional().default([]), }) -/** - * RBACRole - */ -export const zRbacRole = z.object({ - category: z.string().optional().default(''), - description: z.string().optional().default(''), - id: z.string(), - is_builtin: z.boolean().optional().default(false), - name: z.string(), - permission_keys: z.array(z.string()).optional(), - role_tag: z.string().optional().default(''), - tenant_id: z.string().nullish(), - type: z.string(), -}) - -/** - * MemberRolesResponse - */ -export const zMemberRolesResponse = z.object({ - account_id: z.string(), - roles: z.array(zRbacRole).optional(), -}) - /** * _ReplaceBindingsRequest */ @@ -1256,32 +1201,6 @@ export const zPluginPermissionResponse = z.object({ install_permission: zTenantPluginInstallPermission, }) -/** - * Pagination - */ -export const zPagination = z.object({ - current_page: z.int().optional().default(0), - per_page: z.int().optional().default(0), - total_count: z.int().optional().default(0), - total_pages: z.int().optional().default(0), -}) - -/** - * _AccessPolicyList - */ -export const zAccessPolicyList = z.object({ - data: z.array(zAccessPolicy).optional(), - pagination: zPagination.nullish(), -}) - -/** - * _RBACRoleList - */ -export const zRbacRoleList = z.object({ - data: z.array(zRbacRole).optional(), - pagination: zPagination.nullish(), -}) - /** * AccessPolicyMemberBinding */ @@ -1324,6 +1243,63 @@ export const zRoleBindingsResponse = z.object({ data: z.array(zAccessPolicyRoleBinding).optional(), }) +/** + * Pagination + */ +export const zPagination = z.object({ + current_page: z.int().optional().default(0), + per_page: z.int().optional().default(0), + total_count: z.int().optional().default(0), + total_pages: z.int().optional().default(0), +}) + +/** + * 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 + */ +export const zRbacRole = z.object({ + category: z.string().optional().default(''), + description: z.string().optional().default(''), + id: z.string(), + is_builtin: z.boolean().optional().default(false), + name: z.string(), + permission_keys: z.array(z.string()).optional(), + role_tag: z.string().optional().default(''), + tenant_id: z.string().nullish(), + type: z.string(), +}) + +/** + * MemberRolesResponse + */ +export const zMemberRolesResponse = z.object({ + account_id: z.string(), + roles: z.array(zRbacRole).optional(), +}) + /** * WorkspacePermissionSnapshot */ @@ -1379,6 +1355,14 @@ export const zAccessMatrixItem = z.object({ roles: z.array(zAccessPolicyRole).optional(), }) +/** + * AgentAccessMatrix + */ +export const zAgentAccessMatrix = z.object({ + agent_id: z.string().optional().default(''), + items: z.array(zAccessMatrixItem).optional(), +}) + /** * AppAccessMatrix */ @@ -2553,6 +2537,7 @@ export const zResourcePermissionSnapshot = z.object({ * MyPermissionsResponse */ export const zMyPermissionsResponse = z.object({ + agent: zResourcePermissionSnapshot.optional(), app: zResourcePermissionSnapshot.optional(), dataset: zResourcePermissionSnapshot.optional(), workspace: zWorkspacePermissionSnapshot.optional(), @@ -4843,12 +4828,12 @@ export const zGetWorkspacesCurrentPluginByCategoryListResponse = zPluginCategory /** * Success */ -export const zGetWorkspacesCurrentRbacAccessPoliciesResponse = zAccessPolicyList +export const zGetWorkspacesCurrentRbacAccessPoliciesResponse = z.record(z.string(), z.unknown()) /** - * Policy created + * Success */ -export const zPostWorkspacesCurrentRbacAccessPoliciesResponse = zAccessPolicy +export const zPostWorkspacesCurrentRbacAccessPoliciesResponse = z.record(z.string(), z.unknown()) export const zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({ policy_id: z.uuid(), @@ -4857,7 +4842,10 @@ export const zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object /** * Success */ -export const zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = zAccessPolicy +export const zDeleteWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = z.record( + z.string(), + z.unknown(), +) export const zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({ policy_id: z.uuid(), @@ -4866,7 +4854,10 @@ export const zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({ /** * Success */ -export const zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = zAccessPolicy +export const zGetWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = z.record( + z.string(), + z.unknown(), +) export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({ policy_id: z.uuid(), @@ -4875,16 +4866,22 @@ export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdPath = z.object({ /** * Success */ -export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = zAccessPolicy +export const zPutWorkspacesCurrentRbacAccessPoliciesByPolicyIdResponse = z.record( + z.string(), + z.unknown(), +) export const zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyPath = z.object({ policy_id: z.uuid(), }) /** - * Policy copied + * Success */ -export const zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse = zAccessPolicy +export const zPostWorkspacesCurrentRbacAccessPoliciesByPolicyIdCopyResponse = z.record( + z.string(), + z.unknown(), +) export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockPath = z.object({ binding_id: z.uuid(), @@ -4893,8 +4890,10 @@ export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockPath = /** * Success */ -export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse = - zAccessPolicyBindingState +export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdLockResponse = z.record( + z.string(), + z.unknown(), +) export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockPath = z.object({ binding_id: z.uuid(), @@ -4903,8 +4902,124 @@ export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockPath /** * Success */ -export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse = - zAccessPolicyBindingState +export const zPutWorkspacesCurrentRbacAccessPolicyBindingsByBindingIdUnlockResponse = z.record( + z.string(), + z.unknown(), +) + +export const zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsBody = + zDeleteMemberBindingsRequest + +export const zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsPath = + z.object({ + agent_id: z.uuid(), + policy_id: z.string(), + }) + +/** + * Success + */ +export const zDeleteWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse = + zMemberBindingsResponse + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsPath = + z.object({ + agent_id: z.uuid(), + policy_id: z.string(), + }) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdMemberBindingsResponse = + zMemberBindingsResponse + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsPath = + z.object({ + agent_id: z.uuid(), + policy_id: z.uuid(), + }) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPoliciesByPolicyIdRoleBindingsResponse = + zRoleBindingsResponse + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyPath = z.object({ + agent_id: z.uuid(), +}) + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyQuery = z.object({ + language: z.enum(['en', 'ja', 'zh']).optional(), +}) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacAgentsByAgentIdAccessPolicyResponse = zAgentAccessMatrix + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesPath = z.object({ + agent_id: z.uuid(), +}) + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesQuery = z.object({ + language: z.enum(['en', 'ja', 'zh']).optional(), + limit: z.int().gte(1).lte(99999).optional(), + page: z.int().gte(1).optional(), + reverse: z.boolean().optional(), +}) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacAgentsByAgentIdUserAccessPoliciesResponse = + zResourceUserAccessPoliciesResponse + +export const zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesBody = + zReplaceUserAccessPolicies + +export const zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesPath = + z.object({ + agent_id: z.uuid(), + target_account_id: z.uuid(), + }) + +/** + * Success + */ +export const zPutWorkspacesCurrentRbacAgentsByAgentIdUsersByTargetAccountIdAccessPoliciesResponse = + zReplaceUserAccessPoliciesResponse + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistPath = z.object({ + agent_id: z.uuid(), +}) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse = zResourceWhitelist + +export const zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistBody = zResourceAccessScopeRequest + +export const zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistPath = z.object({ + agent_id: z.uuid(), +}) + +/** + * Success + */ +export const zPutWorkspacesCurrentRbacAgentsByAgentIdWhitelistResponse = zResourceWhitelist + +export const zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigPath = z.object({ + agent_id: z.uuid(), +}) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacAgentsByAgentIdWhitelistConfigResponse = + zResourceWhitelistConfig export const zDeleteWorkspacesCurrentRbacAppsByAppIdAccessPoliciesByPolicyIdMemberBindingsBody = zDeleteMemberBindingsRequest @@ -5163,6 +5278,12 @@ export const zGetWorkspacesCurrentRbacMyPermissionsResponse = zMyPermissionsResp */ export const zGetWorkspacesCurrentRbacRolePermissionsCatalogResponse = zPermissionCatalogResponse +/** + * Success + */ +export const zGetWorkspacesCurrentRbacRolePermissionsCatalogAgentResponse = + zPermissionCatalogResponse + /** * Success */ @@ -5177,12 +5298,12 @@ export const zGetWorkspacesCurrentRbacRolePermissionsCatalogDatasetResponse = /** * Success */ -export const zGetWorkspacesCurrentRbacRolesResponse = zRbacRoleList +export const zGetWorkspacesCurrentRbacRolesResponse = z.record(z.string(), z.unknown()) /** - * Role created + * Success */ -export const zPostWorkspacesCurrentRbacRolesResponse = zRbacRole +export const zPostWorkspacesCurrentRbacRolesResponse = z.record(z.string(), z.unknown()) export const zDeleteWorkspacesCurrentRbacRolesByRoleIdPath = z.object({ role_id: z.uuid(), @@ -5191,7 +5312,7 @@ export const zDeleteWorkspacesCurrentRbacRolesByRoleIdPath = z.object({ /** * Success */ -export const zDeleteWorkspacesCurrentRbacRolesByRoleIdResponse = zRbacRole +export const zDeleteWorkspacesCurrentRbacRolesByRoleIdResponse = z.record(z.string(), z.unknown()) export const zGetWorkspacesCurrentRbacRolesByRoleIdPath = z.object({ role_id: z.uuid(), @@ -5200,7 +5321,7 @@ export const zGetWorkspacesCurrentRbacRolesByRoleIdPath = z.object({ /** * Success */ -export const zGetWorkspacesCurrentRbacRolesByRoleIdResponse = zRbacRole +export const zGetWorkspacesCurrentRbacRolesByRoleIdResponse = z.record(z.string(), z.unknown()) export const zPutWorkspacesCurrentRbacRolesByRoleIdPath = z.object({ role_id: z.uuid(), @@ -5209,16 +5330,16 @@ export const zPutWorkspacesCurrentRbacRolesByRoleIdPath = z.object({ /** * Success */ -export const zPutWorkspacesCurrentRbacRolesByRoleIdResponse = zRbacRole +export const zPutWorkspacesCurrentRbacRolesByRoleIdResponse = z.record(z.string(), z.unknown()) export const zPostWorkspacesCurrentRbacRolesByRoleIdCopyPath = z.object({ role_id: z.uuid(), }) /** - * Role copied + * Success */ -export const zPostWorkspacesCurrentRbacRolesByRoleIdCopyResponse = zRbacRole +export const zPostWorkspacesCurrentRbacRolesByRoleIdCopyResponse = z.record(z.string(), z.unknown()) export const zGetWorkspacesCurrentRbacRolesByRoleIdMembersPath = z.object({ role_id: z.uuid(), @@ -5229,6 +5350,47 @@ export const zGetWorkspacesCurrentRbacRolesByRoleIdMembersPath = z.object({ */ export const zGetWorkspacesCurrentRbacRolesByRoleIdMembersResponse = zMembersInRoleList +export const zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsBody = + zReplaceBindingsRequest + +export const zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsPath = + z.object({ + policy_id: z.uuid(), + }) + +/** + * Success + */ +export const zPutWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdBindingsResponse = + zAccessMatrixItem + +export const zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsPath = + z.object({ + policy_id: z.uuid(), + }) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdMemberBindingsResponse = + zMemberBindingsResponse + +export const zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsPath = + z.object({ + policy_id: z.uuid(), + }) + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPoliciesByPolicyIdRoleBindingsResponse = + zRoleBindingsResponse + +/** + * Success + */ +export const zGetWorkspacesCurrentRbacWorkspaceAgentsAccessPolicyResponse = zWorkspaceAccessMatrix + export const zPutWorkspacesCurrentRbacWorkspaceAppsAccessPoliciesByPolicyIdBindingsBody = zReplaceBindingsRequest diff --git a/packages/contracts/generated/api/service/orpc.gen.ts b/packages/contracts/generated/api/service/orpc.gen.ts index d491e4de72d..de2363aad6d 100644 --- a/packages/contracts/generated/api/service/orpc.gen.ts +++ b/packages/contracts/generated/api/service/orpc.gen.ts @@ -1888,12 +1888,11 @@ export const tags2 = { /** * Delete Knowledge Base * - * Permanently delete a knowledge base and all its documents. The knowledge base must not be in use by any application. + * Permanently delete a knowledge base and all its documents. */ export const delete8 = oc .route({ - description: - 'Permanently delete a knowledge base and all its documents. The knowledge base must not be in use by any application.', + description: 'Permanently delete a knowledge base and all its documents.', inputStructure: 'detailed', method: 'DELETE', operationId: 'deleteDatasetsByDatasetId', diff --git a/packages/contracts/generated/api/service/types.gen.ts b/packages/contracts/generated/api/service/types.gen.ts index e0a115687f0..b51d4c34d93 100644 --- a/packages/contracts/generated/api/service/types.gen.ts +++ b/packages/contracts/generated/api/service/types.gen.ts @@ -585,7 +585,6 @@ export type DatasetDetailResponse = { maintainer?: string | null name: string permission: string - permission_keys?: Array pipeline_id: string | null provider: string retrieval_model_dict: DatasetRetrievalModelResponse @@ -626,7 +625,6 @@ export type DatasetDetailWithPartialMembersResponse = { name: string partial_member_list?: Array | null permission: string - permission_keys?: Array pipeline_id: string | null provider: string retrieval_model_dict: DatasetRetrievalModelResponse @@ -2492,7 +2490,6 @@ export type GetAppsAnnotationReplyByActionStatusByJobIdErrors = { 400: unknown 401: unknown 403: unknown - 404: unknown } export type GetAppsAnnotationReplyByActionStatusByJobIdResponses = { @@ -2668,7 +2665,6 @@ export type PostCompletionMessagesErrors = { 400: unknown 401: unknown 403: unknown - 404: unknown 429: unknown 500: unknown } @@ -3023,7 +3019,6 @@ export type DeleteDatasetsByDatasetIdErrors = { 401: unknown 403: unknown 404: unknown - 409: unknown } export type DeleteDatasetsByDatasetIdResponses = { @@ -3312,7 +3307,6 @@ export type DeleteDatasetsByDatasetIdDocumentsByDocumentIdData = { } export type DeleteDatasetsByDatasetIdDocumentsByDocumentIdErrors = { - 400: unknown 401: unknown 403: unknown 404: unknown @@ -4162,9 +4156,9 @@ export type GetInfoData = { } export type GetInfoErrors = { + 400: unknown 401: unknown 403: unknown - 404: unknown } export type GetInfoResponses = { @@ -4255,9 +4249,9 @@ export type GetMetaData = { } export type GetMetaErrors = { + 400: unknown 401: unknown 403: unknown - 404: unknown } export type GetMetaResponses = { @@ -4277,7 +4271,6 @@ export type GetParametersErrors = { 400: unknown 401: unknown 403: unknown - 404: unknown } export type GetParametersResponses = { @@ -4390,7 +4383,6 @@ export type PostWorkflowsRunErrors = { 400: unknown 401: unknown 403: unknown - 404: unknown 429: unknown 500: unknown } diff --git a/packages/contracts/generated/api/service/zod.gen.ts b/packages/contracts/generated/api/service/zod.gen.ts index 6ff23f78936..c04a4650041 100644 --- a/packages/contracts/generated/api/service/zod.gen.ts +++ b/packages/contracts/generated/api/service/zod.gen.ts @@ -784,7 +784,6 @@ export const zDatasetDetailResponse = z.object({ maintainer: z.string().nullish(), name: z.string(), permission: z.string(), - permission_keys: z.array(z.string()).optional(), pipeline_id: z.string().nullable(), provider: z.string(), retrieval_model_dict: zDatasetRetrievalModelResponse, @@ -828,7 +827,6 @@ export const zDatasetDetailWithPartialMembersResponse = z.object({ name: z.string(), partial_member_list: z.array(z.string()).nullish(), permission: z.string(), - permission_keys: z.array(z.string()).optional(), pipeline_id: z.string().nullable(), provider: z.string(), retrieval_model_dict: zDatasetRetrievalModelResponse, diff --git a/vite.config.ts b/vite.config.ts index 3f97680d425..8d47f7528bb 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -51,6 +51,16 @@ export default defineConfig({ [eslintFiles]: [eslintFix, formatFix], [formatOnlyFiles]: formatFix, '.vite-hooks/*': 'sh -n', + 'api/**/*.{py,pyi}': [ + // Format first so fixable long lines do not fail the API's E501 check. + 'uv run --locked --project api --dev ruff format --force-exclude', + 'uv run --locked --project api --dev ruff check --fix --force-exclude', + 'uv run --locked --project api --dev ruff format --force-exclude', + ], + 'dify-agent/{src,examples,tests,docs}/**/*.py': [ + 'uv run --locked --project dify-agent --dev ruff check --fix --force-exclude', + 'uv run --locked --project dify-agent --dev ruff format --force-exclude', + ], }, fmt: { ignorePatterns: [...nonFrontendIgnores, ...generatedIgnores, ...formatterUnstableInputs], diff --git a/web/.env.example b/web/.env.example index 4433c3282b4..d2fff4dfae4 100644 --- a/web/.env.example +++ b/web/.env.example @@ -107,6 +107,10 @@ NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW=true # Enable Agent v2 frontend entry points. NEXT_PUBLIC_ENABLE_AGENT_V2=true +# Surface the Agent v2 node inside Chatflow (advanced-chat) apps. +# Requires NEXT_PUBLIC_ENABLE_AGENT_V2. Disabled by default. +NEXT_PUBLIC_ENABLE_AGENT_V2_IN_CHATFLOW=false + # The maximum number of tree node depth for workflow NEXT_PUBLIC_MAX_TREE_DEPTH=50 diff --git a/web/AGENTS.md b/web/AGENTS.md index 939bbcbe700..dc59e66c9be 100644 --- a/web/AGENTS.md +++ b/web/AGENTS.md @@ -9,8 +9,9 @@ Web owns application-specific requirements and consumes shared architecture guidance from skills and primitive contracts from Dify UI. Link to those owners instead of redefining their rules here. - For truncated text disclosure and native `title` decisions, follow [Truncated Text Disclosure]. +- When adding or changing page layouts, navigation, or landmark elements, follow [Page landmarks] and inspect the composed page, including parent layouts. - User-facing strings must use `web/i18n/en-US/` keys. When adding or renaming a key, update every supported locale with the correct localized value. -- For new backend calls and migrated surfaces, use generated `consoleQuery` / `consoleClient` APIs from `@/service/client`. Do not add handwritten REST helpers or DTO mirrors, mock-backed app state, or direct edits to generated contracts. +- For new backend calls and migrated surfaces, use generated `consoleQuery` / `consoleClient` APIs from `@/service/console`. Do not add handwritten REST helpers or DTO mirrors, mock-backed app state, or direct edits to generated contracts. - Prefer `@langgenius/dify-ui/*` primitives, data attributes, and design tokens. Use the [Dify UI package index] to find a primitive; read the relevant contract directly when it is already known. Preserve a visible focus indicator on the final focusable element. - Reuse the Web `SearchInput` composite when its search, clear, and IME contract matches the feature; otherwise follow the canonical [Input Group contract]. - Give save and submit flows a real form boundary with visible labels and accessible errors. Use Dify UI `Form` when its structured submission and validation contract is the owner; otherwise use a native form. Follow the canonical [form contract]. @@ -36,5 +37,6 @@ This block is written and re-added by `next dev` — verify at `node_modules/nex [Dify UI package index]: ../packages/dify-ui/README.md [IconButton contract]: ../packages/dify-ui/src/icon-button/README.md [Input Group contract]: ../packages/dify-ui/src/input-group/README.md +[Page landmarks]: docs/landmarks.md [Truncated Text Disclosure]: docs/truncated-text-disclosure.md [form contract]: ../packages/dify-ui/docs/forms.md diff --git a/web/__mocks__/provider-context.ts b/web/__mocks__/provider-context.ts deleted file mode 100644 index 6e47ca112e7..00000000000 --- a/web/__mocks__/provider-context.ts +++ /dev/null @@ -1,84 +0,0 @@ -import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' -import type { UsagePlanInfo } from '@/app/components/billing/type' -import type { ProviderContextState } from '@/context/provider-context' -import { merge } from 'es-toolkit/compat' -import { noop } from 'es-toolkit/function' -import { defaultPlan } from '@/app/components/billing/config' - -// Avoid being mocked in tests -export const baseProviderContextValue: ProviderContextState = { - modelProviders: [], - modelProviderPlugins: {}, - refreshModelProviders: async () => {}, - isLoadingModelProviders: false, - isSuccessModelProviders: false, - textGenerationModelList: [], - supportRetrievalMethods: [], - isAPIKeySet: true, - plan: defaultPlan, - isFetchedPlan: false, - isFetchedPlanInfo: false, - enableBilling: false, - enableSkill: false, - difyBuilderEnabled: false, - onPlanInfoChanged: noop, - enableReplaceWebAppLogo: false, - modelLoadBalancingEnabled: false, - enableEducationPlan: false, - webappCopyrightEnabled: false, - isAllowTransferWorkspace: false, - isAllowPublishAsCustomKnowledgePipelineTemplate: false, - humanInputEmailDeliveryEnabled: false, -} - -export const createMockProviderContextValue = ( - overrides: Partial = {}, -): ProviderContextState => { - const merged = merge({}, baseProviderContextValue, overrides) - - return { - ...merged, - refreshModelProviders: merged.refreshModelProviders ?? noop, - onPlanInfoChanged: merged.onPlanInfoChanged ?? noop, - } -} - -export const createMockPlan = (plan: CloudPlan): ProviderContextState => - createMockProviderContextValue({ - plan: merge({}, defaultPlan, { - type: plan, - }), - }) - -export const createMockPlanUsage = ( - usage: UsagePlanInfo, - ctx: Partial, -): ProviderContextState => - createMockProviderContextValue({ - ...ctx, - plan: merge(ctx.plan, { - usage, - }), - }) - -export const createMockPlanTotal = ( - total: UsagePlanInfo, - ctx: Partial, -): ProviderContextState => - createMockProviderContextValue({ - ...ctx, - plan: merge(ctx.plan, { - total, - }), - }) - -export const createMockPlanReset = ( - reset: Partial, - ctx: Partial, -): ProviderContextState => - createMockProviderContextValue({ - ...ctx, - plan: merge(ctx?.plan, { - reset, - }), - }) diff --git a/web/__tests__/billing/billing-integration.test.tsx b/web/__tests__/billing/billing-integration.test.tsx index 30531a83d98..b3d28cf9c83 100644 --- a/web/__tests__/billing/billing-integration.test.tsx +++ b/web/__tests__/billing/billing-integration.test.tsx @@ -1,21 +1,26 @@ +import type { + GetFeaturesResponse, + GetFeaturesVectorSpaceResponse, +} from '@dify/contracts/api/console/features/types.gen' import type { RenderOptions } from '@testing-library/react' import type { ReactElement } from 'react' -import type { UsagePlanInfo, UsageResetInfo } from '@/app/components/billing/type' +import type { DeepPartial } from '@/test/console/system-features' import { screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' +import dayjs from 'dayjs' import * as React from 'react' import AnnotationFull from '@/app/components/billing/annotation-full' import AnnotationFullModal from '@/app/components/billing/annotation-full/modal' import AppsFull from '@/app/components/billing/apps-full-in-dialog' import Billing from '@/app/components/billing/billing-page' -import { defaultPlan, NUM_INFINITE } from '@/app/components/billing/config' +import { NUM_INFINITE } from '@/app/components/billing/config' import PlanComp from '@/app/components/billing/plan' import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal' import PriorityLabel from '@/app/components/billing/priority-label' import TriggerEventsLimitModal from '@/app/components/billing/trigger-events-limit-modal' import UpgradeBtn from '@/app/components/billing/upgrade-btn' import VectorSpaceFull from '@/app/components/billing/vector-space-full' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, createConsoleQueryWrapper, @@ -23,19 +28,15 @@ import { } from '@/test/console/query-data' import { render as renderWithConsoleState } from '@/test/console/render' -let mockProviderCtx: Record = {} +let mockFeatures: DeepPartial = {} +let mockVectorSpace: GetFeaturesVectorSpaceResponse = { size: 0, limit: 50, usage_unknown: false } let mockConsoleState: Record = {} let mockEducationStatus = { is_student: false, allow_refresh: false, expire_at: null } const render = (ui: ReactElement, options: RenderOptions = {}, vectorSpaceUsageUnknown = false) => { const queryClient = createConsoleQueryClient() - const plan = mockProviderCtx.plan as { - usage: { vectorSpace: number } - total: { vectorSpace: number } - } queryClient.setQueryData(consoleQuery.features.vectorSpace.get.queryOptions().queryKey, { - size: plan.usage.vectorSpace, - limit: plan.total.vectorSpace, + ...mockVectorSpace, usage_unknown: vectorSpaceUsageUnknown, }) queryClient.setQueryData(consoleQuery.billing.invoices.get.queryOptions().queryKey, { @@ -46,6 +47,7 @@ const render = (ui: ReactElement, options: RenderOptions = {}, vectorSpaceUsageU accountProfile: mockConsoleState.userProfile as { email?: string }, accountProfileMeta: { currentVersion: '1.0.0' }, systemFeatures: { deployment_edition: 'CLOUD' }, + features: mockFeatures, queryClient, }) return renderWithConsoleState(ui, { ...options, wrapper }) @@ -53,10 +55,6 @@ const render = (ui: ReactElement, options: RenderOptions = {}, vectorSpaceUsageU const mockSetShowPricingModal = vi.fn() -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockProviderCtx, -})) - vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') return createWorkspaceStateModuleMock(() => mockConsoleState) @@ -85,25 +83,13 @@ vi.mock('@/app/components/header/utils/util', () => ({ })) // ─── Test data factories ──────────────────────────────────────────────────── -type PlanOverrides = { - type?: string - usage?: Partial - total?: Partial - reset?: Partial +type BillingOverrides = DeepPartial & { + vectorSpace?: Partial } -const createPlanData = (overrides: PlanOverrides = {}) => ({ - ...defaultPlan, - ...overrides, - type: overrides.type ?? defaultPlan.type, - usage: { ...defaultPlan.usage, ...overrides.usage }, - total: { ...defaultPlan.total, ...overrides.total }, - reset: { ...defaultPlan.reset, ...overrides.reset }, -}) - -const setupProviderContext = ( - planOverrides: PlanOverrides = {}, - extra: Record = {}, +const setupBilling = ( + { vectorSpace, ...features }: BillingOverrides = {}, + education: { enableEducationPlan?: boolean } = {}, educationStatus: Partial = {}, ) => { mockEducationStatus = { @@ -112,13 +98,8 @@ const setupProviderContext = ( expire_at: null, ...educationStatus, } - mockProviderCtx = { - plan: createPlanData(planOverrides), - enableBilling: true, - isFetchedPlan: true, - enableEducationPlan: false, - ...extra, - } + mockFeatures = { ...features, education: { enabled: education.enableEducationPlan ?? false } } + mockVectorSpace = { size: 0, limit: 50, usage_unknown: false, ...vectorSpace } } const setupConsoleState = (overrides: Record = {}) => { @@ -146,26 +127,15 @@ describe('Billing Page + Plan Integration', () => { // Verify that the billing page renders PlanComp with all 7 usage items describe('Rendering complete plan information', () => { it('should display all 7 usage metrics for sandbox plan', () => { - setupProviderContext({ - type: 'sandbox', - usage: { - buildApps: 3, - teamMembers: 1, - documentsUploadQuota: 10, - vectorSpace: 20, - annotatedResponse: 5, - triggerEvents: 1000, - apiRateLimit: 2000, - }, - total: { - buildApps: 5, - teamMembers: 1, - documentsUploadQuota: 50, - vectorSpace: 50, - annotatedResponse: 10, - triggerEvents: 3000, - apiRateLimit: 5000, - }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + apps: { size: 3, limit: 5 }, + members: { size: 1, limit: 1 }, + documents_upload_quota: { size: 10, limit: 50 }, + annotation_quota_limit: { size: 5, limit: 10 }, + trigger_event: { usage: 1000, limit: 3000 }, + api_rate_limit: { usage: 2000, limit: 5000 }, + vectorSpace: { size: 20, limit: 50 }, }) render() @@ -184,10 +154,9 @@ describe('Billing Page + Plan Integration', () => { }) it('should expose each quota card and its value through stable semantics', () => { - setupProviderContext({ - type: 'sandbox', - usage: { teamMembers: 3 }, - total: { teamMembers: 5 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + members: { size: 3, limit: 5 }, }) render() @@ -202,10 +171,9 @@ describe('Billing Page + Plan Integration', () => { }) it('should display unknown vector space usage as a placeholder', () => { - setupProviderContext({ - type: 'sandbox', - usage: { vectorSpace: 0 }, - total: { vectorSpace: 50 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + vectorSpace: { size: 0, limit: 50 }, }) render(, {}, true) @@ -217,9 +185,9 @@ describe('Billing Page + Plan Integration', () => { }) it('should show "unlimited" for infinite quotas (professional API rate limit)', () => { - setupProviderContext({ - type: 'professional', - total: { apiRateLimit: NUM_INFINITE }, + setupBilling({ + billing: { subscription: { plan: 'professional' } }, + api_rate_limit: { limit: NUM_INFINITE }, }) render() @@ -228,10 +196,9 @@ describe('Billing Page + Plan Integration', () => { }) it('should display reset days for trigger events when applicable', () => { - setupProviderContext({ - type: 'professional', - total: { triggerEvents: 20000 }, - reset: { triggerEvents: 7 }, + setupBilling({ + billing: { subscription: { plan: 'professional' } }, + trigger_event: { limit: 20000, reset_date: dayjs().add(7, 'day').startOf('day').unix() }, }) render() @@ -244,7 +211,7 @@ describe('Billing Page + Plan Integration', () => { // Verify billing URL button visibility and behavior describe('Billing URL button', () => { it('should show billing button to managers without billing permission keys', () => { - setupProviderContext({ type: 'sandbox' }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }) setupConsoleState({ isCurrentWorkspaceManager: true, workspacePermissionKeys: [], @@ -257,7 +224,7 @@ describe('Billing Page + Plan Integration', () => { }) it('should hide billing button from non-manager members', () => { - setupProviderContext({ type: 'sandbox' }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }) setupConsoleState({ isCurrentWorkspaceManager: false, }) @@ -268,7 +235,7 @@ describe('Billing Page + Plan Integration', () => { }) it('should show billing button when a manager has no billing permission keys', () => { - setupProviderContext({ type: 'sandbox' }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }) setupConsoleState({ isCurrentWorkspaceManager: true, workspacePermissionKeys: [], @@ -278,14 +245,6 @@ describe('Billing Page + Plan Integration', () => { expect(screen.getByText(/viewBillingTitle/i)).toBeInTheDocument() }) - - it('should hide billing button when billing is disabled', () => { - setupProviderContext({ type: 'sandbox' }, { enableBilling: false }) - - render() - - expect(screen.queryByText(/viewBillingTitle/i)).not.toBeInTheDocument() - }) }) }) @@ -300,7 +259,7 @@ describe('Plan Type Display Integration', () => { }) it('should render sandbox plan with upgrade button (premium badge)', () => { - setupProviderContext({ type: 'sandbox' }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }) render() @@ -311,7 +270,7 @@ describe('Plan Type Display Integration', () => { }) it('should render professional plan with plain upgrade button', () => { - setupProviderContext({ type: 'professional' }) + setupBilling({ billing: { subscription: { plan: 'professional' } } }) render() @@ -321,7 +280,7 @@ describe('Plan Type Display Integration', () => { }) it('should render team plan with plain-style upgrade button', () => { - setupProviderContext({ type: 'team' }) + setupBilling({ billing: { subscription: { plan: 'team' } } }) render() @@ -331,7 +290,7 @@ describe('Plan Type Display Integration', () => { }) it('should show education verify button when enableEducationPlan is true and not yet verified', () => { - setupProviderContext({ type: 'sandbox' }, { enableEducationPlan: true }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }, { enableEducationPlan: true }) render() @@ -339,7 +298,11 @@ describe('Plan Type Display Integration', () => { }) it('should show education discount to managers without billing permission keys', () => { - setupProviderContext({ type: 'sandbox' }, { enableEducationPlan: true }, { is_student: true }) + setupBilling( + { billing: { subscription: { plan: 'sandbox' } } }, + { enableEducationPlan: true }, + { is_student: true }, + ) setupConsoleState({ isCurrentWorkspaceManager: true, workspacePermissionKeys: [] }) render() @@ -348,7 +311,11 @@ describe('Plan Type Display Integration', () => { }) it('should hide education discount from non-manager members', () => { - setupProviderContext({ type: 'sandbox' }, { enableEducationPlan: true }, { is_student: true }) + setupBilling( + { billing: { subscription: { plan: 'sandbox' } } }, + { enableEducationPlan: true }, + { is_student: true }, + ) setupConsoleState({ isCurrentWorkspaceManager: false, workspacePermissionKeys: ['billing.manage'], @@ -369,7 +336,7 @@ describe('Upgrade Flow Integration', () => { beforeEach(() => { vi.clearAllMocks() setupConsoleState() - setupProviderContext({ type: 'sandbox' }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }) }) // UpgradeBtn triggers pricing modal @@ -495,7 +462,7 @@ describe('Upgrade Flow Integration', () => { describe('PlanComp upgrade button triggers pricing', () => { it('should open pricing modal when clicking upgrade in sandbox plan', async () => { const user = userEvent.setup() - setupProviderContext({ type: 'sandbox' }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }) render() @@ -521,11 +488,7 @@ describe('Capacity Full Components Integration', () => { // AppsFull renders with correct messaging and components describe('AppsFull integration', () => { it('should display upgrade tip and upgrade button for sandbox plan at capacity', () => { - setupProviderContext({ - type: 'sandbox', - usage: { buildApps: 5 }, - total: { buildApps: 5 }, - }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } }, apps: { size: 5, limit: 5 } }) render() @@ -540,10 +503,9 @@ describe('Capacity Full Components Integration', () => { }) it('should display upgrade tip and upgrade button for professional plan', () => { - setupProviderContext({ - type: 'professional', - usage: { buildApps: 48 }, - total: { buildApps: 50 }, + setupBilling({ + billing: { subscription: { plan: 'professional' } }, + apps: { size: 48, limit: 50 }, }) render() @@ -553,11 +515,7 @@ describe('Capacity Full Components Integration', () => { }) it('should display contact tip and contact button for team plan', () => { - setupProviderContext({ - type: 'team', - usage: { buildApps: 200 }, - total: { buildApps: 200 }, - }) + setupBilling({ billing: { subscription: { plan: 'team' } }, apps: { size: 200, limit: 200 } }) render() @@ -570,11 +528,7 @@ describe('Capacity Full Components Integration', () => { it('should render progress bar with correct color based on usage percentage', () => { // 100% usage should show error color - setupProviderContext({ - type: 'sandbox', - usage: { buildApps: 5 }, - total: { buildApps: 5 }, - }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } }, apps: { size: 5, limit: 5 } }) const { container } = render() @@ -585,10 +539,9 @@ describe('Capacity Full Components Integration', () => { // VectorSpaceFull renders with VectorSpaceInfo and UpgradeBtn describe('VectorSpaceFull integration', () => { it('should display full tip, upgrade button, and vector space usage info', () => { - setupProviderContext({ - type: 'sandbox', - usage: { vectorSpace: 50 }, - total: { vectorSpace: 50 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + vectorSpace: { size: 50, limit: 50 }, }) render() @@ -606,10 +559,9 @@ describe('Capacity Full Components Integration', () => { // AnnotationFull renders with Usage component and UpgradeBtn describe('AnnotationFull integration', () => { it('should display annotation full tip, upgrade button, and usage info', () => { - setupProviderContext({ - type: 'sandbox', - usage: { annotatedResponse: 10 }, - total: { annotatedResponse: 10 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + annotation_quota_limit: { size: 10, limit: 10 }, }) render() @@ -626,10 +578,9 @@ describe('Capacity Full Components Integration', () => { // AnnotationFullModal shows modal with usage and upgrade button describe('AnnotationFullModal integration', () => { it('should render modal with annotation info and upgrade button when show is true', () => { - setupProviderContext({ - type: 'sandbox', - usage: { annotatedResponse: 10 }, - total: { annotatedResponse: 10 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + annotation_quota_limit: { size: 10, limit: 10 }, }) render() @@ -640,10 +591,9 @@ describe('Capacity Full Components Integration', () => { }) it('should not render content when show is false', () => { - setupProviderContext({ - type: 'sandbox', - usage: { annotatedResponse: 10 }, - total: { annotatedResponse: 10 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + annotation_quota_limit: { size: 10, limit: 10 }, }) render() @@ -655,7 +605,7 @@ describe('Capacity Full Components Integration', () => { // TriggerEventsLimitModal renders PlanUpgradeModal with embedded UsageInfo describe('TriggerEventsLimitModal integration', () => { it('should display trigger limit title, usage info, and upgrade button', () => { - setupProviderContext({ type: 'professional' }) + setupBilling({ billing: { subscription: { plan: 'professional' } } }) render( { const user = userEvent.setup() const onClose = vi.fn() const onUpgrade = vi.fn() - setupProviderContext({ type: 'professional' }) + setupBilling({ billing: { subscription: { plan: 'professional' } } }) render( { }) it('should display "standard" priority for sandbox plan', () => { - setupProviderContext({ type: 'sandbox' }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } } }) render() @@ -726,7 +676,7 @@ describe('PriorityLabel Integration', () => { }) it('should display "priority" for professional plan with icon', () => { - setupProviderContext({ type: 'professional' }) + setupBilling({ billing: { subscription: { plan: 'professional' } } }) const { container } = render() @@ -736,7 +686,7 @@ describe('PriorityLabel Integration', () => { }) it('should display "top-priority" for team plan with icon', () => { - setupProviderContext({ type: 'team' }) + setupBilling({ billing: { subscription: { plan: 'team' } } }) const { container } = render() @@ -758,10 +708,9 @@ describe('Usage Display Edge Cases', () => { // Vector space storage mode behavior describe('VectorSpace storage mode in PlanComp', () => { it('should show "< 50" for sandbox plan with low vector space usage', () => { - setupProviderContext({ - type: 'sandbox', - usage: { vectorSpace: 10 }, - total: { vectorSpace: 50 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + vectorSpace: { size: 10, limit: 50 }, }) render() @@ -771,10 +720,9 @@ describe('Usage Display Edge Cases', () => { }) it('should show indeterminate progress bar for usage below threshold', () => { - setupProviderContext({ - type: 'sandbox', - usage: { vectorSpace: 10 }, - total: { vectorSpace: 50 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + vectorSpace: { size: 10, limit: 50 }, }) render() @@ -784,10 +732,9 @@ describe('Usage Display Edge Cases', () => { }) it('should show actual usage for pro plan above threshold', () => { - setupProviderContext({ - type: 'professional', - usage: { vectorSpace: 1024 }, - total: { vectorSpace: 5120 }, + setupBilling({ + billing: { subscription: { plan: 'professional' } }, + vectorSpace: { size: 1024, limit: 5120 }, }) render() @@ -800,11 +747,7 @@ describe('Usage Display Edge Cases', () => { // Progress bar color logic through real components describe('Progress bar color reflects usage severity', () => { it('should show normal color for low usage percentage', () => { - setupProviderContext({ - type: 'sandbox', - usage: { buildApps: 1 }, - total: { buildApps: 5 }, - }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } }, apps: { size: 1, limit: 5 } }) const { container } = render() @@ -818,10 +761,9 @@ describe('Usage Display Edge Cases', () => { // Reset days calculation in PlanComp describe('Reset days integration', () => { it('should not show reset for sandbox trigger events (no reset_date)', () => { - setupProviderContext({ - type: 'sandbox', - total: { triggerEvents: 3000 }, - reset: { triggerEvents: null }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + trigger_event: { limit: 3000, reset_date: 0 }, }) render() @@ -834,10 +776,9 @@ describe('Usage Display Edge Cases', () => { }) it('should show reset for professional trigger events with reset date', () => { - setupProviderContext({ - type: 'professional', - total: { triggerEvents: 20000 }, - reset: { triggerEvents: 14 }, + setupBilling({ + billing: { subscription: { plan: 'professional' } }, + trigger_event: { limit: 20000, reset_date: dayjs().add(14, 'day').startOf('day').unix() }, }) render() @@ -861,11 +802,7 @@ describe('Cross-Component Upgrade Flow', () => { it('should trigger pricing from AppsFull upgrade button', async () => { const user = userEvent.setup() - setupProviderContext({ - type: 'sandbox', - usage: { buildApps: 5 }, - total: { buildApps: 5 }, - }) + setupBilling({ billing: { subscription: { plan: 'sandbox' } }, apps: { size: 5, limit: 5 } }) render() @@ -877,10 +814,9 @@ describe('Cross-Component Upgrade Flow', () => { it('should trigger pricing from VectorSpaceFull upgrade button', async () => { const user = userEvent.setup() - setupProviderContext({ - type: 'sandbox', - usage: { vectorSpace: 50 }, - total: { vectorSpace: 50 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + vectorSpace: { size: 50, limit: 50 }, }) render() @@ -893,10 +829,9 @@ describe('Cross-Component Upgrade Flow', () => { it('should trigger pricing from AnnotationFull upgrade button', async () => { const user = userEvent.setup() - setupProviderContext({ - type: 'sandbox', - usage: { annotatedResponse: 10 }, - total: { annotatedResponse: 10 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + annotation_quota_limit: { size: 10, limit: 10 }, }) render() @@ -910,7 +845,7 @@ describe('Cross-Component Upgrade Flow', () => { it('should trigger pricing from TriggerEventsLimitModal through PlanUpgradeModal', async () => { const user = userEvent.setup() const onClose = vi.fn() - setupProviderContext({ type: 'professional' }) + setupBilling({ billing: { subscription: { plan: 'professional' } } }) render( { it('should trigger pricing from AnnotationFullModal upgrade button', async () => { const user = userEvent.setup() - setupProviderContext({ - type: 'sandbox', - usage: { annotatedResponse: 10 }, - total: { annotatedResponse: 10 }, + setupBilling({ + billing: { subscription: { plan: 'sandbox' } }, + annotation_quota_limit: { size: 10, limit: 10 }, }) render() diff --git a/web/__tests__/billing/cloud-plan-payment-flow.test.tsx b/web/__tests__/billing/cloud-plan-payment-flow.test.tsx index 7525f331796..eb8ea8da748 100644 --- a/web/__tests__/billing/cloud-plan-payment-flow.test.tsx +++ b/web/__tests__/billing/cloud-plan-payment-flow.test.tsx @@ -30,8 +30,8 @@ vi.mock('@/context/workspace-state', async () => { return createWorkspaceStateModuleMock(() => mockConsoleState) }) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() return { ...actual, consoleClient: new Proxy(actual.consoleClient, { diff --git a/web/__tests__/billing/education-verification-flow.test.tsx b/web/__tests__/billing/education-verification-flow.test.tsx index e9f79a71697..23a57eb55e1 100644 --- a/web/__tests__/billing/education-verification-flow.test.tsx +++ b/web/__tests__/billing/education-verification-flow.test.tsx @@ -1,11 +1,14 @@ +import type { + GetFeaturesResponse, + GetFeaturesVectorSpaceResponse, +} from '@dify/contracts/api/console/features/types.gen' import type { RenderOptions } from '@testing-library/react' import type { ReactElement } from 'react' -import type { UsagePlanInfo, UsageResetInfo } from '@/app/components/billing/type' +import type { DeepPartial } from '@/test/console/system-features' import { cleanup, screen } from '@testing-library/react' import * as React from 'react' -import { defaultPlan } from '@/app/components/billing/config' import PlanComp from '@/app/components/billing/plan' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, createConsoleQueryWrapper, @@ -13,19 +16,15 @@ import { } from '@/test/console/query-data' import { render as renderWithConsoleState } from '@/test/console/render' -let mockProviderCtx: Record = {} +let mockFeatures: DeepPartial = {} +let mockVectorSpace: GetFeaturesVectorSpaceResponse = { size: 0, limit: 50, usage_unknown: false } let mockConsoleState: Record = {} let mockEducationStatus = { is_student: false, allow_refresh: false, expire_at: null } const render = (ui: ReactElement, options: RenderOptions = {}) => { const queryClient = createConsoleQueryClient() - const plan = mockProviderCtx.plan as { - usage: { vectorSpace: number } - total: { vectorSpace: number } - } queryClient.setQueryData(consoleQuery.features.vectorSpace.get.queryOptions().queryKey, { - size: plan.usage.vectorSpace, - limit: plan.total.vectorSpace, + ...mockVectorSpace, usage_unknown: false, }) seedEducationStatus(queryClient, mockEducationStatus) @@ -33,6 +32,7 @@ const render = (ui: ReactElement, options: RenderOptions = {}) => { accountProfile: mockConsoleState.userProfile as { email?: string }, accountProfileMeta: { currentVersion: '1.0.0' }, systemFeatures: { deployment_edition: 'CLOUD' }, + features: mockFeatures, queryClient, }) return renderWithConsoleState(ui, { ...options, wrapper }) @@ -42,9 +42,6 @@ const render = (ui: ReactElement, options: RenderOptions = {}) => { const mockSetShowPricingModal = vi.fn() // ─── Context mocks ─────────────────────────────────────────────────────────── -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockProviderCtx, -})) vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') @@ -63,25 +60,13 @@ vi.mock('@/next/navigation', () => ({ })) // ─── Test data factories ──────────────────────────────────────────────────── -type PlanOverrides = { - type?: string - usage?: Partial - total?: Partial - reset?: Partial +type BillingOverrides = DeepPartial & { + vectorSpace?: Partial } -const createPlanData = (overrides: PlanOverrides = {}) => ({ - ...defaultPlan, - ...overrides, - type: overrides.type ?? defaultPlan.type, - usage: { ...defaultPlan.usage, ...overrides.usage }, - total: { ...defaultPlan.total, ...overrides.total }, - reset: { ...defaultPlan.reset, ...overrides.reset }, -}) - -const setupContexts = ( - planOverrides: PlanOverrides = {}, - providerOverrides: Record = {}, +const setupBilling = ( + { vectorSpace, ...features }: BillingOverrides = {}, + education: { enableEducationPlan?: boolean } = {}, appOverrides: Record = {}, educationStatus: Partial = {}, ) => { @@ -91,13 +76,8 @@ const setupContexts = ( expire_at: null, ...educationStatus, } - mockProviderCtx = { - plan: createPlanData(planOverrides), - enableBilling: true, - isFetchedPlan: true, - enableEducationPlan: false, - ...providerOverrides, - } + mockFeatures = { ...features, education: { enabled: education.enableEducationPlan ?? false } } + mockVectorSpace = { size: 0, limit: 50, usage_unknown: false, ...vectorSpace } mockConsoleState = { isCurrentWorkspaceManager: true, userProfile: { email: 'student@university.edu' }, @@ -111,13 +91,13 @@ describe('Education Verification Flow', () => { beforeEach(() => { vi.clearAllMocks() cleanup() - setupContexts() + setupBilling() }) // ─── 1. Education Button Visibility ───────────────────────────────────── describe('Education button visibility', () => { it('should not show verify button when enableEducationPlan is false', () => { - setupContexts({}, { enableEducationPlan: false }) + setupBilling({}, { enableEducationPlan: false }) render() @@ -125,7 +105,7 @@ describe('Education Verification Flow', () => { }) it('should show verify button when enableEducationPlan is true and not yet verified', () => { - setupContexts({}, { enableEducationPlan: true }) + setupBilling({}, { enableEducationPlan: true }) render() @@ -136,7 +116,7 @@ describe('Education Verification Flow', () => { }) it('should not show verify button when already verified and not about to expire', () => { - setupContexts({}, { enableEducationPlan: true }, {}, { is_student: true }) + setupBilling({}, { enableEducationPlan: true }, {}, { is_student: true }) render() @@ -144,12 +124,7 @@ describe('Education Verification Flow', () => { }) it('should show verify button when the education status allows refresh', () => { - setupContexts( - {}, - { enableEducationPlan: true }, - {}, - { is_student: true, allow_refresh: true }, - ) + setupBilling({}, { enableEducationPlan: true }, {}, { is_student: true, allow_refresh: true }) render() @@ -160,7 +135,10 @@ describe('Education Verification Flow', () => { // ─── 2. Education + Upgrade Coexistence ───────────────────────────────── describe('Education and upgrade button coexistence', () => { it('should show both education verify and upgrade buttons for sandbox user', () => { - setupContexts({ type: 'sandbox' }, { enableEducationPlan: true }) + setupBilling( + { billing: { subscription: { plan: 'sandbox' } } }, + { enableEducationPlan: true }, + ) render() @@ -169,7 +147,7 @@ describe('Education Verification Flow', () => { }) it('should show team plan with plain upgrade button and education button', () => { - setupContexts({ type: 'team' }, { enableEducationPlan: true }) + setupBilling({ billing: { subscription: { plan: 'team' } } }, { enableEducationPlan: true }) render() diff --git a/web/__tests__/billing/pricing-modal-flow.test.tsx b/web/__tests__/billing/pricing-modal-flow.test.tsx index 6f32dc9d044..29c7d3db54b 100644 --- a/web/__tests__/billing/pricing-modal-flow.test.tsx +++ b/web/__tests__/billing/pricing-modal-flow.test.tsx @@ -32,7 +32,6 @@ const render = (ui: React.ReactElement) => { }) seedFeatures(queryClient, { billing: { - enabled: true, subscription: { interval: 'month', plan: mockCurrentPlan }, }, education: { enabled: mockEducationEnabled }, @@ -50,8 +49,8 @@ vi.mock('@/context/i18n', () => ({ useGetPricingPageLanguage: () => 'en', })) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() return { ...actual, consoleClient: new Proxy(actual.consoleClient, { diff --git a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx index fb9ce499b03..3e8b05dbfab 100644 --- a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx +++ b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx @@ -11,7 +11,6 @@ const mocks = vi.hoisted(() => ({ workspaceQueryOptions: vi.fn(), permissionQueryFn: vi.fn(), permissionQueryOptions: vi.fn(), - getServerConsoleClientContext: vi.fn(), redirect: vi.fn((url: string) => { throw new Error(`NEXT_REDIRECT:${url}`) }), @@ -48,10 +47,12 @@ vi.mock('@/features/account-profile/server', () => ({ }), })) -vi.mock('@/service/server', () => ({ - getServerConsoleClientContext: () => mocks.getServerConsoleClientContext(), +vi.mock('@/service/console/server', () => ({ resolveServerConsoleApiUrl: (...args: unknown[]) => mocks.resolveServerConsoleApiUrl(...args), - serverConsoleQuery: { +})) + +vi.mock('@/service/console', () => ({ + consoleQuery: { workspaces: { current: { summary: { @@ -107,14 +108,10 @@ describe('CommonLayoutHydrationBoundary', () => { credits: 200, }) mocks.permissionQueryFn.mockResolvedValue({ - workspace: { permission_keys: ['agent.manage'] }, + workspace: { permission_keys: ['agent.acl.preview'] }, app: { default_permission_keys: [], overrides: [] }, dataset: { default_permission_keys: [], overrides: [] }, }) - mocks.getServerConsoleClientContext.mockResolvedValue({ - cookie: 'session=abc', - csrfToken: 'csrf-token', - }) mocks.workspaceQueryOptions.mockReturnValue({ queryKey: ['console', 'workspaces', 'current', 'summary', 'get'], queryFn: mocks.workspaceQueryFn, @@ -144,20 +141,11 @@ describe('CommonLayoutHydrationBoundary', () => { ) expect(screen.getByText('Common shell')).toBeInTheDocument() expect(mocks.profileQueryFn).toHaveBeenCalledTimes(1) - expect(mocks.getServerConsoleClientContext).toHaveBeenCalledTimes(1) expect(mocks.workspaceQueryOptions).toHaveBeenCalledWith({ - context: { - cookie: 'session=abc', - csrfToken: 'csrf-token', - }, retry: false, }) expect(mocks.workspaceQueryFn).toHaveBeenCalledTimes(1) expect(mocks.permissionQueryOptions).toHaveBeenCalledWith({ - context: { - cookie: 'session=abc', - csrfToken: 'csrf-token', - }, retry: false, }) expect(mocks.permissionQueryFn).toHaveBeenCalledTimes(1) diff --git a/web/app/(commonLayout)/agents/__tests__/agents-access-guard.spec.tsx b/web/app/(commonLayout)/agents/__tests__/agents-access-guard.spec.tsx index 14feed6124e..b7c4d8507d5 100644 --- a/web/app/(commonLayout)/agents/__tests__/agents-access-guard.spec.tsx +++ b/web/app/(commonLayout)/agents/__tests__/agents-access-guard.spec.tsx @@ -25,7 +25,7 @@ vi.mock('@/context/permission-state', async () => { vi.mock('@/features/agent-v2/permissions', () => { return { useCanManageAgents: () => - mockConsoleStateReader().workspacePermissionKeys.includes('agent.manage'), + mockConsoleStateReader().workspacePermissionKeys.includes('agent.acl.preview'), } }) @@ -41,7 +41,7 @@ type ConsoleStateFixture = { const baseContext: ConsoleStateFixture = { isLoadingCurrentWorkspace: false, isLoadingWorkspacePermissionKeys: false, - workspacePermissionKeys: ['agent.manage'], + workspacePermissionKeys: ['agent.acl.preview'], currentWorkspace: { id: 'workspace-1', }, @@ -88,7 +88,7 @@ describe('AgentsAccessGuard', () => { expect(mockReplace).not.toHaveBeenCalled() }) - it('redirects to /apps without agent.manage', async () => { + it('redirects to /apps without agent.acl.preview', async () => { setConsoleState({ workspacePermissionKeys: ['dataset.create_and_management'] }) render( @@ -103,7 +103,7 @@ describe('AgentsAccessGuard', () => { }) }) - it('renders children with agent.manage', () => { + it('renders children with agent.acl.preview', () => { render(
agents
diff --git a/web/app/(commonLayout)/datasets/layout.spec.tsx b/web/app/(commonLayout)/datasets/layout.spec.tsx index 4dc7bb758d9..5821350e393 100644 --- a/web/app/(commonLayout)/datasets/layout.spec.tsx +++ b/web/app/(commonLayout)/datasets/layout.spec.tsx @@ -26,7 +26,6 @@ vi.mock('@/context/permission-state', async () => { }) type ConsoleStateFixture = { - isCurrentWorkspaceEditor: boolean isCurrentWorkspaceDatasetOperator: boolean isLoadingCurrentWorkspace: boolean isLoadingWorkspacePermissionKeys: boolean @@ -37,7 +36,6 @@ type ConsoleStateFixture = { } const baseContext: ConsoleStateFixture = { - isCurrentWorkspaceEditor: true, isCurrentWorkspaceDatasetOperator: false, isLoadingCurrentWorkspace: false, isLoadingWorkspacePermissionKeys: false, @@ -97,7 +95,6 @@ describe('DatasetsLayout', () => { it('should render children without a page-level dataset permission', () => { setConsoleState({ - isCurrentWorkspaceEditor: true, isCurrentWorkspaceDatasetOperator: true, workspacePermissionKeys: ['dataset.create_and_management', 'dataset.external.connect'], }) @@ -114,7 +111,6 @@ describe('DatasetsLayout', () => { it('should render children on the dataset list route without dataset permissions', () => { setConsoleState({ - isCurrentWorkspaceEditor: false, isCurrentWorkspaceDatasetOperator: false, workspacePermissionKeys: [], }) diff --git a/web/app/(commonLayout)/external-service-sync.tsx b/web/app/(commonLayout)/external-service-sync.tsx index 4e27aba7551..6316fa41437 100644 --- a/web/app/(commonLayout)/external-service-sync.tsx +++ b/web/app/(commonLayout)/external-service-sync.tsx @@ -20,7 +20,7 @@ import { getLangGeniusVersionInfo } from '@/context/app-context-normalizers' import { currentWorkspaceAtom } from '@/context/workspace-state' import { userProfileQueryOptions } from '@/features/account-profile/client' import { systemFeaturesQueryOptions } from '@/features/system-features/client' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' type AmplitudeProperties = Record @@ -133,6 +133,20 @@ function ZendeskConversationSync() { deploymentEdition: data.deployment_edition, }), }) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: systemFeatures.deploymentEdition === 'CLOUD' && Boolean(ZENDESK_FIELD_IDS.PLAN), + select: (data) => data.billing.subscription.plan, + }), + ) + useEffect(() => { + if (systemFeatures.deploymentEdition !== 'CLOUD' || !plan || !ZENDESK_FIELD_IDS.PLAN) return + zendeskRuntime.setConversationFields( + [{ id: ZENDESK_FIELD_IDS.PLAN, value: `${plan}-plan` }], + systemFeatures.deploymentEdition, + ) + }, [plan, systemFeatures.deploymentEdition]) + const currentWorkspace = useAtomValue(currentWorkspaceAtom) const { data: versionData } = useQuery( consoleQuery.version.get.queryOptions({ diff --git a/web/app/(commonLayout)/hydration-boundary.tsx b/web/app/(commonLayout)/hydration-boundary.tsx index b7da5353bbe..dcd8c05ed0e 100644 --- a/web/app/(commonLayout)/hydration-boundary.tsx +++ b/web/app/(commonLayout)/hydration-boundary.tsx @@ -4,11 +4,8 @@ import { getQueryClient } from '@/app/get-query-client' import { serverUserProfileQueryOptions } from '@/features/account-profile/server' import { headers } from '@/next/headers' import { redirect } from '@/next/navigation' -import { - getServerConsoleClientContext, - resolveServerConsoleApiUrl, - serverConsoleQuery, -} from '@/service/server' +import { consoleQuery } from '@/service/console' +import { resolveServerConsoleApiUrl } from '@/service/console/server' const CURRENT_PATHNAME_HEADER = 'x-dify-pathname' const CURRENT_SEARCH_HEADER = 'x-dify-search' @@ -60,22 +57,18 @@ export async function CommonLayoutHydrationBoundary({ children }: { children: Re if (accountProfileUrl) { try { - const context = await getServerConsoleClientContext() - await Promise.all([ queryClient.query(serverUserProfileQueryOptions()), queryClient .query( - serverConsoleQuery.workspaces.current.summary.get.queryOptions({ - context, + consoleQuery.workspaces.current.summary.get.queryOptions({ retry: false, }), ) .catch(noop), queryClient .query( - serverConsoleQuery.workspaces.current.rbac.myPermissions.get.queryOptions({ - context, + consoleQuery.workspaces.current.rbac.myPermissions.get.queryOptions({ retry: false, }), ) diff --git a/web/app/(commonLayout)/providers.tsx b/web/app/(commonLayout)/providers.tsx index f414de22036..4cfb70c1ec8 100644 --- a/web/app/(commonLayout)/providers.tsx +++ b/web/app/(commonLayout)/providers.tsx @@ -2,7 +2,6 @@ import type { ReactNode } from 'react' import { OAuthRegistrationAnalytics } from '@/app/components/oauth-registration-analytics' import { EventEmitterContextProvider } from '@/context/event-emitter-provider' import { ModalContextProvider } from '@/context/modal-context-provider' -import { ProviderContextProvider } from '@/context/provider-context-provider' import { ExternalServiceSync } from './external-service-sync' import { CommonLayoutHydrationBoundary } from './hydration-boundary' @@ -21,9 +20,7 @@ export async function ConsoleRuntimeProviders({ children }: { children: ReactNod export function ConsoleContextProviders({ children }: { children: ReactNode }) { return ( - - {children} - + {children} ) } diff --git a/web/app/__tests__/layout.spec.tsx b/web/app/__tests__/layout.spec.tsx index ca67d22f92c..cee0bd121ed 100644 --- a/web/app/__tests__/layout.spec.tsx +++ b/web/app/__tests__/layout.spec.tsx @@ -4,6 +4,8 @@ const mocks = vi.hoisted(() => ({ headers: vi.fn(async () => new Headers()), })) +vi.mock('@/service/console/server', () => ({})) + vi.mock('@/features/system-features/server', () => ({ dehydrateSystemFeatures: mocks.dehydrateSystemFeatures, getOptionalSystemFeatures: mocks.getOptionalSystemFeatures, diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsx index 2c21ef117c5..6fa3ee3d882 100644 --- a/web/app/account/(commonLayout)/account-page/index.tsx +++ b/web/app/account/(commonLayout)/account-page/index.tsx @@ -16,11 +16,10 @@ import AppIcon from '@/app/components/base/app-icon' import PremiumBadge from '@/app/components/base/premium-badge' import Collapse from '@/app/components/header/account-setting/collapse' import { validPassword } from '@/config' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' import { systemFeaturesQueryOptions } from '@/features/system-features/client' -import { consoleQuery } from '@/service/client' import { updateUserProfile } from '@/service/common' +import { consoleQuery } from '@/service/console' import DeleteAccount from '../delete-account' import AvatarWithEdit from './AvatarWithEdit' import EmailChangeModal from './email-change-modal' @@ -55,10 +54,14 @@ export default function AccountPage() { const userProfile = userProfileResp.profile const mutateUserProfile = () => queryClient.invalidateQueries({ queryKey: userProfileQueryOptions().queryKey }) - const { enableEducationPlan } = useProviderContext() + const { data: enableEducationPlan } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.education.enabled, + }), + ) const { data: isEducationAccount = false } = useQuery( consoleQuery.account.education.get.queryOptions({ - enabled: enableEducationPlan, + enabled: enableEducationPlan === true, select: ({ is_student }) => is_student ?? false, }), ) diff --git a/web/app/account/(commonLayout)/avatar.tsx b/web/app/account/(commonLayout)/avatar.tsx index dc62b7931d4..ab87124de25 100644 --- a/web/app/account/(commonLayout)/avatar.tsx +++ b/web/app/account/(commonLayout)/avatar.tsx @@ -11,10 +11,9 @@ import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useTranslation } from 'react-i18next' import { resetUser } from '@/app/components/base/amplitude/utils' import PremiumBadge from '@/app/components/base/premium-badge' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useLogout } from '@/service/use-common' export default function AppSelector() { @@ -23,10 +22,14 @@ export default function AppSelector() { // Cache is hydrated by CommonLayoutHydrationBoundary; this hits cache synchronously. const { data: userProfileResp } = useSuspenseQuery(userProfileQueryOptions()) const userProfile = userProfileResp.profile - const { enableEducationPlan } = useProviderContext() + const { data: enableEducationPlan } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.education.enabled, + }), + ) const { data: isEducationAccount = false } = useQuery( consoleQuery.account.education.get.queryOptions({ - enabled: enableEducationPlan, + enabled: enableEducationPlan === true, select: ({ is_student }) => is_student ?? false, }), ) diff --git a/web/app/account/oauth/authorize/page.tsx b/web/app/account/oauth/authorize/page.tsx index 215d9d2f5b5..7853316aa0c 100644 --- a/web/app/account/oauth/authorize/page.tsx +++ b/web/app/account/oauth/authorize/page.tsx @@ -20,7 +20,7 @@ import { isLegacyBase401, userProfileQueryOptions } from '@/features/account-pro import useDocumentTitle from '@/hooks/use-document-title' import Link from '@/next/link' import { useRouter, useSearchParams } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useLogout } from '@/service/use-common' import { buildOAuthCallbackUrl, buildReturnUrl, useSilentAuthorize } from './use-silent-authorize' diff --git a/web/app/auth/refresh/route.ts b/web/app/auth/refresh/route.ts index 698ca6df24c..350492315cd 100644 --- a/web/app/auth/refresh/route.ts +++ b/web/app/auth/refresh/route.ts @@ -1,5 +1,5 @@ import type { LoginRedirectTarget } from '@/utils/login-redirect' -import { resolveServerConsoleApiUrl } from '@/service/server' +import { resolveServerConsoleApiUrl } from '@/service/console/server' import { getServerLoginFallback, resolveLoginRedirectTarget } from '@/utils/login-redirect' import { basePath } from '@/utils/var' diff --git a/web/app/components/api-key/__tests__/api-key-modal.spec.tsx b/web/app/components/api-key/__tests__/api-key-modal.spec.tsx index 175208af370..9c033af232f 100644 --- a/web/app/components/api-key/__tests__/api-key-modal.spec.tsx +++ b/web/app/components/api-key/__tests__/api-key-modal.spec.tsx @@ -25,7 +25,7 @@ const apiMocks = vi.hoisted(() => ({ deleteEnvironment: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apps: { byResourceId: { @@ -123,7 +123,6 @@ vi.mock('@/context/workspace-state', async () => { return createWorkspaceStateModuleMock(() => ({ currentWorkspace: mockCurrentWorkspace(), isCurrentWorkspaceManager: true, - isCurrentWorkspaceEditor: true, })) }) diff --git a/web/app/components/api-key/api-key-modal.tsx b/web/app/components/api-key/api-key-modal.tsx index d3317469041..d9cabd605f2 100644 --- a/web/app/components/api-key/api-key-modal.tsx +++ b/web/app/components/api-key/api-key-modal.tsx @@ -24,7 +24,7 @@ import { useState } from 'react' import { useTranslation } from 'react-i18next' import Loading from '@/app/components/base/loading' import { currentWorkspaceAtom } from '@/context/workspace-state' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { ApiKeyTable } from './api-key-table' import { CreatedApiKeyDialog } from './created-api-key-dialog' import { DatasetScopeDialog } from './dataset-scope-dialog' diff --git a/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx b/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx index 27546c4eb51..89276d1ca51 100644 --- a/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx +++ b/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx @@ -44,9 +44,7 @@ vi.mock('@/context/permission-state', async () => { }) vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') - return createWorkspaceStateModuleMock(() => ({ - isCurrentWorkspaceEditor: false, - })) + return createWorkspaceStateModuleMock(() => ({})) }) vi.mock('@/next/navigation', () => ({ usePathname: () => mockPathname, diff --git a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts index bef3bcc1e7d..a07aae99ba1 100644 --- a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts +++ b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts @@ -1,6 +1,7 @@ import { act, renderHook } from '@testing-library/react' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' +import { getRedirection } from '@/utils/app-redirection' import { useAppInfoActions } from '../use-app-info-actions' const toastMocks = vi.hoisted(() => { @@ -16,7 +17,6 @@ const toastMocks = vi.hoisted(() => { } }) const mockReplace = vi.fn() -const mockOnPlanInfoChanged = vi.fn() const mockInvalidateQueries = vi.fn() const mockSetAppDetail = vi.fn() const mockUpdateAppInfo = vi.fn() @@ -47,10 +47,6 @@ vi.mock('@/next/navigation', () => ({ useRouter: () => ({ replace: mockReplace }), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ onPlanInfoChanged: mockOnPlanInfoChanged }), -})) - vi.mock('@/app/components/app/store', () => ({ useStore: (selector: (state: Record) => unknown) => selector({ @@ -87,6 +83,13 @@ vi.mock('@tanstack/react-query', () => ({ useSuspenseQuery: () => ({ data: { rbac_enabled: true }, }), + useMutation: ({ mutationKey }: { mutationKey: unknown }) => ({ + mutateAsync: + JSON.stringify(mutationKey) === + JSON.stringify(consoleQuery.apps.byAppId.copy.post.mutationOptions().mutationKey) + ? mockCopyApp + : mockDeleteApp, + }), useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries, setQueryData: mockSetQueryData, @@ -95,8 +98,6 @@ vi.mock('@tanstack/react-query', () => ({ vi.mock('@/service/apps', () => ({ updateAppInfo: (...args: unknown[]) => mockUpdateAppInfo(...args), - copyApp: (...args: unknown[]) => mockCopyApp(...args), - deleteApp: (...args: unknown[]) => mockDeleteApp(...args), fetchAppDetail: (...args: unknown[]) => mockFetchAppDetail(...args), })) @@ -306,29 +307,50 @@ describe('useAppInfoActions', () => { }) describe('onCopy', () => { - it('should copy app and redirect on success', async () => { - const newApp = { id: 'app-2', name: 'Copy', mode: 'chat' } - mockCopyApp.mockResolvedValue(newApp) + it.each(['completed', 'pending'] as const)( + 'should redirect only when the copy is completed (%s)', + async (status) => { + const newApp = { id: 'app-2', name: 'Copy', mode: 'chat' } + mockCopyApp.mockResolvedValue( + status === 'completed' + ? newApp + : { + id: 'import-1', + status: 'pending', + current_dsl_version: '1.0.0', + }, + ) - const { result } = renderHook(() => useAppInfoActions({})) + const { result } = renderHook(() => useAppInfoActions({})) - await act(async () => { - await result.current.onCopy({ - name: 'Copy', - icon_type: 'emoji', - icon: '🤖', - icon_background: '#fff', + await act(async () => { + await result.current.onCopy({ + name: 'Copy', + icon_type: 'emoji', + icon: '🤖', + icon_background: '#fff', + }) }) - }) - expect(mockCopyApp).toHaveBeenCalled() - expect(mockInvalidateQueries).toHaveBeenCalledTimes(3) - expect(toastMocks.call).toHaveBeenCalledWith({ - type: 'success', - message: 'app.newApp.appCreated', - }) - expect(mockOnPlanInfoChanged).toHaveBeenCalled() - }) + expect(mockCopyApp).toHaveBeenCalledWith({ + params: { app_id: 'app-1' }, + body: { name: 'Copy', icon_type: 'emoji', icon: '🤖', icon_background: '#fff' }, + }) + if (status === 'completed') { + expect(toastMocks.call).toHaveBeenCalledWith({ + type: 'success', + message: 'app.newApp.appCreated', + }) + expect(getRedirection).toHaveBeenCalledWith(newApp, mockReplace, { isRbacEnabled: true }) + } else { + expect(toastMocks.call).toHaveBeenCalledWith({ + type: 'error', + message: 'app.newApp.appCreateFailed', + }) + expect(getRedirection).not.toHaveBeenCalled() + } + }, + ) it('should notify error on copy failure', async () => { mockCopyApp.mockRejectedValue(new Error('fail')) @@ -507,12 +529,11 @@ describe('useAppInfoActions', () => { await result.current.onConfirmDelete() }) - expect(mockDeleteApp).toHaveBeenCalledWith('app-1') + expect(mockDeleteApp).toHaveBeenCalledWith({ params: { app_id: 'app-1' } }) expect(mockMarkAppDeletionStarted).toHaveBeenCalledWith('app-1') expect(mockMarkAppDeletionSucceeded).toHaveBeenCalledWith('app-1') expect(mockMarkAppDeletionFailed).not.toHaveBeenCalled() expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'app.appDeleted' }) - expect(mockInvalidateQueries).toHaveBeenCalledTimes(3) expect(mockReplace).toHaveBeenCalledWith('/apps') expect(mockSetAppDetail).toHaveBeenCalledWith() }) diff --git a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts index f0dabb42820..6936882a1b1 100644 --- a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts +++ b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts @@ -7,12 +7,11 @@ import type { DuplicateAppModalProps } from '@/app/components/app/duplicate-moda import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal' import type { App } from '@/types/app' import { toast } from '@langgenius/dify-ui/toast' -import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query' +import { useMutation, useQueryClient, useSuspenseQuery } from '@tanstack/react-query' import { useCallback, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { useStore as useAppStore } from '@/app/components/app/store' import { useExportAppDsl, useExportWorkflowAppDsl } from '@/app/components/app/use-export-app-dsl' -import { useProviderContext } from '@/context/provider-context' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { useRouter } from '@/next/navigation' import { @@ -20,8 +19,8 @@ import { markAppDeletionStarted, markAppDeletionSucceeded, } from '@/service/app-deletion' -import { copyApp, deleteApp, fetchAppDetail, updateAppInfo } from '@/service/apps' -import { consoleQuery } from '@/service/client' +import { fetchAppDetail, updateAppInfo } from '@/service/apps' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' import { getRedirection } from '@/utils/app-redirection' @@ -94,7 +93,10 @@ export function useAppInfoActions({ resetKey }: UseAppInfoActionsParams) { const { t } = useTranslation() const { replace } = useRouter() const queryClient = useQueryClient() - const { onPlanInfoChanged } = useProviderContext() + const { mutateAsync: copyApp } = useMutation( + consoleQuery.apps.byAppId.copy.post.mutationOptions(), + ) + const { mutateAsync: deleteApp } = useMutation(consoleQuery.apps.byAppId.delete.mutationOptions()) const appDetail = useAppStore((state) => state.appDetail) const setAppDetail = useAppStore((state) => state.setAppDetail) const { exportAppDsl, isExporting: isAppDslExporting } = useExportAppDsl() @@ -251,22 +253,21 @@ export function useAppInfoActions({ resetKey }: UseAppInfoActionsParams) { if (!appDetail) return try { const newApp = await copyApp({ - appID: appDetail.id, - name, - icon_type, - icon, - icon_background, - mode: appDetail.mode, + params: { app_id: appDetail.id }, + body: { name, icon_type, icon, icon_background }, }) + if (!('mode' in newApp)) { + toast( + t(($) => $['newApp.appCreateFailed'], { ns: 'app' }), + { type: 'error' }, + ) + return + } closeModal() toast( t(($) => $['newApp.appCreated'], { ns: 'app' }), { type: 'success' }, ) - void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.get.key() }) - void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.starred.get.key() }) - void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.recent.get.key() }) - onPlanInfoChanged() getRedirection(newApp, replace, { isRbacEnabled }) } catch { toast( @@ -275,7 +276,7 @@ export function useAppInfoActions({ resetKey }: UseAppInfoActionsParams) { ) } }, - [appDetail, closeModal, isRbacEnabled, onPlanInfoChanged, queryClient, replace, t], + [appDetail, closeModal, copyApp, isRbacEnabled, replace, t], ) const onExport = useCallback( @@ -313,16 +314,12 @@ export function useAppInfoActions({ resetKey }: UseAppInfoActionsParams) { if (!appDetail) return markAppDeletionStarted(appDetail.id) try { - await deleteApp(appDetail.id) + await deleteApp({ params: { app_id: appDetail.id } }) markAppDeletionSucceeded(appDetail.id) toast( t(($) => $.appDeleted, { ns: 'app' }), { type: 'success' }, ) - void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.get.key() }) - void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.starred.get.key() }) - void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.recent.get.key() }) - onPlanInfoChanged() setAppDetail() replace('/apps') } catch (e: unknown) { @@ -333,7 +330,7 @@ export function useAppInfoActions({ resetKey }: UseAppInfoActionsParams) { ) } closeModal() - }, [appDetail, closeModal, onPlanInfoChanged, queryClient, replace, setAppDetail, t]) + }, [appDetail, closeModal, deleteApp, replace, setAppDetail, t]) return { appDetail, diff --git a/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx b/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx index c581748c520..315b6adb42c 100644 --- a/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx +++ b/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx @@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({ toastPromise: vi.fn((promise: Promise) => promise), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { apps: { byAppId: { diff --git a/web/app/components/app/access-config/index.tsx b/web/app/components/app/access-config/index.tsx index 1452615d87b..79acb7e7b3c 100644 --- a/web/app/components/app/access-config/index.tsx +++ b/web/app/components/app/access-config/index.tsx @@ -202,7 +202,7 @@ const AppAccessConfigContent = ({ appId, maintainerId }: AppAccessConfigContentP {t(($) => $['accessRule.appDescription'], { ns: 'permission' })}

-
+
-
+ ) } diff --git a/web/app/components/app/access-point/__tests__/api-secret-key-button.spec.tsx b/web/app/components/app/access-point/__tests__/api-secret-key-button.spec.tsx index 6a70fe9e4c0..a26df699c62 100644 --- a/web/app/components/app/access-point/__tests__/api-secret-key-button.spec.tsx +++ b/web/app/components/app/access-point/__tests__/api-secret-key-button.spec.tsx @@ -1,7 +1,7 @@ import type { ReactElement } from 'react' import { screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { ApiSecretKeyButton } from '../shared/api-secret-key-button' diff --git a/web/app/components/app/access-point/__tests__/environment-access-control.spec.tsx b/web/app/components/app/access-point/__tests__/environment-access-control.spec.tsx index 8c805d69980..a3e5376086b 100644 --- a/web/app/components/app/access-point/__tests__/environment-access-control.spec.tsx +++ b/web/app/components/app/access-point/__tests__/environment-access-control.spec.tsx @@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({ updateAccessMode: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { enterprise: { appDeploy: { diff --git a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx index 8a9f11c2444..210dd6b189a 100644 --- a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx +++ b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx @@ -19,65 +19,6 @@ const mocks = vi.hoisted(() => ({ apiKeyButtonProps: vi.fn(), })) -vi.mock('@/service/client', () => ({ - consoleQuery: { - enterprise: { - appDeploy: { - accessService: { - getEnvironmentApi: { - queryOptions: ({ - input, - }: { - input: { params: { app_id: string; environment_id: string } } - }) => ({ - queryKey: ['environment-api', input.params.app_id, input.params.environment_id], - queryFn: () => mocks.getApi(input), - }), - }, - getEnvironmentSite: { - queryOptions: ({ - input, - }: { - input: { params: { app_id: string; environment_id: string } } - }) => ({ - queryKey: ['environment-site', input.params.app_id, input.params.environment_id], - queryFn: () => mocks.getSite(input), - }), - }, - getEnvironmentWebAppSubjects: { - queryOptions: ({ - input, - }: { - input: { params: { app_id: string; environment_id: string } } - }) => ({ - queryKey: ['environment-subjects', input.params.app_id, input.params.environment_id], - queryFn: () => mocks.getSubjects(input), - }), - }, - resetEnvironmentSiteAccessToken: { - mutationOptions: (options = {}) => ({ - mutationFn: mocks.resetSite, - ...options, - }), - }, - updateEnvironmentApi: { - mutationOptions: (options = {}) => ({ - mutationFn: mocks.updateApi, - ...options, - }), - }, - updateEnvironmentSite: { - mutationOptions: (options = {}) => ({ - mutationFn: mocks.updateSite, - ...options, - }), - }, - }, - }, - }, - }, -})) - vi.mock('@/features/system-features/client', () => ({ systemFeaturesQueryOptions: () => ({ queryKey: ['system-features'], @@ -189,8 +130,7 @@ const api = { enabled: true, } -function renderCard(ui: ReactElement) { - const queryClient = createTestQueryClient() +function renderCard(ui: ReactElement, queryClient = createTestQueryClient()) { queryClient.setQueryData(['system-features'], { webapp_auth: { enabled: true, @@ -211,9 +151,46 @@ function createDeferredPromise() { return { promise, reject, resolve } } +// Keep HTTP mocked through Testing Library's asynchronous cleanup. +afterAll(() => vi.unstubAllGlobals()) + describe('environment access point cards', () => { beforeEach(() => { vi.clearAllMocks() + mockAppMode = 'workflow' + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + const path = new URL(request.url).pathname + const match = /\/enterprise\/app-deploy\/apps\/([^/]+)\/environments\/([^/]+)\/(.+)$/.exec( + path, + ) + if (!match) throw new Error(`Unexpected request: ${request.method} ${path}`) + const params = { app_id: match[1], environment_id: match[2] } + let data: unknown + switch (`${request.method} ${match[3]}`) { + case 'GET api': + data = await mocks.getApi({ params }) + break + case 'GET site': + data = await mocks.getSite({ params }) + break + case 'GET webapp/subjects': + data = await mocks.getSubjects({ params }) + break + case 'POST site/access-token-reset': + data = await mocks.resetSite({ params }) + break + case 'PATCH api': + data = await mocks.updateApi({ params, body: await request.json() }) + break + case 'PATCH site': + data = await mocks.updateSite({ params, body: await request.json() }) + break + default: + throw new Error(`Unexpected request: ${request.method} ${path}`) + } + return Response.json(data) + }) mocks.getApi.mockResolvedValue(api) mocks.getSite.mockResolvedValue(site) mocks.getSubjects.mockResolvedValue({ @@ -243,6 +220,45 @@ describe('environment access point cards', () => { }) }) + it.each(['site', 'api'] as const)( + 'keeps the saved %s status when reopening an environment without changing another environment', + async (target) => { + const user = userEvent.setup() + const queryClient = createTestQueryClient() + const card = (environmentId: string) => + target === 'site' ? ( + + ) : ( + + ) + + const staging = renderCard(card('staging'), queryClient) + const toggle = await screen.findByRole('switch') + expect(toggle).toHaveAttribute('aria-checked', 'true') + await user.click(toggle) + await waitFor(() => + expect(target === 'site' ? mocks.updateSite : mocks.updateApi).toHaveBeenCalled(), + ) + staging.unmount() + + const production = renderCard(card('production'), queryClient) + expect(await screen.findByRole('switch')).toHaveAttribute('aria-checked', 'true') + production.unmount() + + renderCard(card('staging'), queryClient) + expect(await screen.findByRole('switch')).toHaveAttribute('aria-checked', 'false') + }, + ) + it('sends a chatflow app to the chat web app shell', async () => { mockAppMode = 'advanced-chat' @@ -258,8 +274,6 @@ describe('environment access point cards', () => { expect(await screen.findByText(/environment\/chat\/site-code/)).toHaveTextContent( 'https://site.example.test/environment/chat/site-code', ) - - mockAppMode = 'workflow' }) it('renders the real environment Web app URL and workflow actions without Embed', async () => { @@ -281,7 +295,9 @@ describe('environment access point cards', () => { }), ).toBeEnabled() expect(screen.queryByRole('button', { name: /embedIntoSite/ })).not.toBeInTheDocument() - expect(screen.getByRole('button', { name: /customize\.entry/ })).toBeEnabled() + await waitFor(() => + expect(screen.getByRole('button', { name: /customize\.entry/ })).toBeEnabled(), + ) expect(screen.getByRole('button', { name: /settings\.settings/ })).toBeEnabled() }) @@ -307,8 +323,9 @@ describe('environment access point cards', () => { ).toBeEnabled() }) - it('shows the environment Web app query as loading instead of failed', () => { - mocks.getSite.mockImplementation(() => new Promise(() => {})) + it('shows loading until the environment Web app becomes available', async () => { + const pending = createDeferredPromise() + mocks.getSite.mockReturnValue(pending.promise) renderCard( { expect( screen.queryByText('deployments.health.ENVIRONMENT_STATUS_FAILED'), ).not.toBeInTheDocument() + pending.resolve(site) + expect(await screen.findByRole('link', { name: /studio\.accessPoint\.open/ })).toBeEnabled() + expect(card).not.toHaveAttribute('aria-busy', 'true') }) it('does not announce the access control placeholder as loading after the Site query fails', async () => { @@ -446,6 +466,9 @@ describe('environment access point cards', () => { ) await screen.findByText(/environment\/workflow\/site-code/) + await waitFor(() => + expect(screen.getByRole('button', { name: /customize\.entry/ })).toBeEnabled(), + ) await user.click(screen.getByRole('button', { name: /customize\.entry/ })) expect(screen.getByRole('dialog', { name: 'environment customize' })).toHaveTextContent( 'https://api.example.test/v1', @@ -487,7 +510,9 @@ describe('environment access point cards', () => { expect(await screen.findByRole('switch')).toBeEnabled() expect(screen.getByRole('button', { name: /regenerate/ })).toBeEnabled() - expect(screen.getByRole('button', { name: /customize\.entry/ })).toBeEnabled() + await waitFor(() => + expect(screen.getByRole('button', { name: /customize\.entry/ })).toBeEnabled(), + ) expect(screen.getByRole('button', { name: /settings\.settings/ })).toBeEnabled() expect( screen.getByRole('button', { name: /accessControlDialog\.accessItems\.specific/ }), diff --git a/web/app/components/app/access-point/__tests__/index.spec.tsx b/web/app/components/app/access-point/__tests__/index.spec.tsx index 493216c0316..ee234efb99f 100644 --- a/web/app/components/app/access-point/__tests__/index.spec.tsx +++ b/web/app/components/app/access-point/__tests__/index.spec.tsx @@ -5,7 +5,7 @@ import { EnvironmentStatus } from '@dify/contracts/enterprise-app-deploy/types.g import { screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { NuqsTestingAdapter } from 'nuqs/adapters/testing' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { seedAccountProfileQuery } from '@/test/console/account-profile' import { QueryClientTestProvider } from '@/test/console/query-provider' import { render } from '@/test/console/render' diff --git a/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx b/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx index 1f96c4a5429..2e47e1084bd 100644 --- a/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx +++ b/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx @@ -27,7 +27,7 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ }, })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apps: { byAppId: { diff --git a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx index 3fac29c2f3d..f317ef8880a 100644 --- a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx +++ b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx @@ -21,7 +21,7 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ }, })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apps: { byAppId: { diff --git a/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx b/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx index aeac874d8ba..c07e7592f70 100644 --- a/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx +++ b/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx @@ -39,7 +39,7 @@ vi.mock('@/context/i18n', () => ({ useDocLink: () => (path: string) => `https://docs.example.test/en${path}`, })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apps: { byAppId: { diff --git a/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.ts b/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.ts index 3d192055cce..b0b169bbc0b 100644 --- a/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.ts +++ b/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.ts @@ -23,7 +23,7 @@ vi.mock('@/service/apps', () => ({ updateAppSiteConfig: mocks.updateAppSiteConfig, })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apps: { get: { key: () => ['apps'] }, diff --git a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx index aa96922b3d6..4115a40e206 100644 --- a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx +++ b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx @@ -25,7 +25,7 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ }, })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apps: { byAppId: { diff --git a/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx b/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx index a3cd201d887..eff1bf597fe 100644 --- a/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx +++ b/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx @@ -19,7 +19,7 @@ import { AccessPointCard } from '@/app/components/base/access-point/card' import { AccessPointUrl } from '@/app/components/base/access-point/url' import MCPServerModal from '@/app/components/tools/mcp/mcp-server-modal' import { BlockEnum } from '@/app/components/workflow/types' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useInvalidateMCPServerDetail, useMCPServerDetail, diff --git a/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx b/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx index fb47f578ea3..09f1506ce88 100644 --- a/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx +++ b/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx @@ -7,7 +7,7 @@ import { useMutation } from '@tanstack/react-query' import { useTranslation } from 'react-i18next' import { useStore as useAppStore } from '@/app/components/app/store' import { getAccessPointStatus } from '@/app/components/base/access-point/status' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { ServiceApiCardView } from '../shared/service-api-card-view' import { getBuiltInAccessUrls } from '../shared/utils' diff --git a/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx b/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx index ad57d3252fe..a5850a1f8ca 100644 --- a/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx +++ b/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx @@ -15,7 +15,7 @@ import { useTriggerStatusStore } from '@/app/components/workflow/store/trigger-s import { BlockEnum } from '@/app/components/workflow/types' import { useDocLink } from '@/context/i18n' import Link from '@/next/link' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useAppTriggers, useInvalidateAppTriggers } from '@/service/use-tools' import { useAllTriggerPlugins } from '@/service/use-triggers' import { canFindTool } from '@/utils' diff --git a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx index 787db1dc263..6f7e09de87c 100644 --- a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx +++ b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx @@ -30,7 +30,7 @@ import { AccessPointUrl } from '@/app/components/base/access-point/url' import AppIcon from '@/app/components/base/app-icon' import { AccessMode } from '@/models/access-control' import { useAppWhiteListSubjects } from '@/service/access-control/use-app-access-control' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label' import { getBuiltInAccessUrls, getHiddenStartInputs } from '../shared/utils' diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx b/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx index 64637ef4afd..3213bcb5afc 100644 --- a/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx +++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx @@ -13,7 +13,7 @@ import { useTranslation } from 'react-i18next' import { AccessControlForm } from '@/app/components/app/app-access-control/access-control-form' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { AccessMode, SubjectType } from '@/models/access-control' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' const EMPTY_SUBJECTS: AccessControlSubjects = { groups: [], diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx b/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx index 9641b96b81a..bcc25889b07 100644 --- a/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx +++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx @@ -4,7 +4,7 @@ import { toast } from '@langgenius/dify-ui/toast' import { useMutation, useQuery } from '@tanstack/react-query' import { useTranslation } from 'react-i18next' import { useStore as useAppStore } from '@/app/components/app/store' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { ServiceApiCardView } from '../shared/service-api-card-view' type EnvironmentServiceApiCardProps = { diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx index cf6651a67ab..0e8ce4ca6e6 100644 --- a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx +++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx @@ -23,7 +23,7 @@ import { AccessPointUrl } from '@/app/components/base/access-point/url' import AppIcon from '@/app/components/base/app-icon' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { AccessMode, isAccessMode } from '@/models/access-control' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useAccessPointActions } from '../shared/use-access-point-actions' import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label' import { diff --git a/web/app/components/app/access-point/index.tsx b/web/app/components/app/access-point/index.tsx index cda649d7c58..6aa7750dc16 100644 --- a/web/app/components/app/access-point/index.tsx +++ b/web/app/components/app/access-point/index.tsx @@ -67,7 +67,7 @@ function AccessPointContent({ environment === selectedEnvironment ? highlightedAccessPoint : null return ( -
+
@@ -145,7 +145,7 @@ function AccessPointContent({ -
+ ) } diff --git a/web/app/components/app/access-point/shared/api-secret-key-button.tsx b/web/app/components/app/access-point/shared/api-secret-key-button.tsx index c640e5ca51d..2341797888e 100644 --- a/web/app/components/app/access-point/shared/api-secret-key-button.tsx +++ b/web/app/components/app/access-point/shared/api-secret-key-button.tsx @@ -6,7 +6,7 @@ import { skipToken, useQuery } from '@tanstack/react-query' import { useState } from 'react' import { useTranslation } from 'react-i18next' import { ApiKeyModal } from '@/app/components/api-key/api-key-modal' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' type ApiSecretKeyButtonProps = { appId: string diff --git a/web/app/components/app/access-point/shared/use-access-point-actions.ts b/web/app/components/app/access-point/shared/use-access-point-actions.ts index c82373dea0b..eb82d3d5743 100644 --- a/web/app/components/app/access-point/shared/use-access-point-actions.ts +++ b/web/app/components/app/access-point/shared/use-access-point-actions.ts @@ -9,7 +9,7 @@ import { useCallback } from 'react' import { useTranslation } from 'react-i18next' import { useStore as useAppStore } from '@/app/components/app/store' import { fetchAppDetail, updateAppSiteConfig } from '@/service/apps' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { asyncRunSafe } from '@/utils' export function useAccessPointActions(appId: string, canManageAccessPoint: boolean) { diff --git a/web/app/components/app/access-point/state.ts b/web/app/components/app/access-point/state.ts index e83e759b670..410c7c4d761 100644 --- a/web/app/components/app/access-point/state.ts +++ b/web/app/components/app/access-point/state.ts @@ -5,7 +5,7 @@ import { skipToken } from '@tanstack/react-query' import { atom } from 'jotai' import { atomWithQuery } from 'jotai-tanstack-query' import { selectAtom, useHydrateAtoms } from 'jotai/utils' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' export const BUILT_IN_ENVIRONMENT_ID = 'built-in' diff --git a/web/app/components/app/annotation/__tests__/index.spec.tsx b/web/app/components/app/annotation/__tests__/index.spec.tsx index 54b3dda2075..2f69bf83d7a 100644 --- a/web/app/components/app/annotation/__tests__/index.spec.tsx +++ b/web/app/components/app/annotation/__tests__/index.spec.tsx @@ -1,11 +1,10 @@ -/* oxlint-disable typescript/no-explicit-any */ +import type { ReactElement } from 'react' import type { Mock } from 'vite-plus/test' import type { AnnotationItem } from '../type' import type { App } from '@/types/app' import { toast } from '@langgenius/dify-ui/toast' -import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, fireEvent, screen, waitFor } from '@testing-library/react' import * as React from 'react' -import { useProviderContext } from '@/context/provider-context' import { addAnnotation, delAnnotation, @@ -17,10 +16,14 @@ import { updateAnnotationScore, updateAnnotationStatus, } from '@/service/annotation' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { AppModeEnum } from '@/types/app' import Annotation from '../index' import { AnnotationEnableStatus, JobStatus } from '../type' +let annotationQuota = { size: 0, limit: 10 } +/* oxlint-disable typescript/no-explicit-any */ + vi.mock('@/context/i18n', () => ({ useDocLink: () => (path: string) => `https://docs.example.com${path}`, })) @@ -41,10 +44,6 @@ vi.mock('@/service/annotation', () => ({ updateAnnotationStatus: vi.fn(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: vi.fn(), -})) - vi.mock('../filter', () => ({ default: ({ children }: { children: React.ReactNode }) => (
{children}
@@ -180,7 +179,6 @@ const fetchAnnotationListMock = fetchAnnotationList as Mock const queryAnnotationJobStatusMock = queryAnnotationJobStatus as Mock const updateAnnotationScoreMock = updateAnnotationScore as Mock const updateAnnotationStatusMock = updateAnnotationStatus as Mock -const useProviderContextMock = useProviderContext as Mock const appDetail = { id: 'app-id', @@ -197,6 +195,13 @@ const createAnnotation = (overrides: Partial = {}): AnnotationIt const renderComponent = () => render() +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { annotation_quota_limit: annotationQuota }, + }) +} + describe('Annotation', () => { beforeEach(() => { vi.clearAllMocks() @@ -215,13 +220,7 @@ describe('Annotation', () => { updateAnnotationStatusMock.mockResolvedValue({ job_id: 'job-1' }) updateAnnotationScoreMock.mockResolvedValue(undefined) editAnnotationMock.mockResolvedValue(undefined) - useProviderContextMock.mockReturnValue({ - plan: { - usage: { annotatedResponse: 0 }, - total: { annotatedResponse: 10 }, - }, - enableBilling: false, - }) + annotationQuota = { size: 0, limit: 10 } }) it('should render empty element when no annotations are returned', async () => { @@ -338,13 +337,7 @@ describe('Annotation', () => { }) it('should show the annotation-full modal when enabling annotations exceeds the plan quota', async () => { - useProviderContextMock.mockReturnValue({ - plan: { - usage: { annotatedResponse: 10 }, - total: { annotatedResponse: 10 }, - }, - enableBilling: true, - }) + annotationQuota = { size: 10, limit: 10 } renderComponent() diff --git a/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx index 7129cfcf885..dfade0ee399 100644 --- a/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx +++ b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx @@ -1,13 +1,9 @@ -import type { Mock } from 'vite-plus/test' -import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import type { ReactElement } from 'react' +import { act, fireEvent, screen, waitFor } from '@testing-library/react' import * as React from 'react' -import { useProviderContext } from '@/context/provider-context' +import { renderWithConsoleQuery } from '@/test/console/query-data' import AddAnnotationModal from '../index' -vi.mock('@/context/provider-context', () => ({ - useProviderContext: vi.fn(), -})) - const mockToastNotify = vi.fn() vi.mock('@langgenius/dify-ui/toast', () => ({ default: { @@ -25,15 +21,14 @@ vi.mock('@/app/components/billing/annotation-full', () => ({ default: () =>
, })) -const mockUseProviderContext = useProviderContext as Mock +let annotationQuota = { size: 0, limit: 10 } -const getProviderContext = ({ usage = 0, total = 10, enableBilling = false } = {}) => ({ - plan: { - usage: { annotatedResponse: usage }, - total: { annotatedResponse: total }, - }, - enableBilling, -}) +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { annotation_quota_limit: annotationQuota }, + }) +} describe('AddAnnotationModal', () => { const baseProps = { @@ -44,7 +39,7 @@ describe('AddAnnotationModal', () => { beforeEach(() => { vi.clearAllMocks() - mockUseProviderContext.mockReturnValue(getProviderContext()) + annotationQuota = { size: 0, limit: 10 } }) const typeQuestion = (value: string) => { @@ -82,9 +77,7 @@ describe('AddAnnotationModal', () => { }) it('should show annotation full notice and disable submit when quota exceeded', () => { - mockUseProviderContext.mockReturnValue( - getProviderContext({ usage: 10, total: 10, enableBilling: true }), - ) + annotationQuota = { size: 10, limit: 10 } render() expect(screen.getByTestId('annotation-full')).toBeInTheDocument() diff --git a/web/app/components/app/annotation/add-annotation-modal/index.tsx b/web/app/components/app/annotation/add-annotation-modal/index.tsx index 69e16fe405d..f42400f84d0 100644 --- a/web/app/components/app/annotation/add-annotation-modal/index.tsx +++ b/web/app/components/app/annotation/add-annotation-modal/index.tsx @@ -14,11 +14,14 @@ import { DrawerViewport, } from '@langgenius/dify-ui/drawer' import { toast } from '@langgenius/dify-ui/toast' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useState } from 'react' import { useTranslation } from 'react-i18next' import AnnotationFull from '@/app/components/billing/annotation-full' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' +import { consoleQuery } from '@/service/console' import EditItem, { EditItemType } from './edit-item' type Props = Readonly<{ @@ -29,9 +32,21 @@ type Props = Readonly<{ const AddAnnotationModal: FC = ({ isShow, onHide, onAdd }) => { const { t } = useTranslation() - const { plan, enableBilling } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: annotationQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.annotation_quota_limit, + }), + ) + const isAnnotationQuotaUnavailable = + deploymentEdition === 'CLOUD' && annotationQuota === undefined + // A limit of 0 means unlimited. const isAnnotationFull = - enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse + deploymentEdition === 'CLOUD' && + annotationQuota !== undefined && + annotationQuota.limit > 0 && + annotationQuota.size >= annotationQuota.limit const [question, setQuestion] = useState('') const [answer, setAnswer] = useState('') const [isCreateNext, setIsCreateNext] = useState(false) @@ -46,6 +61,7 @@ const AddAnnotationModal: FC = ({ isShow, onHide, onAdd }) => { } const handleSave = async () => { + if (isAnnotationQuotaUnavailable || isAnnotationFull) return const payload = { question, answer, @@ -123,7 +139,7 @@ const AddAnnotationModal: FC = ({ isShow, onHide, onAdd }) => { variant="primary" onClick={handleSave} loading={isSaving} - disabled={isAnnotationFull} + disabled={isAnnotationQuotaUnavailable || isAnnotationFull} > {t(($) => $['operation.add'], { ns: 'common' })} diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx index 521e54a1ed2..7ecd4160d62 100644 --- a/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx +++ b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx @@ -1,20 +1,19 @@ +import type { ReactElement } from 'react' import type { Mock } from 'vite-plus/test' import type { IBatchModalProps } from '../index' -import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, fireEvent, screen, waitFor } from '@testing-library/react' import * as React from 'react' -import { useProviderContext } from '@/context/provider-context' import { annotationBatchImport, checkAnnotationBatchImportProgress } from '@/service/annotation' +import { renderWithConsoleQuery } from '@/test/console/query-data' import BatchModal, { ProcessStatus } from '../index' +let annotationQuota = { size: 0, limit: 10 } + vi.mock('@/service/annotation', () => ({ annotationBatchImport: vi.fn(), checkAnnotationBatchImportProgress: vi.fn(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: vi.fn(), -})) - vi.mock('../csv-downloader', () => ({ default: () =>
, })) @@ -54,7 +53,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ info: (message: string) => mockNotify({ type: 'info', message }), }, })) -const useProviderContextMock = useProviderContext as Mock const annotationBatchImportMock = annotationBatchImport as Mock const checkAnnotationBatchImportProgressMock = checkAnnotationBatchImportProgress as Mock @@ -72,27 +70,22 @@ const renderComponent = (props: Partial = {}) => { } } +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { annotation_quota_limit: annotationQuota }, + }) +} + describe('BatchModal', () => { beforeEach(() => { vi.clearAllMocks() lastUploadedFile = undefined - useProviderContextMock.mockReturnValue({ - plan: { - usage: { annotatedResponse: 0 }, - total: { annotatedResponse: 10 }, - }, - enableBilling: false, - }) + annotationQuota = { size: 0, limit: 10 } }) it('should disable run action and show billing hint when annotation quota is full', () => { - useProviderContextMock.mockReturnValue({ - plan: { - usage: { annotatedResponse: 10 }, - total: { annotatedResponse: 10 }, - }, - enableBilling: true, - }) + annotationQuota = { size: 10, limit: 10 } renderComponent() diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx index 7127758e761..ff4d2ba0242 100644 --- a/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx +++ b/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx @@ -4,12 +4,15 @@ import { Button } from '@langgenius/dify-ui/button' import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog' import { toast } from '@langgenius/dify-ui/toast' import { RiCloseLine } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import AnnotationFull from '@/app/components/billing/annotation-full' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' import { annotationBatchImport, checkAnnotationBatchImportProgress } from '@/service/annotation' +import { consoleQuery } from '@/service/console' import CSVDownloader from './csv-downloader' import CSVUploader from './csv-uploader' @@ -29,9 +32,21 @@ export type IBatchModalProps = { const BatchModal: FC = ({ appId, isShow, onCancel, onAdded }) => { const { t } = useTranslation() - const { plan, enableBilling } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: annotationQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.annotation_quota_limit, + }), + ) + const isAnnotationQuotaUnavailable = + deploymentEdition === 'CLOUD' && annotationQuota === undefined + // A limit of 0 means unlimited. const isAnnotationFull = - enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse + deploymentEdition === 'CLOUD' && + annotationQuota !== undefined && + annotationQuota.limit > 0 && + annotationQuota.size >= annotationQuota.limit const [currentCSV, setCurrentCSV] = useState() const handleFile = (file?: File) => setCurrentCSV(file) @@ -112,7 +127,7 @@ const BatchModal: FC = ({ appId, isShow, onCancel, onAdded })
- {isAnnotationFull && ( -
- +
+
setShowModal(true)} + > + +
{t(($) => $['editModal.removeThisCache'], { ns: 'appAnnotation' })}
- )} - - {annotationId ? ( -
-
setShowModal(true)} - > - -
- {t(($) => $['editModal.removeThisCache'], { ns: 'appAnnotation' })} -
+ {!!createdAt && ( +
+ {t(($) => $['editModal.createdAt'], { ns: 'appAnnotation' })} +   + {formatTime( + createdAt, + t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, + )}
- {!!createdAt && ( -
- {t(($) => $['editModal.createdAt'], { ns: 'appAnnotation' })} -   - {formatTime( - createdAt, - t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, - )} -
- )} -
- ) : undefined} + )} +
diff --git a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx index 723399f2177..6435c5d343f 100644 --- a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx +++ b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx @@ -1,15 +1,17 @@ -/* oxlint-disable typescript/no-explicit-any */ import type { ComponentProps } from 'react' import type { Mock } from 'vite-plus/test' import type { AnnotationItemBasic } from '../../type' import type { Locale } from '@/i18n-config' -import { act, render, screen, waitFor } from '@testing-library/react' +import { act, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useLocale } from '@/context/i18n' import { LanguagesSupported } from '@/i18n-config/language' import { clearAllAnnotations, fetchExportAnnotationList } from '@/service/annotation' +import { renderWithConsoleQuery as render } from '@/test/console/query-data' import HeaderOptions from '../index' +/* oxlint-disable typescript/no-explicit-any */ + const mockJsonToCSV = vi.fn((_: unknown) => 'csv-content') const mockCSVDownloader = vi.fn(({ children }) => <>{children}) @@ -26,16 +28,6 @@ vi.mock('@/service/annotation', () => ({ clearAllAnnotations: vi.fn(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - plan: { - usage: { annotatedResponse: 0 }, - total: { annotatedResponse: 10 }, - }, - enableBilling: false, - }), -})) - vi.mock('@/app/components/billing/annotation-full', () => ({ default: () =>
, })) diff --git a/web/app/components/app/annotation/index.tsx b/web/app/components/app/annotation/index.tsx index b50c9db10cf..6a3297f7b2a 100644 --- a/web/app/components/app/annotation/index.tsx +++ b/web/app/components/app/annotation/index.tsx @@ -10,7 +10,9 @@ import { Pagination } from '@langgenius/dify-ui/pagination' import { Switch } from '@langgenius/dify-ui/switch' import { toast } from '@langgenius/dify-ui/toast' import { RiEqualizer2Line } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' import { useDebounce } from 'ahooks' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' @@ -20,7 +22,7 @@ import Loading from '@/app/components/base/loading' import AnnotationFullModal from '@/app/components/billing/annotation-full/modal' import { APP_PAGE_LIMIT } from '@/config' import { useDocLink } from '@/context/i18n' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' import { addAnnotation, delAnnotation, @@ -32,6 +34,7 @@ import { updateAnnotationScore, updateAnnotationStatus, } from '@/service/annotation' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' import { sleep } from '@/utils' import PageTitle from '../log-annotation/page-title' @@ -54,9 +57,21 @@ const Annotation: FC = (props) => { const [annotationConfig, setAnnotationConfig] = useState(null) const [isChatApp] = useState(appDetail.mode !== AppModeEnum.COMPLETION) const [controlRefreshSwitch, setControlRefreshSwitch] = useState(() => Date.now()) - const { plan, enableBilling } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: annotationQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.annotation_quota_limit, + }), + ) + const isAnnotationQuotaUnavailable = + deploymentEdition === 'CLOUD' && annotationQuota === undefined + // A limit of 0 means unlimited. const isAnnotationFull = - enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse + deploymentEdition === 'CLOUD' && + annotationQuota !== undefined && + annotationQuota.limit > 0 && + annotationQuota.size >= annotationQuota.limit const [isShowAnnotationFullModal, setIsShowAnnotationFullModal] = useState(false) const [queryParams, setQueryParams] = useState({}) const [currPage, setCurrPage] = useState(0) @@ -177,9 +192,11 @@ const Annotation: FC = (props) => { { if (value) { + if (isAnnotationQuotaUnavailable) return if (isAnnotationFull) { setIsShowAnnotationFullModal(true) setControlRefreshSwitch(Date.now()) diff --git a/web/app/components/app/app-access-control/__tests__/index.spec.tsx b/web/app/components/app/app-access-control/__tests__/index.spec.tsx index 4a3463896f0..5e41e3cd594 100644 --- a/web/app/components/app/app-access-control/__tests__/index.spec.tsx +++ b/web/app/components/app/app-access-control/__tests__/index.spec.tsx @@ -32,7 +32,7 @@ vi.mock('@/service/access-control', () => ({ mockUseSearchForWhiteListCandidates(...args), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { systemFeatures: { get: { diff --git a/web/app/components/app/app-access-control/index.tsx b/web/app/components/app/app-access-control/index.tsx index 24b1fe341da..b6fddfe41d4 100644 --- a/web/app/components/app/app-access-control/index.tsx +++ b/web/app/components/app/app-access-control/index.tsx @@ -13,7 +13,7 @@ import { useTranslation } from 'react-i18next' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { AccessMode, isAccessMode, SubjectType } from '@/models/access-control' import { useAppWhiteListSubjects } from '@/service/access-control' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { AccessControlForm } from './access-control-form' const EMPTY_SUBJECTS: AccessControlSubjects = { diff --git a/web/app/components/app/app-publisher/__tests__/environment-deployment-flow.spec.tsx b/web/app/components/app/app-publisher/__tests__/environment-deployment-flow.spec.tsx index e151473db72..96642b8c1fe 100644 --- a/web/app/components/app/app-publisher/__tests__/environment-deployment-flow.spec.tsx +++ b/web/app/components/app/app-publisher/__tests__/environment-deployment-flow.spec.tsx @@ -14,7 +14,7 @@ import userEvent from '@testing-library/user-event' import { createStore, Provider, useAtomValue, useSetAtom } from 'jotai' import { queryClientAtom } from 'jotai-tanstack-query' import { useEffect } from 'react' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, renderWithConsoleQuery as render, diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsx index bb9766c54fd..e174dc0674e 100644 --- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx +++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx @@ -5,7 +5,7 @@ import userEvent from '@testing-library/user-event' import * as React from 'react' import { WorkflowContext } from '@/app/components/workflow/context' import { AccessMode } from '@/models/access-control' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { appWorkflowVersionsInfiniteQueryOptions } from '@/service/workflow-queries' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { AppModeEnum } from '@/types/app' @@ -149,7 +149,6 @@ vi.mock('@/service/use-tools', () => ({ vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') return createWorkspaceStateModuleMock(() => ({ - isCurrentWorkspaceEditor: false, isCurrentWorkspaceManager: true, workspacePermissionKeys: mockWorkspacePermissionKeys, })) diff --git a/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx b/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx index ab987936659..3832523e919 100644 --- a/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx +++ b/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx @@ -2,9 +2,10 @@ import { fireEvent, render, screen } from '@testing-library/react' import * as React from 'react' import PublishWithMultipleModel from '../publish-with-multiple-model' -const mockUseProviderContext = vi.fn() -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockUseProviderContext(), +const mockModelListQuery = vi.fn() +vi.mock('@tanstack/react-query', async (importOriginal) => ({ + ...(await importOriginal()), + useQuery: () => mockModelListQuery(), })) vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ @@ -18,8 +19,8 @@ vi.mock('../../header/account-setting/model-provider-page/model-icon', () => ({ describe('PublishWithMultipleModel', () => { beforeEach(() => { vi.clearAllMocks() - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [ + mockModelListQuery.mockReturnValue({ + data: [ { provider: 'openai', models: [ diff --git a/web/app/components/app/app-publisher/__tests__/state.spec.tsx b/web/app/components/app/app-publisher/__tests__/state.spec.tsx index 624205f869a..2652e4f7ebd 100644 --- a/web/app/components/app/app-publisher/__tests__/state.spec.tsx +++ b/web/app/components/app/app-publisher/__tests__/state.spec.tsx @@ -51,7 +51,7 @@ const queryMocks = vi.hoisted(() => ({ environmentRequest: vi.fn(), })) -vi.mock('@/service/client', async () => { +vi.mock('@/service/console', async () => { const { skipToken } = await import('@tanstack/react-query') return { diff --git a/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.ts b/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.ts index de262d0263d..e8cf084b3f6 100644 --- a/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.ts +++ b/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.ts @@ -5,7 +5,7 @@ import { useQueryClient } from '@tanstack/react-query' import { useAtomValue, useSetAtom } from 'jotai' import { useEffect, useRef } from 'react' import { shouldPollEnvironmentDeployment } from '@/app/components/app/deploy/utils/environment-deployment' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { appPublisherOpenAtom, finishPublisherEnvironmentDeploymentPollingAtom, diff --git a/web/app/components/app/app-publisher/publish-with-multiple-model.tsx b/web/app/components/app/app-publisher/publish-with-multiple-model.tsx index 4e26d0e5638..299e62f2c84 100644 --- a/web/app/components/app/app-publisher/publish-with-multiple-model.tsx +++ b/web/app/components/app/app-publisher/publish-with-multiple-model.tsx @@ -1,9 +1,9 @@ +import type { + ProviderModelWithStatusEntity, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' import type { FC } from 'react' import type { ModelAndParameter } from '../configuration/debug/types' -import type { - Model, - ModelItem, -} from '@/app/components/header/account-setting/model-provider-page/declarations' import { Button } from '@langgenius/dify-ui/button' import { DropdownMenu, @@ -12,31 +12,39 @@ import { DropdownMenuTrigger, } from '@langgenius/dify-ui/dropdown-menu' import { RiArrowDownSLine } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' import { useState } from 'react' import { useTranslation } from 'react-i18next' +import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks' -import { useProviderContext } from '@/context/provider-context' +import { renderI18nObject } from '@/i18n-config' +import { consoleQuery } from '@/service/console' import ModelIcon from '../../header/account-setting/model-provider-page/model-icon' type PublishWithMultipleModelProps = { disabled?: boolean multipleModelConfigs: ModelAndParameter[] - // textGenerationModelList?: Model[] onSelect: (v: ModelAndParameter) => void } const PublishWithMultipleModel: FC = ({ disabled = false, multipleModelConfigs, - // textGenerationModelList = [], onSelect, }) => { const { t } = useTranslation() const language = useLanguage() - const { textGenerationModelList } = useProviderContext() + const { data: textGenerationModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) const [open, setOpen] = useState(false) - const validModelConfigs: (ModelAndParameter & { modelItem: ModelItem; providerItem: Model })[] = - [] + const validModelConfigs: (ModelAndParameter & { + modelItem: ProviderModelWithStatusEntity + providerItem: ProviderWithModelsResponse + })[] = [] multipleModelConfigs.forEach((item) => { const provider = textGenerationModelList.find((model) => model.provider === item.provider) @@ -80,9 +88,9 @@ const PublishWithMultipleModel: FC = ({
- {item.modelItem.label[language]} + {renderI18nObject(item.modelItem.label, language)}
))} diff --git a/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts b/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts index 67b280867f2..6f7052cd4b0 100644 --- a/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts +++ b/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts @@ -12,7 +12,7 @@ import { trackEvent } from '@/app/components/base/amplitude' import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager' import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager' import { WorkflowContext } from '@/app/components/workflow/context' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useAppWorkflow, useInvalidateAppWorkflow } from '@/service/use-workflow' import { appWorkflowQueryOptions, diff --git a/web/app/components/app/app-publisher/state.ts b/web/app/components/app/app-publisher/state.ts index 87bbf47eb44..190e79d2b88 100644 --- a/web/app/components/app/app-publisher/state.ts +++ b/web/app/components/app/app-publisher/state.ts @@ -7,7 +7,7 @@ import { atom } from 'jotai' import { atomWithQuery } from 'jotai-tanstack-query' import { selectAtom, useHydrateAtoms } from 'jotai/utils' import { shouldPollEnvironmentDeployment } from '@/app/components/app/deploy/utils/environment-deployment' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' export const BUILT_IN_ENVIRONMENT_ID = 'built-in' const PUBLISHER_DEPLOYMENT_POLLING_INTERVAL = 3000 diff --git a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx index 6116def05fb..d8b3bd70b56 100644 --- a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx +++ b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx @@ -98,7 +98,6 @@ const createDeletedAgentTool = (providerId: string): AgentTool => ({ const createContextValue = (): ComponentProps['value'] => ({ appId: 'app-1', - isAPIKeySet: true, isTrailFinished: false, mode: AppModeEnum.CHAT, modelModeType: ModelModeType.chat, diff --git a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx index 083e6fafc7f..ea078771e37 100644 --- a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx +++ b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx @@ -25,7 +25,7 @@ import Loading from '@/app/components/base/loading' import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks' import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { generateBasicAppFirstTimeRule, generateRule } from '@/service/debug' import { useAutoGenModel } from '../auto-gen-model-storage' import IdeaOutput from './idea-output' diff --git a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx index 7d015e4501e..ce0a57b76d9 100644 --- a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx +++ b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx @@ -24,7 +24,7 @@ import Loading from '@/app/components/base/loading' import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks' import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { generateRule } from '@/service/debug' import { languageMap } from '../../../../workflow/nodes/_base/components/editor/code-editor/index' import { useAutoGenModel } from '../auto-gen-model-storage' diff --git a/web/app/components/app/configuration/configuration-view/index.tsx b/web/app/components/app/configuration/configuration-view/index.tsx index debbb78ed15..5138469b888 100644 --- a/web/app/components/app/configuration/configuration-view/index.tsx +++ b/web/app/components/app/configuration/configuration-view/index.tsx @@ -177,7 +177,6 @@ const ConfigurationView: FC = ({ >
= ({ />
({ useDocLink: () => (path: string) => `https://docs${path}`, })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - modelProviders: [], - textGenerationModelList: [], - }), -})) - vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ - useModelList: (...args: unknown[]) => mockUseModelList(...args), - useModelListAndDefaultModel: (...args: unknown[]) => mockUseModelListAndDefaultModel(...args), + useModelListAndDefaultModel: (...args: unknown[]) => mockModelListQueryAndDefaultModel(...args), useModelListAndDefaultModelAndCurrentProviderAndModel: (...args: unknown[]) => - mockUseModelListAndDefaultModelAndCurrentProviderAndModel(...args), + mockModelListQueryAndDefaultModelAndCurrentProviderAndModel(...args), useCurrentProviderAndModel: (...args: unknown[]) => mockUseCurrentProviderAndModel(...args), })) @@ -251,7 +245,7 @@ describe('SettingsModal', () => { ], }, } as ReturnType) - mockUseModelList.mockImplementation((type: ModelTypeEnum) => { + mockModelListQuery.mockImplementation((type: ModelTypeEnum) => { if (type === ModelTypeEnum.rerank) { return { data: [ @@ -264,8 +258,8 @@ describe('SettingsModal', () => { } return { data: [{ provider: 'embed-provider', models: [{ model: 'embed-model' }] }] } }) - mockUseModelListAndDefaultModel.mockReturnValue({ modelList: [], defaultModel: null }) - mockUseModelListAndDefaultModelAndCurrentProviderAndModel.mockReturnValue({ + mockModelListQueryAndDefaultModel.mockReturnValue({ modelList: [], defaultModel: null }) + mockModelListQueryAndDefaultModelAndCurrentProviderAndModel.mockReturnValue({ defaultModel: null, currentModel: null, }) @@ -436,7 +430,7 @@ describe('SettingsModal', () => { it('should block save when reranking is enabled without model', async () => { // Arrange const user = userEvent.setup() - mockUseModelList.mockReturnValue({ data: [] }) + mockModelListQuery.mockReturnValue({ data: [] }) const dataset = createDataset( {}, createRetrievalConfig({ @@ -601,3 +595,22 @@ describe('SettingsModal', () => { }) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + + const args = options.queryKey[1].input?.params?.model_type + if (!args) throw new Error('Missing model type in query') + return mockModelListQuery(args) + }, + } +}) diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx index 16c60ea0038..c9d42d9a6aa 100644 --- a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx +++ b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx @@ -1,3 +1,5 @@ +import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import type { ReactElement } from 'react' import type { DataSet } from '@/models/datasets' import type { RetrievalConfig } from '@/types/app' @@ -12,15 +14,15 @@ import { DataSourceType, RerankingModeEnum, } from '@/models/datasets' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { withSelectorKey } from '@/test/i18n-mock' import { RETRIEVE_METHOD } from '@/types/app' import { RetrievalChangeTip, RetrievalSection } from '../retrieval-section' -const mockUseModelList = vi.fn() -const mockUseModelListAndDefaultModel = vi.fn() -const mockUseModelListAndDefaultModelAndCurrentProviderAndModel = vi.fn() +const mockModelListQuery = vi.fn() +const mockModelListQueryAndDefaultModel = vi.fn() +const mockModelListQueryAndDefaultModelAndCurrentProviderAndModel = vi.fn() const mockUseCurrentProviderAndModel = vi.fn() vi.mock('ky', () => { @@ -30,18 +32,11 @@ vi.mock('ky', () => { return { __esModule: true, default: ky } }) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - modelProviders: [], - textGenerationModelList: [], - }), -})) - vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ useModelListAndDefaultModelAndCurrentProviderAndModel: (...args: unknown[]) => - mockUseModelListAndDefaultModelAndCurrentProviderAndModel(...args), - useModelListAndDefaultModel: (...args: unknown[]) => mockUseModelListAndDefaultModel(...args), - useModelList: (...args: unknown[]) => mockUseModelList(...args), + mockModelListQueryAndDefaultModelAndCurrentProviderAndModel(...args), + useModelListAndDefaultModel: (...args: unknown[]) => mockModelListQueryAndDefaultModel(...args), + useCurrentProviderAndModel: (...args: unknown[]) => mockUseCurrentProviderAndModel(...args), })) @@ -221,13 +216,13 @@ describe('RetrievalSection', () => { beforeEach(() => { vi.clearAllMocks() - mockUseModelList.mockImplementation((type: ModelTypeEnum) => { + mockModelListQuery.mockImplementation((type: ModelTypeEnum) => { if (type === ModelTypeEnum.rerank) return { data: [{ provider: 'rerank-provider', models: [{ model: 'rerank-model' }] }] } return { data: [] } }) - mockUseModelListAndDefaultModel.mockReturnValue({ modelList: [], defaultModel: null }) - mockUseModelListAndDefaultModelAndCurrentProviderAndModel.mockReturnValue({ + mockModelListQueryAndDefaultModel.mockReturnValue({ modelList: [], defaultModel: null }) + mockModelListQueryAndDefaultModelAndCurrentProviderAndModel.mockReturnValue({ defaultModel: null, currentModel: null, }) @@ -338,3 +333,22 @@ describe('RetrievalSection', () => { ) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + + const args = options.queryKey[1].input?.params?.model_type + if (!args) throw new Error('Missing model type in query') + return mockModelListQuery(args) + }, + } +}) diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx index a36903a222a..c20fe6381af 100644 --- a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx +++ b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx @@ -8,6 +8,7 @@ import { cn } from '@langgenius/dify-ui/cn' import { Input } from '@langgenius/dify-ui/input' import { Textarea } from '@langgenius/dify-ui/textarea' import { RiCloseLine } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' import { isEqual } from 'es-toolkit/predicate' import { useQueryState } from 'nuqs' import { useEffect, useId, useMemo, useRef, useState } from 'react' @@ -19,7 +20,6 @@ import IndexMethod from '@/app/components/datasets/settings/index-method' import PermissionSelector from '@/app/components/datasets/settings/permission-selector' import { checkShowMultiModalTip } from '@/app/components/datasets/settings/utils' import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' -import { useModelList } from '@/app/components/header/account-setting/model-provider-page/hooks' import { ModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector' import { settingsQueryParamName, @@ -27,6 +27,7 @@ import { } from '@/app/components/header/account-setting/query-params' import { useDocLink } from '@/context/i18n' import { DatasetPermission } from '@/models/datasets' +import { consoleQuery } from '@/service/console' import { updateDatasetSetting } from '@/service/datasets' import { useMembers } from '@/service/use-common' import { RetrievalChangeTip, RetrievalSection } from './retrieval-section' @@ -52,8 +53,18 @@ const SettingsModal: FC = ({ onCancel, onSave, }) => { - const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding) - const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank) + const { data: embeddingModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textEmbedding } }, + select: (response) => response.data, + }), + ) + const { data: rerankModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.rerank } }, + select: (response) => response.data, + }), + ) const { t } = useTranslation() const translateRetrieval: RetrievalTranslate = (selector, options) => t(selector, options) const docLink = useDocLink() diff --git a/web/app/components/app/configuration/debug/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/__tests__/index.spec.tsx index a1c68fcb783..97940c03d18 100644 --- a/web/app/components/app/configuration/debug/__tests__/index.spec.tsx +++ b/web/app/components/app/configuration/debug/__tests__/index.spec.tsx @@ -39,9 +39,10 @@ const mockState = vi.hoisted(() => ({ fileUploadConfig: undefined as { image_file_size_limit?: number } | undefined, }, }, - mockProviderContext: { - textGenerationModelList: [] as Array<{ + mockModelListResult: { + data: [] as Array<{ provider: string + status: string models: Array<{ model: string features?: string[] @@ -209,8 +210,9 @@ vi.mock('@/context/event-emitter', () => ({ }), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockState.mockProviderContext, +vi.mock('@tanstack/react-query', async (importOriginal) => ({ + ...(await importOriginal()), + useQuery: () => mockState.mockModelListResult, })) vi.mock('@/service/debug', () => ({ @@ -307,7 +309,6 @@ const createContextValue = (overrides: Partial = {}): DebugCo readonly: false, canTestAndRun: true, appId: 'app-id', - isAPIKeySet: true, isTrailFinished: false, mode: AppModeEnum.CHAT, modelModeType: ModelModeType.chat, @@ -454,7 +455,6 @@ const renderDebug = ( ) => { const onSetting = vi.fn() const props: ComponentProps = { - isAPIKeySet: true, onSetting, inputs: {}, modelParameterParams: { @@ -499,10 +499,11 @@ describe('Debug', () => { text2speech: { enabled: false }, file: { enabled: false, allowed_file_upload_methods: [], fileUploadConfig: undefined }, } - mockState.mockProviderContext = { - textGenerationModelList: [ + mockState.mockModelListResult = { + data: [ { provider: 'openai', + status: 'active', models: [ { model: 'vision-model', @@ -525,9 +526,7 @@ describe('Debug', () => { model_id: '', }, }, - props: { - isAPIKeySet: false, - }, + props: {}, }) expect(screen.getByText('appDebug.noModelProviderConfigured'))!.toBeInTheDocument() @@ -546,9 +545,7 @@ describe('Debug', () => { model_id: '', }, }, - props: { - isAPIKeySet: true, - }, + props: {}, }) expect(screen.getByText('appDebug.noModelSelected'))!.toBeInTheDocument() diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx index 3b5d28b439d..9ea7884d95c 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx @@ -9,7 +9,7 @@ import ChatItem from '../chat-item' const mockConsoleStateReader = vi.fn() const mockUseDebugConfigurationContext = vi.fn() -const mockUseProviderContext = vi.fn() +const mockModelListQuery = vi.fn() const mockUseFeatures = vi.fn() const mockUseConfigFromDebugContext = vi.fn() const mockUseFormattingChangedSubscription = vi.fn() @@ -39,8 +39,9 @@ vi.mock('@/context/debug-configuration', () => ({ useDebugConfigurationContext: () => mockUseDebugConfigurationContext(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockUseProviderContext(), +vi.mock('@tanstack/react-query', async (importOriginal) => ({ + ...(await importOriginal()), + useQuery: () => mockModelListQuery(), })) vi.mock('@/app/components/base/features/hooks', () => ({ @@ -137,8 +138,8 @@ const createDefaultMocks = () => { canTestAndRun: true, }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [ + mockModelListQuery.mockReturnValue({ + data: [ { provider: 'openai', models: [ @@ -429,8 +430,8 @@ describe('ChatItem', () => { }) it('should not include files when vision is not supported', () => { - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [ + mockModelListQuery.mockReturnValue({ + data: [ { provider: 'openai', models: [ @@ -624,8 +625,8 @@ describe('ChatItem', () => { describe('edge cases', () => { it('should handle missing provider in textGenerationModelList', () => { - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [], + mockModelListQuery.mockReturnValue({ + data: [], }) const handleSend = vi.fn() diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx index 17a13ddc697..85f4a8a9d4b 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx @@ -8,7 +8,7 @@ import DebugItem from '../debug-item' const mockUseDebugConfigurationContext = vi.fn() const mockUseDebugWithMultipleModelContext = vi.fn() -const mockUseProviderContext = vi.fn() +const mockModelListQuery = vi.fn() let capturedModelParameterTriggerProps: { modelAndParameter: ModelAndParameter @@ -22,8 +22,9 @@ vi.mock('../context', () => ({ useDebugWithMultipleModelContext: () => mockUseDebugWithMultipleModelContext(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockUseProviderContext(), +vi.mock('@tanstack/react-query', async (importOriginal) => ({ + ...(await importOriginal()), + useQuery: () => mockModelListQuery(), })) vi.mock('../chat-item', () => ({ @@ -106,10 +107,8 @@ describe('DebugItem', () => { onDebugWithMultipleModelChange: vi.fn(), }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ - { provider: 'openai', model: 'gpt-3.5-turbo' }, - ]), + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([{ provider: 'openai', model: 'gpt-3.5-turbo' }]), }) }) @@ -158,8 +157,8 @@ describe('DebugItem', () => { describe('ChatItem rendering', () => { it('should render ChatItem in CHAT mode with active model', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active }, ]), }) @@ -172,8 +171,8 @@ describe('DebugItem', () => { it('should render ChatItem in AGENT_CHAT mode with active model', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.AGENT_CHAT }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active }, ]), }) @@ -185,8 +184,8 @@ describe('DebugItem', () => { it('should not render ChatItem when model is not active', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.disabled }, ]), }) @@ -198,8 +197,8 @@ describe('DebugItem', () => { it('should not render ChatItem when provider not found', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'anthropic', model: 'claude-3', status: ModelStatusEnum.active }, ]), }) @@ -211,8 +210,8 @@ describe('DebugItem', () => { it('should not render ChatItem when model not found', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'openai', model: 'gpt-4', status: ModelStatusEnum.active }, ]), }) @@ -226,8 +225,8 @@ describe('DebugItem', () => { describe('TextGenerationItem rendering', () => { it('should render TextGenerationItem in COMPLETION mode with active model', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.COMPLETION }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active }, ]), }) @@ -240,8 +239,8 @@ describe('DebugItem', () => { it('should not render TextGenerationItem when provider is not found', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.COMPLETION }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'anthropic', model: 'claude-3', status: ModelStatusEnum.active }, ]), }) @@ -493,8 +492,8 @@ describe('DebugItem', () => { }) it('should handle empty textGenerationModelList', () => { - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [], + mockModelListQuery.mockReturnValue({ + data: [], }) renderComponent() @@ -505,8 +504,8 @@ describe('DebugItem', () => { it('should handle model with quotaExceeded status', () => { mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: createTextGenerationModelList([ + mockModelListQuery.mockReturnValue({ + data: createTextGenerationModelList([ { provider: 'anthropic', model: 'not-matching', status: ModelStatusEnum.quotaExceeded }, ]), }) diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/model-parameter-trigger.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/model-parameter-trigger.spec.tsx index edbd7b0f374..5aeb435cd43 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/model-parameter-trigger.spec.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/model-parameter-trigger.spec.tsx @@ -7,7 +7,6 @@ import type { } from '@/app/components/header/account-setting/model-provider-page/declarations' import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { createMockProviderContextValue } from '@/__mocks__/provider-context' import { ConfigurationMethodEnum, CurrentSystemQuotaTypeEnum, @@ -162,15 +161,15 @@ describe('ModelParameterTrigger', () => { onDebugWithMultipleModelChange: vi.fn(), }) mockProvidersSummary.mockReturnValue( - createMockProviderContextValue({ - modelProviders: [ + { + data: [ { ...createModelProvider(), is_configured: true, plugin_id: 'langgenius/openai', } as unknown as ModelProviderSummaryResponse, ], - }).modelProviders, + }.data, ) mockUseCredentialPanelState.mockReturnValue({ variant: 'api-active', diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/text-generation-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/text-generation-item.spec.tsx index 96728e360d9..176ead8e435 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/text-generation-item.spec.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/text-generation-item.spec.tsx @@ -5,7 +5,7 @@ import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../../types' import TextGenerationItem from '../text-generation-item' const mockUseDebugConfigurationContext = vi.fn() -const mockUseProviderContext = vi.fn() +const mockModelListQuery = vi.fn() const mockUseFeatures = vi.fn() const mockUseTextGeneration = vi.fn() const mockUseEventEmitterContextContext = vi.fn() @@ -30,8 +30,9 @@ vi.mock('@/context/debug-configuration', () => ({ useDebugConfigurationContext: () => mockUseDebugConfigurationContext(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockUseProviderContext(), +vi.mock('@tanstack/react-query', async (importOriginal) => ({ + ...(await importOriginal()), + useQuery: () => mockModelListQuery(), })) vi.mock('@/app/components/base/features/hooks', () => ({ @@ -105,8 +106,8 @@ const createDefaultMocks = () => { datasetConfigs: { retrieval_model: 'single' }, }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [ + mockModelListQuery.mockReturnValue({ + data: [ { provider: 'openai', models: [ @@ -597,8 +598,8 @@ describe('TextGenerationItem', () => { messageId: null, }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [ + mockModelListQuery.mockReturnValue({ + data: [ { provider: 'openai', models: [ @@ -643,8 +644,8 @@ describe('TextGenerationItem', () => { messageId: null, }) - mockUseProviderContext.mockReturnValue({ - textGenerationModelList: [], + mockModelListQuery.mockReturnValue({ + data: [], }) renderComponent() diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx index 6f0d8756c33..09a68780389 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx @@ -3,18 +3,21 @@ import type { ModelAndParameter } from '../types' import type { InputForm } from '@/app/components/base/chat/chat/type' import type { ChatConfig, OnSend } from '@/app/components/base/chat/types' import { Avatar } from '@langgenius/dify-ui/avatar' -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { memo, useCallback, useMemo } from 'react' import { toast } from '@/app/components/app/configuration/toast' import Chat from '@/app/components/base/chat/chat' import { useChat } from '@/app/components/base/chat/chat/hooks' import { getLastAnswer } from '@/app/components/base/chat/utils' import { useFeatures } from '@/app/components/base/features/hooks' -import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' +import { + ModelFeatureEnum, + ModelTypeEnum, +} from '@/app/components/header/account-setting/model-provider-page/declarations' import { useDebugConfigurationContext } from '@/context/debug-configuration' import { useEventEmitterContextContext } from '@/context/event-emitter' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' +import { consoleQuery } from '@/service/console' import { fetchConversationMessages, fetchSuggestedQuestions, @@ -39,7 +42,12 @@ const ChatItem: FC = ({ modelAndParameter }) => { collectionList, canTestAndRun = false, } = useDebugConfigurationContext() - const { textGenerationModelList } = useProviderContext() + const { data: textGenerationModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) const features = useFeatures((s) => s.features) const configTemplate = useConfigFromDebugContext() const config = useMemo(() => { diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx index dc715f84077..e0c1ed8620e 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx @@ -8,11 +8,15 @@ import { DropdownMenuTrigger, } from '@langgenius/dify-ui/dropdown-menu' import { IconButton } from '@langgenius/dify-ui/icon-button' +import { useQuery } from '@tanstack/react-query' import { memo } from 'react' import { useTranslation } from 'react-i18next' -import { ModelStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' +import { + ModelStatusEnum, + ModelTypeEnum, +} from '@/app/components/header/account-setting/model-provider-page/declarations' import { useDebugConfigurationContext } from '@/context/debug-configuration' -import { useProviderContext } from '@/context/provider-context' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' import ChatItem from './chat-item' import { useDebugWithMultipleModelContext } from './context' @@ -29,7 +33,12 @@ const DebugItem: FC = ({ modelAndParameter, className, style }) const { mode } = useDebugConfigurationContext() const { multipleModelConfigs, onMultipleModelConfigsChange, onDebugWithMultipleModelChange } = useDebugWithMultipleModelContext() - const { textGenerationModelList } = useProviderContext() + const { data: textGenerationModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) const index = multipleModelConfigs.findIndex((v) => v.id === modelAndParameter.id) const currentProvider = textGenerationModelList.find( diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsx index 886b2a41a43..3a6ec1662ac 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsx @@ -17,7 +17,7 @@ import ModelName from '@/app/components/header/account-setting/model-provider-pa import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal' import { useCredentialPanelState } from '@/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state' import { useDebugConfigurationContext } from '@/context/debug-configuration' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useDebugWithMultipleModelContext } from './context' type ModelParameterTriggerProps = { diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/text-generation-item.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/text-generation-item.tsx index 97bd8c7ec00..c0feb9de223 100644 --- a/web/app/components/app/configuration/debug/debug-with-multiple-model/text-generation-item.tsx +++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/text-generation-item.tsx @@ -1,6 +1,7 @@ import type { FC } from 'react' import type { ModelAndParameter } from '../types' import type { OnSend, TextGenerationConfig } from '@/app/components/base/text-generation/types' +import { useQuery } from '@tanstack/react-query' import { noop } from 'es-toolkit/function' import { cloneDeep } from 'es-toolkit/object' import { memo } from 'react' @@ -9,10 +10,11 @@ import TextGeneration from '@/app/components/app/text-generate/item' import { TransferMethod } from '@/app/components/base/chat/types' import { useFeatures } from '@/app/components/base/features/hooks' import { useTextGeneration } from '@/app/components/base/text-generation/hooks' +import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config' import { useDebugConfigurationContext } from '@/context/debug-configuration' import { useEventEmitterContextContext } from '@/context/event-emitter' -import { useProviderContext } from '@/context/provider-context' +import { consoleQuery } from '@/service/console' import { AppSourceType } from '@/service/share' import { promptVariablesToUserInputsForm } from '@/utils/model-config' import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../types' @@ -37,7 +39,12 @@ const TextGenerationItem: FC = ({ modelAndParameter }) dataSets, datasetConfigs, } = useDebugConfigurationContext() - const { textGenerationModelList } = useProviderContext() + const { data: textGenerationModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) const features = useFeatures((s) => s.features) const postDatasets = dataSets.map(({ id }) => ({ dataset: { diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx index ecd3fd442ee..7d1b4c89abc 100644 --- a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx +++ b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx @@ -4,17 +4,10 @@ import type { DebugWithSingleModelRefType } from '../index' import type { ChatItem } from '@/app/components/base/chat/types' import type { FileEntity } from '@/app/components/base/file-uploader/types' import type { Collection } from '@/app/components/tools/types' -import type { ProviderContextState } from '@/context/provider-context' import type { DatasetConfigs, ModelConfig } from '@/models/debug' import { act, fireEvent, screen, waitFor } from '@testing-library/react' import { createRef } from 'react' import { useStore as useAppStore } from '@/app/components/app/store' -import { - ConfigurationMethodEnum, - ModelFeatureEnum, - ModelStatusEnum, - ModelTypeEnum, -} from '@/app/components/header/account-setting/model-provider-page/declarations' import { CollectionType } from '@/app/components/tools/types' import { SupportUploadFileTypes } from '@/app/components/workflow/types' import { PromptMode } from '@/models/debug' @@ -93,44 +86,6 @@ function createMockCollections(collections: Partial[] = []): Collect ) } -/** - * Factory function for creating mock Provider Context - */ -function createMockProviderContext( - overrides: Partial = {}, -): ProviderContextState { - return { - textGenerationModelList: [ - { - provider: 'openai', - label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, - icon_small: { en_US: 'icon', zh_Hans: 'icon' }, - status: ModelStatusEnum.active, - models: [ - { - model: 'gpt-3.5-turbo', - label: { en_US: 'GPT-3.5', zh_Hans: 'GPT-3.5' }, - model_type: ModelTypeEnum.textGeneration, - features: [ModelFeatureEnum.vision], - fetch_from: ConfigurationMethodEnum.predefinedModel, - model_properties: {}, - deprecated: false, - }, - ], - }, - ], - hasSettedApiKey: true, - modelProviders: [], - speech2textDefaultModel: null, - ttsDefaultModel: null, - agentThoughtDefaultModel: null, - updateModelList: vi.fn(), - onPlanInfoChanged: vi.fn(), - refreshModelProviders: vi.fn(), - ...overrides, - } as ProviderContextState -} - // ============================================================================ // Mock External Dependencies ONLY (Following testing.md guidelines) // ============================================================================ @@ -187,7 +142,6 @@ const mockDebugConfigContext = { readonly: false, canTestAndRun: true, appId: 'test-app-id', - isAPIKeySet: true, isTrailFinished: false, mode: AppModeEnum.CHAT, modelModeType: ModelModeType.chat, @@ -303,18 +257,6 @@ vi.mock('@/context/debug-configuration', () => ({ useDebugConfigurationContext: mockUseDebugConfigurationContext, })) -const mockProviderContext = createMockProviderContext() - -const { mockUseProviderContext } = vi.hoisted(() => ({ - mockUseProviderContext: vi.fn(), -})) - -mockUseProviderContext.mockReturnValue(mockProviderContext) - -vi.mock('@/context/provider-context', () => ({ - useProviderContext: mockUseProviderContext, -})) - const mockConsoleState = { userProfile: { id: 'user-1', @@ -625,7 +567,6 @@ describe('DebugWithSingleModel', () => { // Reset mock implementations using module-level mocks mockUseDebugConfigurationContext.mockReturnValue(mockDebugConfigContext) - mockUseProviderContext.mockReturnValue(mockProviderContext) mockConsoleStateReader.mockReturnValue(mockConsoleState) mockUseConfigFromDebugContext.mockReturnValue(mockConfigFromDebugContext) mockUseFormattingChangedSubscription.mockReturnValue(undefined) @@ -808,52 +749,12 @@ describe('DebugWithSingleModel', () => { }) it('should handle model without vision support', () => { - mockUseProviderContext.mockReturnValue( - createMockProviderContext({ - textGenerationModelList: [ - { - provider: 'openai', - label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, - icon_small: { en_US: 'icon', zh_Hans: 'icon' }, - status: ModelStatusEnum.active, - models: [ - { - model: 'gpt-3.5-turbo', - label: { en_US: 'GPT-3.5', zh_Hans: 'GPT-3.5' }, - model_type: ModelTypeEnum.textGeneration, - features: [], // No vision support - fetch_from: ConfigurationMethodEnum.predefinedModel, - model_properties: {}, - deprecated: false, - status: ModelStatusEnum.active, - load_balancing_enabled: false, - }, - ], - }, - ], - }), - ) - render(} />) expect(screen.getByTestId('chat-component'))!.toBeInTheDocument() }) it('should handle missing model in provider list', () => { - mockUseProviderContext.mockReturnValue( - createMockProviderContext({ - textGenerationModelList: [ - { - provider: 'different-provider', - label: { en_US: 'Different Provider', zh_Hans: '不同提供商' }, - icon_small: { en_US: 'icon', zh_Hans: 'icon' }, - status: ModelStatusEnum.active, - models: [], - }, - ], - }), - ) - render(} />) expect(screen.getByTestId('chat-component'))!.toBeInTheDocument() @@ -1027,32 +928,6 @@ describe('DebugWithSingleModel', () => { }), }) - mockUseProviderContext.mockReturnValue( - createMockProviderContext({ - textGenerationModelList: [ - { - provider: 'openai', - label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, - icon_small: { en_US: 'icon', zh_Hans: 'icon' }, - status: ModelStatusEnum.active, - models: [ - { - model: 'gpt-3.5-turbo', - label: { en_US: 'GPT-3.5', zh_Hans: 'GPT-3.5' }, - model_type: ModelTypeEnum.textGeneration, - features: [ModelFeatureEnum.document], - fetch_from: ConfigurationMethodEnum.predefinedModel, - model_properties: {}, - deprecated: false, - status: ModelStatusEnum.active, - load_balancing_enabled: false, - }, - ], - }, - ], - }), - ) - mockFeaturesState = { ...defaultFeatures, file: { enabled: true }, @@ -1085,32 +960,6 @@ describe('DebugWithSingleModel', () => { }), }) - mockUseProviderContext.mockReturnValue( - createMockProviderContext({ - textGenerationModelList: [ - { - provider: 'openai', - label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, - icon_small: { en_US: 'icon', zh_Hans: 'icon' }, - status: ModelStatusEnum.active, - models: [ - { - model: 'gpt-4-vision', - label: { en_US: 'GPT-4 Vision', zh_Hans: 'GPT-4 Vision' }, - model_type: ModelTypeEnum.textGeneration, - features: [ModelFeatureEnum.vision], - fetch_from: ConfigurationMethodEnum.predefinedModel, - model_properties: {}, - deprecated: false, - status: ModelStatusEnum.active, - load_balancing_enabled: false, - }, - ], - }, - ], - }), - ) - mockFeaturesState = { ...defaultFeatures, file: { enabled: true }, diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx index 4b5e73a6cff..8c47ed04099 100644 --- a/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx +++ b/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx @@ -11,7 +11,6 @@ import { useChat } from '@/app/components/base/chat/chat/hooks' import { getLastAnswer, isValidGeneratedAnswer } from '@/app/components/base/chat/utils' import { useFeatures } from '@/app/components/base/features/hooks' import { useDebugConfigurationContext } from '@/context/debug-configuration' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' import { fetchConversationMessages, @@ -49,7 +48,6 @@ const DebugWithSingleModel = ({ } = useDebugConfigurationContext() const debugInputReadonly = !canTestAndRun const canManageAnnotation = !readonly && canTestAndRun - const { textGenerationModelList } = useProviderContext() const features = useFeatures((s) => s.features) const configTemplate = useConfigFromDebugContext() const config = useMemo(() => { @@ -140,7 +138,6 @@ const DebugWithSingleModel = ({ modelConfig.mode, modelConfig.model_id, modelConfig.provider, - textGenerationModelList, ], ) diff --git a/web/app/components/app/configuration/debug/index.tsx b/web/app/components/app/configuration/debug/index.tsx index 58be6575175..13e9c8b4703 100644 --- a/web/app/components/app/configuration/debug/index.tsx +++ b/web/app/components/app/configuration/debug/index.tsx @@ -9,6 +9,7 @@ import { Button } from '@langgenius/dify-ui/button' import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible' import { IconButton } from '@langgenius/dify-ui/icon-button' import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip' +import { useQuery } from '@tanstack/react-query' import { useBoolean } from 'ahooks' import { noop } from 'es-toolkit/function' import { cloneDeep } from 'es-toolkit/object' @@ -34,7 +35,7 @@ import { useDefaultModel } from '@/app/components/header/account-setting/model-p import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config' import ConfigContext from '@/context/debug-configuration' import { useEventEmitterContextContext } from '@/context/event-emitter' -import { useProviderContext } from '@/context/provider-context' +import { consoleQuery } from '@/service/console' import { sendCompletionMessage } from '@/service/debug' import { AppSourceType } from '@/service/share' import { AppModeEnum, ModelModeType, TransferMethod } from '@/types/app' @@ -48,7 +49,7 @@ import DebugWithSingleModel from './debug-with-single-model' import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from './types' type IDebug = { - isAPIKeySet: boolean + isPreview?: boolean onSetting: () => void inputs: Inputs modelParameterParams: Pick @@ -58,7 +59,7 @@ type IDebug = { } const Debug: FC = ({ - isAPIKeySet = true, + isPreview = false, onSetting, inputs, modelParameterParams, @@ -332,9 +333,16 @@ const Debug: FC = ({ } }) - const { textGenerationModelList } = useProviderContext() + const { data: textGenerationModelList } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) + const hasActiveProvider = + isPreview || !!textGenerationModelList?.some((provider) => provider.status === 'active') const handleChangeToSingleModel = (item: ModelAndParameter) => { - const currentProvider = textGenerationModelList.find( + const currentProvider = textGenerationModelList?.find( (modelItem) => modelItem.provider === item.provider, ) const currentModel = currentProvider?.models.find((model) => model.model === item.model) @@ -342,8 +350,11 @@ const Debug: FC = ({ modelParameterParams.setModel({ modelId: item.model, provider: item.provider, - mode: currentModel?.model_properties.mode as string, - features: currentModel?.features, + mode: + typeof currentModel?.model_properties.mode === 'string' + ? currentModel.model_properties.mode + : undefined, + features: currentModel?.features ?? undefined, }) modelParameterParams.onCompletionParamsChange(item.parameters) onMultipleModelConfigsChange(false, []) @@ -352,7 +363,7 @@ const Debug: FC = ({ const handleVisionConfigInMultipleModel = useCallback(() => { if (debugWithMultipleModel && mode) { const supportedVision = multipleModelConfigs.some((modelConfig) => { - const currentProvider = textGenerationModelList.find( + const currentProvider = textGenerationModelList?.find( (modelItem) => modelItem.provider === modelConfig.provider, ) const currentModel = currentProvider?.models.find( @@ -541,9 +552,11 @@ const Debug: FC = ({ {!debugWithMultipleModel && (
{/* No model provider configured */} - {(!modelConfig.provider || !isAPIKeySet) && } + {(!modelConfig.provider || !hasActiveProvider) && ( + + )} {/* No model selected */} - {modelConfig.provider && isAPIKeySet && !modelConfig.model_id && ( + {modelConfig.provider && hasActiveProvider && !modelConfig.model_id && (
diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx index 4781627325e..e07696ba26b 100644 --- a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx +++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx @@ -1,7 +1,7 @@ /* oxlint-disable typescript/no-explicit-any */ import { act, waitFor } from '@testing-library/react' import { updateAppModelConfig } from '@/service/apps' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { seedAccountProfileQuery } from '@/test/console/account-profile' import { createQueryClientWrapper } from '@/test/console/query-client' import { renderHook as renderHookWithConsoleState } from '@/test/console/render' @@ -84,12 +84,6 @@ vi.mock('nuqs', async (importOriginal) => { return { ...actual, useQueryState: () => [null, mockSetSettingsDestination] } }) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - isAPIKeySet: true, - }), -})) - vi.mock('@/app/components/app/store', () => ({ useStore: (selector: (state: Record) => unknown) => selector({ diff --git a/web/app/components/app/configuration/hooks/build-configuration-context.ts b/web/app/components/app/configuration/hooks/build-configuration-context.ts index bed0d03f54a..12d60053793 100644 --- a/web/app/components/app/configuration/hooks/build-configuration-context.ts +++ b/web/app/components/app/configuration/hooks/build-configuration-context.ts @@ -29,7 +29,6 @@ type ContextBase = Pick< | 'isShowDocumentConfig' | 'isShowVisionConfig' | 'isTrailFinished' - | 'isAPIKeySet' | 'mode' | 'modelModeType' | 'prevPromptConfig' diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-app-context.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-app-context.ts index fb6ff9256b8..aee4a24f53c 100644 --- a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-app-context.ts +++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-app-context.ts @@ -8,7 +8,7 @@ import { currentWorkspaceAtom, currentWorkspaceLoadingAtom } from '@/context/wor import { userProfileQueryOptions } from '@/features/account-profile/client' import { usePathname } from '@/next/navigation' import { updateAppModelConfig } from '@/service/apps' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { getAppACLCapabilities } from '@/utils/permission' export function useConfigurationAppContext() { diff --git a/web/app/components/app/configuration/hooks/use-configuration.ts b/web/app/components/app/configuration/hooks/use-configuration.ts index be2cc6da71c..571bd5830b8 100644 --- a/web/app/components/app/configuration/hooks/use-configuration.ts +++ b/web/app/components/app/configuration/hooks/use-configuration.ts @@ -22,7 +22,6 @@ import { settingsQueryParamName, settingsQueryParser, } from '@/app/components/header/account-setting/query-params' -import { useProviderContext } from '@/context/provider-context' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' import { PromptMode } from '@/models/debug' import { useFileUploadConfig } from '@/service/use-common' @@ -128,7 +127,6 @@ export const useConfiguration = (): ConfigurationViewModel => { const { currentModel: currentRerankModel, currentProvider: currentRerankProvider } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.rerank) - const { isAPIKeySet } = useProviderContext() const { currentModel: currModel } = useTextGenerationCurrentProviderAndModelAndModelList({ provider: modelConfig.provider, model: modelConfig.model_id, @@ -367,7 +365,6 @@ export const useConfiguration = (): ConfigurationViewModel => { isAdvancedMode, isAgent, isAllowVideoUpload, - isAPIKeySet, isFunctionCall, isOpenAI: modelConfig.provider === 'langgenius/openai/openai', isShowAudioConfig, diff --git a/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx index 6741e058c92..1fb7cd6be68 100644 --- a/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx +++ b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx @@ -5,14 +5,14 @@ import CreateAppTemplateDialog from '../index' vi.mock('../app-list', () => ({ default: function MockAppList({ onCreateFromBlank, - onSuccess, + onClose, }: { onCreateFromBlank?: () => void - onSuccess: () => void + onClose: () => void }) { return (
- {onCreateFromBlank && ( @@ -28,7 +28,6 @@ vi.mock('../app-list', () => ({ describe('CreateAppTemplateDialog', () => { const defaultProps = { show: false, - onSuccess: vi.fn(), onClose: vi.fn(), onCreateFromBlank: vi.fn(), } @@ -103,21 +102,12 @@ describe('CreateAppTemplateDialog', () => { expect(screen.getByRole('button', { name: 'Success' }))!.toBeInTheDocument() }) - it('should call both onSuccess and onClose when app list success is triggered', () => { - const mockOnSuccess = vi.fn() + it('should close when an app is created from the list', () => { const mockOnClose = vi.fn() - render( - , - ) + render() fireEvent.click(screen.getByRole('button', { name: 'Success' })) - expect(mockOnSuccess).toHaveBeenCalledTimes(1) expect(mockOnClose).toHaveBeenCalledTimes(1) }) @@ -143,7 +133,6 @@ describe('CreateAppTemplateDialog', () => { render( , @@ -154,12 +143,7 @@ describe('CreateAppTemplateDialog', () => { it('should handle undefined props gracefully', () => { expect(() => { render( - , + , ) }).not.toThrow() }) @@ -193,7 +177,6 @@ describe('CreateAppTemplateDialog', () => { it('should work with all required props only', () => { const requiredProps = { show: true, - onSuccess: vi.fn(), onClose: vi.fn(), } diff --git a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx index 6477928e437..4c36c5d6990 100644 --- a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx +++ b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx @@ -131,8 +131,8 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ vi.mock('@/utils/create-app-tracking', () => ({ trackCreateApp: (...args: unknown[]) => mockTrackCreateApp(...args), })) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() return { ...actual, @@ -247,7 +247,7 @@ describe('Apps', () => { }) it('renders template cards when data is available', () => { - render() + render() expect(screen.getAllByTestId('app-card')).toHaveLength(6) expect(screen.getByText('Alpha'))!.toBeInTheDocument() @@ -255,7 +255,7 @@ describe('Apps', () => { }) it('opens create modal when a template card is clicked', () => { - render() + render() fireEvent.click(screen.getAllByTestId('app-card')[0]!) expect(screen.getByTestId('create-from-template-modal'))!.toBeInTheDocument() @@ -264,7 +264,7 @@ describe('Apps', () => { it('passes app.create_and_management permission to template cards even when user is not a workspace editor', () => { mockWorkspacePermissionKeys = ['app.create_and_management'] - render() + render() expect(screen.getAllByTestId('app-card')[0]).toHaveAttribute('data-can-create', 'true') }) @@ -272,7 +272,7 @@ describe('Apps', () => { it('does not allow template creation when app.create_and_management permission is missing', () => { mockWorkspacePermissionKeys = [] - render() + render() expect(screen.getAllByTestId('app-card')[0]).toHaveAttribute('data-can-create', 'false') }) @@ -283,14 +283,14 @@ describe('Apps', () => { isLoading: false, }) - render() + render() expect(screen.getByText('app.newApp.noTemplateFound'))!.toBeInTheDocument() expect(screen.getByText('app.newApp.noTemplateFoundTip'))!.toBeInTheDocument() }) it('filters templates by keyword and selected app type', async () => { - render() + render() fireEvent.change(screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate'), { target: { value: 'Bravo' }, @@ -314,9 +314,9 @@ describe('Apps', () => { }) it('creates an app from a template and redirects after import succeeds', async () => { - const onSuccess = vi.fn() + const onClose = vi.fn() - render() + render() fireEvent.click(screen.getAllByTestId('app-card')[0]!) fireEvent.click(screen.getByTestId('confirm-create')) @@ -337,7 +337,7 @@ describe('Apps', () => { templateId: 'Alpha', }) expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated') - expect(onSuccess).toHaveBeenCalled() + expect(onClose).toHaveBeenCalledTimes(1) expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('created-app-id') expect(mockGetRedirection).toHaveBeenCalledWith( { @@ -361,7 +361,7 @@ describe('Apps', () => { app_mode: AppModeEnum.WORKFLOW, }) - render() + render() fireEvent.click(screen.getAllByTestId('app-card')[0]!) fireEvent.click(screen.getByTestId('confirm-create')) @@ -387,7 +387,7 @@ describe('Apps', () => { it('shows an error toast when importing the template fails', async () => { mockImportDSL.mockRejectedValueOnce(new Error('failed')) - render() + render() fireEvent.click(screen.getAllByTestId('app-card')[0]!) fireEvent.click(screen.getByTestId('confirm-create')) @@ -400,7 +400,7 @@ describe('Apps', () => { it('forwards the create-from-blank action from the sidebar', () => { const onCreateFromBlank = vi.fn() - render() + render() fireEvent.click(screen.getByText('app.newApp.startFromBlank')) @@ -413,7 +413,7 @@ describe('Apps', () => { isLoading: true, }) - render() + render() expect(screen.getByRole('status'))!.toBeInTheDocument() }) @@ -424,13 +424,13 @@ describe('Apps', () => { isLoading: false, }) - render() + render() expect(screen.getByText('app.newApp.noTemplateFound'))!.toBeInTheDocument() }) it('should filter templates by category and the remaining app modes', async () => { - render() + render() fireEvent.click(screen.getByText('Cat C')) expect(screen.queryByText('Alpha')).not.toBeInTheDocument() @@ -473,7 +473,7 @@ describe('Apps', () => { isLoading: false, }) - render() + render() expect(screen.getByText('Cat A'))!.toBeInTheDocument() expect(screen.queryByRole('button', { name: 'v' })).not.toBeInTheDocument() @@ -481,7 +481,7 @@ describe('Apps', () => { }) it('should clear the search, hide the sidebar during search, and close the modal when requested', async () => { - render() + render() const searchInput = screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate') fireEvent.change(searchInput, { @@ -510,7 +510,7 @@ describe('Apps', () => { it('clears an active search immediately and returns focus to the searchbox', async () => { const user = userEvent.setup() - render() + render() const searchInput = screen.getByRole('searchbox', { name: 'app.newAppFromTemplate.searchAllTemplate', diff --git a/web/app/components/app/create-app-dialog/app-list/index.tsx b/web/app/components/app/create-app-dialog/app-list/index.tsx index e0a0145dfad..691a97eac43 100644 --- a/web/app/components/app/create-app-dialog/app-list/index.tsx +++ b/web/app/components/app/create-app-dialog/app-list/index.tsx @@ -21,7 +21,7 @@ import { workspacePermissionKeysAtom } from '@/context/permission-state' import { userProfileQueryOptions } from '@/features/account-profile/client' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { fetchAppDetail } from '@/service/explore' import { useExploreAppList } from '@/service/use-explore' import { AppModeEnum } from '@/types/app' @@ -32,7 +32,7 @@ import AppCard from '../app-card' import Sidebar, { AppCategories, AppCategoryLabel } from './sidebar' type AppsProps = { - onSuccess?: () => void + onClose: () => void onCreateFromBlank?: () => void } @@ -41,7 +41,7 @@ type AppsProps = { // CREATE = 'create', // } -const Apps = ({ onSuccess, onCreateFromBlank }: AppsProps) => { +const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => { const { t } = useTranslation() const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions()) const { data: currentUserId } = useSuspenseQuery({ @@ -151,7 +151,7 @@ const Apps = ({ onSuccess, onCreateFromBlank }: AppsProps) => { setIsShowCreateModal(false) toast.success(t(($) => $['newApp.appCreated'], { ns: 'app' })) - if (onSuccess) onSuccess() + onClose() await handleCheckPluginDependencies(app.app_id) getRedirection( { id: app.app_id, mode: app.app_mode, permission_keys: app.permission_keys }, diff --git a/web/app/components/app/create-app-dialog/index.tsx b/web/app/components/app/create-app-dialog/index.tsx index 73ece1e3fef..8916ebff77e 100644 --- a/web/app/components/app/create-app-dialog/index.tsx +++ b/web/app/components/app/create-app-dialog/index.tsx @@ -5,17 +5,11 @@ import AppList from './app-list' type CreateAppDialogProps = { show: boolean - onSuccess: () => void onClose: () => void onCreateFromBlank?: () => void } -const CreateAppTemplateDialog = ({ - show, - onSuccess, - onClose, - onCreateFromBlank, -}: CreateAppDialogProps) => { +const CreateAppTemplateDialog = ({ show, onClose, onCreateFromBlank }: CreateAppDialogProps) => { const { t } = useTranslation() return ( @@ -24,13 +18,7 @@ const CreateAppTemplateDialog = ({ title={t(($) => $['newApp.startFromTemplate'], { ns: 'app' })} onClose={onClose} > - { - onSuccess() - onClose() - }} - /> + ) } diff --git a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx index b8beadb4232..3bbe0d7c8a1 100644 --- a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx +++ b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx @@ -1,9 +1,9 @@ +import type { ReactElement } from 'react' import type { App } from '@/types/app' import { fireEvent, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' -import { useProviderContext } from '@/context/provider-context' import { useRouter } from '@/next/navigation' -import { renderWithConsoleQuery as render } from '@/test/console/query-data' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { AppModeEnum } from '@/types/app' import { getRedirection } from '@/utils/app-redirection' import { trackCreateApp } from '@/utils/create-app-tracking' @@ -41,13 +41,14 @@ vi.mock('@/next/navigation', () => ({ vi.mock('@/utils/create-app-tracking', () => ({ trackCreateApp: vi.fn(), })) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() return { ...actual, consoleQuery: { ...actual.consoleQuery, + features: actual.consoleQuery.features, account: { profile: { get: { @@ -90,9 +91,6 @@ vi.mock('@/app/components/base/app-icon', () => ({ vi.mock('@/utils/app-redirection', () => ({ getRedirection: vi.fn(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: vi.fn(), -})) vi.mock('@/context/permission-state', async () => { const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture') @@ -110,33 +108,29 @@ const mockUseRouter = vi.mocked(useRouter) const mockPush = vi.fn() const mockTrackCreateApp = vi.mocked(trackCreateApp) const mockGetRedirection = vi.mocked(getRedirection) -const mockUseProviderContext = vi.mocked(useProviderContext) const { mockToastSuccess, mockToastError } = toastMocks -const defaultPlanUsage = { - buildApps: 0, - teamMembers: 0, - annotatedResponse: 0, - documentsUploadQuota: 0, - apiRateLimit: 0, - triggerEvents: 0, - vectorSpace: 0, -} +let appQuota = { size: 0, limit: 1 } const renderModal = () => { const onClose = vi.fn() - const onSuccess = vi.fn() const onCreateFromTemplate = vi.fn() render( , ) - return { onClose, onSuccess, onCreateFromTemplate } + return { onClose, onCreateFromTemplate } +} + +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { apps: appQuota }, + }) } describe('CreateAppModal', () => { @@ -144,15 +138,7 @@ describe('CreateAppModal', () => { vi.clearAllMocks() ahooksMocks.keyPressHandlers.length = 0 mockUseRouter.mockReturnValue({ push: mockPush } as unknown as ReturnType) - mockUseProviderContext.mockReturnValue({ - plan: { - type: AppModeEnum.ADVANCED_CHAT, - usage: defaultPlanUsage, - total: { ...defaultPlanUsage, buildApps: 1 }, - reset: {}, - }, - enableBilling: true, - } as unknown as ReturnType) + appQuota = { size: 0, limit: 1 } mockConsoleStateReader.mockReturnValue({ userProfile: { id: 'user-1' }, workspacePermissionKeys: ['app.create_and_management'], @@ -168,7 +154,7 @@ describe('CreateAppModal', () => { maintainer: 'user-1', } mockCreateApp.mockResolvedValue(mockApp as App) - const { onClose, onSuccess } = renderModal() + const { onClose } = renderModal() const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder') fireEvent.change(nameInput, { target: { value: 'My App' } }) @@ -190,8 +176,7 @@ describe('CreateAppModal', () => { appMode: AppModeEnum.ADVANCED_CHAT, }) expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated') - expect(onSuccess).toHaveBeenCalled() - expect(onClose).toHaveBeenCalled() + expect(onClose).toHaveBeenCalledTimes(1) await waitFor(() => expect(mockGetRedirection).toHaveBeenCalledWith(mockApp, mockPush, { currentUserId: 'user-1', @@ -256,15 +241,7 @@ describe('CreateAppModal', () => { }) it('shows the apps-full notice and disables creation when the workspace quota is exhausted', () => { - mockUseProviderContext.mockReturnValue({ - plan: { - type: AppModeEnum.ADVANCED_CHAT, - usage: { ...defaultPlanUsage, buildApps: 1 }, - total: { ...defaultPlanUsage, buildApps: 1 }, - reset: {}, - }, - enableBilling: true, - } as unknown as ReturnType) + appQuota = { size: 1, limit: 1 } renderModal() @@ -326,15 +303,7 @@ describe('CreateAppModal', () => { }) it('ignores the keyboard shortcut when the app quota is exhausted and closes the icon picker', async () => { - mockUseProviderContext.mockReturnValue({ - plan: { - type: AppModeEnum.ADVANCED_CHAT, - usage: { ...defaultPlanUsage, buildApps: 1 }, - total: { ...defaultPlanUsage, buildApps: 1 }, - reset: {}, - }, - enableBilling: true, - } as unknown as ReturnType) + appQuota = { size: 1, limit: 1 } renderModal() diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsx index fd0ad9311b6..47f2810f4ea 100644 --- a/web/app/components/app/create-app-modal/index.tsx +++ b/web/app/components/app/create-app-modal/index.tsx @@ -10,7 +10,7 @@ import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd' import { Textarea } from '@langgenius/dify-ui/textarea' import { toast } from '@langgenius/dify-ui/toast' import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys' -import { useMutation, useSuspenseQuery } from '@tanstack/react-query' +import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useDebounceFn } from 'ahooks' import { useAtomValue } from 'jotai' import { useCallback, useId, useRef, useState } from 'react' @@ -19,12 +19,11 @@ import AppIcon from '@/app/components/base/app-icon' import Divider from '@/app/components/base/divider' import AppsFull from '@/app/components/billing/apps-full-in-dialog' import { workspacePermissionKeysAtom } from '@/context/permission-state' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import useTheme from '@/hooks/use-theme' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' import { getRedirection } from '@/utils/app-redirection' import { trackCreateApp } from '@/utils/create-app-tracking' @@ -34,7 +33,6 @@ import AppIconPicker from '../../base/app-icon-picker' import { CreateAppDialogShell } from '../create-app-dialog-shell' type CreateAppProps = { - onSuccess: () => void onClose: () => void onCreateFromTemplate?: () => void defaultAppMode?: AppModeEnum @@ -50,7 +48,7 @@ const shouldExpandBeginnerAppTypes = (appMode?: AppModeEnum) => { ) } -function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: CreateAppProps) { +function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppProps) { const { t } = useTranslation() const { push } = useRouter() const nameInputId = useId() @@ -68,9 +66,21 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: shouldExpandBeginnerAppTypes(defaultAppMode), ) - const { plan, enableBilling } = useProviderContext() - const isAppsFull = enableBilling && plan.usage.buildApps >= plan.total.buildApps const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions()) + const deploymentEdition = systemFeatures.deployment_edition + const { data: appQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.apps, + }), + ) + const isAppQuotaUnavailable = deploymentEdition === 'CLOUD' && appQuota === undefined + // A limit of 0 means unlimited. + const isAppsFull = + deploymentEdition === 'CLOUD' && + appQuota !== undefined && + appQuota.limit > 0 && + appQuota.size >= appQuota.limit const { data: currentUserId } = useSuspenseQuery({ ...userProfileQueryOptions(), select: (data) => data.profile.id, @@ -83,7 +93,7 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: const [isCreating, setIsCreating] = useState(false) const onCreate = useCallback(async () => { - if (!canCreateApp) return + if (isAppQuotaUnavailable || isAppsFull || !canCreateApp) return if (!appMode) { toast.error(t(($) => $['newApp.appTypeRequired'], { ns: 'app' })) @@ -120,7 +130,6 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: } toast.success(t(($) => $['newApp.appCreated'], { ns: 'app' })) - onSuccess() onClose() getRedirection(app, push, { currentUserId, @@ -139,6 +148,8 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: setIsCreating(false) } }, [ + isAppQuotaUnavailable, + isAppsFull, canCreateApp, currentUserId, name, @@ -146,7 +157,6 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: appMode, appIcon, description, - onSuccess, onClose, push, workspacePermissionKeys, @@ -158,7 +168,7 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: useHotkey( CREATE_APP_HOTKEY, () => { - if (isAppsFull || !canCreateApp) return + if (isAppQuotaUnavailable || isAppsFull || !canCreateApp) return handleCreateApp() }, { @@ -361,7 +371,7 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:
{deploymentRequest && ( (queryFn: QueryFunction): QueryFunction { diff --git a/web/app/components/app/deploy/state.ts b/web/app/components/app/deploy/state.ts index e634cba9839..789889a54f5 100644 --- a/web/app/components/app/deploy/state.ts +++ b/web/app/components/app/deploy/state.ts @@ -6,7 +6,7 @@ import { atom } from 'jotai' import { atomWithInfiniteQuery, atomWithQuery } from 'jotai-tanstack-query' import { selectAtom, useHydrateAtoms } from 'jotai/utils' import { useTranslation } from 'react-i18next' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { appWorkflowQueryOptions, appWorkflowVersionsInfiniteQueryOptions, diff --git a/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx index 865ece216c3..1f5adc98622 100644 --- a/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx +++ b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx @@ -1,22 +1,19 @@ -import { render, screen, waitFor } from '@testing-library/react' +import type { ReactElement } from 'react' +import { act, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' +import { consoleQuery } from '@/service/console' +import { + createConsoleQueryClient, + renderWithConsoleQuery, + seedFeatures, +} from '@/test/console/query-data' import DuplicateAppModal from '../index' -const { mockProviderContext, toastErrorMock } = vi.hoisted(() => ({ - mockProviderContext: { - plan: { - usage: { buildApps: 0 }, - total: { buildApps: 1 }, - }, - enableBilling: true, - }, +const { mockAppQuota, toastErrorMock } = vi.hoisted(() => ({ + mockAppQuota: { size: 0, limit: 1 }, toastErrorMock: vi.fn(), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockProviderContext, -})) - vi.mock('@langgenius/dify-ui/toast', () => ({ toast: { error: (...args: unknown[]) => toastErrorMock(...args), @@ -70,6 +67,13 @@ vi.mock('@/app/components/base/app-icon-picker', () => ({ }, })) +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { apps: mockAppQuota }, + }) +} + describe('DuplicateAppModal', () => { const getIconButton = () => screen.getByRole('button', { @@ -78,8 +82,8 @@ describe('DuplicateAppModal', () => { beforeEach(() => { vi.clearAllMocks() - mockProviderContext.plan.usage.buildApps = 0 - mockProviderContext.plan.total.buildApps = 1 + mockAppQuota.size = 0 + mockAppQuota.limit = 1 }) it('should render a named dialog', () => { @@ -212,7 +216,7 @@ describe('DuplicateAppModal', () => { const onConfirm = vi.fn() const onHide = vi.fn() const user = userEvent.setup() - mockProviderContext.plan.usage.buildApps = 1 + mockAppQuota.size = 1 render( { ) }) }) + +it('waits for the real Cloud quota and allows an unlimited quota without an upgrade notice', async () => { + const queryClient = createConsoleQueryClient() + void queryClient.query({ + ...consoleQuery.features.get.queryOptions(), + queryFn: () => new Promise(() => {}), + }) + const onConfirm = vi.fn() + renderWithConsoleQuery( + , + { queryClient, systemFeatures: { deployment_edition: 'CLOUD' } }, + ) + const button = screen.getByRole('button', { name: /(?:^|\.)duplicate(?=$|:)/ }) + expect(button).toBeDisabled() + expect(screen.queryByText('apps-full')).not.toBeInTheDocument() + await act(async () => { + seedFeatures(queryClient, { apps: { size: 100, limit: 0 } }) + }) + await waitFor(() => expect(button).toBeEnabled()) + await userEvent.setup().click(button) + expect(onConfirm).toHaveBeenCalledOnce() +}) diff --git a/web/app/components/app/duplicate-modal/index.tsx b/web/app/components/app/duplicate-modal/index.tsx index 86458018dda..85e6cab976b 100644 --- a/web/app/components/app/duplicate-modal/index.tsx +++ b/web/app/components/app/duplicate-modal/index.tsx @@ -6,12 +6,15 @@ import { Field, FieldLabel } from '@langgenius/dify-ui/field' import { IconButton } from '@langgenius/dify-ui/icon-button' import { Input } from '@langgenius/dify-ui/input' import { toast } from '@langgenius/dify-ui/toast' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useState } from 'react' import { useTranslation } from 'react-i18next' import AppIcon from '@/app/components/base/app-icon' import AppsFull from '@/app/components/billing/apps-full-in-dialog' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' +import { consoleQuery } from '@/service/console' import AppIconPicker from '../../base/app-icon-picker' export type DuplicateAppModalProps = { @@ -51,11 +54,23 @@ const DuplicateAppModal = ({ : { type: 'emoji' as const, icon, background: icon_background }, ) - const { plan, enableBilling } = useProviderContext() - const isAppsFull = enableBilling && plan.usage.buildApps >= plan.total.buildApps + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: appQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.apps, + }), + ) + const isAppQuotaUnavailable = deploymentEdition === 'CLOUD' && appQuota === undefined + // A limit of 0 means unlimited. + const isAppsFull = + deploymentEdition === 'CLOUD' && + appQuota !== undefined && + appQuota.limit > 0 && + appQuota.size >= appQuota.limit const submit = () => { - if (isAppsFull) return + if (isAppQuotaUnavailable || isAppsFull) return if (!name.trim()) { toast.error(t(($) => $['appCustomize.nameRequired'], { ns: 'explore' })) @@ -130,7 +145,12 @@ const DuplicateAppModal = ({ {isAppsFull && }
-
- {webappCopyrightEnabled ? ( + {webappCopyrightEnabled !== false ? ( $[`${prefixSettings}.more.copyright`], { ns: 'appOverview', })} @@ -701,6 +710,7 @@ const SettingsModal: FC = ({ ns: 'appOverview', })} className="mt-2 h-10" + disabled={webappCopyrightEnabled !== true} value={inputInfo.copyright} onChange={onChange('copyright')} placeholder={ diff --git a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx index 3868b51505e..f8ade350ced 100644 --- a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx +++ b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx @@ -1,9 +1,10 @@ import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen' +import type { ReactElement } from 'react' import { screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import * as React from 'react' import { useStore as useAppStore } from '@/app/components/app/store' -import { renderWithConsoleQuery as render } from '@/test/console/query-data' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { AppModeEnum } from '@/types/app' import SwitchAppModal from '../index' @@ -37,7 +38,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -let mockEnableBilling = false +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' let mockPlan = { type: 'sandbox', usage: { @@ -59,12 +60,6 @@ let mockPlan = { vectorSpace: 0, }, } -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - plan: mockPlan, - enableBilling: mockEnableBilling, - }), -})) vi.mock('@/app/components/billing/apps-full-in-dialog', () => ({ default: ({ loc }: { loc: string }) => ( @@ -140,6 +135,13 @@ const renderComponent = (overrides: Partial { beforeEach(() => { vi.clearAllMocks() @@ -152,7 +154,7 @@ describe('SwitchAppModal', () => { originalSetAppDetail(...args) }) useAppStore.setState({ setAppDetail: setAppDetailSpy as typeof originalSetAppDetail }) - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' mockPlan = { type: 'sandbox', usage: { @@ -216,7 +218,7 @@ describe('SwitchAppModal', () => { it('should render the apps full warning when plan limits are reached', () => { // Arrange - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlan = { ...mockPlan, usage: { ...mockPlan.usage, buildApps: 10 }, diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsx index 821513f2e8f..ba56025dbf8 100644 --- a/web/app/components/app/switch-app-modal/index.tsx +++ b/web/app/components/app/switch-app-modal/index.tsx @@ -17,16 +17,15 @@ import { cn } from '@langgenius/dify-ui/cn' import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog' import { Input } from '@langgenius/dify-ui/input' import { toast } from '@langgenius/dify-ui/toast' -import { useMutation, useSuspenseQuery } from '@tanstack/react-query' +import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useId, useState } from 'react' import { useTranslation } from 'react-i18next' import { useStore as useAppStore } from '@/app/components/app/store' import AppIcon from '@/app/components/base/app-icon' import AppsFull from '@/app/components/billing/apps-full-in-dialog' -import { useProviderContext } from '@/context/provider-context' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' import { getRedirection } from '@/utils/app-redirection' import AppIconPicker from '../../base/app-icon-picker' @@ -49,8 +48,20 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switc const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions()) const isRbacEnabled = systemFeatures.rbac_enabled - const { plan, enableBilling } = useProviderContext() - const isAppsFull = enableBilling && plan.usage.buildApps >= plan.total.buildApps + const deploymentEdition = systemFeatures.deployment_edition + const { data: appQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.apps, + }), + ) + const isAppQuotaUnavailable = deploymentEdition === 'CLOUD' && appQuota === undefined + // A limit of 0 means unlimited. + const isAppsFull = + deploymentEdition === 'CLOUD' && + appQuota !== undefined && + appQuota.limit > 0 && + appQuota.size >= appQuota.limit const [showAppIconPicker, setShowAppIconPicker] = useState(false) const appIconType = zIconType.safeParse(appDetail.icon_type).data @@ -75,6 +86,7 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switc ) const goStart = async () => { + if (isAppQuotaUnavailable || isAppsFull) return try { const { new_app_id: newAppID, permission_keys } = await convertToWorkflow({ params: { app_id: appDetail.id }, @@ -214,7 +226,7 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switc - @@ -98,13 +79,7 @@ vi.mock( onEdit: () => void cached: boolean }) { - const { setShowAnnotationFullModal } = useModalContext() - const { plan, enableBilling } = useProviderContext() const handleAdd = () => { - if (enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse) { - setShowAnnotationFullModal() - return - } onAdded('ann-new', 'Test User') } return ( @@ -266,8 +241,7 @@ describe('Operation', () => { mockContextValue.onAnnotationRemoved = vi.fn() mockContextValue.readonly = false mockContextValue.showRegenerate = false - mockProviderContext.plan.usage.annotatedResponse = 0 - mockProviderContext.enableBilling = false + mockAddAnnotation.mockResolvedValue({ id: 'ann-new', account: { name: 'Test User' } }) }) @@ -1060,17 +1034,6 @@ describe('Operation', () => { ) }) - it('should show annotation full modal when limit reached', async () => { - const user = userEvent.setup() - mockProviderContext.enableBilling = true - mockProviderContext.plan.usage.annotatedResponse = 100 - renderOperation() - const addBtn = screen.getByTestId('annotation-add-btn') - await user.click(addBtn) - expect(mockSetShowAnnotationFullModal).toHaveBeenCalled() - expect(mockAddAnnotation).not.toHaveBeenCalled() - }) - it('should open edit reply modal when cached annotation exists', async () => { const user = userEvent.setup() const item = { @@ -1096,19 +1059,6 @@ describe('Operation', () => { expect(mockContextValue.onAnnotationEdited).toHaveBeenCalledWith('eq', 'ea', 0) }) - it('should call onAnnotationAdded from edit reply modal', async () => { - const user = userEvent.setup() - const item = { - ...baseItem, - annotation: { id: 'ann-1', created_at: 123, authorName: 'test author' }, - } - renderOperation({ ...baseProps, item }) - const editBtn = screen.getByTestId('annotation-edit-btn') - await user.click(editBtn) - await user.click(screen.getByTestId('modal-add')) - expect(mockContextValue.onAnnotationAdded).toHaveBeenCalledWith('a1', 'author', 'eq', 'ea', 0) - }) - it('should call onAnnotationRemoved from edit reply modal', async () => { const user = userEvent.setup() const item = { diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsx index b19665a2bd4..5efbe278609 100644 --- a/web/app/components/base/chat/chat/answer/operation.tsx +++ b/web/app/components/base/chat/chat/answer/operation.tsx @@ -443,21 +443,18 @@ function Operation({
)}
- {canManageAnnotation && ( + {canManageAnnotation && annotation?.id && isShowReplyModal && ( setIsShowReplyModal(false)} query={question} answer={content} onEdited={(editedQuery, editedAnswer) => onAnnotationEdited?.(editedQuery, editedAnswer, index) } - onAdded={(annotationId, authorName, editedQuery, editedAnswer) => - onAnnotationAdded?.(annotationId, authorName, editedQuery, editedAnswer, index) - } appId={config?.appId || ''} messageId={id} - annotationId={annotation?.id || ''} + annotationId={annotation.id} createdAt={annotation?.created_at} onRemove={() => onAnnotationRemoved?.(index)} /> diff --git a/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsx b/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsx index 34cc4225f3a..d5db454180f 100644 --- a/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsx +++ b/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsx @@ -1,5 +1,6 @@ import type { Features } from '../../types' -import { render, screen } from '@testing-library/react' +import { screen } from '@testing-library/react' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { FeaturesProvider } from '../../context' import NewFeaturePanel from '../index' @@ -88,7 +89,7 @@ const renderPanel = ( showAnnotationReply: boolean }> = {}, ) => { - return render( + return renderWithConsoleQuery( ({ })) let mockAnnotatedResponseUsage = 5 -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - plan: { - usage: { - get annotatedResponse() { - return mockAnnotatedResponseUsage - }, - }, - total: { annotatedResponse: 100 }, - }, - enableBilling: true, - }), -})) const mockAddAnnotation = vi.fn().mockResolvedValue({ id: 'annotation-1', @@ -42,6 +31,13 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ }, })) +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { annotation_quota_limit: { size: mockAnnotatedResponseUsage, limit: 100 } }, + }) +} + describe('AnnotationCtrlButton', () => { beforeEach(() => { vi.clearAllMocks() diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/use-annotation-config.spec.ts b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/use-annotation-config.spec.ts index b001f0542c3..ec76acd16fa 100644 --- a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/use-annotation-config.spec.ts +++ b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/use-annotation-config.spec.ts @@ -1,19 +1,11 @@ import type { AnnotationReplyConfig } from '@/models/debug' -import { act, renderHook } from '@testing-library/react' +import { act } from '@testing-library/react' import { queryAnnotationJobStatus, updateAnnotationStatus } from '@/service/annotation' +import { renderHookWithConsoleQuery } from '@/test/console/query-data' import { sleep } from '@/utils' import useAnnotationConfig from '../use-annotation-config' let mockIsAnnotationFull = false -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - plan: { - usage: { annotatedResponse: mockIsAnnotationFull ? 100 : 5 }, - total: { annotatedResponse: 100 }, - }, - enableBilling: true, - }), -})) vi.mock('@/service/annotation', () => ({ updateAnnotationStatus: vi.fn().mockResolvedValue({ job_id: 'test-job-id' }), @@ -24,6 +16,13 @@ vi.mock('@/utils', () => ({ sleep: vi.fn().mockResolvedValue(undefined), })) +function renderHook(callback: () => Result) { + return renderHookWithConsoleQuery(callback, { + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { annotation_quota_limit: { size: mockIsAnnotationFull ? 100 : 5, limit: 100 } }, + }) +} + describe('useAnnotationConfig', () => { const defaultConfig: AnnotationReplyConfig = { id: 'test-id', @@ -40,6 +39,27 @@ describe('useAnnotationConfig', () => { mockIsAnnotationFull = false }) + it('edits enabled annotation parameters without depending on unused creation quota', async () => { + const setAnnotationConfig = vi.fn() + const { result } = renderHookWithConsoleQuery( + () => + useAnnotationConfig({ + appId: 'test-app', + annotationConfig: { ...defaultConfig, enabled: true }, + setAnnotationConfig, + }), + { systemFeatures: { deployment_edition: 'CLOUD' } }, + ) + + act(() => result.current.setIsShowAnnotationConfigInit(true)) + expect(result.current.isShowAnnotationConfigInit).toBe(true) + await act(async () => { + await result.current.handleEnableAnnotation(defaultConfig.embedding_model!) + }) + expect(updateAnnotationStatus).toHaveBeenCalled() + expect(setAnnotationConfig).toHaveBeenCalled() + }) + it('should initialize with annotation config init hidden', () => { const setAnnotationConfig = vi.fn() const { result } = renderHook(() => diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx index 71275d8f39b..a1a09a71167 100644 --- a/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx +++ b/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx @@ -4,11 +4,14 @@ import { IconButton } from '@langgenius/dify-ui/icon-button' import { toast } from '@langgenius/dify-ui/toast' import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip' import { RiEditLine, RiFileEditLine } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useTranslation } from 'react-i18next' import { useModalContext } from '@/context/modal-context' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' import { addAnnotation } from '@/service/annotation' +import { consoleQuery } from '@/service/console' type Props = Readonly<{ appId: string @@ -29,11 +32,24 @@ const AnnotationCtrlButton: FC = ({ onEdit, }) => { const { t } = useTranslation() - const { plan, enableBilling } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: annotationQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.annotation_quota_limit, + }), + ) + const isAnnotationQuotaUnavailable = + deploymentEdition === 'CLOUD' && annotationQuota === undefined + // A limit of 0 means unlimited. const isAnnotationFull = - enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse + deploymentEdition === 'CLOUD' && + annotationQuota !== undefined && + annotationQuota.limit > 0 && + annotationQuota.size >= annotationQuota.limit const { setShowAnnotationFullModal } = useModalContext() const handleAdd = async () => { + if (isAnnotationQuotaUnavailable) return if (isAnnotationFull) { setShowAnnotationFullModal() return @@ -71,6 +87,7 @@ const AnnotationCtrlButton: FC = ({ render={ $['feature.annotation.add'], { ns: 'appDebug' })} + disabled={isAnnotationQuotaUnavailable} onClick={handleAdd} > diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/index.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/index.tsx index 5dc697148ef..80945a22809 100644 --- a/web/app/components/base/features/new-feature-panel/annotation-reply/index.tsx +++ b/web/app/components/base/features/new-feature-panel/annotation-reply/index.tsx @@ -43,6 +43,7 @@ const AnnotationReply = ({ disabled, onChange }: Props) => { ) const { + isAnnotationQuotaUnavailable, handleEnableAnnotation, handleDisableAnnotation, isShowAnnotationConfigInit, @@ -86,7 +87,7 @@ const AnnotationReply = ({ disabled, onChange }: Props) => { onChange={(state) => handleSwitch(state)} onMouseEnter={() => setIsHovering(true)} onMouseLeave={() => setIsHovering(false)} - disabled={disabled} + disabled={disabled || (!annotationReply?.enabled && isAnnotationQuotaUnavailable)} > <> {!annotationReply?.enabled && ( diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/use-annotation-config.ts b/web/app/components/base/features/new-feature-panel/annotation-reply/use-annotation-config.ts index 8cde3021d1f..58e4b238979 100644 --- a/web/app/components/base/features/new-feature-panel/annotation-reply/use-annotation-config.ts +++ b/web/app/components/base/features/new-feature-panel/annotation-reply/use-annotation-config.ts @@ -1,12 +1,15 @@ import type { EmbeddingModelConfig } from '@/app/components/app/annotation/type' import type { AnnotationReplyConfig } from '@/models/debug' +import { useQuery } from '@tanstack/react-query' import { produce } from 'immer' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useState } from 'react' import { AnnotationEnableStatus, JobStatus } from '@/app/components/app/annotation/type' import { ANNOTATION_DEFAULT } from '@/config' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' import { queryAnnotationJobStatus, updateAnnotationStatus } from '@/service/annotation' +import { consoleQuery } from '@/service/console' import { sleep } from '@/utils' type Params = { @@ -15,13 +18,26 @@ type Params = { setAnnotationConfig: (annotationConfig: AnnotationReplyConfig) => void } const useAnnotationConfig = ({ appId, annotationConfig, setAnnotationConfig }: Params) => { - const { plan, enableBilling } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: annotationQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD' && !annotationConfig.enabled, + select: (data) => data.annotation_quota_limit, + }), + ) + const isAnnotationQuotaUnavailable = + deploymentEdition === 'CLOUD' && annotationQuota === undefined + // A limit of 0 means unlimited. const isAnnotationFull = - enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse + deploymentEdition === 'CLOUD' && + annotationQuota !== undefined && + annotationQuota.limit > 0 && + annotationQuota.size >= annotationQuota.limit const [isShowAnnotationFullModal, setIsShowAnnotationFullModal] = useState(false) const [isShowAnnotationConfigInit, doSetIsShowAnnotationConfigInit] = React.useState(false) const setIsShowAnnotationConfigInit = (isShow: boolean) => { - if (isShow) { + if (isShow && !annotationConfig.enabled) { + if (isAnnotationQuotaUnavailable) return if (isAnnotationFull) { setIsShowAnnotationFullModal(true) return @@ -41,7 +57,7 @@ const useAnnotationConfig = ({ appId, annotationConfig, setAnnotationConfig }: P } const handleEnableAnnotation = async (embeddingModel: EmbeddingModelConfig, score?: number) => { - if (isAnnotationFull) return + if (!annotationConfig.enabled && (isAnnotationQuotaUnavailable || isAnnotationFull)) return const { job_id: jobId }: any = await updateAnnotationStatus( appId, @@ -81,6 +97,7 @@ const useAnnotationConfig = ({ appId, annotationConfig, setAnnotationConfig }: P } return { + isAnnotationQuotaUnavailable, handleEnableAnnotation, handleDisableAnnotation, isShowAnnotationConfigInit, diff --git a/web/app/components/base/features/new-feature-panel/text-to-speech/param-config-content.tsx b/web/app/components/base/features/new-feature-panel/text-to-speech/param-config-content.tsx index 588b4f9836d..7eb99ac4095 100644 --- a/web/app/components/base/features/new-feature-panel/text-to-speech/param-config-content.tsx +++ b/web/app/components/base/features/new-feature-panel/text-to-speech/param-config-content.tsx @@ -22,7 +22,7 @@ import { useFeatures, useFeaturesStore } from '@/app/components/base/features/ho import { Infotip } from '@/app/components/base/infotip' import { languages } from '@/i18n-config/language' import { usePathname } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { TtsAutoPlay } from '@/types/app' type SelectOption = { diff --git a/web/app/components/base/markdown-blocks/__tests__/shiki-highlight.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/shiki-highlight.spec.tsx new file mode 100644 index 00000000000..7c30b275259 --- /dev/null +++ b/web/app/components/base/markdown-blocks/__tests__/shiki-highlight.spec.tsx @@ -0,0 +1,40 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { highlightCode } from '../shiki-highlight' + +describe('README code highlighting', () => { + it.each(['github-light', 'github-dark'] as const)('highlights dotenv with %s', async (theme) => { + const code = 'OPENAI_API_KEY=your-api-key\n# OPENAI_ORGANIZATION=org-id' + const result = renderToStaticMarkup(await highlightCode({ code, language: 'dotenv', theme })) + + expect(result).toContain('OPENAI_API_KEY') + expect(result).toContain('your-api-key') + expect(result).toContain('OPENAI_ORGANIZATION=org-id') + expect(result).toContain(' { diff --git a/web/app/components/base/markdown-blocks/shiki-highlight.tsx b/web/app/components/base/markdown-blocks/shiki-highlight.tsx index cfc075827f4..beae5f80189 100644 --- a/web/app/components/base/markdown-blocks/shiki-highlight.tsx +++ b/web/app/components/base/markdown-blocks/shiki-highlight.tsx @@ -1,13 +1,13 @@ import type { JSX } from 'react' -import type { BundledLanguage, BundledTheme } from 'shiki/bundle/web' +import type { BundledTheme } from 'shiki/bundle/web' import { toJsxRuntime } from 'hast-util-to-jsx-runtime' import { Fragment } from 'react' import { jsx, jsxs } from 'react/jsx-runtime' -import { codeToHast } from 'shiki/bundle/web' +import { bundledLanguages, getSingletonHighlighter } from 'shiki/bundle/web' type HighlightCodeOptions = { code: string - language: BundledLanguage + language: string theme: BundledTheme } @@ -16,8 +16,19 @@ export const highlightCode = async ({ language, theme, }: HighlightCodeOptions): Promise => { - const hast = await codeToHast(code, { - lang: language, + const normalizedLanguage = language.trim().toLowerCase() + const lang = + normalizedLanguage === 'dotenv' || Object.hasOwn(bundledLanguages, normalizedLanguage) + ? normalizedLanguage + : 'text' + // README fences may name languages outside the web bundle. Load dotenv on + // demand and keep unknown languages readable without throwing an error. + const highlighter = await getSingletonHighlighter({ + langs: lang === 'dotenv' ? [(await import('shiki/langs/dotenv.mjs')).default] : [lang], + themes: [theme], + }) + const hast = highlighter.codeToHast(code, { + lang, theme, }) diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx index 70391788716..f70f16c604e 100644 --- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx +++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx @@ -3,16 +3,27 @@ import type { UpdateWorkflowNodesMapPayload } from '../index' import type { ValueSelector, Var } from '@/app/components/workflow/types' import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext' import { mergeRegister } from '@lexical/utils' -import { act, render, screen } from '@testing-library/react' +import { act, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useReactFlow, useStoreApi } from 'reactflow' import { Type } from '@/app/components/workflow/nodes/llm/types' import { BlockEnum, VarType } from '@/app/components/workflow/types' +import { consoleQuery } from '@/service/console' +import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { useSelectOrDelete } from '../../../hooks' import WorkflowVariableBlockComponent from '../component' import { UPDATE_WORKFLOW_NODES_MAP } from '../index' import { WorkflowVariableBlockNode } from '../node' +const render: typeof renderWithConsoleQuery = (ui, options) => { + const queryClient = createConsoleQueryClient() + queryClient.setQueryData(consoleQuery.workspaces.current.modelProviders.summary.get.queryKey(), { + data: [], + plugins: {}, + }) + return renderWithConsoleQuery(ui, { ...options, queryClient }) +} + const { mockVarLabel, mockIsExceptionVariable, mockForcedVariableKind } = vi.hoisted(() => ({ mockVarLabel: vi.fn(), mockIsExceptionVariable: vi.fn<(variable: string, nodeType?: BlockEnum) => boolean>(() => false), diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/use-llm-model-plugin-installed.spec.ts b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/use-llm-model-plugin-installed.spec.ts index 94bf87001c0..2466eca3c8a 100644 --- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/use-llm-model-plugin-installed.spec.ts +++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/use-llm-model-plugin-installed.spec.ts @@ -1,15 +1,28 @@ +import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen' import type { WorkflowNodesMap } from '@/app/components/base/prompt-editor/types' -import { renderHook } from '@testing-library/react' import { BlockEnum } from '@/app/components/workflow/types' +import { consoleQuery } from '@/service/console' +import { createConsoleQueryClient, renderHookWithConsoleQuery } from '@/test/console/query-data' import { useLlmModelPluginInstalled } from '../use-llm-model-plugin-installed' -let mockModelProviders: Array<{ provider: string }> = [] +const providerSummaryFixture = { + provider: 'openai', + plugin_id: 'langgenius/openai', + label: { en_US: 'OpenAI' }, + configurate_methods: ['predefined-model'], + supported_model_types: ['llm'], + preferred_provider_type: 'custom', + is_configured: true, + system_configuration: { enabled: false }, + custom_configuration: { + status: 'active', + available_credentials: [], + current_credential_usable: true, + has_custom_models: false, + }, +} satisfies ModelProviderSummaryResponse -vi.mock('@/context/provider-context', () => ({ - useProviderContextSelector: ( - selector: (state: { modelProviders: Array<{ provider: string }> }) => T, - ): T => selector({ modelProviders: mockModelProviders }), -})) +let mockModelProviders: Array<{ provider: string }> = [] const createWorkflowNodesMap = (node: Record): WorkflowNodesMap => ({ @@ -20,6 +33,18 @@ const createWorkflowNodesMap = (node: Record): WorkflowNodesMap }, }) as unknown as WorkflowNodesMap +const renderHook: typeof renderHookWithConsoleQuery = (callback, options) => { + const queryClient = createConsoleQueryClient() + queryClient.setQueryData(consoleQuery.workspaces.current.modelProviders.summary.get.queryKey(), { + data: mockModelProviders.map( + (provider) => + ({ ...providerSummaryFixture, ...provider }) satisfies ModelProviderSummaryResponse, + ), + plugins: {}, + }) + return renderHookWithConsoleQuery(callback, { ...options, queryClient }) +} + describe('useLlmModelPluginInstalled', () => { beforeEach(() => { vi.clearAllMocks() diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.ts b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.ts index 5c6f1b17375..5922a992a46 100644 --- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.ts +++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.ts @@ -1,7 +1,8 @@ import type { WorkflowNodesMap } from '@/app/components/base/prompt-editor/types' +import { useQuery } from '@tanstack/react-query' import { BlockEnum } from '@/app/components/workflow/types' import { extractPluginId } from '@/app/components/workflow/utils/plugin' -import { useProviderContextSelector } from '@/context/provider-context' +import { consoleQuery } from '@/service/console' export function useLlmModelPluginInstalled( nodeId: string, @@ -11,8 +12,13 @@ export function useLlmModelPluginInstalled( const modelProvider = node?.type === BlockEnum.LLM ? node.modelProvider : undefined const modelPluginId = modelProvider ? extractPluginId(modelProvider) : undefined - return useProviderContextSelector((state) => { - if (!modelPluginId) return true - return state.modelProviders.some((p) => extractPluginId(p.provider) === modelPluginId) - }) + const { data: isInstalled = !modelPluginId } = useQuery( + consoleQuery.workspaces.current.modelProviders.summary.get.queryOptions({ + select: (response) => + !modelPluginId || + response.data.some((provider) => extractPluginId(provider.provider) === modelPluginId), + }), + ) + + return isInstalled } diff --git a/web/app/components/base/voice-input/__tests__/api.spec.ts b/web/app/components/base/voice-input/__tests__/api.spec.ts index 3f155c6ae33..30ccf7db2eb 100644 --- a/web/app/components/base/voice-input/__tests__/api.spec.ts +++ b/web/app/components/base/voice-input/__tests__/api.spec.ts @@ -1,4 +1,4 @@ -import { consoleClient } from '@/service/client' +import { consoleClient } from '@/service/console' import { AppSourceType, audioToText } from '@/service/share' import { transcribeAudio } from '../api' @@ -10,7 +10,7 @@ vi.mock('@/service/share', async (importOriginal) => { } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { apps: { byAppId: { diff --git a/web/app/components/base/voice-input/api.ts b/web/app/components/base/voice-input/api.ts index 13e31eefdba..3d1cc8f6193 100644 --- a/web/app/components/base/voice-input/api.ts +++ b/web/app/components/base/voice-input/api.ts @@ -7,7 +7,7 @@ export async function transcribeAudio( signal?: AbortSignal, ): Promise<{ text: string }> { if (target.type === 'agent' || target.type === 'consoleApp') { - const { consoleClient } = await import('@/service/client') + const { consoleClient } = await import('@/service/console') if (target.type === 'agent') { return consoleClient.agent.byAgentId.audioToText.post( { diff --git a/web/app/components/billing/__tests__/query-state.spec.tsx b/web/app/components/billing/__tests__/query-state.spec.tsx new file mode 100644 index 00000000000..68571d5989b --- /dev/null +++ b/web/app/components/billing/__tests__/query-state.spec.tsx @@ -0,0 +1,150 @@ +import { act, render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { ModalContextProvider } from '@/context/modal-context-provider' +import { consoleQuery } from '@/service/console' +import { + createConsoleQueryClient, + createConsoleQueryWrapper, + seedFeatures, +} from '@/test/console/query-data' +import { createNuqsTestWrapper } from '@/test/nuqs-testing' +import AnnotationUsage from '../annotation-full/usage' +import Billing from '../billing-page' + +vi.mock('@/service/base', () => ({ + request: vi.fn(() => new Promise(() => {})), + sseGeneratorPost: vi.fn(), +})) +vi.mock('../upgrade-btn', () => ({ default: () => null })) +vi.mock('../hooks/use-education-discount', () => ({ + useEducationDiscount: () => ({ + handleEducationDiscount: vi.fn(), + isEducationDiscountLoading: false, + }), +})) + +it('reveals the plan and all usage together when both billing queries have data', async () => { + const queryClient = createConsoleQueryClient() + const { wrapper } = createConsoleQueryWrapper({ + queryClient, + systemFeatures: { deployment_edition: 'CLOUD' }, + }) + render(, { wrapper }) + expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument() + expect(screen.queryByText('billing.plans.sandbox.name')).not.toBeInTheDocument() + expect( + screen.queryByRole('group', { name: 'billing.usagePage.buildApps' }), + ).not.toBeInTheDocument() + await act(async () => { + seedFeatures(queryClient, { + billing: { subscription: { plan: 'professional' } }, + apps: { size: 17, limit: 50 }, + }) + }) + expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument() + expect( + screen.queryByRole('group', { name: 'billing.usagePage.buildApps' }), + ).not.toBeInTheDocument() + await act(async () => { + queryClient.setQueryData(consoleQuery.features.vectorSpace.get.queryKey(), { + size: 256, + limit: 900, + usage_unknown: false, + }) + }) + const apps = await screen.findByRole('group', { name: 'billing.usagePage.buildApps' }) + expect(within(apps).getByText('17')).toBeInTheDocument() + expect(within(apps).getByText('50')).toBeInTheDocument() + expect(screen.getByText('billing.plans.professional.name')).toBeInTheDocument() + const storage = screen.getByRole('group', { name: 'billing.usagePage.vectorSpace' }) + expect(within(storage).getByText('256')).toBeInTheDocument() + expect(within(storage).getByText('900MB')).toBeInTheDocument() + expect(screen.queryByRole('status', { name: 'appApi.loading' })).not.toBeInTheDocument() +}) + +it('renders annotation usage only from returned data and preserves zero as an unlimited quota', async () => { + const queryClient = createConsoleQueryClient() + const { wrapper } = createConsoleQueryWrapper({ queryClient }) + render(, { wrapper }) + expect( + screen.queryByRole('group', { name: 'billing.annotatedResponse.quotaTitle' }), + ).not.toBeInTheDocument() + await act(async () => { + seedFeatures(queryClient, { annotation_quota_limit: { size: 4, limit: 0 } }) + }) + const annotation = await screen.findByRole('group', { + name: 'billing.annotatedResponse.quotaTitle', + }) + expect(within(annotation).getByText('4')).toBeInTheDocument() + expect(within(annotation).getByText('billing.plansCommon.unlimited')).toBeInTheDocument() +}) + +it.each([ + { limit: 0, usage: 0, percent: 100 }, + { limit: -1, usage: 25, percent: 0 }, + { limit: 100, usage: 25, percent: 25 }, + { limit: 100, usage: 100, percent: 100 }, +])( + 'renders event and API quotas with limit $limit and usage $usage', + async ({ limit, usage, percent }) => { + const { queryClient, wrapper } = createConsoleQueryWrapper({ + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { + trigger_event: { limit, usage }, + api_rate_limit: { limit, usage }, + apps: { size: 4, limit: 0 }, + }, + }) + queryClient.setQueryData(consoleQuery.features.vectorSpace.get.queryKey(), { + size: 256, + limit: 900, + usage_unknown: false, + }) + render(, { wrapper }) + + for (const name of ['billing.usagePage.triggerEvents', 'billing.plansCommon.apiRateLimit']) { + const quota = within(await screen.findByRole('group', { name })) + expect(quota.getByTestId('billing-quota-value')).toHaveTextContent( + `${usage}/${limit === -1 ? 'billing.plansCommon.unlimited' : limit}`, + ) + expect(quota.getByRole('meter', { name })).toHaveAttribute('aria-valuenow', String(percent)) + if (limit !== -1) + expect(quota.queryByText('billing.plansCommon.unlimited')).not.toBeInTheDocument() + } + + const apps = within(screen.getByRole('group', { name: 'billing.usagePage.buildApps' })) + expect(apps.getByText('billing.plansCommon.unlimited')).toBeInTheDocument() + }, +) + +it('shows a dismissible limit dialog when the workspace receives a zero event quota', async () => { + localStorage.clear() + const user = userEvent.setup() + const { queryClient, wrapper } = createConsoleQueryWrapper({ + systemFeatures: { deployment_edition: 'CLOUD' }, + currentWorkspace: { id: 'workspace-zero-quota' }, + }) + const { wrapper: NuqsWrapper } = createNuqsTestWrapper() + render( + + + Workspace + + , + { wrapper }, + ) + + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + await act(async () => { + seedFeatures(queryClient, { + billing: { subscription: { plan: 'professional' } }, + trigger_event: { limit: 0, usage: 0, reset_date: -1 }, + }) + }) + const dialog = await screen.findByRole('dialog', { name: 'billing.triggerLimitModal.title' }) + expect(within(dialog).getByTestId('billing-quota-value')).toHaveTextContent('0/0') + await user.click( + within(dialog).getByRole('button', { name: 'billing.triggerLimitModal.dismiss' }), + ) + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) +}) diff --git a/web/app/components/billing/annotation-full/usage.tsx b/web/app/components/billing/annotation-full/usage.tsx index 614d27f67bb..3ec5817599d 100644 --- a/web/app/components/billing/annotation-full/usage.tsx +++ b/web/app/components/billing/annotation-full/usage.tsx @@ -1,10 +1,12 @@ 'use client' import type { FC } from 'react' +import { useQuery } from '@tanstack/react-query' import * as React from 'react' import { useTranslation } from 'react-i18next' -import { useProviderContext } from '@/context/provider-context' +import { consoleQuery } from '@/service/console' import { MessageFastPlus } from '../../base/icons/src/vender/line/communication' import UsageInfo from '../usage-info' +import { parseLimit } from '../utils' type Props = Readonly<{ className?: string @@ -12,15 +14,19 @@ type Props = Readonly<{ const Usage: FC = ({ className }) => { const { t } = useTranslation() - const { plan } = useProviderContext() - const { usage, total } = plan + const { data: annotationQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.annotation_quota_limit, + }), + ) + if (!annotationQuota) return null return ( $['annotatedResponse.quotaTitle'], { ns: 'billing' })} - usage={usage.annotatedResponse} - total={total.annotatedResponse} + usage={annotationQuota.size} + total={parseLimit(annotationQuota.limit)} /> ) } diff --git a/web/app/components/billing/apps-full-in-dialog/index.tsx b/web/app/components/billing/apps-full-in-dialog/index.tsx index 0f53af787ef..92fe2e606ef 100644 --- a/web/app/components/billing/apps-full-in-dialog/index.tsx +++ b/web/app/components/billing/apps-full-in-dialog/index.tsx @@ -4,18 +4,22 @@ import type { FC } from 'react' import { buttonVariants } from '@langgenius/dify-ui/button' import { cn } from '@langgenius/dify-ui/cn' import { Meter, MeterIndicator, MeterTrack } from '@langgenius/dify-ui/meter' -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import * as React from 'react' import { useTranslation } from 'react-i18next' import { mailToSupport } from '@/app/components/header/utils/util' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' +import { consoleQuery } from '@/service/console' import UpgradeBtn from '../upgrade-btn' import s from './style.module.css' const AppsFull: FC<{ loc: string; className?: string }> = ({ loc, className }) => { const { t } = useTranslation() - const { plan } = useProviderContext() + const { data: billing } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (data) => ({ plan: data.billing.subscription.plan, apps: data.apps }), + }), + ) const { data: accountProfile } = useSuspenseQuery({ ...userProfileQueryOptions(), select: (data) => ({ @@ -23,9 +27,10 @@ const AppsFull: FC<{ loc: string; className?: string }> = ({ loc, className }) = currentVersion: data.meta.currentVersion, }), }) - const isTeam = plan.type === 'team' - const usage = plan.usage.buildApps - const total = plan.total.buildApps + if (!billing) return null + const isTeam = billing.plan === 'team' + const usage = billing.apps.size + const total = billing.apps.limit const percent = total > 0 ? (usage / total) * 100 : 0 const tone: MeterTone = percent >= 80 ? 'error' : percent >= 50 ? 'warning' : 'neutral' const buildAppsLabel = t(($) => $['usagePage.buildApps'], { ns: 'billing' }) @@ -57,16 +62,16 @@ const AppsFull: FC<{ loc: string; className?: string }> = ({ loc, className }) =
)} - {(plan.type === 'sandbox' || plan.type === 'professional') && ( + {(billing.plan === 'sandbox' || billing.plan === 'professional') && ( )} - {plan.type !== 'sandbox' && plan.type !== 'professional' && ( + {billing.plan !== 'sandbox' && billing.plan !== 'professional' && ( ({ request: vi.fn(() => new Promise(() => {})), @@ -25,12 +25,6 @@ vi.mock('@/context/workspace-state', async () => { })) }) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - enableBilling, - }), -})) - vi.mock('../../plan', () => ({ default: ({ loc }: { loc: string }) =>
, })) @@ -42,7 +36,10 @@ const renderBilling = () => { url: currentBillingUrl, }) } - const { wrapper } = createConsoleQueryWrapper({ queryClient }) + const { wrapper } = createConsoleQueryWrapper({ + queryClient, + systemFeatures: { deployment_edition: deploymentEdition }, + }) return render(, { wrapper }) } @@ -52,7 +49,7 @@ describe('Billing', () => { vi.clearAllMocks() currentBillingUrl = 'https://billing.example.com' isManager = true - enableBilling = true + deploymentEdition = 'CLOUD' }) it('renders the billing portal as a keyboard-accessible external link for workspace managers', async () => { @@ -77,7 +74,7 @@ describe('Billing', () => { }) it('hides the billing action when billing is disabled', () => { - enableBilling = false + deploymentEdition = 'COMMUNITY' renderBilling() diff --git a/web/app/components/billing/billing-page/index.tsx b/web/app/components/billing/billing-page/index.tsx index 7b27f632412..0fd7a891dd3 100644 --- a/web/app/components/billing/billing-page/index.tsx +++ b/web/app/components/billing/billing-page/index.tsx @@ -1,29 +1,40 @@ 'use client' import type { FC } from 'react' import { cn } from '@langgenius/dify-ui/cn' -import { useQuery } from '@tanstack/react-query' +import { usePrefetchQuery, useQuery } from '@tanstack/react-query' import { useAtomValue } from 'jotai' import * as React from 'react' import { useTranslation } from 'react-i18next' -import { useProviderContext } from '@/context/provider-context' +import Loading from '@/app/components/base/loading' import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state' -import { consoleQuery } from '@/service/client' +import { deploymentEditionAtom } from '@/features/system-features/state' +import { consoleQuery } from '@/service/console' import PlanComp from '../plan' const Billing: FC = () => { const { t } = useTranslation() const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom) - const { enableBilling } = useProviderContext() - const canManageBilling = enableBilling && isCurrentWorkspaceManager + const deploymentEdition = useAtomValue(deploymentEditionAtom) + usePrefetchQuery(consoleQuery.features.vectorSpace.get.queryOptions()) const { data: billing } = useQuery( - consoleQuery.billing.invoices.get.queryOptions({ enabled: canManageBilling }), + consoleQuery.billing.invoices.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD' && isCurrentWorkspaceManager, + }), ) const billingUrl = billing?.url return (
- - {canManageBilling && ( +
+ + } + > + + +
+ {deploymentEdition === 'CLOUD' && isCurrentWorkspaceManager && (
= { logHistory: NUM_INFINITE, }, } - -export const defaultPlan = { - type: 'sandbox' as const, - usage: { - documents: 50, - vectorSpace: 1, - buildApps: 1, - teamMembers: 1, - annotatedResponse: 1, - documentsUploadQuota: 0, - apiRateLimit: 0, - triggerEvents: 0, - }, - total: { - documents: 50, - vectorSpace: 10, - buildApps: 10, - teamMembers: 1, - annotatedResponse: 10, - documentsUploadQuota: 0, - apiRateLimit: ALL_PLANS.sandbox.apiRateLimit, - triggerEvents: ALL_PLANS.sandbox.triggerEvents, - }, - reset: { - apiRateLimit: null, - triggerEvents: null, - }, -} diff --git a/web/app/components/billing/hooks/use-education-discount.ts b/web/app/components/billing/hooks/use-education-discount.ts index 2fec57d41fd..10dbd209ec8 100644 --- a/web/app/components/billing/hooks/use-education-discount.ts +++ b/web/app/components/billing/hooks/use-education-discount.ts @@ -4,7 +4,7 @@ import { useAtomValue } from 'jotai' import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state' -import { consoleClient } from '@/service/client' +import { consoleClient } from '@/service/console' export function useEducationDiscount() { const { t } = useTranslation() diff --git a/web/app/components/billing/partner-stack/use-ps-info.ts b/web/app/components/billing/partner-stack/use-ps-info.ts index 7fdeb260f21..d961569de99 100644 --- a/web/app/components/billing/partner-stack/use-ps-info.ts +++ b/web/app/components/billing/partner-stack/use-ps-info.ts @@ -4,7 +4,7 @@ import Cookies from 'js-cookie' import { useCallback } from 'react' import { PARTNER_STACK_CONFIG } from '@/config' import { useSearchParams } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' const usePSInfo = () => { const searchParams = useSearchParams() diff --git a/web/app/components/billing/plan/__tests__/index.spec.tsx b/web/app/components/billing/plan/__tests__/index.spec.tsx index f9ecda11e9a..2d975695aab 100644 --- a/web/app/components/billing/plan/__tests__/index.spec.tsx +++ b/web/app/components/billing/plan/__tests__/index.spec.tsx @@ -1,5 +1,4 @@ import { screen } from '@testing-library/react' -import { baseProviderContextValue } from '@/context/provider-context' import { createConsoleQueryWrapper } from '@/test/console/query-data' import { render } from '@/test/console/render' import PlanComp from '../index' @@ -11,24 +10,6 @@ vi.mock('@/context/workspace-state', async () => { })) }) -vi.mock('@/context/provider-context', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - useProviderContext: () => ({ - ...baseProviderContextValue, - enableEducationPlan: true, - }), - } -}) - -vi.mock('@/app/components/billing/hooks/use-education-discount', () => ({ - useEducationDiscount: () => ({ - handleEducationDiscount: vi.fn(), - isEducationDiscountLoading: false, - }), -})) - vi.mock('@/app/components/billing/upgrade-btn', () => ({ default: () => , })) @@ -37,10 +18,6 @@ vi.mock('@/app/components/billing/usage-info', () => ({ default: () => null, })) -vi.mock('@/app/components/billing/usage-info/apps-info', () => ({ - default: () => null, -})) - vi.mock('@/app/components/billing/usage-info/vector-space-info', () => ({ default: () => null, })) @@ -54,6 +31,7 @@ vi.mock('../assets', () => ({ const renderPlan = (educationStatus = { allow_refresh: false, is_student: false }) => { const { wrapper } = createConsoleQueryWrapper({ educationStatus, + features: { education: { enabled: true } }, systemFeatures: { deployment_edition: 'CLOUD' }, }) diff --git a/web/app/components/billing/plan/index.tsx b/web/app/components/billing/plan/index.tsx index d544275c54b..5f82f145834 100644 --- a/web/app/components/billing/plan/index.tsx +++ b/web/app/components/billing/plan/index.tsx @@ -2,25 +2,24 @@ import type { EducationStatusResponse } from '@dify/contracts/api/console/account/types.gen' import type { FC } from 'react' import { Button, buttonVariants } from '@langgenius/dify-ui/button' -import { RiBook2Line, RiFileEditLine, RiGroupLine } from '@remixicon/react' +import { RiApps2Line, RiBook2Line, RiFileEditLine, RiGroupLine } from '@remixicon/react' import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useAtomValue } from 'jotai' import * as React from 'react' import { useTranslation } from 'react-i18next' import { ApiAggregate, TriggerAll } from '@/app/components/base/icons/src/vender/workflow' import UsageInfo from '@/app/components/billing/usage-info' -import { useProviderContext } from '@/context/provider-context' import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import Link from '@/next/link' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { getDaysUntilEndOfMonth } from '@/utils/time' import Loading from '../../base/icons/src/public/thought/Loading' import { NUM_INFINITE } from '../config' import { useEducationDiscount } from '../hooks/use-education-discount' import UpgradeBtn from '../upgrade-btn' -import AppsInfo from '../usage-info/apps-info' import VectorSpaceInfo from '../usage-info/vector-space-info' +import { getResetInDaysFromDate, parseLimit } from '../utils' import { Professional, Sandbox, Team } from './assets' type Props = Readonly<{ @@ -40,7 +39,8 @@ const PlanComp: FC = ({ loc }) => { }) const isCloudEdition = deploymentEdition === 'CLOUD' const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom) - const { plan, enableEducationPlan } = useProviderContext() + const { data: features } = useSuspenseQuery(consoleQuery.features.get.queryOptions()) + const enableEducationPlan = features.education.enabled const { data: educationStatus } = useQuery( consoleQuery.account.education.get.queryOptions({ enabled: enableEducationPlan, @@ -48,16 +48,17 @@ const PlanComp: FC = ({ loc }) => { }), ) const { isAboutToExpire = false, isEducationAccount = false } = educationStatus ?? {} - const { type } = plan - - const { usage, total, reset } = plan + const type = features.billing.subscription.plan + const triggerEventsLimit = features.trigger_event.limit + const apiRateLimit = features.api_rate_limit.limit + const apiRateLimitReset = getResetInDaysFromDate(features.api_rate_limit.reset_date) const triggerEventsResetInDays = - type === 'professional' && total.triggerEvents !== NUM_INFINITE - ? (reset.triggerEvents ?? undefined) + type === 'professional' && triggerEventsLimit !== NUM_INFINITE + ? (getResetInDaysFromDate(features.trigger_event.reset_date) ?? undefined) : undefined const apiRateLimitResetInDays = (() => { - if (total.apiRateLimit === NUM_INFINITE) return undefined - if (typeof reset.apiRateLimit === 'number') return reset.apiRateLimit + if (apiRateLimit === NUM_INFINITE) return undefined + if (typeof apiRateLimitReset === 'number') return apiRateLimitReset if (type === 'sandbox') return getDaysUntilEndOfMonth() return undefined })() @@ -66,9 +67,9 @@ const PlanComp: FC = ({ loc }) => { return (
- {plan.type === 'sandbox' && } - {plan.type === 'professional' && } - {plan.type === 'team' && } + {type === 'sandbox' && } + {type === 'professional' && } + {type === 'team' && }
@@ -110,41 +111,46 @@ const PlanComp: FC = ({ loc }) => {
{/* Plan detail */}
- + $['usagePage.buildApps'], { ns: 'billing' })} + usage={features.apps.size} + total={parseLimit(features.apps.limit)} + /> $['usagePage.teamMembers'], { ns: 'billing' })} - usage={usage.teamMembers} - total={total.teamMembers} + usage={features.members.size} + total={parseLimit(features.members.limit)} /> $['usagePage.documentsUploadQuota'], { ns: 'billing' })} - usage={usage.documentsUploadQuota} - total={total.documentsUploadQuota} + usage={features.documents_upload_quota.size} + total={parseLimit(features.documents_upload_quota.limit)} /> $['usagePage.annotationQuota'], { ns: 'billing' })} - usage={usage.annotatedResponse} - total={total.annotatedResponse} + usage={features.annotation_quota_limit.size} + total={parseLimit(features.annotation_quota_limit.limit)} /> $['usagePage.triggerEvents'], { ns: 'billing' })} - usage={usage.triggerEvents} - total={total.triggerEvents} + usage={features.trigger_event.usage} + total={triggerEventsLimit} tooltip={t(($) => $['plansCommon.triggerEvents.tooltip'], { ns: 'billing' }) as string} resetInDays={triggerEventsResetInDays} /> $['plansCommon.apiRateLimit'], { ns: 'billing' })} - usage={usage.apiRateLimit} - total={total.apiRateLimit} + usage={features.api_rate_limit.usage} + total={apiRateLimit} tooltip={ - total.apiRateLimit === NUM_INFINITE + apiRateLimit === NUM_INFINITE ? undefined : (t(($) => $['plansCommon.apiRateLimitTooltip'], { ns: 'billing' }) as string) } diff --git a/web/app/components/billing/pricing/content.tsx b/web/app/components/billing/pricing/content.tsx index 45f93415d0d..1db55c4eefc 100644 --- a/web/app/components/billing/pricing/content.tsx +++ b/web/app/components/billing/pricing/content.tsx @@ -8,7 +8,7 @@ import * as React from 'react' import { useTranslation } from 'react-i18next' import Divider from '@/app/components/base/divider' import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import Cloud from './assets/cloud' import NoiseBottom from './assets/noise-bottom' import NoiseTop from './assets/noise-top' diff --git a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx index 15800b60505..c225cf4b1e7 100644 --- a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx +++ b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx @@ -16,7 +16,7 @@ import * as React from 'react' import { useTranslation } from 'react-i18next' import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state' import { useAsyncWindowOpen } from '@/hooks/use-async-window-open' -import { consoleClient } from '@/service/client' +import { consoleClient } from '@/service/console' import { ALL_PLANS } from '../../../config' import { useEducationDiscount } from '../../../hooks/use-education-discount' import Professional from '../../assets/professional' diff --git a/web/app/components/billing/priority-label/index.tsx b/web/app/components/billing/priority-label/index.tsx index e50a4553fc9..6586183b350 100644 --- a/web/app/components/billing/priority-label/index.tsx +++ b/web/app/components/billing/priority-label/index.tsx @@ -1,9 +1,11 @@ import { cn } from '@langgenius/dify-ui/cn' import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip' import { RiAedFill } from '@remixicon/react' -import { useMemo } from 'react' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import { useTranslation } from 'react-i18next' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' +import { consoleQuery } from '@/service/console' type PriorityLabelProps = { className?: string @@ -11,17 +13,17 @@ type PriorityLabelProps = { const PriorityLabel = ({ className }: PriorityLabelProps) => { const { t } = useTranslation() - const { plan } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.billing.subscription.plan, + }), + ) - const priority = useMemo(() => { - if (plan.type === 'sandbox') return 'standard' - - if (plan.type === 'professional') return 'priority' - - if (plan.type === 'team') return 'top-priority' - - return 'standard' - }, [plan]) + if (deploymentEdition !== 'CLOUD' || plan === undefined) return null + const priority = { sandbox: 'standard', professional: 'priority', team: 'top-priority' } as const + const label = priority[plan] return ( @@ -35,17 +37,15 @@ const PriorityLabel = ({ className }: PriorityLabelProps) => { /> } > - {(plan.type === 'professional' || plan.type === 'team') && ( - - )} - {t(($) => $[`plansCommon.priority.${priority}`], { ns: 'billing' })} + {(plan === 'professional' || plan === 'team') && } + {t(($) => $[`plansCommon.priority.${label}`], { ns: 'billing' })}
{t(($) => $['plansCommon.documentProcessingPriority'], { ns: 'billing' })}:{' '} - {t(($) => $[`plansCommon.priority.${priority}`], { ns: 'billing' })} + {t(($) => $[`plansCommon.priority.${label}`], { ns: 'billing' })}
- {priority !== 'top-priority' && ( + {label !== 'top-priority' && (
{t(($) => $['plansCommon.documentProcessingPriorityTip'], { ns: 'billing' })}
diff --git a/web/app/components/billing/type.ts b/web/app/components/billing/type.ts index 22e62c02fa0..6adddc29f0f 100644 --- a/web/app/components/billing/type.ts +++ b/web/app/components/billing/type.ts @@ -18,18 +18,3 @@ export type PlanInfo = { triggerEvents: number annotatedResponse: number } - -export type UsagePlanInfo = { - buildApps: number - teamMembers: number - annotatedResponse: number - documentsUploadQuota: number - apiRateLimit: number - triggerEvents: number - vectorSpace: number -} - -export type UsageResetInfo = { - apiRateLimit?: number | null - triggerEvents?: number | null -} diff --git a/web/app/components/billing/usage-info/apps-info.tsx b/web/app/components/billing/usage-info/apps-info.tsx deleted file mode 100644 index 8aab1a4273d..00000000000 --- a/web/app/components/billing/usage-info/apps-info.tsx +++ /dev/null @@ -1,27 +0,0 @@ -'use client' -import type { FC } from 'react' -import { RiApps2Line } from '@remixicon/react' -import * as React from 'react' -import { useTranslation } from 'react-i18next' -import { useProviderContext } from '@/context/provider-context' -import UsageInfo from '../usage-info' - -type Props = Readonly<{ - className?: string -}> - -const AppsInfo: FC = ({ className }) => { - const { t } = useTranslation() - const { plan } = useProviderContext() - const { usage, total } = plan - return ( - $['usagePage.buildApps'], { ns: 'billing' })} - usage={usage.buildApps} - total={total.buildApps} - /> - ) -} -export default React.memo(AppsInfo) diff --git a/web/app/components/billing/usage-info/index.tsx b/web/app/components/billing/usage-info/index.tsx index d71507ca02c..3aed8589b50 100644 --- a/web/app/components/billing/usage-info/index.tsx +++ b/web/app/components/billing/usage-info/index.tsx @@ -52,11 +52,10 @@ const UsageInfo: FC = ({ const isBelowThreshold = !usageUnknown && storageMode && usage < storageThreshold const isSandboxFull = !usageUnknown && storageMode && isSandboxPlan && usage >= storageThreshold - // Single source of truth: sandbox full is visually clamped to 100%; all other - // determinate cases show the real percent capped at 100. Tone derives from - // this, so we never need a separate tone override. + // Zero count quotas have no remaining capacity; storage keeps its separate limit convention. + const isZeroQuota = !storageMode && total === 0 const rawPercent = total > 0 ? (usage / total) * 100 : 0 - const effectivePercent = isSandboxFull ? 100 : Math.min(rawPercent, 100) + const effectivePercent = isSandboxFull || isZeroQuota ? 100 : Math.min(rawPercent, 100) const tone: MeterTone = effectivePercent >= 100 ? 'error' : effectivePercent >= 80 ? 'warning' : 'neutral' diff --git a/web/app/components/billing/usage-info/vector-space-info.tsx b/web/app/components/billing/usage-info/vector-space-info.tsx index 1a039cb5640..b6c0df571a8 100644 --- a/web/app/components/billing/usage-info/vector-space-info.tsx +++ b/web/app/components/billing/usage-info/vector-space-info.tsx @@ -1,11 +1,10 @@ 'use client' import type { FC } from 'react' import { RiHardDrive3Line } from '@remixicon/react' -import { useQuery } from '@tanstack/react-query' +import { useSuspenseQueries } from '@tanstack/react-query' import * as React from 'react' import { useTranslation } from 'react-i18next' -import { useProviderContext } from '@/context/provider-context' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import UsageInfo from '../usage-info' import { getPlanVectorSpaceLimitMB } from '../utils' @@ -18,11 +17,14 @@ const STORAGE_THRESHOLD_MB = getPlanVectorSpaceLimitMB('sandbox') const VectorSpaceInfo: FC = ({ className }) => { const { t } = useTranslation() - const { plan } = useProviderContext() - const { data: vectorSpace } = useQuery(consoleQuery.features.vectorSpace.get.queryOptions()) - const vectorSpaceUsage = vectorSpace?.size ?? plan.usage.vectorSpace - const vectorSpaceLimit = vectorSpace?.limit ?? getPlanVectorSpaceLimitMB(plan.type) - const isSandbox = plan.type === 'sandbox' + const [{ data: plan }, { data: vectorSpace }] = useSuspenseQueries({ + queries: [ + consoleQuery.features.get.queryOptions({ + select: (features) => features.billing.subscription.plan, + }), + consoleQuery.features.vectorSpace.get.queryOptions(), + ], + }) return ( = ({ className }) => { Icon={RiHardDrive3Line} name={t(($) => $['usagePage.vectorSpace'], { ns: 'billing' })} tooltip={t(($) => $['usagePage.vectorSpaceTooltip'], { ns: 'billing' }) as string} - usage={vectorSpaceUsage} - total={vectorSpaceLimit} + usage={vectorSpace.size} + total={vectorSpace.limit} unit="MB" unitPosition="inline" storageMode storageThreshold={STORAGE_THRESHOLD_MB} storageTooltip={t(($) => $['usagePage.storageThresholdTooltip'], { ns: 'billing' }) as string} - isSandboxPlan={isSandbox} - usageUnknown={vectorSpace?.usage_unknown} + isSandboxPlan={plan === 'sandbox'} + usageUnknown={vectorSpace.usage_unknown} /> ) } diff --git a/web/app/components/billing/utils/__tests__/index.spec.ts b/web/app/components/billing/utils/__tests__/index.spec.ts index c09c2490e26..d728b1bf8a9 100644 --- a/web/app/components/billing/utils/__tests__/index.spec.ts +++ b/web/app/components/billing/utils/__tests__/index.spec.ts @@ -1,5 +1,9 @@ -import type { GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen' -import { getPlanVectorSpaceLimitMB, parseCurrentPlan, parseVectorSpaceToMB } from '../index' +import { + getPlanVectorSpaceLimitMB, + getResetInDaysFromDate, + parseLimit, + parseVectorSpaceToMB, +} from '../index' describe('billing utils', () => { // parseVectorSpaceToMB tests @@ -42,279 +46,29 @@ describe('billing utils', () => { }) }) - // parseCurrentPlan tests - describe('parseCurrentPlan', () => { - const createMockPlanData = ( - overrides: Partial = {}, - ): GetFeaturesResponse => ({ - annotation_quota_limit: { - size: 5, - limit: 10, - }, - api_rate_limit: { - usage: 0, - limit: 5000, - reset_date: -1, - }, - apps: { - size: 2, - limit: 5, - }, - billing: { - enabled: true, - subscription: { - interval: '', - plan: 'sandbox', - }, - }, - can_replace_logo: false, - dataset_operator_enabled: false, - dify_builder_enabled: false, - docs_processing: '', - documents_upload_quota: { - size: 20, - limit: 0, - }, - education: { - activated: false, - enabled: false, - }, - enable_skill: false, - human_input_email_delivery_enabled: false, - is_allow_transfer_workspace: false, - knowledge_pipeline: { - publish_enabled: false, - }, - knowledge_rate_limit: 0, - members: { - size: 1, - limit: 1, - }, - model_load_balancing_enabled: false, - next_credit_reset_date: 0, - skill_learning_policy: '', - trigger_event: { - usage: 0, - limit: 3000, - reset_date: -1, - }, - vector_space: null, - webapp_copyright_enabled: false, - workspace_members: { - enabled: false, - size: 0, - limit: 0, - }, - ...overrides, + describe('quota reset dates', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date(2026, 8, 7, 12)) }) - - it('should parse plan type correctly', () => { - const data = createMockPlanData() - const result = parseCurrentPlan(data) - expect(result.type).toBe('sandbox') + afterEach(() => vi.useRealTimers()) + it('handles Unix timestamps in seconds and milliseconds', () => { + const resetDate = new Date(2026, 8, 14).getTime() + expect(getResetInDaysFromDate(resetDate)).toBe(7) + expect(getResetInDaysFromDate(resetDate / 1000)).toBe(7) }) - - it('should parse usage values correctly', () => { - const data = createMockPlanData() - const result = parseCurrentPlan(data) - - expect(result.usage.vectorSpace).toBe(0) - expect(result.usage.buildApps).toBe(2) - expect(result.usage.teamMembers).toBe(1) - expect(result.usage.annotatedResponse).toBe(5) - expect(result.usage.documentsUploadQuota).toBe(20) + it('handles calendar dates and omits absent or past resets', () => { + expect(getResetInDaysFromDate(20260914)).toBe(7) + expect(getResetInDaysFromDate(0)).toBeNull() + expect(getResetInDaysFromDate(-1)).toBeNull() + expect(getResetInDaysFromDate(20260901)).toBeNull() }) + }) - it('should parse total limits correctly', () => { - const data = createMockPlanData() - const result = parseCurrentPlan(data) - - expect(result.total.vectorSpace).toBe(50) - expect(result.total.buildApps).toBe(5) - expect(result.total.teamMembers).toBe(1) - expect(result.total.annotatedResponse).toBe(10) - }) - - it('should not read vector space usage from current plan info', () => { - const data = createMockPlanData() - const result = parseCurrentPlan(data) - - expect(result.usage.vectorSpace).toBe(0) - expect(result.total.vectorSpace).toBe(50) - }) - - it('should derive vector space total from plan config', () => { - const data = createMockPlanData({ - billing: { - enabled: true, - subscription: { - interval: '', - plan: 'professional', - }, - }, - }) - const result = parseCurrentPlan(data) - - expect(result.usage.vectorSpace).toBe(0) - expect(result.total.vectorSpace).toBe(5 * 1024) - }) - - it('should convert 0 limits to NUM_INFINITE (-1)', () => { - const data = createMockPlanData({ - documents_upload_quota: { - size: 20, - limit: 0, - }, - }) - const result = parseCurrentPlan(data) - expect(result.total.documentsUploadQuota).toBe(-1) - }) - - it('should handle api_rate_limit quota', () => { - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: 0, - }, - }) - const result = parseCurrentPlan(data) - - expect(result.usage.apiRateLimit).toBe(100) - expect(result.total.apiRateLimit).toBe(5000) - }) - - it('should handle trigger_event quota', () => { - const data = createMockPlanData({ - trigger_event: { - usage: 50, - limit: 3000, - reset_date: 0, - }, - }) - const result = parseCurrentPlan(data) - - expect(result.usage.triggerEvents).toBe(50) - expect(result.total.triggerEvents).toBe(3000) - }) - - it('should convert 0 or -1 rate limits to NUM_INFINITE', () => { - const data = createMockPlanData({ - api_rate_limit: { - usage: 0, - limit: 0, - reset_date: 0, - }, - }) - const result = parseCurrentPlan(data) - expect(result.total.apiRateLimit).toBe(-1) - - const data2 = createMockPlanData({ - api_rate_limit: { - usage: 0, - limit: -1, - reset_date: 0, - }, - }) - const result2 = parseCurrentPlan(data2) - expect(result2.total.apiRateLimit).toBe(-1) - }) - - it('should handle reset dates with milliseconds timestamp', () => { - const futureDate = Date.now() + 86400000 // Tomorrow in ms - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: futureDate, - }, - }) - const result = parseCurrentPlan(data) - - expect(result.reset.apiRateLimit).toBe(1) - }) - - it('should handle reset dates with seconds timestamp', () => { - const futureDate = Math.floor(Date.now() / 1000) + 86400 // Tomorrow in seconds - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: futureDate, - }, - }) - const result = parseCurrentPlan(data) - - expect(result.reset.apiRateLimit).toBe(1) - }) - - it('should handle reset dates in YYYYMMDD format', () => { - const tomorrow = new Date() - tomorrow.setDate(tomorrow.getDate() + 1) - const year = tomorrow.getFullYear() - const month = String(tomorrow.getMonth() + 1).padStart(2, '0') - const day = String(tomorrow.getDate()).padStart(2, '0') - const dateNumber = Number.parseInt(`${year}${month}${day}`, 10) - - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: dateNumber, - }, - }) - const result = parseCurrentPlan(data) - - expect(result.reset.apiRateLimit).toBe(1) - }) - - it('should return null for invalid reset dates', () => { - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: 0, - }, - }) - const result = parseCurrentPlan(data) - expect(result.reset.apiRateLimit).toBeNull() - }) - - it('should return null for negative reset dates', () => { - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: -1, - }, - }) - const result = parseCurrentPlan(data) - expect(result.reset.apiRateLimit).toBeNull() - }) - - it('should return null when reset date is in the past', () => { - const pastDate = Date.now() - 86400000 // Yesterday - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: pastDate, - }, - }) - const result = parseCurrentPlan(data) - expect(result.reset.apiRateLimit).toBeNull() - }) - - it('should return null for unrecognized date format', () => { - const data = createMockPlanData({ - api_rate_limit: { - usage: 100, - limit: 5000, - reset_date: 12345, // Unrecognized format - }, - }) - const result = parseCurrentPlan(data) - expect(result.reset.apiRateLimit).toBeNull() + describe('quota display', () => { + it('displays zero count limits as unlimited', () => { + expect(parseLimit(0)).toBe(-1) + expect(parseLimit(10)).toBe(10) }) }) }) diff --git a/web/app/components/billing/utils/index.ts b/web/app/components/billing/utils/index.ts index 559c113fa9d..740da620893 100644 --- a/web/app/components/billing/utils/index.ts +++ b/web/app/components/billing/utils/index.ts @@ -1,4 +1,4 @@ -import type { CloudPlan, GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen' +import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' import dayjs from 'dayjs' import { ALL_PLANS, NUM_INFINITE } from '@/app/components/billing/config' @@ -23,18 +23,14 @@ export const getPlanVectorSpaceLimitMB = (planType: CloudPlan): number => { return parseVectorSpaceToMB(ALL_PLANS[planType].vectorSpace) } -const parseLimit = (limit: number) => { +// App, member, document upload, and annotation quotas use 0 for unlimited. +// Event and API quotas use -1 for unlimited and must preserve 0 as zero capacity. +export const parseLimit = (limit: number) => { if (limit === 0) return NUM_INFINITE return limit } -const parseRateLimit = (limit: number) => { - if (limit === 0 || limit === -1) return NUM_INFINITE - - return limit -} - const normalizeResetDate = (resetDate: number) => { if (resetDate <= 0) return null @@ -54,7 +50,7 @@ const normalizeResetDate = (resetDate: number) => { return null } -const getResetInDaysFromDate = (resetDate: number) => { +export const getResetInDaysFromDate = (resetDate: number) => { const resetDay = normalizeResetDate(resetDate) if (!resetDay) return null @@ -63,34 +59,3 @@ const getResetInDaysFromDate = (resetDate: number) => { return diff } - -export const parseCurrentPlan = (data: GetFeaturesResponse) => { - const planType = data.billing.subscription.plan - const vectorSpaceLimit = getPlanVectorSpaceLimitMB(planType) - - return { - type: planType, - usage: { - vectorSpace: 0, - buildApps: data.apps.size, - teamMembers: data.members.size, - annotatedResponse: data.annotation_quota_limit.size, - documentsUploadQuota: data.documents_upload_quota.size, - apiRateLimit: data.api_rate_limit.usage, - triggerEvents: data.trigger_event.usage, - }, - total: { - vectorSpace: vectorSpaceLimit, - buildApps: parseLimit(data.apps.limit), - teamMembers: parseLimit(data.members.limit), - annotatedResponse: parseLimit(data.annotation_quota_limit.limit), - documentsUploadQuota: parseLimit(data.documents_upload_quota.limit), - apiRateLimit: parseRateLimit(data.api_rate_limit.limit), - triggerEvents: parseRateLimit(data.trigger_event.limit), - }, - reset: { - apiRateLimit: getResetInDaysFromDate(data.api_rate_limit.reset_date), - triggerEvents: getResetInDaysFromDate(data.trigger_event.reset_date), - }, - } -} diff --git a/web/app/components/billing/vector-space-full/index.tsx b/web/app/components/billing/vector-space-full/index.tsx index 7d98709891d..b19d5d01663 100644 --- a/web/app/components/billing/vector-space-full/index.tsx +++ b/web/app/components/billing/vector-space-full/index.tsx @@ -25,7 +25,9 @@ const VectorSpaceFull: FC = () => {
- + + +
) diff --git a/web/app/components/custom/custom-page/__tests__/index.spec.tsx b/web/app/components/custom/custom-page/__tests__/index.spec.tsx index b25b9856264..28d77862fa5 100644 --- a/web/app/components/custom/custom-page/__tests__/index.spec.tsx +++ b/web/app/components/custom/custom-page/__tests__/index.spec.tsx @@ -1,16 +1,19 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' +import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen' import type { ReactElement } from 'react' import { screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' -import { createMockProviderContextValue } from '@/__mocks__/provider-context' -import { contactSalesUrl, defaultPlan } from '@/app/components/billing/config' +import { contactSalesUrl } from '@/app/components/billing/config' import { useModalContext } from '@/context/modal-context' -import { useProviderContext } from '@/context/provider-context' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import CustomPage from '../index' +let deploymentEdition: GetSystemFeaturesResponse['deployment_edition'] = 'COMMUNITY' +let canReplaceLogo = true +let plan: CloudPlan = 'professional' + vi.mock('@/config', async (importOriginal) => { const actual = await importOriginal() return { @@ -18,7 +21,7 @@ vi.mock('@/config', async (importOriginal) => { } }) -const render = (ui: ReactElement) => { +function render(ui: ReactElement) { const queryClient = createConsoleQueryClient() queryClient.setQueryData(consoleQuery.workspaces.customConfig.get.queryKey(), { remove_webapp_brand: false, @@ -27,8 +30,12 @@ const render = (ui: ReactElement) => { return renderWithConsoleQuery(ui, { queryClient, + features: { + can_replace_logo: canReplaceLogo, + billing: { subscription: { plan } }, + }, systemFeatures: { - deployment_edition: 'CLOUD', + deployment_edition: deploymentEdition, branding: { enabled: true, workspace_logo: 'https://example.com/workspace-logo.png', @@ -49,9 +56,7 @@ const { mockToast } = vi.hoisted(() => { }) return { mockToast } }) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: vi.fn(), -})) + vi.mock('@/context/modal-context', () => ({ useModalContext: vi.fn(), })) @@ -59,32 +64,17 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ toast: mockToast, })) -const mockUseProviderContext = vi.mocked(useProviderContext) const mockUseModalContext = vi.mocked(useModalContext) -const createProviderContext = ({ - enableBilling = false, - planType = 'professional', -}: { - enableBilling?: boolean - planType?: CloudPlan -} = {}) => { - return createMockProviderContextValue({ - enableBilling, - plan: { - ...defaultPlan, - type: planType, - }, - }) -} - describe('CustomPage', () => { const setShowPricingModal = vi.fn() beforeEach(() => { vi.clearAllMocks() - mockUseProviderContext.mockReturnValue(createProviderContext()) + deploymentEdition = 'COMMUNITY' + canReplaceLogo = true + plan = 'professional' mockUseModalContext.mockReturnValue({ setShowPricingModal, } as unknown as ReturnType) @@ -102,13 +92,10 @@ describe('CustomPage', () => { }) it('should show the upgrade banner and open pricing modal for sandbox billing', async () => { + deploymentEdition = 'CLOUD' const user = userEvent.setup() - mockUseProviderContext.mockReturnValue( - createProviderContext({ - enableBilling: true, - planType: 'sandbox', - }), - ) + plan = 'sandbox' + canReplaceLogo = false render() @@ -121,12 +108,8 @@ describe('CustomPage', () => { }) it('should show the contact link for professional workspaces', () => { - mockUseProviderContext.mockReturnValue( - createProviderContext({ - enableBilling: true, - planType: 'professional', - }), - ) + deploymentEdition = 'CLOUD' + canReplaceLogo = true render() @@ -138,12 +121,9 @@ describe('CustomPage', () => { }) it('should show the contact link for team workspaces', () => { - mockUseProviderContext.mockReturnValue( - createProviderContext({ - enableBilling: true, - planType: 'team', - }), - ) + plan = 'team' + deploymentEdition = 'CLOUD' + canReplaceLogo = true render() @@ -151,13 +131,8 @@ describe('CustomPage', () => { expect(screen.queryByText('custom.upgradeTip.title')).not.toBeInTheDocument() }) - it('should hide both billing sections when billing is disabled', () => { - mockUseProviderContext.mockReturnValue( - createProviderContext({ - enableBilling: false, - planType: 'sandbox', - }), - ) + it('should hide both billing sections for Community deployments', () => { + canReplaceLogo = false render() diff --git a/web/app/components/custom/custom-page/index.tsx b/web/app/components/custom/custom-page/index.tsx index eaa0ae6a66b..a663bb2c968 100644 --- a/web/app/components/custom/custom-page/index.tsx +++ b/web/app/components/custom/custom-page/index.tsx @@ -1,9 +1,9 @@ -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useTranslation } from 'react-i18next' import { contactSalesUrl } from '@/app/components/billing/config' import { useModalContext } from '@/context/modal-context' -import { useProviderContext } from '@/context/provider-context' import { systemFeaturesQueryOptions } from '@/features/system-features/client' +import { consoleQuery } from '@/service/console' import CustomWebAppBrand from '../custom-web-app-brand' const CustomPage = () => { @@ -12,10 +12,19 @@ const CustomPage = () => { ...systemFeaturesQueryOptions(), select: ({ deployment_edition }) => deployment_edition, }) - const { plan, enableBilling } = useProviderContext() + const { data: billing } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => ({ + plan: data.billing.subscription.plan, + canReplaceLogo: data.can_replace_logo, + }), + }), + ) const { setShowPricingModal } = useModalContext() - const showBillingTip = deploymentEdition === 'CLOUD' && enableBilling && plan.type === 'sandbox' - const showContact = enableBilling && (plan.type === 'professional' || plan.type === 'team') + const showBillingTip = deploymentEdition === 'CLOUD' && billing?.canReplaceLogo === false + const showContact = + deploymentEdition === 'CLOUD' && (billing?.plan === 'professional' || billing?.plan === 'team') return (
diff --git a/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsx b/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsx index 11f6b3a273f..28b80f5bc02 100644 --- a/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsx +++ b/web/app/components/custom/custom-web-app-brand/__tests__/index.spec.tsx @@ -21,7 +21,7 @@ const createHookState = ( isCustomConfigUnavailable: false, uploadDisabled: false, workspaceLogo: 'https://example.com/workspace-logo.png', - isSandbox: false, + canReplaceLogo: true, canManageCustomBrand: true, handleApply: vi.fn(), handleCancel: vi.fn(), @@ -88,7 +88,7 @@ describe('CustomWebAppBrand', () => { it('should disable the switch when sandbox restrictions are active', () => { renderComponent({ - isSandbox: true, + canReplaceLogo: false, }) expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true') diff --git a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx index b2e664b3ff0..a8eb5060e94 100644 --- a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx +++ b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx @@ -1,16 +1,14 @@ -import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen' import type { ChangeEvent } from 'react' import type { ConsoleStateFixture } from '@/test/console/state-fixture' import { act, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' -import { createMockProviderContextValue } from '@/__mocks__/provider-context' import { getImageUploadErrorMessage, imageUpload } from '@/app/components/base/image-uploader/utils' -import { defaultPlan } from '@/app/components/billing/config' -import { useProviderContext } from '@/context/provider-context' import { createConsoleQueryClient, renderHookWithConsoleQuery } from '@/test/console/query-data' import useWebAppBrand from '../use-web-app-brand' +let canReplaceLogo = true + let currentBrandingOverrides: Partial = {} let customConfig = { replace_webapp_logo: 'https://example.com/replace.png', @@ -32,6 +30,9 @@ const renderHook = (callback: (props: Props) => Result) => }, }, queryClient, + features: { + can_replace_logo: canReplaceLogo, + }, }) } @@ -56,8 +57,8 @@ const mockUpdateCustomConfig = vi.hoisted(() => vi.fn()) vi.mock('@langgenius/dify-ui/toast', () => ({ toast: mockToast, })) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() const consoleQuery = new Proxy(actual.consoleQuery, { get(target, prop, receiver) { if (prop === 'workspaces') { @@ -113,15 +114,12 @@ vi.mock('@/context/permission-state', async () => { refreshCurrentWorkspace: consoleStateRef.value?.refreshCurrentWorkspace, })) }) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: vi.fn(), -})) + vi.mock('@/app/components/base/image-uploader/utils', () => ({ imageUpload: vi.fn(), getImageUploadErrorMessage: vi.fn(), })) -const mockUseProviderContext = vi.mocked(useProviderContext) const mockImageUpload = vi.mocked(imageUpload) const mockGetImageUploadErrorMessage = vi.mocked(getImageUploadErrorMessage) @@ -134,28 +132,11 @@ const testUserProfile = { is_password_set: false, } -const createProviderContext = ({ - enableBilling = false, - planType = 'professional', -}: { - enableBilling?: boolean - planType?: CloudPlan -} = {}) => { - return createMockProviderContextValue({ - enableBilling, - plan: { - ...defaultPlan, - type: planType, - }, - }) -} - const createConsoleState = (overrides: Partial = {}): ConsoleStateFixture => { return { userProfile: testUserProfile, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: false, - isCurrentWorkspaceEditor: false, isCurrentWorkspaceDatasetOperator: false, workspacePermissionKeys: ['customization.manage'], refreshCurrentWorkspace: vi.fn(), @@ -183,7 +164,7 @@ describe('useWebAppBrand', () => { customConfigQueryPending = false customConfigQueryError = undefined mockUpdateCustomConfig.mockResolvedValue(customConfig) - mockUseProviderContext.mockReturnValue(createProviderContext()) + canReplaceLogo = true mockGetImageUploadErrorMessage.mockReturnValue('upload error') }) @@ -228,17 +209,12 @@ describe('useWebAppBrand', () => { }) it('should disable uploads in sandbox workspaces and when branding is removed', () => { - mockUseProviderContext.mockReturnValue( - createProviderContext({ - enableBilling: true, - planType: 'sandbox', - }), - ) + canReplaceLogo = false customConfig = { ...customConfig, remove_webapp_brand: true } const { result } = renderHook(() => useWebAppBrand()) - expect(result.current.isSandbox).toBe(true) + expect(!result.current.canReplaceLogo).toBe(true) expect(result.current.webappBrandRemoved).toBe(true) expect(result.current.uploadDisabled).toBe(true) }) diff --git a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts index c6851a67109..7dd76072233 100644 --- a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts +++ b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts @@ -7,16 +7,19 @@ import { useState } from 'react' import { useTranslation } from 'react-i18next' import { getImageUploadErrorMessage, imageUpload } from '@/app/components/base/image-uploader/utils' import { workspacePermissionKeysAtom } from '@/context/permission-state' -import { useProviderContext } from '@/context/provider-context' import { systemFeaturesQueryOptions } from '@/features/system-features/client' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { hasPermission } from '@/utils/permission' const MAX_LOGO_FILE_SIZE = 5 * 1024 * 1024 const WEB_APP_LOGO_UPLOAD_URL = '/workspaces/custom-config/webapp-logo/upload' const useWebAppBrand = () => { const { t } = useTranslation() - const { plan, enableBilling } = useProviderContext() + const { data: canReplaceLogo } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (data) => data.can_replace_logo, + }), + ) const queryClient = useQueryClient() const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom) const [fileId, setFileId] = useState('') @@ -28,24 +31,25 @@ const useWebAppBrand = () => { const updateCustomConfigMutation = useMutation( consoleQuery.workspaces.customConfig.post.mutationOptions(), ) - const isSandbox = enableBilling && plan.type === 'sandbox' const uploading = uploadProgress > 0 && uploadProgress < 100 const webappLogo = customConfig?.replace_webapp_logo || '' const webappBrandRemoved = customConfig?.remove_webapp_brand ?? undefined const canManageCustomBrand = hasPermission(workspacePermissionKeys, 'customization.manage') - const isCustomConfigUnavailable = customConfigQuery.isPending || customConfigQuery.isError + const isCustomConfigUnavailable = customConfig === undefined || canReplaceLogo === undefined const uploadDisabled = - isCustomConfigUnavailable || isSandbox || webappBrandRemoved || !canManageCustomBrand + isCustomConfigUnavailable || !canReplaceLogo || webappBrandRemoved || !canManageCustomBrand const workspaceLogo = systemFeatures.branding.enabled ? systemFeatures.branding.workspace_logo : '' const persistWorkspaceBrand = async (body: WorkspaceCustomConfigPayload) => { + if (isCustomConfigUnavailable || !canReplaceLogo || !canManageCustomBrand) return await updateCustomConfigMutation.mutateAsync({ body }) await queryClient.invalidateQueries({ queryKey: consoleQuery.workspaces.customConfig.get.key(), }) } const handleChange = (e: ChangeEvent) => { + if (uploadDisabled) return const file = e.target.files?.[0] if (!file) return if (file.size > MAX_LOGO_FILE_SIZE) { @@ -107,7 +111,7 @@ const useWebAppBrand = () => { isCustomConfigUnavailable, uploadDisabled, workspaceLogo, - isSandbox, + canReplaceLogo, canManageCustomBrand, handleApply, handleCancel, diff --git a/web/app/components/custom/custom-web-app-brand/index.tsx b/web/app/components/custom/custom-web-app-brand/index.tsx index a76ca4eb1af..ad0530d423d 100644 --- a/web/app/components/custom/custom-web-app-brand/index.tsx +++ b/web/app/components/custom/custom-web-app-brand/index.tsx @@ -22,7 +22,7 @@ const CustomWebAppBrand = () => { uploadDisabled, workspaceLogo, canManageCustomBrand, - isSandbox, + canReplaceLogo, handleApply, handleCancel, handleChange, @@ -37,7 +37,7 @@ const CustomWebAppBrand = () => {
@@ -106,7 +106,12 @@ const CustomWebAppBrand = () => { variant="primary" className="mr-2" onClick={handleApply} - disabled={isCustomConfigUnavailable || webappBrandRemoved || !canManageCustomBrand} + disabled={ + isCustomConfigUnavailable || + !canReplaceLogo || + webappBrandRemoved || + !canManageCustomBrand + } > {t(($) => $.apply, { ns: 'custom' })} diff --git a/web/app/components/datasets/access-config/index.tsx b/web/app/components/datasets/access-config/index.tsx index 780ffe75f37..3e2fa4e73b8 100644 --- a/web/app/components/datasets/access-config/index.tsx +++ b/web/app/components/datasets/access-config/index.tsx @@ -231,7 +231,7 @@ const DatasetAccessConfigPage = ({ datasetId }: DatasetAccessConfigPageProps) => {t(($) => $['accessRule.datasetDescription'], { ns: 'permission' })}

-
+
onBatchRemoveAccessPolicyMemberBindings={handleBatchRemoveAccessPolicyMemberBindings} onAddAccessSubject={handleAddAccessSubject} /> -
+
) } diff --git a/web/app/components/datasets/common/__tests__/check-rerank-model.spec.ts b/web/app/components/datasets/common/__tests__/check-rerank-model.spec.ts index 21bee3a24d1..8ed9980b9e2 100644 --- a/web/app/components/datasets/common/__tests__/check-rerank-model.spec.ts +++ b/web/app/components/datasets/common/__tests__/check-rerank-model.spec.ts @@ -1,7 +1,7 @@ import type { - Model, - ModelItem, -} from '@/app/components/header/account-setting/model-provider-page/declarations' + ProviderModelWithStatusEntity, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' import type { RetrievalConfig } from '@/types/app' import { describe, expect, it } from 'vite-plus/test' import { @@ -27,7 +27,7 @@ const createRetrievalConfig = (overrides: Partial = {}): Retrie ...overrides, }) -const createModelItem = (model: string): ModelItem => ({ +const createModelItem = (model: string): ProviderModelWithStatusEntity => ({ model, label: { en_US: model, zh_Hans: model }, model_type: ModelTypeEnum.rerank, @@ -37,8 +37,9 @@ const createModelItem = (model: string): ModelItem => ({ load_balancing_enabled: false, }) -const createRerankModelList = (): Model[] => [ +const createRerankModelList = (): ProviderWithModelsResponse[] => [ { + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: '', zh_Hans: '' }, label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, @@ -46,6 +47,7 @@ const createRerankModelList = (): Model[] => [ status: ModelStatusEnum.active, }, { + tenant_id: 'test-workspace', provider: 'cohere', icon_small: { en_US: '', zh_Hans: '' }, label: { en_US: 'Cohere', zh_Hans: 'Cohere' }, diff --git a/web/app/components/datasets/common/check-rerank-model.ts b/web/app/components/datasets/common/check-rerank-model.ts index 19655d6aa50..e5271c1bd10 100644 --- a/web/app/components/datasets/common/check-rerank-model.ts +++ b/web/app/components/datasets/common/check-rerank-model.ts @@ -1,4 +1,4 @@ -import type { Model } from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' import type { RetrievalConfig } from '@/types/app' import { RerankingModeEnum } from '@/models/datasets' import { RETRIEVE_METHOD } from '@/types/app' @@ -9,7 +9,7 @@ export const isReRankModelSelected = ({ indexMethod, }: { retrievalConfig: RetrievalConfig - rerankModelList: Model[] + rerankModelList: ProviderWithModelsResponse[] indexMethod?: string }) => { const rerankModelSelected = (() => { diff --git a/web/app/components/datasets/common/document-status-with-action/__tests__/auto-disabled-document.spec.tsx b/web/app/components/datasets/common/document-status-with-action/__tests__/auto-disabled-document.spec.tsx index 780d2fb6ec8..619dc6a5922 100644 --- a/web/app/components/datasets/common/document-status-with-action/__tests__/auto-disabled-document.spec.tsx +++ b/web/app/components/datasets/common/document-status-with-action/__tests__/auto-disabled-document.spec.tsx @@ -1,7 +1,10 @@ import { toast } from '@langgenius/dify-ui/toast' -import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { queryOptions, useQuery } from '@tanstack/react-query' +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' import { useAutoDisabledDocuments } from '@/service/knowledge/use-document' +import { createConsoleQueryWrapper } from '@/test/console/query-data' import AutoDisabledDocument from '../auto-disabled-document' const { mockToastSuccess } = vi.hoisted(() => ({ @@ -89,6 +92,29 @@ describe('AutoDisabledDocument', () => { }) }) + it('enables the current document IDs after the initial query completes', async () => { + const user = userEvent.setup() + mockUseAutoDisabledDocuments.mockImplementation(() => + useQuery( + queryOptions({ + queryKey: ['disabled-documents'], + queryFn: () => new Promise(() => {}), + }), + ), + ) + const { wrapper, queryClient } = createConsoleQueryWrapper() + render(, { wrapper }) + expect(screen.queryByRole('button', { name: /enable/i })).not.toBeInTheDocument() + await act(async () => { + queryClient.setQueryData(['disabled-documents'], { document_ids: ['returned-document'] }) + }) + await user.click(await screen.findByRole('button', { name: /enable/i })) + expect(mockMutateAsync).toHaveBeenCalledWith({ + datasetId: 'dataset', + documentIds: ['returned-document'], + }) + }) + describe('User Interactions', () => { it('should call enableDocument when action button is clicked', async () => { mockUseAutoDisabledDocuments.mockReturnValue( diff --git a/web/app/components/datasets/common/document-status-with-action/auto-disabled-document.tsx b/web/app/components/datasets/common/document-status-with-action/auto-disabled-document.tsx index 63765d25702..ee034e8810e 100644 --- a/web/app/components/datasets/common/document-status-with-action/auto-disabled-document.tsx +++ b/web/app/components/datasets/common/document-status-with-action/auto-disabled-document.tsx @@ -2,7 +2,6 @@ import type { FC } from 'react' import { toast } from '@langgenius/dify-ui/toast' import * as React from 'react' -import { useCallback } from 'react' import { useTranslation } from 'react-i18next' import { useAutoDisabledDocuments, @@ -20,14 +19,14 @@ const AutoDisabledDocument: FC = ({ datasetId }) => { const { data, isLoading } = useAutoDisabledDocuments(datasetId) const invalidDisabledDocument = useInvalidDisabledDocument() const documentIds = data?.document_ids - const hasDisabledDocument = documentIds && documentIds.length > 0 const { mutateAsync: enableDocument } = useDocumentEnable() - const handleEnableDocuments = useCallback(async () => { + if (!documentIds?.length || isLoading) return null + + const handleEnableDocuments = async () => { await enableDocument({ datasetId, documentIds }) invalidDisabledDocument() toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' })) - }, []) - if (!hasDisabledDocument || isLoading) return null + } return ( ({ +const createEmbeddingModelProvider = ( + features: ModelFeatureEnum[] = [], +): ProviderWithModelsResponse => ({ + tenant_id: 'test-workspace', provider: 'test-provider', icon_small: { en_US: '', zh_Hans: '' }, label: { en_US: 'Test Provider', zh_Hans: 'Test Provider' }, diff --git a/web/app/components/datasets/common/multimodal-retrieval-guidance/index.tsx b/web/app/components/datasets/common/multimodal-retrieval-guidance/index.tsx index d58d276b35a..59f1fa8d5c2 100644 --- a/web/app/components/datasets/common/multimodal-retrieval-guidance/index.tsx +++ b/web/app/components/datasets/common/multimodal-retrieval-guidance/index.tsx @@ -1,9 +1,6 @@ 'use client' - -import type { - DefaultModel, - Model, -} from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' +import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import { cn } from '@langgenius/dify-ui/cn' import { useTranslation } from 'react-i18next' import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' @@ -18,14 +15,17 @@ type MultimodalRetrievalGuidanceVariant = 'create' | 'settings' | 'pipeline' type MultimodalRetrievalGuidanceProps = { variant: MultimodalRetrievalGuidanceVariant embeddingModel?: DefaultModel - embeddingModelList?: Model[] + embeddingModelList?: ProviderWithModelsResponse[] className?: string } const MULTIMODAL_RETRIEVAL_DOC_URL = 'https://dify.ai/blog/multimodal-retrieval-is-now-available-in-the-knowledge-base' -const isVisionEmbeddingModel = (embeddingModel?: DefaultModel, embeddingModelList?: Model[]) => { +const isVisionEmbeddingModel = ( + embeddingModel?: DefaultModel, + embeddingModelList?: ProviderWithModelsResponse[], +) => { if (!embeddingModel?.provider || !embeddingModel.model) return false const provider = embeddingModelList?.find((item) => item.provider === embeddingModel.provider) diff --git a/web/app/components/datasets/common/retrieval-method-config/__tests__/index.spec.tsx b/web/app/components/datasets/common/retrieval-method-config/__tests__/index.spec.tsx index c09d2909ceb..189712d68b9 100644 --- a/web/app/components/datasets/common/retrieval-method-config/__tests__/index.spec.tsx +++ b/web/app/components/datasets/common/retrieval-method-config/__tests__/index.spec.tsx @@ -2,7 +2,7 @@ import type { RetrievalConfig } from '@/types/app' import { fireEvent, screen } from '@testing-library/react' import * as React from 'react' import { DEFAULT_WEIGHTED_SCORE, RerankingModeEnum, WeightedScoreEnum } from '@/models/datasets' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { RETRIEVE_METHOD } from '@/types/app' import RetrievalMethodConfig from '../index' diff --git a/web/app/components/datasets/common/retrieval-method-config/index.tsx b/web/app/components/datasets/common/retrieval-method-config/index.tsx index b5fed072075..1cbfc2b3594 100644 --- a/web/app/components/datasets/common/retrieval-method-config/index.tsx +++ b/web/app/components/datasets/common/retrieval-method-config/index.tsx @@ -13,7 +13,7 @@ import { import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks' import { DEFAULT_WEIGHTED_SCORE, RerankingModeEnum, WeightedScoreEnum } from '@/models/datasets' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { RETRIEVE_METHOD } from '@/types/app' import { EffectColor } from '../../settings/chunk-structure/types' import OptionCard from '../../settings/option-card' diff --git a/web/app/components/datasets/create/embedding-process/__tests__/index.spec.tsx b/web/app/components/datasets/create/embedding-process/__tests__/index.spec.tsx index 4aa3641eabb..23bfb78c9a1 100644 --- a/web/app/components/datasets/create/embedding-process/__tests__/index.spec.tsx +++ b/web/app/components/datasets/create/embedding-process/__tests__/index.spec.tsx @@ -1,11 +1,13 @@ +import type { ReactElement } from 'react' import type { IndexingStatusResponse } from '@/models/datasets' -import { render, screen } from '@testing-library/react' +import { screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' +import { renderWithConsoleQuery } from '@/test/console/query-data' import EmbeddingProcess from '../index' const mockInvalidDocumentList = vi.fn() -let mockEnableBilling = false -let mockPlanType = 'sandbox' +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' +let mockPlanType: 'sandbox' | 'professional' | 'team' = 'sandbox' let mockPollingState: { statusList: IndexingStatusResponse[] isEmbedding: boolean @@ -45,13 +47,6 @@ vi.mock('@/hooks/use-api-access-url', () => ({ useDatasetApiAccessUrl: () => 'https://api.example.com/docs', })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - enableBilling: mockEnableBilling, - plan: { type: mockPlanType }, - }), -})) - vi.mock('../use-indexing-status-polling', () => ({ useIndexingStatusPolling: () => mockPollingState, })) @@ -84,10 +79,17 @@ vi.mock('@/app/components/datasets/common/vector-space-admission-alert', () => ( ), })) +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: deploymentEdition }, + features: { billing: { subscription: { plan: mockPlanType } } }, + }) +} + describe('EmbeddingProcess', () => { beforeEach(() => { vi.clearAllMocks() - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' mockPlanType = 'sandbox' mockPollingState = { statusList: [], @@ -156,7 +158,7 @@ describe('EmbeddingProcess', () => { }) it('does not suggest an upgrade to team users', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'team' mockPollingState = { statusList: [ @@ -200,7 +202,7 @@ describe('EmbeddingProcess', () => { }) it('offers a processing-priority upgrade outside the team plan', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' render() diff --git a/web/app/components/datasets/create/embedding-process/__tests__/indexing-progress-item.spec.tsx b/web/app/components/datasets/create/embedding-process/__tests__/indexing-progress-item.spec.tsx index 825fe39e3ab..cf16e383329 100644 --- a/web/app/components/datasets/create/embedding-process/__tests__/indexing-progress-item.spec.tsx +++ b/web/app/components/datasets/create/embedding-process/__tests__/indexing-progress-item.spec.tsx @@ -106,16 +106,4 @@ describe('IndexingProgressItem', () => { expect(screen.getByText('common.error')).toBeInTheDocument() }) - - it('should show priority label when billing is enabled', () => { - render() - - expect(screen.getByTestId('priority-label')).toBeInTheDocument() - }) - - it('should not show priority label when billing is disabled', () => { - render() - - expect(screen.queryByTestId('priority-label')).not.toBeInTheDocument() - }) }) diff --git a/web/app/components/datasets/create/embedding-process/index.tsx b/web/app/components/datasets/create/embedding-process/index.tsx index 54719c14628..7a98c4010e7 100644 --- a/web/app/components/datasets/create/embedding-process/index.tsx +++ b/web/app/components/datasets/create/embedding-process/index.tsx @@ -4,13 +4,16 @@ import type { RETRIEVE_METHOD } from '@/types/app' import { buttonVariants } from '@langgenius/dify-ui/button' import { cn } from '@langgenius/dify-ui/cn' import { RiArrowRightLine, RiLoader2Fill, RiTerminalBoxLine } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import { useMemo } from 'react' import { useTranslation } from 'react-i18next' import Divider from '@/app/components/base/divider' import VectorSpaceAdmissionAlert from '@/app/components/datasets/common/vector-space-admission-alert' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url' import Link from '@/next/link' +import { consoleQuery } from '@/service/console' import { useProcessRule } from '@/service/knowledge/use-dataset' import { useInvalidDocumentList } from '@/service/knowledge/use-document' import IndexingProgressItem from './indexing-progress-item' @@ -85,7 +88,13 @@ const EmbeddingProcess: FC = ({ indexingType, retrievalMethod, }) => { - const { enableBilling, plan } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.billing.subscription.plan, + }), + ) const invalidDocumentList = useInvalidDocumentList() const apiReferenceUrl = useDatasetApiAccessUrl() @@ -104,9 +113,10 @@ const EmbeddingProcess: FC = ({ const documentsHref = `/datasets/${datasetId}/documents` - const showUpgradeBanner = enableBilling && plan.type !== 'team' + const showUpgradeBanner = + deploymentEdition === 'CLOUD' && (plan === 'sandbox' || plan === 'professional') const showVectorSpaceUpgrade = - enableBilling && (plan.type === 'sandbox' || plan.type === 'professional') + deploymentEdition === 'CLOUD' && (plan === 'sandbox' || plan === 'professional') const vectorSpaceAdmissionError = statusList.find( (detail) => detail.error_code === 'vector_space_estimate_exceeded', ) @@ -135,7 +145,6 @@ const EmbeddingProcess: FC = ({ name={documentLookup.getName(detail.id)} sourceType={documentLookup.getSourceType(detail.id)} notionIcon={documentLookup.getNotionIcon(detail.id)} - enableBilling={enableBilling} /> ))}
diff --git a/web/app/components/datasets/create/embedding-process/indexing-progress-item.tsx b/web/app/components/datasets/create/embedding-process/indexing-progress-item.tsx index 571a8ced063..d1b0dd6d89a 100644 --- a/web/app/components/datasets/create/embedding-process/indexing-progress-item.tsx +++ b/web/app/components/datasets/create/embedding-process/indexing-progress-item.tsx @@ -15,7 +15,6 @@ type IndexingProgressItemProps = { name?: string sourceType?: DataSourceType notionIcon?: string - enableBilling?: boolean } // Status icon component for completed/error states @@ -71,7 +70,6 @@ const IndexingProgressItem: FC = ({ name, sourceType, notionIcon, - enableBilling, }) => { const isEmbedding = isSourceEmbedding(detail) const percent = getSourcePercent(detail) @@ -94,7 +92,7 @@ const IndexingProgressItem: FC = ({
{name}
- {enableBilling && } +
{isEmbedding &&
{`${percent}%`}
} diff --git a/web/app/components/datasets/create/file-uploader/components/__tests__/upload-dropzone.spec.tsx b/web/app/components/datasets/create/file-uploader/components/__tests__/upload-dropzone.spec.tsx index dfe04d39361..49d4a8a053c 100644 --- a/web/app/components/datasets/create/file-uploader/components/__tests__/upload-dropzone.spec.tsx +++ b/web/app/components/datasets/create/file-uploader/components/__tests__/upload-dropzone.spec.tsx @@ -1,17 +1,11 @@ -import type { RefObject } from 'react' +import type { ReactElement, RefObject } from 'react' import type { UploadDropzoneProps } from '../upload-dropzone' -import type { ProviderContextState } from '@/context/provider-context' -import { fireEvent, render, screen } from '@testing-library/react' +import { fireEvent, screen } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' +import { renderWithConsoleQuery } from '@/test/console/query-data' import UploadDropzone from '../upload-dropzone' -let mockEnableBilling = false - -vi.mock('@/context/provider-context', () => ({ - useProviderContextSelector: ( - selector: (state: Pick) => T, - ): T => selector({ enableBilling: mockEnableBilling }), -})) +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' // Helper to create mock ref objects for testing const createMockRef = (value: T | null = null): RefObject => ({ current: value }) @@ -36,7 +30,7 @@ describe('UploadDropzone', () => { beforeEach(() => { vi.clearAllMocks() - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' }) describe('rendering', () => { @@ -83,7 +77,7 @@ describe('UploadDropzone', () => { describe('tip rendering by billing state', () => { it('should render tip without total count limit when billing is disabled', () => { - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' render() @@ -97,7 +91,7 @@ describe('UploadDropzone', () => { }) it('should render tip with total count limit when billing is enabled', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' render() @@ -110,7 +104,7 @@ describe('UploadDropzone', () => { }) it('should pass file size, batch count and supported types to tip when billing is disabled', () => { - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' render() @@ -122,7 +116,7 @@ describe('UploadDropzone', () => { }) it('should additionally pass total count to tip when billing is enabled', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' render() @@ -275,3 +269,10 @@ describe('UploadDropzone', () => { }) }) }) + +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: deploymentEdition }, + features: {}, + }) +} diff --git a/web/app/components/datasets/create/file-uploader/components/upload-dropzone.tsx b/web/app/components/datasets/create/file-uploader/components/upload-dropzone.tsx index 0531f399479..bcf3b783e9e 100644 --- a/web/app/components/datasets/create/file-uploader/components/upload-dropzone.tsx +++ b/web/app/components/datasets/create/file-uploader/components/upload-dropzone.tsx @@ -2,8 +2,9 @@ import type { RefObject } from 'react' import type { FileUploadConfig } from '../hooks/use-file-upload' import { cn } from '@langgenius/dify-ui/cn' +import { useAtomValue } from 'jotai' import { useTranslation } from 'react-i18next' -import { useProviderContextSelector } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' export type UploadDropzoneProps = { dropRef: RefObject @@ -31,7 +32,7 @@ const UploadDropzone = ({ onFileChange, }: UploadDropzoneProps) => { const { t } = useTranslation() - const enableBilling = useProviderContextSelector((state) => state.enableBilling) + const deploymentEdition = useAtomValue(deploymentEditionAtom) return ( <> @@ -69,7 +70,7 @@ const UploadDropzone = ({
- {enableBilling + {deploymentEdition === 'CLOUD' ? t(($) => $['stepOne.uploader.tipWithTotalLimit'], { ns: 'datasetCreation', size: fileUploadConfig.file_size_limit, diff --git a/web/app/components/datasets/create/step-one/__tests__/index.spec.tsx b/web/app/components/datasets/create/step-one/__tests__/index.spec.tsx index 07d59a7ce8f..56aa9b22bad 100644 --- a/web/app/components/datasets/create/step-one/__tests__/index.spec.tsx +++ b/web/app/components/datasets/create/step-one/__tests__/index.spec.tsx @@ -4,7 +4,7 @@ import type { NotionPage } from '@/models/common' import type { CrawlOptions, CrawlResultItem, DataSet, FileItem } from '@/models/datasets' import { fireEvent, screen } from '@testing-library/react' import { DataSourceType } from '@/models/datasets' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import StepOne from '../index' @@ -28,6 +28,8 @@ let mockPlan: { total: { vectorSpace: 100, buildApps: 0, documentsUploadQuota: 0, vectorStorageQuota: 0 }, } +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' + const render = (ui: React.ReactElement, vectorSpaceUsageUnknown = false) => { const queryClient = createConsoleQueryClient() queryClient.setQueryData(consoleQuery.features.vectorSpace.get.queryOptions().queryKey, { @@ -36,8 +38,9 @@ const render = (ui: React.ReactElement, vectorSpaceUsageUnknown = false) => { usage_unknown: vectorSpaceUsageUnknown, }) return renderWithConsoleQuery(ui, { - systemFeatures: { deployment_edition: 'CLOUD' }, + systemFeatures: { deployment_edition: deploymentEdition }, queryClient, + features: { billing: { subscription: { plan: mockPlan.type } } }, }) } @@ -60,14 +63,6 @@ vi.mock('@/context/dataset-detail', () => ({ })) // Mock provider context -let mockEnableBilling = false - -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - plan: mockPlan, - enableBilling: mockEnableBilling, - }), -})) vi.mock('../../file-uploader', () => ({ default: ({ onPreview, fileList }: { onPreview: (file: File) => void; fileList: FileItem[] }) => ( @@ -250,7 +245,7 @@ describe('StepOne', () => { usage: { vectorSpace: 50, buildApps: 0, documentsUploadQuota: 0, vectorStorageQuota: 0 }, total: { vectorSpace: 100, buildApps: 0, documentsUploadQuota: 0, vectorStorageQuota: 0 }, } - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' }) describe('Rendering', () => { @@ -430,7 +425,7 @@ describe('StepOne', () => { }) it('should show plan upgrade modal when batch upload not supported and multiple files', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlan.type = 'sandbox' const files = [createMockFileItem(), createMockFileItem()] render() @@ -441,7 +436,7 @@ describe('StepOne', () => { }) it('should show upgrade card immediately when in sandbox plan', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlan.type = 'sandbox' render() @@ -453,7 +448,7 @@ describe('StepOne', () => { // Vector Space Full Tests describe('Vector Space Full', () => { it('should show VectorSpaceFull when vector space is full and billing is enabled', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlan.usage.vectorSpace = 100 mockPlan.total.vectorSpace = 100 const files = [createMockFileItem()] @@ -464,7 +459,7 @@ describe('StepOne', () => { }) it('should disable next button when vector space is full', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlan.usage.vectorSpace = 100 mockPlan.total.vectorSpace = 100 const files = [createMockFileItem()] @@ -475,7 +470,7 @@ describe('StepOne', () => { }) it('should require sandbox users to retry when vector space usage is unknown', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlan.type = 'sandbox' mockPlan.usage.vectorSpace = 100 mockPlan.total.vectorSpace = 100 @@ -490,7 +485,7 @@ describe('StepOne', () => { }) it('should allow paid users to continue when vector space usage is unknown', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlan.type = 'professional' const files = [createMockFileItem()] diff --git a/web/app/components/datasets/create/step-one/index.tsx b/web/app/components/datasets/create/step-one/index.tsx index 65867fdbf37..afff9959ce7 100644 --- a/web/app/components/datasets/create/step-one/index.tsx +++ b/web/app/components/datasets/create/step-one/index.tsx @@ -7,6 +7,7 @@ import { cn } from '@langgenius/dify-ui/cn' import { RiFolder6Line } from '@remixicon/react' import { useQuery } from '@tanstack/react-query' import { useBoolean } from 'ahooks' +import { useAtomValue } from 'jotai' import { useCallback, useMemo } from 'react' import { useTranslation } from 'react-i18next' import NotionConnector from '@/app/components/base/notion-connector' @@ -14,9 +15,9 @@ import { NotionPageSelector } from '@/app/components/base/notion-page-selector' import VectorSpaceFull from '@/app/components/billing/vector-space-full' import VectorSpaceUnavailable from '@/app/components/billing/vector-space-unavailable' import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' import { DataSourceType } from '@/models/datasets' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import EmptyDatasetCreationModal from '../empty-dataset-creation-modal' import FileUploader from '../file-uploader' import Website from '../website' @@ -100,7 +101,13 @@ const StepOne = ({ }: IStepOneProps) => { const { t } = useTranslation() const dataset = useDatasetDetailContextWithSelector((state) => state.dataset) - const { plan, enableBilling } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.billing.subscription.plan, + }), + ) // Preview state management const { @@ -134,7 +141,7 @@ const StepOne = ({ const allFileLoaded = files.length > 0 && files.every((file) => file.file.id) const hasNotion = notionPages.length > 0 - const shouldCheckVectorSpace = enableBilling && (allFileLoaded || hasNotion) + const shouldCheckVectorSpace = deploymentEdition === 'CLOUD' && (allFileLoaded || hasNotion) const { data: vectorSpace, isFetching: isFetchingVectorSpacePlan, @@ -144,14 +151,17 @@ const StepOne = ({ ) const isCheckingVectorSpace = shouldCheckVectorSpace && !vectorSpace && isFetchingVectorSpacePlan const isVectorSpaceUnavailable = - shouldCheckVectorSpace && plan.type === 'sandbox' && !!vectorSpace?.usage_unknown + shouldCheckVectorSpace && plan === 'sandbox' && !!vectorSpace?.usage_unknown const isVectorSpaceFull = !!vectorSpace && !vectorSpace.usage_unknown && vectorSpace.limit > 0 && vectorSpace.size >= vectorSpace.limit - const isShowVectorSpaceFull = (allFileLoaded || hasNotion) && isVectorSpaceFull && enableBilling - const supportBatchUpload = !enableBilling || plan.type !== 'sandbox' + const isShowVectorSpaceFull = + (allFileLoaded || hasNotion) && isVectorSpaceFull && deploymentEdition === 'CLOUD' + const isPlanUnavailable = deploymentEdition === 'CLOUD' && plan === undefined + const supportBatchUpload = + deploymentEdition !== 'CLOUD' || plan === 'professional' || plan === 'team' const isNotionAuthed = useMemo( () => checkNotionAuth(authedDataSourceList), @@ -181,6 +191,7 @@ const StepOne = ({ // Handle step change with batch upload check const onStepChange = useCallback(() => { + if (isPlanUnavailable) return if (!supportBatchUpload && dataSourceType) { const checkFn = MULTIPLE_ITEMS_CHECK[dataSourceType] if (checkFn?.({ files, notionPages, websitePages })) { @@ -193,6 +204,7 @@ const StepOne = ({ dataSourceType, doOnStepChange, files, + isPlanUnavailable, supportBatchUpload, notionPages, showPlanUpgradeModal, @@ -247,8 +259,11 @@ const StepOne = ({ />
)} - - {enableBilling && plan.type === 'sandbox' && ( + + {deploymentEdition === 'CLOUD' && plan === 'sandbox' && (
@@ -292,7 +307,10 @@ const StepOne = ({ )} @@ -322,7 +340,7 @@ const StepOne = ({
)} diff --git a/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx b/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx index 6913fa65dfc..cc03749fff2 100644 --- a/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx +++ b/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx @@ -1,4 +1,8 @@ -import type { Model } from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { + GetWorkspacesCurrentModelsModelTypesByModelTypeData, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import type { DataSourceProvider, NotionPage } from '@/models/common' import type { CrawlOptions, @@ -75,8 +79,9 @@ const mockDefaultEmbeddingModel = { model: 'text-embedding-ada-002', } // Model[] type structure for rerank model list (simplified mock) -const mockRerankModelList: Model[] = [ +const mockRerankModelList: ProviderWithModelsResponse[] = [ { + tenant_id: 'test-workspace', provider: 'cohere', icon_small: { en_US: 'cohere-icon', zh_Hans: 'cohere-icon' }, label: { en_US: 'Cohere', zh_Hans: 'Cohere' }, @@ -104,7 +109,7 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () defaultModel: mockRerankDefaultModel, currentModel: mockIsRerankDefaultModelValid, }), - useModelList: () => ({ data: mockEmbeddingModelList }), + useDefaultModel: () => ({ data: mockDefaultEmbeddingModel }), })) @@ -2620,3 +2625,19 @@ describe('StepTwo Component', () => { }) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + return { data: mockEmbeddingModelList } + }, + } +}) diff --git a/web/app/components/datasets/create/step-two/components/indexing-mode-section.tsx b/web/app/components/datasets/create/step-two/components/indexing-mode-section.tsx index 8f0e02a4ee5..bc6c1bd1676 100644 --- a/web/app/components/datasets/create/step-two/components/indexing-mode-section.tsx +++ b/web/app/components/datasets/create/step-two/components/indexing-mode-section.tsx @@ -1,10 +1,7 @@ 'use client' - +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' import type { FC } from 'react' -import type { - DefaultModel, - Model, -} from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { RetrievalConfig } from '@/types/app' import { AlertDialog, @@ -40,7 +37,7 @@ type IndexingModeSectionProps = { hasSetIndexType: boolean docForm: ChunkingMode embeddingModel: DefaultModel - embeddingModelList?: Model[] + embeddingModelList?: ProviderWithModelsResponse[] retrievalConfig: RetrievalConfig showMultiModalTip: boolean // Flags diff --git a/web/app/components/datasets/create/step-two/hooks/__tests__/use-indexing-config.spec.ts b/web/app/components/datasets/create/step-two/hooks/__tests__/use-indexing-config.spec.ts index 94c7c28a6fa..b299dcd457d 100644 --- a/web/app/components/datasets/create/step-two/hooks/__tests__/use-indexing-config.spec.ts +++ b/web/app/components/datasets/create/step-two/hooks/__tests__/use-indexing-config.spec.ts @@ -1,3 +1,5 @@ +import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import { act, renderHook } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' import { RETRIEVE_METHOD } from '@/types/app' @@ -17,7 +19,7 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () defaultModel: mocks.rerankDefaultModel, currentModel: mocks.isRerankDefaultModelValid, }), - useModelList: () => ({ data: mocks.embeddingModelList }), + useDefaultModel: () => ({ data: mocks.defaultEmbeddingModel }), })) @@ -159,3 +161,19 @@ describe('useIndexingConfig', () => { }) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + return { data: mocks.embeddingModelList } + }, + } +}) diff --git a/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts b/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts index b17bb62383f..7c7b38af414 100644 --- a/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts +++ b/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts @@ -1,7 +1,5 @@ -import type { - DefaultModel, - Model, -} from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' +import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { NotionPage } from '@/models/common' import type { ChunkingMode, @@ -60,7 +58,7 @@ type ValidationParams = { overlap: number indexType: IndexingType embeddingModel: DefaultModel - rerankModelList: Model[] + rerankModelList: ProviderWithModelsResponse[] retrievalConfig: RetrievalConfig } export const useDocumentCreation = (options: UseDocumentCreationOptions) => { diff --git a/web/app/components/datasets/create/step-two/hooks/use-indexing-config.ts b/web/app/components/datasets/create/step-two/hooks/use-indexing-config.ts index 04b9f907634..e87a337d1c6 100644 --- a/web/app/components/datasets/create/step-two/hooks/use-indexing-config.ts +++ b/web/app/components/datasets/create/step-two/hooks/use-indexing-config.ts @@ -1,13 +1,14 @@ import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { RetrievalConfig } from '@/types/app' +import { useQuery } from '@tanstack/react-query' import { useEffect, useMemo, useState } from 'react' import { checkShowMultiModalTip } from '@/app/components/datasets/settings/utils' import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' import { useDefaultModel, - useModelList, useModelListAndDefaultModelAndCurrentProviderAndModel, } from '@/app/components/header/account-setting/model-provider-page/hooks' +import { consoleQuery } from '@/service/console' import { RETRIEVE_METHOD } from '@/types/app' export enum IndexingType { @@ -52,7 +53,12 @@ export const useIndexingConfig = (options: UseIndexingConfigOptions) => { } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.rerank) // Embedding model list - const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding) + const { data: embeddingModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textEmbedding } }, + select: (response) => response.data, + }), + ) const { data: defaultEmbeddingModel } = useDefaultModel(ModelTypeEnum.textEmbedding) // Index type state diff --git a/web/app/components/datasets/documents/__tests__/index.spec.tsx b/web/app/components/datasets/documents/__tests__/index.spec.tsx index f3a4e1834a5..ba98e6ef6c7 100644 --- a/web/app/components/datasets/documents/__tests__/index.spec.tsx +++ b/web/app/components/datasets/documents/__tests__/index.spec.tsx @@ -3,7 +3,6 @@ import type { DocumentListResponse } from '@/models/datasets' import { QueryClientProvider } from '@tanstack/react-query' import { act, fireEvent, screen } from '@testing-library/react' import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail' -import { useProviderContext } from '@/context/provider-context' import { DataSourceType } from '@/models/datasets' import { useDocumentList } from '@/service/knowledge/use-document' import { createAccountProfileQueryClient } from '@/test/console/account-profile' @@ -54,12 +53,6 @@ vi.mock('@/context/dataset-detail', () => ({ }), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: vi.fn(() => ({ - plan: { type: 'professional' }, - })), -})) - vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') @@ -193,7 +186,6 @@ vi.mock('../components/documents-header', () => ({ datasetId: string dataSourceType?: string embeddingAvailable: boolean - isFreePlan: boolean statusFilterValue: string sortValue: string inputValue: string @@ -719,16 +711,6 @@ describe('Documents', () => { expect(screen.getByTestId('header-embedding-available')).toHaveTextContent('false') }) - - it('should handle free plan user', () => { - vi.mocked(useProviderContext).mockReturnValueOnce({ - plan: { type: 'sandbox' }, - } as ReturnType) - - render() - - expect(screen.getByTestId('documents-header')).toBeInTheDocument() - }) }) describe('Pagination', () => { diff --git a/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsx b/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsx index 17bc7f7f6b1..a230dfd7951 100644 --- a/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsx +++ b/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsx @@ -36,7 +36,6 @@ describe('DocumentsHeader', () => { canManageMetadata: true, canAddDocument: true, canEditDocument: true, - isFreePlan: false, statusFilterValue: 'all', sortValue: 'created_at' as SortType, inputValue: '', @@ -104,16 +103,6 @@ describe('DocumentsHeader', () => { }) describe('AutoDisabledDocument', () => { - it('should show AutoDisabledDocument when not free plan', () => { - render() - expect(screen.getByTestId('auto-disabled-document')).toBeInTheDocument() - }) - - it('should not show AutoDisabledDocument when on free plan', () => { - render() - expect(screen.queryByTestId('auto-disabled-document')).not.toBeInTheDocument() - }) - it('should not show AutoDisabledDocument without document edit permission', () => { render() expect(screen.queryByTestId('auto-disabled-document')).not.toBeInTheDocument() diff --git a/web/app/components/datasets/documents/components/documents-header.tsx b/web/app/components/datasets/documents/components/documents-header.tsx index 14dc12b5dcf..35b5e3f6e18 100644 --- a/web/app/components/datasets/documents/components/documents-header.tsx +++ b/web/app/components/datasets/documents/components/documents-header.tsx @@ -32,7 +32,6 @@ type DocumentsHeaderProps = { canManageMetadata?: boolean canAddDocument?: boolean canEditDocument?: boolean - isFreePlan: boolean // Filter & sort statusFilterValue: string @@ -66,7 +65,6 @@ const DocumentsHeader: FC = ({ canManageMetadata = false, canAddDocument = false, canEditDocument = false, - isFreePlan, statusFilterValue, sortValue, inputValue, @@ -174,7 +172,7 @@ const DocumentsHeader: FC = ({ {/* Right: Actions */}
- {!isFreePlan && canEditDocument && } + {canEditDocument && } {canEditDocument && } {!embeddingAvailable && ( { @@ -16,7 +16,11 @@ const render = (ui: React.ReactElement, vectorSpaceUsageUnknown = false) => { limit: mockPlan.total.vectorSpace, usage_unknown: vectorSpaceUsageUnknown, }) - return renderWithConsoleQuery(ui, { queryClient }) + return renderWithConsoleQuery(ui, { + queryClient, + systemFeatures: { deployment_edition: 'CLOUD' }, + features: { billing: { subscription: { plan: mockPlan.type } } }, + }) } let mockDatasetPermissionKeys = ['dataset.acl.use'] @@ -24,12 +28,6 @@ let mockAllFileLoaded = false const mockRouterReplace = vi.fn() const mockStepOneContent = vi.fn() -vi.mock('@/context/provider-context', () => ({ - useProviderContextSelector: ( - selector: (state: { plan: typeof mockPlan; enableBilling: boolean }) => unknown, - ) => selector({ plan: mockPlan, enableBilling: true }), -})) - vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') @@ -37,6 +35,7 @@ vi.mock('@/context/workspace-state', async () => { userProfile: { id: 'user-1' }, workspacePermissionKeys: ['dataset.create_and_management'], isLoadingWorkspacePermissionKeys: false, + deploymentEdition: 'CLOUD', })) }) @@ -47,6 +46,7 @@ vi.mock('@/context/permission-state', async () => { userProfile: { id: 'user-1' }, workspacePermissionKeys: ['dataset.create_and_management'], isLoadingWorkspacePermissionKeys: false, + deploymentEdition: 'CLOUD', })) }) @@ -57,6 +57,7 @@ vi.mock('@/features/system-features/state', async () => { userProfile: { id: 'user-1' }, workspacePermissionKeys: ['dataset.create_and_management'], isLoadingWorkspacePermissionKeys: false, + deploymentEdition: 'CLOUD', })) }) diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/__tests__/index.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/__tests__/index.spec.tsx index 9a975ec0a4e..b30a97ad00e 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/__tests__/index.spec.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/__tests__/index.spec.tsx @@ -1,6 +1,7 @@ import type { FileItem } from '@/models/datasets' -import { render, screen } from '@testing-library/react' +import { screen } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' +import { renderWithConsoleQuery as render } from '@/test/console/query-data' import LocalFile from '../index' // Mock the hook @@ -16,9 +17,6 @@ vi.mock('@/hooks/use-theme', () => ({ })) // Mock theme types -vi.mock('@/types/app', () => ({ - Theme: { dark: 'dark', light: 'light' }, -})) // Mock DocumentFileIcon vi.mock('@/app/components/datasets/common/document-file-icon', () => ({ diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/__tests__/upload-dropzone.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/__tests__/upload-dropzone.spec.tsx index e7e1c43b766..a3ac19aa750 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/__tests__/upload-dropzone.spec.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/__tests__/upload-dropzone.spec.tsx @@ -1,17 +1,11 @@ -import type { RefObject } from 'react' +import type { ReactElement, RefObject } from 'react' import type { UploadDropzoneProps } from '../upload-dropzone' -import type { ProviderContextState } from '@/context/provider-context' -import { fireEvent, render, screen } from '@testing-library/react' +import { fireEvent, screen } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' +import { renderWithConsoleQuery } from '@/test/console/query-data' import UploadDropzone from '../upload-dropzone' -let mockEnableBilling = false - -vi.mock('@/context/provider-context', () => ({ - useProviderContextSelector: ( - selector: (state: Pick) => T, - ): T => selector({ enableBilling: mockEnableBilling }), -})) +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' // Helper to create mock ref objects for testing const createMockRef = (value: T | null = null): RefObject => ({ current: value }) @@ -37,7 +31,7 @@ describe('UploadDropzone', () => { beforeEach(() => { vi.clearAllMocks() - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' }) describe('rendering', () => { @@ -89,7 +83,7 @@ describe('UploadDropzone', () => { describe('tip rendering by billing state', () => { it('should render tip without total count limit when billing is disabled', () => { - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' render() @@ -103,7 +97,7 @@ describe('UploadDropzone', () => { }) it('should render tip with total count limit when billing is enabled', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' render() @@ -116,7 +110,7 @@ describe('UploadDropzone', () => { }) it('should pass file size, batch count and supported types to tip when billing is disabled', () => { - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' render() @@ -128,7 +122,7 @@ describe('UploadDropzone', () => { }) it('should additionally pass total count to tip when billing is enabled', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' render() @@ -294,3 +288,10 @@ describe('UploadDropzone', () => { }) }) }) + +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: deploymentEdition }, + features: {}, + }) +} diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/upload-dropzone.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/upload-dropzone.tsx index d1d0f06af05..fb8e363bc45 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/upload-dropzone.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/components/upload-dropzone.tsx @@ -1,7 +1,8 @@ import type { ChangeEvent, RefObject } from 'react' import { cn } from '@langgenius/dify-ui/cn' +import { useAtomValue } from 'jotai' import { useTranslation } from 'react-i18next' -import { useProviderContextSelector } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' type FileUploadConfig = { file_size_limit: number @@ -37,7 +38,7 @@ const UploadDropzone = ({ allowedExtensions, }: UploadDropzoneProps) => { const { t } = useTranslation() - const enableBilling = useProviderContextSelector((state) => state.enableBilling) + const deploymentEdition = useAtomValue(deploymentEditionAtom) return ( <> @@ -75,7 +76,7 @@ const UploadDropzone = ({
- {enableBilling + {deploymentEdition === 'CLOUD' ? t(($) => $['stepOne.uploader.tipWithTotalLimit'], { ns: 'datasetCreation', size: fileUploadConfig.file_size_limit, diff --git a/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-ui-state.spec.ts b/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-ui-state.spec.ts index ae821912cd4..fdb40b23a0c 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-ui-state.spec.ts +++ b/web/app/components/datasets/documents/create-from-pipeline/hooks/__tests__/use-datasource-ui-state.spec.ts @@ -15,7 +15,7 @@ describe('useDatasourceUIState', () => { selectedFileIdsLength: 0, onlineDriveFileList: [] as OnlineDriveFile[], isVectorSpaceFull: false, - enableBilling: false, + currentWorkspacePagesLength: 0, fileUploadConfig: { file_size_limit: 50, batch_count_limit: 20 }, } @@ -39,19 +39,12 @@ describe('useDatasourceUIState', () => { }) describe('isShowVectorSpaceFull', () => { - it('should be false when billing disabled', () => { - const { result } = renderHook(() => - useDatasourceUIState({ ...defaultParams, isVectorSpaceFull: true }), - ) - expect(result.current.isShowVectorSpaceFull).toBe(false) - }) - it('should be true when billing enabled and space is full for local file', () => { const { result } = renderHook(() => useDatasourceUIState({ ...defaultParams, isVectorSpaceFull: true, - enableBilling: true, + allFileLoaded: true, }), ) @@ -64,7 +57,6 @@ describe('useDatasourceUIState', () => { ...defaultParams, datasource: undefined, isVectorSpaceFull: true, - enableBilling: true, }), ) expect(result.current.isShowVectorSpaceFull).toBe(false) diff --git a/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-ui-state.ts b/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-ui-state.ts index a84de2e1f95..52a8ad86182 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-ui-state.ts +++ b/web/app/components/datasets/documents/create-from-pipeline/hooks/use-datasource-ui-state.ts @@ -14,7 +14,6 @@ type DatasourceUIStateParams = { onlineDriveFileList: OnlineDriveFile[] isVectorSpaceFull: boolean isCheckingVectorSpace?: boolean - enableBilling: boolean currentWorkspacePagesLength: number fileUploadConfig: { file_size_limit: number; batch_count_limit: number } } @@ -32,7 +31,6 @@ export const useDatasourceUIState = ({ onlineDriveFileList, isVectorSpaceFull, isCheckingVectorSpace = false, - enableBilling, currentWorkspacePagesLength, fileUploadConfig, }: DatasourceUIStateParams) => { @@ -51,7 +49,7 @@ export const useDatasourceUIState = ({ } const condition = vectorSpaceFullConditions[datasourceType] - return condition && isVectorSpaceFull && enableBilling + return condition && isVectorSpaceFull }, [ datasource, datasourceType, @@ -60,7 +58,6 @@ export const useDatasourceUIState = ({ websitePagesLength, onlineDriveFileList.length, isVectorSpaceFull, - enableBilling, ]) // Lookup table for next button disabled conditions diff --git a/web/app/components/datasets/documents/create-from-pipeline/index.tsx b/web/app/components/datasets/documents/create-from-pipeline/index.tsx index e8e959cfc88..3289ca27632 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/index.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/index.tsx @@ -16,11 +16,11 @@ import { workspacePermissionKeysAtom, workspacePermissionKeysLoadingAtom, } from '@/context/permission-state' -import { useProviderContextSelector } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' +import { deploymentEditionAtom } from '@/features/system-features/state' import { DatasourceType } from '@/models/pipeline' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useFileUploadConfig } from '@/service/use-common' import { usePublishedPipelineInfo } from '@/service/use-pipeline' import { getDatasetACLCapabilities } from '@/utils/permission' @@ -42,8 +42,13 @@ import { StepOnePreview, StepTwoPreview } from './steps/preview-panel' const CreateFormPipeline = () => { const { t } = useTranslation() const router = useRouter() - const plan = useProviderContextSelector((state) => state.plan) - const enableBilling = useProviderContextSelector((state) => state.enableBilling) + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.billing.subscription.plan, + }), + ) const dataset = useDatasetDetailContextWithSelector((s) => s.dataset) const pipelineId = dataset?.pipeline_id const { data: currentUserId } = useSuspenseQuery({ @@ -119,7 +124,7 @@ const CreateFormPipeline = () => { // Computed values const shouldCheckVectorSpace = - enableBilling && + deploymentEdition === 'CLOUD' && (allFileLoaded || onlineDocuments.length > 0 || websitePages.length > 0 || @@ -133,13 +138,16 @@ const CreateFormPipeline = () => { ) const isCheckingVectorSpace = shouldCheckVectorSpace && !vectorSpace && isFetchingVectorSpacePlan const isVectorSpaceUnavailable = - shouldCheckVectorSpace && plan.type === 'sandbox' && !!vectorSpace?.usage_unknown + shouldCheckVectorSpace && plan === 'sandbox' && !!vectorSpace?.usage_unknown const isVectorSpaceFull = + deploymentEdition === 'CLOUD' && !!vectorSpace && !vectorSpace.usage_unknown && vectorSpace.limit > 0 && vectorSpace.size >= vectorSpace.limit - const supportBatchUpload = !enableBilling || plan.type !== 'sandbox' + const isPlanUnavailable = deploymentEdition === 'CLOUD' && plan === undefined + const supportBatchUpload = + deploymentEdition !== 'CLOUD' || plan === 'professional' || plan === 'team' // UI state const { @@ -160,7 +168,6 @@ const CreateFormPipeline = () => { onlineDriveFileList, isVectorSpaceFull, isCheckingVectorSpace: isCheckingVectorSpace || isVectorSpaceUnavailable, - enableBilling, currentWorkspacePagesLength: currentWorkspace?.pages.length ?? 0, fileUploadConfig, }) @@ -173,6 +180,7 @@ const CreateFormPipeline = () => { // Next step with batch upload check const handleNextStep = useCallback(() => { + if (isPlanUnavailable) return if (!supportBatchUpload) { const multipleCheckMap: Record = { [DatasourceType.localFile]: localFileList.length, @@ -194,6 +202,7 @@ const CreateFormPipeline = () => { onlineDocuments.length, selectedFileIds.length, showPlanUpgradeModal, + isPlanUnavailable, supportBatchUpload, websitePages.length, ]) @@ -222,7 +231,7 @@ const CreateFormPipeline = () => { setEstimateData, setBatchId, setDocuments, - handleNextStep, + handleNextStep: doHandleNextStep, PagesMapAndSelectedPagesId, currentWorkspacePages: currentWorkspace?.pages, clearOnlineDocumentData, @@ -257,6 +266,7 @@ const CreateFormPipeline = () => { datasourceType={datasourceType} pipelineNodes={(pipelineInfo?.graph.nodes || []) as Node[]} supportBatchUpload={supportBatchUpload} + showBatchUploadUpgrade={deploymentEdition === 'CLOUD' && plan === 'sandbox'} isShowVectorSpaceFull={isShowVectorSpaceFull} isShowVectorSpaceUnavailable={isVectorSpaceUnavailable} isRetryingVectorSpace={isFetchingVectorSpacePlan} @@ -264,7 +274,7 @@ const CreateFormPipeline = () => { totalOptions={totalOptions} selectedOptions={selectedOptions} tip={tip} - nextBtnDisabled={nextBtnDisabled} + nextBtnDisabled={isPlanUnavailable || nextBtnDisabled} onSelectDataSource={handleSwitchDataSource} onCredentialChange={handleCredentialChange} onSelectAll={handleSelectAll} diff --git a/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsx index 3318b62f7e2..2dd678103b0 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsx @@ -1,4 +1,5 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' +import type { ReactElement } from 'react' import type { Mock } from 'vite-plus/test' import type { DocumentIndexingStatus, IndexingStatusResponse } from '@/models/datasets' import type { InitialDocumentDetail } from '@/models/pipeline' @@ -6,7 +7,7 @@ import { fireEvent, screen, waitFor } from '@testing-library/react' import * as React from 'react' import { IndexingType } from '@/app/components/datasets/create/step-two' import { DatasourceType } from '@/models/pipeline' -import { renderWithConsoleQuery as render } from '@/test/console/query-data' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { RETRIEVE_METHOD } from '@/types/app' import EmbeddingProcess from '../index' @@ -29,14 +30,8 @@ vi.mock('@/next/link', () => ({ })) // Mock provider context -let mockEnableBilling = false +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' let mockPlanType: CloudPlan = 'sandbox' -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - enableBilling: mockEnableBilling, - plan: { type: mockPlanType }, - }), -})) vi.mock('@/app/components/datasets/common/vector-space-admission-alert', () => ({ default: ({ @@ -142,6 +137,13 @@ const createDefaultProps = ( ...overrides, }) +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: deploymentEdition }, + features: { billing: { subscription: { plan: mockPlanType } } }, + }) +} + describe('EmbeddingProcess', () => { beforeEach(() => { vi.clearAllMocks() @@ -151,7 +153,7 @@ describe('EmbeddingProcess', () => { documentIdCounter = 0 // Reset mock states - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' mockPlanType = 'sandbox' mockIndexingStatusData = [] @@ -192,7 +194,7 @@ describe('EmbeddingProcess', () => { describe('Billing and Upgrade Banner', () => { // Tests for billing-related UI it('should not show upgrade banner when billing is disabled', () => { - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' const props = createDefaultProps() render() @@ -203,7 +205,7 @@ describe('EmbeddingProcess', () => { }) it('should show upgrade banner when billing is enabled and plan is not team', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'sandbox' const props = createDefaultProps() @@ -215,7 +217,7 @@ describe('EmbeddingProcess', () => { }) it('should not show upgrade banner when plan is team', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'team' const props = createDefaultProps() @@ -227,7 +229,7 @@ describe('EmbeddingProcess', () => { }) it('should show upgrade banner for professional plan', () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'professional' const props = createDefaultProps() @@ -379,7 +381,7 @@ describe('EmbeddingProcess', () => { }) it('should not suggest an upgrade to team users', async () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'team' const doc1 = createMockDocument({ id: 'doc-1' }) mockIndexingStatusData = [ @@ -1052,7 +1054,7 @@ describe('EmbeddingProcess', () => { describe('Priority Label', () => { // Tests for priority label display it('should show priority label when billing is enabled', async () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'sandbox' const doc1 = createMockDocument({ id: 'doc-1' }) mockIndexingStatusData = [ @@ -1071,7 +1073,7 @@ describe('EmbeddingProcess', () => { }) it('should not show priority label when billing is disabled', async () => { - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' const doc1 = createMockDocument({ id: 'doc-1' }) mockIndexingStatusData = [ createMockIndexingStatus({ id: 'doc-1', indexing_status: 'indexing' }), diff --git a/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/index.tsx b/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/index.tsx index d9e95b5be8a..b6773c9c43d 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/index.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/index.tsx @@ -13,6 +13,8 @@ import { RiLoader2Fill, RiTerminalBoxLine, } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useEffect, useMemo, useState } from 'react' import { useTranslation } from 'react-i18next' @@ -22,10 +24,11 @@ import PriorityLabel from '@/app/components/billing/priority-label' import UpgradeBtn from '@/app/components/billing/upgrade-btn' import DocumentFileIcon from '@/app/components/datasets/common/document-file-icon' import VectorSpaceAdmissionAlert from '@/app/components/datasets/common/vector-space-admission-alert' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url' import { DatasourceType } from '@/models/pipeline' import Link from '@/next/link' +import { consoleQuery } from '@/service/console' import { useIndexingStatusBatch, useProcessRule } from '@/service/knowledge/use-dataset' import { useInvalidDocumentList } from '@/service/knowledge/use-document' import RuleDetail from './rule-detail' @@ -46,7 +49,13 @@ const EmbeddingProcess = ({ retrievalMethod, }: EmbeddingProcessProps) => { const { t } = useTranslation() - const { enableBilling, plan } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.billing.subscription.plan, + }), + ) const [indexingStatusBatchDetail, setIndexingStatusDetail] = useState( [], ) @@ -114,7 +123,8 @@ const EmbeddingProcess = ({ ), [indexingStatusBatchDetail], ) - const showUpgrade = enableBilling && (plan.type === 'sandbox' || plan.type === 'professional') + const showUpgrade = + deploymentEdition === 'CLOUD' && (plan === 'sandbox' || plan === 'professional') const getSourceName = (id: string) => { const doc = documents.find((document) => document.id === id) @@ -166,7 +176,7 @@ const EmbeddingProcess = ({ planLimitMb={vectorSpaceAdmissionError.vector_space_limit_mb} /> )} - {enableBilling && plan.type !== 'team' && ( + {deploymentEdition === 'CLOUD' && (plan === 'sandbox' || plan === 'professional') && (
@@ -216,7 +226,7 @@ const EmbeddingProcess = ({
{getSourceName(indexingStatusDetail.id)}
- {enableBilling && } +
{isSourceEmbedding(indexingStatusDetail) && (
{`${getSourcePercent(indexingStatusDetail)}%`}
diff --git a/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsx index 44daa66f682..9fb3775372a 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsx @@ -254,6 +254,7 @@ describe('StepOneContent', () => { datasourceType: DatasourceType.localFile, pipelineNodes: mockPipelineNodes, supportBatchUpload: true, + showBatchUploadUpgrade: false, isShowVectorSpaceFull: false, isShowVectorSpaceUnavailable: false, isRetryingVectorSpace: false, @@ -346,7 +347,20 @@ describe('StepOneContent', () => { }) describe('Conditional Rendering - UpgradeCard', () => { - it('should render UpgradeCard immediately when batch upload is not supported', () => { + it('should render UpgradeCard for a Sandbox local file source', () => { + render( + , + ) + // UpgradeCard contains an upgrade button + expect(screen.getByTestId('upgrade-btn')).toBeInTheDocument() + }) + + it('does not infer an upgrade requirement from unavailable batch upload', () => { render( { datasourceType={DatasourceType.localFile} />, ) - // UpgradeCard contains an upgrade button - expect(screen.getByTestId('upgrade-btn')).toBeInTheDocument() + expect(screen.queryByTestId('upgrade-btn')).not.toBeInTheDocument() }) it('should not render UpgradeCard when batch upload is supported', () => { diff --git a/web/app/components/datasets/documents/create-from-pipeline/steps/step-one-content.tsx b/web/app/components/datasets/documents/create-from-pipeline/steps/step-one-content.tsx index 440c8a33b7d..13cbd1c6e67 100644 --- a/web/app/components/datasets/documents/create-from-pipeline/steps/step-one-content.tsx +++ b/web/app/components/datasets/documents/create-from-pipeline/steps/step-one-content.tsx @@ -20,6 +20,7 @@ type StepOneContentProps = { datasourceType: string | undefined pipelineNodes: Node[] supportBatchUpload: boolean + showBatchUploadUpgrade: boolean isShowVectorSpaceFull: boolean isShowVectorSpaceUnavailable: boolean isRetryingVectorSpace: boolean @@ -40,6 +41,7 @@ const StepOneContent = ({ datasourceType, pipelineNodes, supportBatchUpload, + showBatchUploadUpgrade, isShowVectorSpaceFull, isShowVectorSpaceUnavailable, isRetryingVectorSpace, @@ -54,7 +56,7 @@ const StepOneContent = ({ onRetryVectorSpace, onNextStep, }: StepOneContentProps) => { - const showUpgradeCard = !supportBatchUpload && datasourceType === DatasourceType.localFile + const showUpgradeCard = showBatchUploadUpgrade && datasourceType === DatasourceType.localFile return (
diff --git a/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsx index b7b2db0d237..da69780ae22 100644 --- a/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsx +++ b/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsx @@ -1,26 +1,28 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' +import type { ReactElement } from 'react' import type { SegmentImportStatus } from '@/types/dataset' import { fireEvent, screen } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' -import { renderWithConsoleQuery as render } from '@/test/console/query-data' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { segmentImportStatus } from '@/types/dataset' import { SegmentAdd } from '../index' // Mock provider context let mockPlan: { type: CloudPlan } = { type: 'professional' } -let mockEnableBilling = true -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - plan: mockPlan, - enableBilling: mockEnableBilling, - }), -})) +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'CLOUD' + +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: deploymentEdition }, + features: { billing: { subscription: { plan: mockPlan.type } } }, + }) +} describe('SegmentAdd', () => { beforeEach(() => { vi.clearAllMocks() mockPlan = { type: 'professional' } - mockEnableBilling = true + deploymentEdition = 'CLOUD' }) const defaultProps = { @@ -192,7 +194,7 @@ describe('SegmentAdd', () => { it('should allow add when billing is disabled regardless of plan', () => { mockPlan = { type: 'sandbox' } - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' const mockShowNewSegmentModal = vi.fn() render() diff --git a/web/app/components/datasets/documents/detail/segment-add/index.tsx b/web/app/components/datasets/documents/detail/segment-add/index.tsx index 81c6fb4fb84..b69a13adc91 100644 --- a/web/app/components/datasets/documents/detail/segment-add/index.tsx +++ b/web/app/components/datasets/documents/detail/segment-add/index.tsx @@ -7,10 +7,13 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from '@langgenius/dify-ui/dropdown-menu' +import { useQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import { useState } from 'react' import { useTranslation } from 'react-i18next' import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' +import { consoleQuery } from '@/service/console' import { segmentImportStatus } from '@/types/dataset' type SegmentAddProps = { @@ -30,15 +33,22 @@ export function SegmentAdd({ }: SegmentAddProps) { const { t } = useTranslation() const [isPlanUpgradeModalOpen, setIsPlanUpgradeModalOpen] = useState(false) - const { plan, enableBilling } = useProviderContext() - const canAddChunks = !enableBilling || plan.type !== 'sandbox' + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.billing.subscription.plan, + }), + ) + const isPlanUnavailable = deploymentEdition === 'CLOUD' && plan === undefined const textColor = embedding ? 'text-components-button-secondary-accent-text-disabled' : 'text-components-button-secondary-accent-text' const openSegmentDialog = (openDialog: () => void) => { - if (!canAddChunks) { + if (isPlanUnavailable) return + if (deploymentEdition === 'CLOUD' && plan === 'sandbox') { setIsPlanUpgradeModalOpen(true) return } @@ -123,7 +133,7 @@ export function SegmentAdd({ type="button" className={`inline-flex items-center rounded-l-lg border-0 border-r border-r-divider-subtle bg-transparent px-2.5 py-2 text-left hover:bg-state-base-hover disabled:cursor-not-allowed disabled:hover:bg-transparent`} onClick={() => openSegmentDialog(showNewSegmentModal)} - disabled={embedding} + disabled={embedding || isPlanUnavailable} > $['list.action.batchAdd'], { ns: 'datasetDocuments' })} - disabled={embedding} + disabled={embedding || isPlanUnavailable} className={cn( `rounded-l-none rounded-r-lg border-0 bg-transparent p-2 backdrop-blur-[5px] hover:bg-state-base-hover disabled:cursor-not-allowed disabled:bg-transparent disabled:hover:bg-transparent data-popup-open:bg-state-base-hover`, )} diff --git a/web/app/components/datasets/documents/index.tsx b/web/app/components/datasets/documents/index.tsx index 44b9660aa1a..e05cfbd2414 100644 --- a/web/app/components/datasets/documents/index.tsx +++ b/web/app/components/datasets/documents/index.tsx @@ -7,7 +7,6 @@ import { useCallback } from 'react' import Loading from '@/app/components/base/loading' import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail' import { workspacePermissionKeysAtom } from '@/context/permission-state' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' import { DataSourceType } from '@/models/datasets' import { useRouter } from '@/next/navigation' @@ -35,8 +34,6 @@ const FORCED_POLLING_STATUSES = new Set(['queuing', 'indexing', 'paused']) const Documents: FC = ({ datasetId }) => { const router = useRouter() - const { plan } = useProviderContext() - const isFreePlan = plan.type === 'sandbox' const dataset = useDatasetDetailContextWithSelector((s) => s.dataset) const { data: currentUserId } = useSuspenseQuery({ @@ -185,7 +182,6 @@ const Documents: FC = ({ datasetId }) => { canManageMetadata={datasetACLCapabilities.canEdit} canAddDocument={datasetACLCapabilities.canUse} canEditDocument={datasetACLCapabilities.canEdit} - isFreePlan={isFreePlan} statusFilterValue={statusFilterValue} sortValue={sortValue} inputValue={inputValue} diff --git a/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsx b/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsx index dcced4455ca..cc09fb8be7d 100644 --- a/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsx +++ b/web/app/components/datasets/external-api/external-api-panel/__tests__/index.spec.tsx @@ -31,7 +31,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { datasets: { externalKnowledgeApi: { diff --git a/web/app/components/datasets/external-api/external-api-panel/index.tsx b/web/app/components/datasets/external-api/external-api-panel/index.tsx index f344dd08520..7783db3e458 100644 --- a/web/app/components/datasets/external-api/external-api-panel/index.tsx +++ b/web/app/components/datasets/external-api/external-api-panel/index.tsx @@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next' import Loading from '@/app/components/base/loading' import { useDocLink } from '@/context/i18n' import { useModalContext } from '@/context/modal-context' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import ExternalKnowledgeAPICard from '../external-knowledge-api-card' type ExternalAPIPanelProps = { diff --git a/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsx b/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsx index 6826448df8d..5e989cf31ce 100644 --- a/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsx +++ b/web/app/components/datasets/external-api/external-knowledge-api-card/__tests__/index.spec.tsx @@ -38,7 +38,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { datasets: { externalKnowledgeApi: { diff --git a/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsx b/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsx index 10cf7ea15fb..56ed1f085f4 100644 --- a/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsx +++ b/web/app/components/datasets/external-api/external-knowledge-api-card/index.tsx @@ -15,7 +15,7 @@ import * as React from 'react' import { useState } from 'react' import { useTranslation } from 'react-i18next' import { useModalContext } from '@/context/modal-context' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { checkUsageExternalAPI, deleteExternalAPI, diff --git a/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx b/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx index 2fe6bfdb624..972214965cc 100644 --- a/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx +++ b/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx @@ -92,7 +92,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { datasets: { externalKnowledgeApi: { diff --git a/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelect.tsx b/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelect.tsx index 251d5ce1ad8..9b709615317 100644 --- a/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelect.tsx +++ b/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelect.tsx @@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next' import { ApiConnectionMod } from '@/app/components/base/icons/src/vender/solid/development' import { useModalContext } from '@/context/modal-context' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' type ApiItem = { value: string diff --git a/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelection.tsx b/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelection.tsx index bf404ac2b30..438550799b2 100644 --- a/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelection.tsx +++ b/web/app/components/datasets/external-knowledge-base/create/ExternalApiSelection.tsx @@ -9,7 +9,7 @@ import { useEffect, useId, useState } from 'react' import { useTranslation } from 'react-i18next' import { useModalContext } from '@/context/modal-context' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import ExternalApiSelect from './ExternalApiSelect' type ExternalApiSelectionProps = { diff --git a/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelect.spec.tsx b/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelect.spec.tsx index 74e27ff89bf..ef776f5d1a7 100644 --- a/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelect.spec.tsx +++ b/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelect.spec.tsx @@ -32,7 +32,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { datasets: { externalKnowledgeApi: { diff --git a/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelection.spec.tsx b/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelection.spec.tsx index f59765cb4fb..96231733e65 100644 --- a/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelection.spec.tsx +++ b/web/app/components/datasets/external-knowledge-base/create/__tests__/ExternalApiSelection.spec.tsx @@ -35,7 +35,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { datasets: { externalKnowledgeApi: { diff --git a/web/app/components/datasets/external-knowledge-base/create/__tests__/index.spec.tsx b/web/app/components/datasets/external-knowledge-base/create/__tests__/index.spec.tsx index d8a210d0796..7e2cdfafaeb 100644 --- a/web/app/components/datasets/external-knowledge-base/create/__tests__/index.spec.tsx +++ b/web/app/components/datasets/external-knowledge-base/create/__tests__/index.spec.tsx @@ -80,7 +80,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { datasets: { externalKnowledgeApi: { diff --git a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx index 4120370fc93..038a3d386d7 100644 --- a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx +++ b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx @@ -1,3 +1,5 @@ +import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import type { ReactNode } from 'react' import type { DataSet, HitTesting, HitTestingRecord, HitTestingResponse } from '@/models/datasets' import type { RetrievalConfig } from '@/types/app' @@ -154,11 +156,11 @@ vi.mock('@/service/knowledge/use-dataset', () => ({ vi.mock('@/service/knowledge/use-hit-testing', () => ({ useHitTesting: vi.fn(() => ({ mutateAsync: mockHitTestingMutateAsync, - isPending: false, + isLoading: false, })), useExternalKnowledgeBaseHitTesting: vi.fn(() => ({ mutateAsync: mockExternalHitTestingMutateAsync, - isPending: false, + isLoading: false, })), })) @@ -263,10 +265,6 @@ vi.mock('@/context/i18n', () => ({ // Mock model list hook - include all exports used by child components vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ - useModelList: vi.fn(() => ({ - data: [], - isLoading: false, - })), useModelListAndDefaultModelAndCurrentProviderAndModel: vi.fn(() => ({ modelList: [], defaultModel: undefined, @@ -400,11 +398,11 @@ describe('HitTestingPage', () => { await import('@/service/knowledge/use-hit-testing') vi.mocked(useHitTesting).mockReturnValue({ mutateAsync: mockHitTestingMutateAsync, - isPending: false, + isLoading: false, } as unknown as ReturnType) vi.mocked(useExternalKnowledgeBaseHitTesting).mockReturnValue({ mutateAsync: mockExternalHitTestingMutateAsync, - isPending: false, + isLoading: false, } as unknown as ReturnType) const useBreakpoints = await import('@/hooks/use-breakpoints') @@ -578,3 +576,19 @@ describe('HitTestingPage', () => { expect(await screen.findByText('External content')).toBeInTheDocument() }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => + options.queryKey[0].includes('modelTypes') + ? { data: [], isPending: false } + : actual.useQuery(options), + } +}) diff --git a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx index e2e1a6739fd..4a9582db78b 100644 --- a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx +++ b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx @@ -1,3 +1,5 @@ +import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import type { RetrievalConfig } from '@/types/app' import { fireEvent, screen } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' @@ -50,10 +52,6 @@ vi.mock('@/app/components/datasets/common/economical-retrieval-method-config', ( default: () =>
, })) -vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ - useModelList: () => ({ data: [] }), -})) - vi.mock('@/context/dataset-detail', () => ({ useDatasetDetailContextWithSelector: () => 'model-name', })) @@ -125,3 +123,19 @@ describe('ModifyRetrievalModal', () => { expect(screen.getByText('datasetSettings.form.retrievalSetting.learnMore')).toBeInTheDocument() }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + return { data: [] } + }, + } +}) diff --git a/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx b/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx index ce8d887defc..dce7f4d080e 100644 --- a/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx +++ b/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx @@ -5,15 +5,16 @@ import type { RetrievalConfig } from '@/types/app' import { Button } from '@langgenius/dify-ui/button' import { toast } from '@langgenius/dify-ui/toast' import { RiCloseLine } from '@remixicon/react' +import { useQuery } from '@tanstack/react-query' import * as React from 'react' import { useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model' import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/economical-retrieval-method-config' import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config' -import { useModelList } from '@/app/components/header/account-setting/model-provider-page/hooks' import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail' import { useDocLink } from '@/context/i18n' +import { consoleQuery } from '@/service/console' import { ModelTypeEnum } from '../../header/account-setting/model-provider-page/declarations' import { checkShowMultiModalTip } from '../settings/utils' @@ -39,8 +40,18 @@ const ModifyRetrievalModal: FC = ({ indexMethod, value, isShow, onHide, o // if (ref) // onHide() // }, ref) - const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding) - const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank) + const { data: embeddingModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textEmbedding } }, + select: (response) => response.data, + }), + ) + const { data: rerankModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.rerank } }, + select: (response) => response.data, + }), + ) const handleSave = () => { if ( !isReRankModelSelected({ diff --git a/web/app/components/datasets/list/__tests__/datasets.spec.tsx b/web/app/components/datasets/list/__tests__/datasets.spec.tsx index c039b886710..8e282b8ecc6 100644 --- a/web/app/components/datasets/list/__tests__/datasets.spec.tsx +++ b/web/app/components/datasets/list/__tests__/datasets.spec.tsx @@ -299,33 +299,22 @@ describe('Datasets', () => { expect(screen.queryByRole('status', { name: /common\.loading/ })).not.toBeInTheDocument() expect(screen.getByText('Dataset 1')).toBeInTheDocument() }) - - it('should show Loading component when isFetchingNextPage is true', () => { - render() - expect(screen.getByRole('navigation')).toBeInTheDocument() - }) - - it('should NOT show Loading component when isFetchingNextPage is false', () => { - render() - expect(screen.getByRole('navigation')).toBeInTheDocument() - }) }) describe('DatasetList null handling', () => { - it('should handle null datasetList gracefully', () => { - render() - expect(screen.getByRole('navigation')).toBeInTheDocument() - }) - - it('should handle undefined datasetList gracefully', () => { - render() - expect(screen.getByRole('navigation')).toBeInTheDocument() - }) - - it('should handle empty pages array', () => { - render() - expect(screen.getByRole('navigation')).toBeInTheDocument() - }) + it.each([null, undefined, createDatasetListData([])])( + 'shows the empty state when dataset data is unavailable or empty (%j)', + (datasetList) => { + render( + No knowledge bases

} + />, + ) + expect(screen.getByText('No knowledge bases')).toBeInTheDocument() + }, + ) }) describe('IntersectionObserver', () => { @@ -409,20 +398,18 @@ describe('Datasets', () => { }) }) - describe('Styles', () => { - it('should have correct grid styling', () => { - render() - const nav = screen.getByRole('navigation') - expect(nav).toHaveClass( - 'relative', - 'grid', - 'grow', - 'grid-cols-[repeat(auto-fill,minmax(296px,1fr))]', - 'content-start', - 'gap-3', - 'px-8', - 'pt-2', + describe('Landmarks', () => { + it('keeps knowledge cards in the page content without creating another navigation landmark', () => { + render( + , ) + expect(screen.getByText('Dataset 1')).toBeInTheDocument() + expect(screen.queryByRole('navigation')).not.toBeInTheDocument() }) }) diff --git a/web/app/components/datasets/list/__tests__/index.spec.tsx b/web/app/components/datasets/list/__tests__/index.spec.tsx index 6505d8b04f5..1751a5aa107 100644 --- a/web/app/components/datasets/list/__tests__/index.spec.tsx +++ b/web/app/components/datasets/list/__tests__/index.spec.tsx @@ -36,8 +36,8 @@ vi.mock('@tanstack/react-query', async (importOriginal) => { } }) -vi.mock('@/service/client', async (importOriginal) => { - const original = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const original = await importOriginal() return { ...original, consoleQuery: { @@ -71,7 +71,6 @@ function NewKnowledgeGuideDismissedProbe() { const mockPush = vi.fn() const mockReplace = vi.fn() let mockConsoleState = { - isCurrentWorkspaceEditor: true, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: true, knowledgeFsEnabled: false, @@ -247,7 +246,6 @@ describe('List', () => { vi.clearAllMocks() localStorage.clear() mockConsoleState = { - isCurrentWorkspaceEditor: true, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: true, knowledgeFsEnabled: false, @@ -428,7 +426,6 @@ describe('List', () => { it('should hide external API panel button without dataset.external.connect', () => { mockConsoleState = { - isCurrentWorkspaceEditor: true, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: true, knowledgeFsEnabled: false, @@ -539,9 +536,8 @@ describe('List', () => { expect(screen.queryByTestId('datasets-component')).not.toBeInTheDocument() }) - it('should render first empty state when dataset.create_and_management is available without the legacy editor role', async () => { + it('should render first empty state when dataset.create_and_management is available', async () => { mockConsoleState = { - isCurrentWorkspaceEditor: false, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: true, knowledgeFsEnabled: false, @@ -566,7 +562,6 @@ describe('List', () => { it('should render a permission empty state without dataset creation permissions', async () => { mockConsoleState = { - isCurrentWorkspaceEditor: true, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: true, knowledgeFsEnabled: false, @@ -676,7 +671,6 @@ describe('List', () => { it('should not show include all checkbox when not workspace owner', async () => { mockConsoleState = { - isCurrentWorkspaceEditor: true, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: false, knowledgeFsEnabled: false, diff --git a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts index a8bb5fb22ca..a2431ef9931 100644 --- a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts +++ b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts @@ -4,7 +4,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query' import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import { useRouter } from '@/next/navigation' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useExportPipelineDSL } from '@/service/use-pipeline' import { downloadBlob } from '@/utils/download' diff --git a/web/app/components/datasets/list/datasets.tsx b/web/app/components/datasets/list/datasets.tsx index 28c7fbee3c9..fbf6ea88c33 100644 --- a/web/app/components/datasets/list/datasets.tsx +++ b/web/app/components/datasets/list/datasets.tsx @@ -69,7 +69,7 @@ const Datasets = ({ return ( <> - +
) } diff --git a/web/app/components/datasets/settings/__tests__/summary-index-setting.spec.tsx b/web/app/components/datasets/settings/__tests__/summary-index-setting.spec.tsx index 9308feaae7b..93e5390507f 100644 --- a/web/app/components/datasets/settings/__tests__/summary-index-setting.spec.tsx +++ b/web/app/components/datasets/settings/__tests__/summary-index-setting.spec.tsx @@ -1,21 +1,10 @@ +import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import { fireEvent, render, screen } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' import SummaryIndexSetting from '../summary-index-setting' -// Mock useModelList to return a list of text generation models -vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ - useModelList: () => ({ - data: [ - { - provider: 'openai', - label: { en_US: 'OpenAI' }, - models: [ - { model: 'gpt-4', label: { en_US: 'GPT-4' }, model_type: 'llm', status: 'active' }, - ], - }, - ], - }), -})) +// Mock the model list query. // Mock ModelSelector (external component from header module) vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({ @@ -222,3 +211,30 @@ describe('SummaryIndexSetting', () => { }) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + return { + data: [ + { + tenant_id: 'test-workspace', + provider: 'openai', + label: { en_US: 'OpenAI' }, + models: [ + { model: 'gpt-4', label: { en_US: 'GPT-4' }, model_type: 'llm', status: 'active' }, + ], + }, + ], + } + }, + } +}) diff --git a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx b/web/app/components/datasets/settings/form/__tests__/index.spec.tsx index 345b3c595e0..461e1eb7255 100644 --- a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx +++ b/web/app/components/datasets/settings/form/__tests__/index.spec.tsx @@ -1,3 +1,5 @@ +import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import type { ReactElement } from 'react' import type { DataSet } from '@/models/datasets' import type { RetrievalConfig } from '@/types/app' @@ -45,7 +47,7 @@ vi.mock('@/context/permission-state', async () => { })) }) -const render = (ui: ReactElement) => { +function render(ui: ReactElement) { const { wrapper } = createConsoleQueryWrapper({ systemFeatures: { rbac_enabled: false }, }) @@ -177,7 +179,6 @@ vi.mock('@/service/use-common', () => ({ })) vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ - useModelList: () => ({ data: [], mutate: vi.fn(), isLoading: false }), useCurrentProviderAndModel: () => ({ currentProvider: undefined, currentModel: undefined }), useDefaultModel: () => ({ data: undefined, mutate: vi.fn(), isLoading: false }), useModelListAndDefaultModel: () => ({ modelList: [], defaultModel: undefined }), @@ -203,25 +204,6 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () useModelModalHandler: () => vi.fn(), })) -// Mock provider-context -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - textGenerationModelList: [], - embeddingsModelList: [], - rerankModelList: [], - agentThoughtModelList: [], - modelProviders: [], - textEmbeddingModelList: [], - speech2textModelList: [], - ttsModelList: [], - moderationModelList: [], - hasSettedApiKey: true, - plan: { type: 'free' }, - enableBilling: false, - onPlanInfoChanged: vi.fn(), - }), -})) - vi.mock('@/app/components/datasets/common/check-rerank-model', () => ({ isReRankModelSelected: () => true, })) @@ -563,3 +545,19 @@ describe('Form', () => { }) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + return { data: [], refetch: vi.fn(), isPending: false } + }, + } +}) diff --git a/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx b/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx index 04349eea7a0..6fa5f83e660 100644 --- a/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx +++ b/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx @@ -1,7 +1,5 @@ -import type { - DefaultModel, - Model, -} from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' +import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { DataSet, SummaryIndexSetting } from '@/models/datasets' import type { RetrievalConfig } from '@/types/app' import { fireEvent, screen } from '@testing-library/react' @@ -222,8 +220,9 @@ describe('IndexingSection', () => { model: 'text-embedding-ada-002', } - const mockEmbeddingModelList: Model[] = [ + const mockEmbeddingModelList: ProviderWithModelsResponse[] = [ { + tenant_id: 'test-workspace', provider: 'openai', label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, icon_small: { en_US: '', zh_Hans: '' }, diff --git a/web/app/components/datasets/settings/form/components/indexing-section.tsx b/web/app/components/datasets/settings/form/components/indexing-section.tsx index ae18d021ec6..7257e391d55 100644 --- a/web/app/components/datasets/settings/form/components/indexing-section.tsx +++ b/web/app/components/datasets/settings/form/components/indexing-section.tsx @@ -1,8 +1,6 @@ 'use client' -import type { - DefaultModel, - Model, -} from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' +import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { DataSet, SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets' import type { RetrievalConfig } from '@/types/app' import { useSuspenseQuery } from '@tanstack/react-query' @@ -34,7 +32,7 @@ type IndexingSectionProps = { setKeywordNumber: (value: number) => void embeddingModel: DefaultModel setEmbeddingModel: (value: DefaultModel) => void - embeddingModelList: Model[] + embeddingModelList: ProviderWithModelsResponse[] retrievalConfig: RetrievalConfig setRetrievalConfig: (value: RetrievalConfig) => void summaryIndexSetting: SummaryIndexSettingType | undefined @@ -150,7 +148,7 @@ const IndexingSection = ({
)} - {/* Embedding Model */} + {/* Embedding ProviderWithModelsResponse */} {indexMethod === IndexingType.QUALIFIED && (
diff --git a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts index 814074e6f7c..736e8ec15d9 100644 --- a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts +++ b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts @@ -1,3 +1,5 @@ +import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import type { DataSet } from '@/models/datasets' import type { RetrievalConfig } from '@/types/app' import { act, waitFor } from '@testing-library/react' @@ -176,10 +178,6 @@ vi.mock('@/service/use-common', () => ({ }), })) -vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ - useModelList: () => ({ data: [] }), -})) - vi.mock('@/app/components/datasets/common/check-rerank-model', () => ({ isReRankModelSelected: () => true, })) @@ -835,3 +833,19 @@ describe('useFormState', () => { }) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + return { data: [] } + }, + } +}) diff --git a/web/app/components/datasets/settings/form/hooks/use-form-state.ts b/web/app/components/datasets/settings/form/hooks/use-form-state.ts index b02939980d9..3fa3ac4ca36 100644 --- a/web/app/components/datasets/settings/form/hooks/use-form-state.ts +++ b/web/app/components/datasets/settings/form/hooks/use-form-state.ts @@ -1,22 +1,21 @@ 'use client' - import type { AppIconSelection } from '@/app/components/base/app-icon-picker' import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { Member } from '@/models/common' import type { IconInfo, SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets' import type { RetrievalConfig } from '@/types/app' import { toast } from '@langgenius/dify-ui/toast' -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useAtomValue } from 'jotai' import { useCallback, useMemo, useState } from 'react' import { useTranslation } from 'react-i18next' import { isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model' import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' -import { useModelList } from '@/app/components/header/account-setting/model-provider-page/hooks' import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail' import { workspacePermissionKeysAtom } from '@/context/permission-state' import { userProfileQueryOptions } from '@/features/account-profile/client' import { DatasetPermission } from '@/models/datasets' +import { consoleQuery } from '@/service/console' import { updateDatasetSetting } from '@/service/datasets' import { useInvalidDatasetList } from '@/service/knowledge/use-dataset' import { useMembers } from '@/service/use-common' @@ -103,8 +102,18 @@ export const useFormState = () => { ) // Model lists - const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank) - const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding) + const { data: rerankModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.rerank } }, + select: (response) => response.data, + }), + ) + const { data: embeddingModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textEmbedding } }, + select: (response) => response.data, + }), + ) const { data: membersData } = useMembers() const invalidDatasetList = useInvalidDatasetList() diff --git a/web/app/components/datasets/settings/summary-index-setting.tsx b/web/app/components/datasets/settings/summary-index-setting.tsx index 8c524d4a697..d4cbe51e9d8 100644 --- a/web/app/components/datasets/settings/summary-index-setting.tsx +++ b/web/app/components/datasets/settings/summary-index-setting.tsx @@ -2,12 +2,13 @@ import type { DefaultModel } from '@/app/components/header/account-setting/model import type { SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets' import { Switch } from '@langgenius/dify-ui/switch' import { Textarea } from '@langgenius/dify-ui/textarea' +import { useQuery } from '@tanstack/react-query' import { memo, useCallback, useMemo } from 'react' import { useTranslation } from 'react-i18next' import { Infotip } from '@/app/components/base/infotip' import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' -import { useModelList } from '@/app/components/header/account-setting/model-provider-page/hooks' import { ModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector' +import { consoleQuery } from '@/service/console' type SummaryIndexSettingProps = { entry?: 'knowledge-base' | 'dataset-settings' | 'create-document' @@ -22,7 +23,12 @@ const SummaryIndexSetting = ({ readonly = false, }: SummaryIndexSettingProps) => { const { t } = useTranslation() - const { data: textGenerationModelList } = useModelList(ModelTypeEnum.textGeneration) + const { data: textGenerationModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) const summaryIndexModelConfig = useMemo(() => { if (!summaryIndexSetting?.model_name || !summaryIndexSetting?.model_provider_name) return undefined diff --git a/web/app/components/datasets/settings/utils/__tests__/index.spec.ts b/web/app/components/datasets/settings/utils/__tests__/index.spec.ts index 808816a02ac..e7a327bb785 100644 --- a/web/app/components/datasets/settings/utils/__tests__/index.spec.ts +++ b/web/app/components/datasets/settings/utils/__tests__/index.spec.ts @@ -1,8 +1,8 @@ import type { - DefaultModel, - Model, - ModelItem, -} from '@/app/components/header/account-setting/model-provider-page/declarations' + ProviderModelWithStatusEntity, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' +import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import { ConfigurationMethodEnum, ModelFeatureEnum, @@ -14,7 +14,10 @@ import { checkShowMultiModalTip } from '../index' describe('checkShowMultiModalTip', () => { // Helper to create a model item with specific features - const createModelItem = (model: string, features: ModelFeatureEnum[] = []): ModelItem => ({ + const createModelItem = ( + model: string, + features: ModelFeatureEnum[] = [], + ): ProviderModelWithStatusEntity => ({ model, label: { en_US: model, zh_Hans: model }, model_type: ModelTypeEnum.textEmbedding, @@ -27,7 +30,11 @@ describe('checkShowMultiModalTip', () => { }) // Helper to create a model provider - const createModelProvider = (provider: string, models: ModelItem[]): Model => ({ + const createModelProvider = ( + provider: string, + models: ProviderModelWithStatusEntity[], + ): ProviderWithModelsResponse => ({ + tenant_id: 'test-workspace', provider, label: { en_US: provider, zh_Hans: provider }, icon_small: { en_US: '', zh_Hans: '' }, @@ -223,7 +230,7 @@ describe('checkShowMultiModalTip', () => { }) it('should handle model with undefined features', () => { - const modelItem: ModelItem = { + const modelItem: ProviderModelWithStatusEntity = { model: 'test-model', label: { en_US: 'test', zh_Hans: 'test' }, model_type: ModelTypeEnum.textEmbedding, @@ -243,7 +250,7 @@ describe('checkShowMultiModalTip', () => { }) it('should handle model with null features', () => { - const modelItem: ModelItem = { + const modelItem: ProviderModelWithStatusEntity = { model: 'text-embedding-ada-002', label: { en_US: 'test', zh_Hans: 'test' }, model_type: ModelTypeEnum.textEmbedding, diff --git a/web/app/components/datasets/settings/utils/index.tsx b/web/app/components/datasets/settings/utils/index.tsx index beb07e38e2c..be3ced811ae 100644 --- a/web/app/components/datasets/settings/utils/index.tsx +++ b/web/app/components/datasets/settings/utils/index.tsx @@ -1,7 +1,5 @@ -import type { - DefaultModel, - Model, -} from '@/app/components/header/account-setting/model-provider-page/declarations' +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' +import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations' import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations' import { IndexingType } from '../../create/step-two' @@ -13,8 +11,8 @@ type ShowMultiModalTipProps = { rerankingModelName: string } indexMethod: IndexingType | undefined - embeddingModelList: Model[] - rerankModelList: Model[] + embeddingModelList: ProviderWithModelsResponse[] + rerankModelList: ProviderWithModelsResponse[] } export const checkShowMultiModalTip = ({ diff --git a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx index 6c94b14ae0f..6702fc20cf3 100644 --- a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx +++ b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx @@ -1,14 +1,10 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' +import type { ReactElement } from 'react' import type { CreateAppModalProps } from '../index' -import type { UsagePlanInfo } from '@/app/components/billing/type' import { act, fireEvent, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' import * as React from 'react' -import { - createMockPlan, - createMockPlanTotal, - createMockPlanUsage, -} from '@/__mocks__/provider-context' -import { renderWithConsoleQuery as render } from '@/test/console/query-data' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { AppModeEnum } from '@/types/app' import CreateAppModal from '../index' @@ -46,29 +42,10 @@ vi.mock('@/next/navigation', () => ({ useParams: () => ({}), })) -const createPlanInfo = (buildApps: number): UsagePlanInfo => ({ - vectorSpace: 0, - buildApps, - teamMembers: 0, - annotatedResponse: 0, - documentsUploadQuota: 0, - apiRateLimit: 0, - triggerEvents: 0, -}) - -let mockEnableBilling = false +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' let mockPlanType: CloudPlan = 'team' -let mockUsagePlanInfo: UsagePlanInfo = createPlanInfo(1) -let mockTotalPlanInfo: UsagePlanInfo = createPlanInfo(10) - -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => { - const withPlan = createMockPlan(mockPlanType) - const withUsage = createMockPlanUsage(mockUsagePlanInfo, withPlan) - const withTotal = createMockPlanTotal(mockTotalPlanInfo, withUsage) - return { ...withTotal, enableBilling: mockEnableBilling } - }, -})) +let mockAppCount = 1 +const mockAppLimit = 10 type ConfirmPayload = Parameters[0] @@ -114,13 +91,22 @@ const openAppIconPicker = () => { return screen.getByRole('dialog', { name: 'app.iconPicker.emoji' }) } +function render(ui: ReactElement) { + return renderWithConsoleQuery(ui, { + systemFeatures: { deployment_edition: deploymentEdition }, + features: { + billing: { subscription: { plan: mockPlanType } }, + apps: { size: mockAppCount, limit: mockAppLimit }, + }, + }) +} + describe('CreateAppModal', () => { beforeEach(() => { vi.clearAllMocks() - mockEnableBilling = false + deploymentEdition = 'COMMUNITY' mockPlanType = 'team' - mockUsagePlanInfo = createPlanInfo(1) - mockTotalPlanInfo = createPlanInfo(10) + mockAppCount = 1 hotkeyMocks.handlers.clear() }) @@ -222,10 +208,9 @@ describe('CreateAppModal', () => { describe('Quota Gating', () => { it('should show AppsFull and disable create when apps quota is reached', async () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'team' - mockUsagePlanInfo = createPlanInfo(10) - mockTotalPlanInfo = createPlanInfo(10) + mockAppCount = 10 await setup({ isEditModal: false }) @@ -234,10 +219,9 @@ describe('CreateAppModal', () => { }) it('should allow saving when apps quota is reached in edit mode', async () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'team' - mockUsagePlanInfo = createPlanInfo(10) - mockTotalPlanInfo = createPlanInfo(10) + mockAppCount = 10 await setup({ isEditModal: true }) @@ -280,10 +264,9 @@ describe('CreateAppModal', () => { }) it('should not submit when apps quota is reached in create mode', async () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'team' - mockUsagePlanInfo = createPlanInfo(10) - mockTotalPlanInfo = createPlanInfo(10) + mockAppCount = 10 const { onConfirm, onHide } = await setup({ isEditModal: false }) @@ -297,10 +280,9 @@ describe('CreateAppModal', () => { }) it('should submit when apps quota is reached in edit mode', async () => { - mockEnableBilling = true + deploymentEdition = 'CLOUD' mockPlanType = 'team' - mockUsagePlanInfo = createPlanInfo(10) - mockTotalPlanInfo = createPlanInfo(10) + mockAppCount = 10 const { onConfirm, onHide } = await setup({ isEditModal: true }) @@ -555,3 +537,24 @@ describe('CreateAppModal', () => { }) }) }) + +it('edits an existing app without waiting for application quota data', async () => { + const onConfirm = vi.fn() + renderWithConsoleQuery( + , + { systemFeatures: { deployment_edition: 'CLOUD' } }, + ) + const save = screen.getByRole('button', { name: /operation.save/ }) + expect(save).toBeEnabled() + await userEvent.setup().click(save) + await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce()) +}) diff --git a/web/app/components/explore/create-app-modal/index.tsx b/web/app/components/explore/create-app-modal/index.tsx index e0c30bdeb68..d22ba097ec4 100644 --- a/web/app/components/explore/create-app-modal/index.tsx +++ b/web/app/components/explore/create-app-modal/index.tsx @@ -10,13 +10,16 @@ import { Switch } from '@langgenius/dify-ui/switch' import { Textarea } from '@langgenius/dify-ui/textarea' import { toast } from '@langgenius/dify-ui/toast' import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys' +import { useQuery } from '@tanstack/react-query' import { useDebounceFn } from 'ahooks' +import { useAtomValue } from 'jotai' import * as React from 'react' import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import AppIcon from '@/app/components/base/app-icon' import AppsFull from '@/app/components/billing/apps-full-in-dialog' -import { useProviderContext } from '@/context/provider-context' +import { deploymentEditionAtom } from '@/features/system-features/state' +import { consoleQuery } from '@/service/console' import { AppModeEnum } from '@/types/app' import AppIconPicker from '../../base/app-icon-picker' @@ -86,10 +89,24 @@ const CreateAppModal = ({ : '', ) - const { plan, enableBilling } = useProviderContext() - const isAppsFull = enableBilling && plan.usage.buildApps >= plan.total.buildApps + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: appQuota } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD' && !isEditModal, + select: (data) => data.apps, + }), + ) + const isAppQuotaUnavailable = + deploymentEdition === 'CLOUD' && !isEditModal && appQuota === undefined + // A limit of 0 means unlimited. + const isAppsFull = + deploymentEdition === 'CLOUD' && + appQuota !== undefined && + appQuota.limit > 0 && + appQuota.size >= appQuota.limit const submit = useCallback(() => { + if (!isEditModal && (isAppQuotaUnavailable || isAppsFull)) return if (!name.trim()) { toast( t(($) => $['appCustomize.nameRequired'], { ns: 'explore' }), @@ -112,6 +129,9 @@ const CreateAppModal = ({ onConfirm(payload) onHide() }, [ + isEditModal, + isAppQuotaUnavailable, + isAppsFull, name, appIcon, description, @@ -130,7 +150,7 @@ const CreateAppModal = ({ handleSubmit() }, { - enabled: show && !(!isEditModal && isAppsFull) && !!name.trim(), + enabled: show && !isAppQuotaUnavailable && !(!isEditModal && isAppsFull) && !!name.trim(), ignoreInputs: false, }, ) @@ -254,7 +274,12 @@ const CreateAppModal = ({
)} />, - { queryClient }, + { queryClient, features: { education: { enabled: false } } }, ) } @@ -79,9 +73,6 @@ describe('AccountDropdown', () => { beforeEach(() => { vi.clearAllMocks() mockUseRouter.mockReturnValue({ push: mockPush }) - vi.mocked(useProviderContext).mockReturnValue({ - enableEducationPlan: false, - } as ProviderContextState) vi.mocked(useLogout).mockReturnValue({ mutateAsync: mockLogout, } as unknown as ReturnType) @@ -90,7 +81,10 @@ describe('AccountDropdown', () => { it('includes the visible account name in the main navigation trigger accessible name', () => { const queryClient = createAccountProfileQueryClient(userProfile) - renderWithConsoleQuery(, { queryClient }) + renderWithConsoleQuery(, { + queryClient, + features: { education: { enabled: false } }, + }) expect(screen.getByRole('button', { name: accountMenuAccessibleName })).toBeInTheDocument() }) @@ -98,7 +92,10 @@ describe('AccountDropdown', () => { it('keeps the account identity in the compact trigger accessible name', () => { const queryClient = createAccountProfileQueryClient(userProfile) - renderWithConsoleQuery(, { queryClient }) + renderWithConsoleQuery(, { + queryClient, + features: { education: { enabled: false } }, + }) expect(screen.getByRole('button', { name: accountMenuAccessibleName })).toBeInTheDocument() expect(screen.queryByText('Current User')).not.toBeInTheDocument() @@ -108,7 +105,10 @@ describe('AccountDropdown', () => { const user = userEvent.setup() const queryClient = createAccountProfileQueryClient(userProfile) - renderWithConsoleQuery(, { queryClient }) + renderWithConsoleQuery(, { + queryClient, + features: { education: { enabled: false } }, + }) expect(screen.getByText('Current User')).toBeInTheDocument() diff --git a/web/app/components/header/account-dropdown/compliance.tsx b/web/app/components/header/account-dropdown/compliance.tsx index a5c0bf43206..842f18aabc8 100644 --- a/web/app/components/header/account-dropdown/compliance.tsx +++ b/web/app/components/header/account-dropdown/compliance.tsx @@ -10,7 +10,7 @@ import { } from '@langgenius/dify-ui/dropdown-menu' import { toast } from '@langgenius/dify-ui/toast' import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip' -import { useMutation } from '@tanstack/react-query' +import { useMutation, useQuery } from '@tanstack/react-query' import { useQueryState } from 'nuqs' import { useCallback } from 'react' import { useTranslation } from 'react-i18next' @@ -19,8 +19,8 @@ import { settingsQueryParser, } from '@/app/components/header/account-setting/query-params' import { useModalContext } from '@/context/modal-context' -import { useProviderContext } from '@/context/provider-context' import { getDocDownloadUrl } from '@/service/common' +import { consoleQuery } from '@/service/console' import { downloadUrl } from '@/utils/download' import Gdpr from '../../base/icons/src/public/common/Gdpr' import Iso from '../../base/icons/src/public/common/Iso' @@ -101,10 +101,15 @@ type ComplianceDocRowItemProps = { function ComplianceDocRowItem({ icon, label, docName }: ComplianceDocRowItemProps) { const { t } = useTranslation() - const { plan } = useProviderContext() + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: docName !== DocName.GDPR, + select: (data) => data.billing.subscription.plan, + }), + ) const { setShowPricingModal } = useModalContext() const [, setSettingsDestination] = useQueryState(settingsQueryParamName, settingsQueryParser) - const isFreePlan = plan.type === 'sandbox' + const isFreePlan = plan === 'sandbox' const { isPending, mutate: downloadCompliance } = useMutation({ mutationKey: ['downloadCompliance', docName], @@ -127,7 +132,9 @@ function ComplianceDocRowItem({ icon, label, docName }: ComplianceDocRowItemProp [DocName.GDPR]: ['team', 'professional', 'sandbox'], } - const isCurrentPlanCanDownload = whichPlanCanDownloadCompliance[docName].includes(plan.type) + const isCurrentPlanCanDownload = + docName === DocName.GDPR || + (plan !== undefined && whichPlanCanDownloadCompliance[docName].includes(plan)) const handleSelect = useCallback(() => { if (isCurrentPlanCanDownload) { @@ -153,6 +160,8 @@ function ComplianceDocRowItem({ icon, label, docName }: ComplianceDocRowItemProp } const labelTitle = typeof label === 'string' ? label : undefined + if (docName !== DocName.GDPR && plan === undefined) return null + return ( $['operation.download'], { ns: 'common' })} upgradeText={t(($) => $['upgradeBtn.encourageShort'], { ns: 'billing' })} /> diff --git a/web/app/components/header/account-dropdown/main-nav-menu-content.tsx b/web/app/components/header/account-dropdown/main-nav-menu-content.tsx index 2d4b8449a06..bab433bada1 100644 --- a/web/app/components/header/account-dropdown/main-nav-menu-content.tsx +++ b/web/app/components/header/account-dropdown/main-nav-menu-content.tsx @@ -25,10 +25,9 @@ import { settingsQueryParamName, settingsQueryParser, } from '@/app/components/header/account-setting/query-params' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' import Link from '@/next/link' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { ExternalLinkIndicator, MenuItemContent } from './menu-item-content' type MainNavRadioItemContentProps = { @@ -124,10 +123,14 @@ export function MainNavMenuContent({ onLogout }: MainNavMenuContentProps) { ...userProfileQueryOptions(), select: (data) => data.profile, }) - const { enableEducationPlan } = useProviderContext() + const { data: enableEducationPlan } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.education.enabled, + }), + ) const { data: isEducationAccount = false } = useQuery( consoleQuery.account.education.get.queryOptions({ - enabled: enableEducationPlan, + enabled: enableEducationPlan === true, select: ({ is_student }) => is_student ?? false, }), ) diff --git a/web/app/components/header/account-setting/__tests__/index.spec.tsx b/web/app/components/header/account-setting/__tests__/index.spec.tsx index 681ded7772d..bbc99191465 100644 --- a/web/app/components/header/account-setting/__tests__/index.spec.tsx +++ b/web/app/components/header/account-setting/__tests__/index.spec.tsx @@ -3,24 +3,17 @@ import type { ConsoleStateFixture } from '@/test/console/state-fixture' import { fireEvent, screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useState } from 'react' -import { baseProviderContextValue, useProviderContext } from '@/context/provider-context' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' import { renderWithConsoleQuery } from '@/test/console/query-data' import { ACCOUNT_SETTING_TAB } from '../constants' import AccountSetting from '../index' +let canReplaceLogo = true + const mockConsoleState = vi.hoisted(() => ({ current: null as unknown, })) -vi.mock('@/context/provider-context', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - useProviderContext: vi.fn(), - } -}) - vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') return createWorkspaceStateModuleMock(() => mockConsoleState.current ?? {}) @@ -82,12 +75,11 @@ vi.mock('@/service/use-common', async (importOriginal) => { return { ...actual, useMembers: vi.fn(() => ({ data: { accounts: [] }, refetch: vi.fn() })), - useProviderContext: vi.fn(), } }) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() return { ...actual, consoleQuery: new Proxy(actual.consoleQuery, { @@ -151,7 +143,6 @@ const baseConsoleState: ConsoleStateFixture = { }, isCurrentWorkspaceManager: true, isCurrentWorkspaceOwner: true, - isCurrentWorkspaceEditor: true, isCurrentWorkspaceDatasetOperator: false, refreshCurrentWorkspace: vi.fn(), isLoadingCurrentWorkspace: false, @@ -198,6 +189,10 @@ describe('AccountSetting', () => { } return renderWithConsoleQuery(, { + features: { + billing: { subscription: { plan: 'sandbox' } }, + can_replace_logo: canReplaceLogo, + }, accountProfile: (mockConsoleState.current as ConsoleStateFixture).userProfile, systemFeatures: { deployment_edition: deploymentEdition, @@ -212,11 +207,7 @@ describe('AccountSetting', () => { beforeEach(() => { vi.clearAllMocks() - vi.mocked(useProviderContext).mockReturnValue({ - ...baseProviderContextValue, - enableBilling: true, - enableReplaceWebAppLogo: true, - }) + canReplaceLogo = true mockConsoleState.current = baseConsoleState vi.mocked(useBreakpoints).mockReturnValue(MediaType.pc) }) @@ -442,14 +433,10 @@ describe('AccountSetting', () => { it('should hide billing and custom tabs when disabled', () => { // Arrange - vi.mocked(useProviderContext).mockReturnValue({ - ...baseProviderContextValue, - enableBilling: false, - enableReplaceWebAppLogo: false, - }) + canReplaceLogo = false // Act - renderAccountSetting() + renderAccountSetting({ deploymentEdition: 'COMMUNITY' }) // Assert // Assert 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 7c4b00da20e..8ecc52563de 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 @@ -3,7 +3,7 @@ import type { ReactNode } from 'react' import { QueryClientProvider } from '@tanstack/react-query' import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createTestQueryClient } from '@/test/query-client' import PermissionSetModal from '../index' 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 37051dd35f6..70d4de11fab 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 @@ -3,7 +3,7 @@ import type { AccessPolicyResourceType } from '@/models/access-control' import { useQuery } from '@tanstack/react-query' import { useMemo } from 'react' import { useTranslation } from 'react-i18next' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' export const usePermissionsGroups = (resourceType: AccessPolicyResourceType) => { const { t } = useTranslation() diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsx index 7c95d94b908..7e9d6d163d9 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsx @@ -26,7 +26,7 @@ vi.mock('@/context/permission-state', async () => { })) }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { systemFeatures: { get: { diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsx index 013c2a0ac21..b0a76663809 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/item.spec.tsx @@ -9,7 +9,7 @@ const { mockDeleteApiBasedExtension } = vi.hoisted(() => ({ mockDeleteApiBasedExtension: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apiBasedExtension: { byId: { diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsx index 8d699dfe8ff..f5dd0d3057a 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsx @@ -27,7 +27,7 @@ vi.mock('@/context/i18n', () => ({ useDocLink: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apiBasedExtension: { post: { diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx index 9f5663708af..785a1f9ea75 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx @@ -22,7 +22,7 @@ vi.mock('@/context/i18n', () => ({ `https://docs.dify.ai${path}`, })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apiBasedExtension: { get: { diff --git a/web/app/components/header/account-setting/api-based-extension-page/index.tsx b/web/app/components/header/account-setting/api-based-extension-page/index.tsx index 47660dda28d..9b44a240d94 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/index.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/index.tsx @@ -9,7 +9,7 @@ import { SearchInput } from '@/app/components/base/search-input' import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton' import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry' import { workspacePermissionKeysAtom } from '@/context/permission-state' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { hasPermission } from '@/utils/permission' import { Empty } from './empty' import { Item } from './item' diff --git a/web/app/components/header/account-setting/api-based-extension-page/item.tsx b/web/app/components/header/account-setting/api-based-extension-page/item.tsx index 45aaf62129d..331f254bb63 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/item.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/item.tsx @@ -11,7 +11,7 @@ import { Button } from '@langgenius/dify-ui/button' import { useMutation } from '@tanstack/react-query' import { useState } from 'react' import { useTranslation } from 'react-i18next' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' type ItemProps = { apiBasedExtension: ApiBasedExtensionResponse diff --git a/web/app/components/header/account-setting/api-based-extension-page/modal.tsx b/web/app/components/header/account-setting/api-based-extension-page/modal.tsx index 2eb5ac7fd1b..2c09de22bf6 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/modal.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/modal.tsx @@ -12,7 +12,7 @@ import { toast } from '@langgenius/dify-ui/toast' import { useMutation } from '@tanstack/react-query' import { useTranslation } from 'react-i18next' import { useDocLink } from '@/context/i18n' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' type ApiBasedExtensionModalProps = { open: boolean diff --git a/web/app/components/header/account-setting/api-based-extension-page/selector.tsx b/web/app/components/header/account-setting/api-based-extension-page/selector.tsx index 8311b7f7215..0b42c0c6fea 100644 --- a/web/app/components/header/account-setting/api-based-extension-page/selector.tsx +++ b/web/app/components/header/account-setting/api-based-extension-page/selector.tsx @@ -14,7 +14,7 @@ import { settingsQueryParamName, settingsQueryParser, } from '@/app/components/header/account-setting/query-params' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { ApiBasedExtensionModal } from './modal' type ApiBasedExtensionSelectorProps = { diff --git a/web/app/components/header/account-setting/index.tsx b/web/app/components/header/account-setting/index.tsx index b3d8c54194e..68cbb9933c8 100644 --- a/web/app/components/header/account-setting/index.tsx +++ b/web/app/components/header/account-setting/index.tsx @@ -1,4 +1,5 @@ 'use client' + import type { AccountSettingTab } from '@/app/components/header/account-setting/constants' import { cn } from '@langgenius/dify-ui/cn' import { @@ -8,7 +9,7 @@ import { ScrollAreaThumb, ScrollAreaViewport, } from '@langgenius/dify-ui/scroll-area' -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useAtomValue } from 'jotai' import { useRef } from 'react' import { useTranslation } from 'react-i18next' @@ -17,13 +18,13 @@ import CustomPage from '@/app/components/custom/custom-page' import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants' import MenuDialog from '@/app/components/header/account-setting/menu-dialog' import { workspacePermissionKeysAtom } from '@/context/permission-state' -import { useProviderContext } from '@/context/provider-context' import { isCurrentWorkspaceDatasetOperatorAtom, isCurrentWorkspaceManagerAtom, } from '@/context/workspace-state' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' +import { consoleQuery } from '@/service/console' import { hasPermission } from '@/utils/permission' import AccessRulesPage from './access-rules-page' import MembersPage from './members-page' @@ -56,7 +57,11 @@ export default function AccountSetting({ onTabChangeAction, }: IAccountSettingProps) { const { t } = useTranslation() - const { enableBilling, enableReplaceWebAppLogo } = useProviderContext() + const { data: enableReplaceWebAppLogo } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.can_replace_logo, + }), + ) const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions()) const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom) const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom) @@ -64,7 +69,8 @@ export default function AccountSetting({ const isRbacEnabled = systemFeatures.rbac_enabled const canManageWorkspaceRoles = isRbacEnabled && hasPermission(workspacePermissionKeys, 'workspace.role.manage') - const canViewBilling = enableBilling && !isCurrentWorkspaceDatasetOperator + const canViewBilling = + systemFeatures.deployment_edition === 'CLOUD' && !isCurrentWorkspaceDatasetOperator const canViewWorkflowLogArchives = systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceManager const activeMenu = (() => { @@ -144,7 +150,8 @@ export default function AccountSetting({ if (canViewBilling) visibleTabs.push(ACCOUNT_SETTING_TAB.BILLING) - if (enableReplaceWebAppLogo || enableBilling) visibleTabs.push(ACCOUNT_SETTING_TAB.CUSTOM) + if (enableReplaceWebAppLogo || systemFeatures.deployment_edition === 'CLOUD') + visibleTabs.push(ACCOUNT_SETTING_TAB.CUSTOM) if (canViewWorkflowLogArchives) visibleTabs.push(ACCOUNT_SETTING_TAB.WORKFLOW_LOG_ARCHIVES) diff --git a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx index 1e4813cd27a..4453362701e 100644 --- a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx +++ b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx @@ -1,18 +1,20 @@ import type { ReactElement } from 'react' import type { Role } from '@/models/access-control' import type { Member } from '@/models/common' +import type { ConsoleQueryTestOptions } from '@/test/console/query-data' import type { ConsoleStateFixture } from '@/test/console/state-fixture' import { screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { vi } from 'vite-plus/test' -import { createMockProviderContextValue } from '@/__mocks__/provider-context' -import { useProviderContext } from '@/context/provider-context' import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now' import { useUpdateRolesOfMember } from '@/service/access-control/use-member-roles' import { useMembers } from '@/service/use-common' import { renderWithConsoleQuery } from '@/test/console/query-data' import MembersPage from '../index' +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY' +let memberFeatures: ConsoleQueryTestOptions['features'] = {} + const mockConsoleState = vi.hoisted(() => ({ current: {} as Partial, })) @@ -27,15 +29,15 @@ vi.mock('@/context/permission-state', async () => { return createPermissionStateModuleMock(() => mockConsoleState.current) }) -vi.mock('@/context/provider-context') vi.mock('@/hooks/use-format-time-from-now') vi.mock('@/service/access-control/use-member-roles') vi.mock('@/service/use-common') const renderMembersPage = () => renderWithConsoleQuery(, { + features: memberFeatures, accountProfile: mockConsoleState.current.userProfile, - systemFeatures: { is_email_setup: true }, + systemFeatures: { deployment_edition: deploymentEdition, is_email_setup: true }, }) const getMemberDetailsButton = (memberId: string) => @@ -241,12 +243,8 @@ describe('MembersPage', () => { mutateAsync: mockUpdateRolesOfMember, } as unknown as ReturnType) - vi.mocked(useProviderContext).mockReturnValue( - createMockProviderContextValue({ - enableBilling: false, - isAllowTransferWorkspace: true, - }), - ) + deploymentEdition = 'COMMUNITY' + memberFeatures = { ...memberFeatures, is_allow_transfer_workspace: true } vi.mocked(useFormatTimeFromNow).mockReturnValue({ formatTimeFromNow: mockFormatTimeFromNow, @@ -276,7 +274,9 @@ describe('MembersPage', () => { it('should render plural roles column header when RBAC is enabled', () => { renderWithConsoleQuery(, { + features: memberFeatures, systemFeatures: { + deployment_edition: deploymentEdition, is_email_setup: true, rbac_enabled: true, }, @@ -326,12 +326,8 @@ describe('MembersPage', () => { }) it('should show non-interactive owner role when transfer ownership is not allowed', () => { - vi.mocked(useProviderContext).mockReturnValue( - createMockProviderContextValue({ - enableBilling: false, - isAllowTransferWorkspace: false, - }), - ) + deploymentEdition = 'COMMUNITY' + memberFeatures = { ...memberFeatures, is_allow_transfer_workspace: false } renderMembersPage() @@ -394,17 +390,11 @@ describe('MembersPage', () => { }) it('should show billing information for limited plan', () => { - vi.mocked(useProviderContext).mockReturnValue( - createMockProviderContextValue({ - enableBilling: true, - plan: { - type: 'sandbox', - total: { teamMembers: 5 } as unknown as ReturnType< - typeof useProviderContext - >['plan']['total'], - } as unknown as ReturnType['plan'], - }), - ) + deploymentEdition = 'CLOUD' + memberFeatures = { + billing: { subscription: { plan: 'sandbox' } }, + members: { size: 2, limit: 5 }, + } renderMembersPage() @@ -415,17 +405,11 @@ describe('MembersPage', () => { }) it('should show unlimited billing information', () => { - vi.mocked(useProviderContext).mockReturnValue( - createMockProviderContextValue({ - enableBilling: true, - plan: { - type: 'sandbox', - total: { teamMembers: -1 } as unknown as ReturnType< - typeof useProviderContext - >['plan']['total'], - } as unknown as ReturnType['plan'], - }), - ) + deploymentEdition = 'CLOUD' + memberFeatures = { + billing: { subscription: { plan: 'sandbox' } }, + members: { size: 2, limit: 0 }, + } renderMembersPage() @@ -433,17 +417,11 @@ describe('MembersPage', () => { }) it('should show non-billing member format for team plan even when billing is enabled', () => { - vi.mocked(useProviderContext).mockReturnValue( - createMockProviderContextValue({ - enableBilling: true, - plan: { - type: 'team', - total: { teamMembers: 50 } as unknown as ReturnType< - typeof useProviderContext - >['plan']['total'], - } as unknown as ReturnType['plan'], - }), - ) + deploymentEdition = 'CLOUD' + memberFeatures = { + billing: { subscription: { plan: 'team' } }, + members: { size: 2, limit: 50 }, + } renderMembersPage() @@ -543,17 +521,11 @@ describe('MembersPage', () => { data: { accounts: [mockAccounts[0]] }, refetch: mockRefetch, } as unknown as ReturnType) - vi.mocked(useProviderContext).mockReturnValue( - createMockProviderContextValue({ - enableBilling: true, - plan: { - type: 'sandbox', - total: { teamMembers: 5 } as unknown as ReturnType< - typeof useProviderContext - >['plan']['total'], - } as unknown as ReturnType['plan'], - }), - ) + deploymentEdition = 'CLOUD' + memberFeatures = { + billing: { subscription: { plan: 'sandbox' } }, + members: { size: 2, limit: 5 }, + } renderMembersPage() @@ -684,7 +656,9 @@ describe('MembersPage', () => { const user = userEvent.setup() renderWithConsoleQuery(, { + features: memberFeatures, systemFeatures: { + deployment_edition: deploymentEdition, is_email_setup: true, rbac_enabled: true, }, @@ -714,17 +688,11 @@ describe('MembersPage', () => { it('should show the upgrade action without blocking the backend-authoritative invite flow', async () => { const user = userEvent.setup() - vi.mocked(useProviderContext).mockReturnValue( - createMockProviderContextValue({ - enableBilling: true, - plan: { - type: 'sandbox', - total: { teamMembers: 2 } as unknown as ReturnType< - typeof useProviderContext - >['plan']['total'], - } as unknown as ReturnType['plan'], - }), - ) + deploymentEdition = 'CLOUD' + memberFeatures = { + billing: { subscription: { plan: 'sandbox' } }, + members: { size: 2, limit: 2 }, + } renderMembersPage() diff --git a/web/app/components/header/account-setting/members-page/index.tsx b/web/app/components/header/account-setting/members-page/index.tsx index 10023f4ae62..2c9d35f3dce 100644 --- a/web/app/components/header/account-setting/members-page/index.tsx +++ b/web/app/components/header/account-setting/members-page/index.tsx @@ -4,21 +4,20 @@ import type { Role } from '@/models/access-control' import type { Member } from '@/models/common' import { toast } from '@langgenius/dify-ui/toast' import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip' -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useAtomValue } from 'jotai' import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import { WorkspaceAvatar } from '@/app/components/base/workspace-avatar' -import { NUM_INFINITE } from '@/app/components/billing/config' import UpgradeBtn from '@/app/components/billing/upgrade-btn' import { useLocale } from '@/context/i18n' import { workspacePermissionKeysAtom } from '@/context/permission-state' -import { useProviderContext } from '@/context/provider-context' import { currentWorkspaceAtom, isCurrentWorkspaceOwnerAtom } from '@/context/workspace-state' import { userProfileQueryOptions } from '@/features/account-profile/client' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { getAccessControlTemplateLanguage, LanguagesSupported } from '@/i18n-config/language' import { useUpdateRolesOfMember } from '@/service/access-control/use-member-roles' +import { consoleQuery } from '@/service/console' import { useMembers } from '@/service/use-common' import { hasPermission } from '@/utils/permission' import EditWorkspaceModal from './edit-workspace-modal' @@ -48,10 +47,24 @@ const MembersPage = () => { MemberInviteResponse['invitation_results'] | null >(null) const accounts = data?.accounts || [] - const { plan, enableBilling, isAllowTransferWorkspace } = useProviderContext() - const isNotUnlimitedMemberPlan = enableBilling && plan.type !== 'team' + const deploymentEdition = systemFeatures.deployment_edition + const { data: features } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (data) => ({ + plan: data.billing.subscription.plan, + members: data.members, + is_allow_transfer_workspace: data.is_allow_transfer_workspace, + }), + }), + ) + + const isNotUnlimitedMemberPlan = + deploymentEdition === 'CLOUD' && features !== undefined && features.plan !== 'team' + // A limit of 0 means unlimited. const isMemberFull = - enableBilling && isNotUnlimitedMemberPlan && accounts.length >= plan.total.teamMembers + isNotUnlimitedMemberPlan && + features.members.limit > 0 && + accounts.length >= features.members.limit const [editWorkspaceModalVisible, setEditWorkspaceModalVisible] = useState(false) const [showTransferOwnershipModal, setShowTransferOwnershipModal] = useState(false) const [detailsMember, setDetailsMember] = useState(null) @@ -130,7 +143,7 @@ const MembersPage = () => { )}
- {enableBilling && isNotUnlimitedMemberPlan ? ( + {isNotUnlimitedMemberPlan ? (
{t(($) => $['plansCommon.member'], { ns: 'billing' })} @@ -139,9 +152,9 @@ const MembersPage = () => {
{accounts.length}
/
- {plan.total.teamMembers === NUM_INFINITE + {features.members.limit === 0 ? t(($) => $['plansCommon.unlimited'], { ns: 'billing' }) - : plan.total.teamMembers} + : features.members.limit}
) : ( @@ -188,7 +201,9 @@ const MembersPage = () => { roles={account.roles} isCurrentUser={userProfileEmail === account.email} canManage={canManageMembers} - canTransferOwnership={isCurrentWorkspaceOwner && isAllowTransferWorkspace} + canTransferOwnership={ + isCurrentWorkspaceOwner && features?.is_allow_transfer_workspace === true + } allowMultipleRoles={systemFeatures.rbac_enabled} onOpenDetails={handleOpenDetails} onTransferOwnership={handleTransferOwnership} diff --git a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx index eb760277092..275946ac47b 100644 --- a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx +++ b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx @@ -1,12 +1,13 @@ import type { GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen' import type { MemberInviteResponse } from '@dify/contracts/api/console/workspaces/types.gen' -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { QueryClient } from '@tanstack/react-query' import { act, render, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useState } from 'react' import { vi } from 'vite-plus/test' import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles' -import { seedFeatures } from '@/test/console/query-data' +import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data' +import { QueryClientTestProvider } from '@/test/console/query-provider' import { InviteModal } from '../index' const { fetchFeatures, inviteMember } = vi.hoisted(() => ({ @@ -15,27 +16,33 @@ const { fetchFeatures, inviteMember } = vi.hoisted(() => ({ })) vi.mock('@/service/access-control/use-workspace-roles') -vi.mock('@/service/client', () => ({ - consoleQuery: { - features: { - get: { - queryKey: () => ['features'], - queryOptions: () => ({ queryKey: ['features'], queryFn: fetchFeatures }), +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + consoleQuery: { + ...actual.consoleQuery, + systemFeatures: actual.consoleQuery.systemFeatures, + features: { + get: { + queryKey: () => ['features'], + queryOptions: () => ({ queryKey: ['features'], queryFn: fetchFeatures }), + }, }, - }, - workspaces: { - current: { - members: { - inviteEmail: { - post: { - mutationOptions: () => ({ mutationFn: inviteMember }), + workspaces: { + current: { + members: { + inviteEmail: { + post: { + mutationOptions: () => ({ mutationFn: inviteMember }), + }, }, }, }, }, }, - }, -})) + } +}) describe('InviteModal', () => { const onOpenChange = vi.fn() @@ -108,11 +115,12 @@ describe('InviteModal', () => { queryClient?: QueryClient workspaceMembers?: GetFeaturesResponse['workspace_members'] } = {}) => { + seedSystemFeatures(queryClient, { deployment_edition: 'CLOUD' }) const features = seedFeatures(queryClient, { workspace_members: workspaceMembers }) fetchFeatures.mockResolvedValue(features) return render( - + members.invite} @@ -120,7 +128,7 @@ describe('InviteModal', () => { onOpenChange={onOpenChange} onSend={onSend} /> - , + , ) } @@ -658,13 +666,14 @@ describe('InviteModal', () => { it('resets the form after a controlled close', async () => { const user = userEvent.setup() const queryClient = createQueryClient() + seedSystemFeatures(queryClient, { deployment_edition: 'CLOUD' }) const features = seedFeatures(queryClient) fetchFeatures.mockResolvedValue(features) const ControlledInviteModal = () => { const [open, setOpen] = useState(false) return ( - + members.invite} @@ -672,7 +681,7 @@ describe('InviteModal', () => { onOpenChange={setOpen} onSend={onSend} /> - + ) } render() diff --git a/web/app/components/header/account-setting/members-page/invite-modal/index.tsx b/web/app/components/header/account-setting/members-page/invite-modal/index.tsx index b36c4443de8..df9137c48d7 100644 --- a/web/app/components/header/account-setting/members-page/invite-modal/index.tsx +++ b/web/app/components/header/account-setting/members-page/invite-modal/index.tsx @@ -14,10 +14,12 @@ import { import { Form } from '@langgenius/dify-ui/form' import { IconButton } from '@langgenius/dify-ui/icon-button' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import { useState } from 'react' import { useTranslation } from 'react-i18next' import { useLocale } from '@/context/i18n' -import { consoleQuery } from '@/service/client' +import { deploymentEditionAtom } from '@/features/system-features/state' +import { consoleQuery } from '@/service/console' import { commonQueryKeys } from '@/service/use-common' import { mergeEmailRecipients } from './email-recipients' import { EmailRecipientsField } from './email-recipients-field' @@ -48,14 +50,16 @@ function InviteForm({ isEmailSetup, onOpenChange, onSend }: InviteFormProps) { const { t } = useTranslation() const locale = useLocale() const queryClient = useQueryClient() + const deploymentEdition = useAtomValue(deploymentEditionAtom) const { data: features } = useQuery(consoleQuery.features.get.queryOptions()) const [recipients, setRecipients] = useState([]) const [draft, setDraft] = useState('') const [submissionError, setSubmissionError] = useState(null) const fieldErrors = submissionError?.kind === 'fields' ? submissionError.errors : undefined + // A limit of 0 means unlimited. const memberLimit = features?.workspace_members.enabled ? features.workspace_members - : features?.billing.enabled && features.members.limit > 0 + : deploymentEdition === 'CLOUD' && features && features.members.limit > 0 ? features.members : undefined const remainingSeats = diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/derive-model-status.spec.ts b/web/app/components/header/account-setting/model-provider-page/__tests__/derive-model-status.spec.ts index eca7d891121..2ff091c72f0 100644 --- a/web/app/components/header/account-setting/model-provider-page/__tests__/derive-model-status.spec.ts +++ b/web/app/components/header/account-setting/model-provider-page/__tests__/derive-model-status.spec.ts @@ -1,4 +1,8 @@ -import type { Model, ModelItem, ModelProvider } from '../declarations' +import type { + ProviderModelWithStatusEntity, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' +import type { ModelProvider } from '../declarations' import type { CredentialPanelState } from '../provider-added-card/use-credential-panel-state' import { ConfigurationMethodEnum, ModelStatusEnum, ModelTypeEnum } from '../declarations' import { deriveModelStatus } from '../derive-model-status' @@ -17,7 +21,9 @@ const createCredentialState = ( ...overrides, }) -const createModelItem = (overrides: Partial = {}): ModelItem => ({ +const createModelItem = ( + overrides: Partial = {}, +): ProviderModelWithStatusEntity => ({ model: 'text-embedding-3-large', label: { en_US: 'Text Embedding 3 Large', zh_Hans: 'Text Embedding 3 Large' }, model_type: ModelTypeEnum.textEmbedding, @@ -30,7 +36,10 @@ const createModelItem = (overrides: Partial = {}): ModelItem => ({ const createModelProvider = (): ModelProvider => ({ provider: 'openai' }) as ModelProvider -const createModel = (overrides: Partial = {}): Model => ({ +const createModel = ( + overrides: Partial = {}, +): ProviderWithModelsResponse => ({ + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: '', zh_Hans: '' }, label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.ts b/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.ts index f8e03853fbc..4f6c79c5514 100644 --- a/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.ts +++ b/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.ts @@ -1,16 +1,16 @@ +import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen' import type { Mock } from 'vite-plus/test' import type { Credential, CustomConfigurationModelFixedFields, CustomModel, DefaultModelResponse, - Model, ModelProvider, } from '../declarations' import { act, renderHook } from '@testing-library/react' import { useLocale } from '@/context/i18n' -import { consoleQuery } from '@/service/client' import { fetchDefaultModal } from '@/service/common' +import { consoleQuery } from '@/service/console' import { ConfigurationMethodEnum, CurrentSystemQuotaTypeEnum, @@ -26,7 +26,6 @@ import { useInvalidateDefaultModel, useLanguage, useMarketplaceAllPlugins, - useModelList, useModelListAndDefaultModel, useModelListAndDefaultModelAndCurrentProviderAndModel, useModelModalHandler, @@ -51,7 +50,6 @@ vi.mock('@tanstack/react-query', () => ({ vi.mock('@/service/common', () => ({ fetchDefaultModal: vi.fn(), - fetchModelList: vi.fn(), })) vi.mock('@/service/use-common', () => ({ @@ -133,8 +131,9 @@ describe('hooks', () => { }) describe('useSystemDefaultModelAndModelList', () => { - const createMockModelList = (): Model[] => [ + const createMockModelList = (): ProviderWithModelsResponse[] => [ { + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: 'icon', zh_Hans: 'icon' }, label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, @@ -254,106 +253,6 @@ describe('hooks', () => { }) }) - describe('useModelList', () => { - const mockModelData = [ - { provider: 'openai', models: [{ model: 'gpt-4' }] }, - { provider: 'anthropic', models: [{ model: 'claude-3' }] }, - ] - - it('should use the generated model list key and expose the result', () => { - const refetch = vi.fn() - ;(useQuery as Mock).mockReturnValue({ - data: { data: mockModelData }, - isPending: false, - refetch, - }) - - const { result } = renderHook(() => useModelList(ModelTypeEnum.textGeneration)) - - expect(result.current.data).toEqual(mockModelData) - expect(result.current.isLoading).toBe(false) - expect(useQuery).toHaveBeenCalledWith( - expect.objectContaining({ - queryKey: getModelListQueryKey(ModelTypeEnum.textGeneration), - }), - ) - }) - - it('should return empty array when data is undefined', () => { - ;(useQuery as Mock).mockReturnValue({ - data: undefined, - isPending: false, - refetch: vi.fn(), - }) - - const { result } = renderHook(() => useModelList(ModelTypeEnum.textGeneration)) - - expect(result.current.data).toEqual([]) - }) - - it('should keep the query disabled when requested', () => { - ;(useQuery as Mock).mockReturnValue({ - data: undefined, - isPending: true, - refetch: vi.fn(), - }) - - renderHook(() => useModelList(ModelTypeEnum.textEmbedding, { enabled: false })) - - expect(useQuery).toHaveBeenCalledWith( - expect.objectContaining({ - enabled: false, - queryKey: getModelListQueryKey(ModelTypeEnum.textEmbedding), - }), - ) - }) - - it('should handle loading state', () => { - ;(useQuery as Mock).mockReturnValue({ - data: undefined, - isPending: true, - refetch: vi.fn(), - }) - - const { result } = renderHook(() => useModelList(ModelTypeEnum.textGeneration)) - - expect(result.current.isLoading).toBe(true) - }) - - it('should call mutate to refetch data', () => { - const refetch = vi.fn() - ;(useQuery as Mock).mockReturnValue({ - data: { data: mockModelData }, - isPending: false, - refetch, - }) - - const { result } = renderHook(() => useModelList(ModelTypeEnum.textGeneration)) - - act(() => { - result.current.mutate() - }) - - expect(refetch).toHaveBeenCalled() - }) - - it('should work with different model types', () => { - ;(useQuery as Mock).mockReturnValue({ - data: { data: [] }, - isPending: false, - refetch: vi.fn(), - }) - - const { result: result1 } = renderHook(() => useModelList(ModelTypeEnum.textEmbedding)) - const { result: result2 } = renderHook(() => useModelList(ModelTypeEnum.rerank)) - const { result: result3 } = renderHook(() => useModelList(ModelTypeEnum.tts)) - - expect(result1.current.data).toEqual([]) - expect(result2.current.data).toEqual([]) - expect(result3.current.data).toEqual([]) - }) - }) - describe('useDefaultModel', () => { const mockDefaultModel = { model: 'gpt-4', @@ -447,8 +346,9 @@ describe('hooks', () => { }) describe('getCurrentProviderAndModel', () => { - const createModelList = (): Model[] => [ + const createModelList = (): ProviderWithModelsResponse[] => [ { + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: 'icon', zh_Hans: 'icon' }, label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, @@ -526,8 +426,9 @@ describe('hooks', () => { }) describe('useTextGenerationCurrentProviderAndModelAndModelList', () => { - const createModelList = (): Model[] => [ + const createModelList = (): ProviderWithModelsResponse[] => [ { + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: 'icon', zh_Hans: 'icon' }, label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, @@ -545,6 +446,7 @@ describe('hooks', () => { status: ModelStatusEnum.active, }, { + tenant_id: 'test-workspace', provider: 'anthropic', icon_small: { en_US: 'icon', zh_Hans: 'icon' }, label: { en_US: 'Anthropic', zh_Hans: 'Anthropic' }, @@ -554,19 +456,19 @@ describe('hooks', () => { label: { en_US: 'Claude 3', zh_Hans: 'Claude 3' }, model_type: ModelTypeEnum.textGeneration, fetch_from: ConfigurationMethodEnum.predefinedModel, - status: ModelStatusEnum.disabled, + status: 'no-configure', model_properties: {}, load_balancing_enabled: false, }, ], - status: ModelStatusEnum.disabled, + status: 'no-configure', }, ] it('should return all text generation model lists', () => { const modelList = createModelList() ;(useQuery as Mock).mockReturnValue({ - data: { data: modelList }, + data: modelList, isPending: false, refetch: vi.fn(), }) @@ -584,7 +486,7 @@ describe('hooks', () => { it('should filter active models correctly', () => { const modelList = createModelList() ;(useQuery as Mock).mockReturnValue({ - data: { data: modelList }, + data: modelList, isPending: false, refetch: vi.fn(), }) @@ -598,7 +500,7 @@ describe('hooks', () => { it('should find current provider and model', () => { const modelList = createModelList() ;(useQuery as Mock).mockReturnValue({ - data: { data: modelList }, + data: modelList, isPending: false, refetch: vi.fn(), }) @@ -614,7 +516,7 @@ describe('hooks', () => { it('should handle empty model list', () => { ;(useQuery as Mock).mockReturnValue({ - data: { data: [] }, + data: [], isPending: false, refetch: vi.fn(), }) @@ -631,7 +533,7 @@ describe('hooks', () => { const mockModelData = [{ provider: 'openai', models: [] }] const mockDefaultModel = { model: 'gpt-4', provider: { provider: 'openai' } } ;(useQuery as Mock) - .mockReturnValueOnce({ data: { data: mockModelData }, isPending: false, refetch: vi.fn() }) + .mockReturnValueOnce({ data: mockModelData, isPending: false, refetch: vi.fn() }) .mockReturnValueOnce({ data: { data: mockDefaultModel }, isPending: false, @@ -660,6 +562,7 @@ describe('hooks', () => { it('should return complete data structure', () => { const mockModelData = [ { + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: 'icon', zh_Hans: 'icon' }, label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, @@ -683,7 +586,7 @@ describe('hooks', () => { provider: { provider: 'openai', icon_small: { en_US: 'icon', zh_Hans: 'icon' } }, } ;(useQuery as Mock) - .mockReturnValueOnce({ data: { data: mockModelData }, isPending: false, refetch: vi.fn() }) + .mockReturnValueOnce({ data: mockModelData, isPending: false, refetch: vi.fn() }) .mockReturnValueOnce({ data: { data: mockDefaultModel }, isPending: false, @@ -709,7 +612,7 @@ describe('hooks', () => { }, ] ;(useQuery as Mock) - .mockReturnValueOnce({ data: { data: mockModelData }, isPending: false, refetch: vi.fn() }) + .mockReturnValueOnce({ data: mockModelData, isPending: false, refetch: vi.fn() }) .mockReturnValueOnce({ data: undefined, isPending: false, refetch: vi.fn() }) const { result } = renderHook(() => diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx index 52659532eb8..8770adb2b6f 100644 --- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx +++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx @@ -1,20 +1,25 @@ +import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen' import { screen } from '@testing-library/react' -import { renderWithConsoleQuery } from '@/test/console/query-data' -import { - CurrentSystemQuotaTypeEnum, - CustomConfigurationStatusEnum, - QuotaUnitEnum, -} from '../declarations' +import { consoleQuery } from '@/service/console' +import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import ModelProviderPage from '../index' -const mockQuotaConfig = { - quota_type: CurrentSystemQuotaTypeEnum.free, - quota_unit: QuotaUnitEnum.times, - quota_limit: 100, - quota_used: 1, - last_used: 0, - is_valid: true, -} +const providerSummaryFixture = { + provider: 'openai', + plugin_id: 'langgenius/openai', + label: { en_US: 'OpenAI' }, + configurate_methods: ['predefined-model'], + supported_model_types: ['llm'], + preferred_provider_type: 'custom', + is_configured: true, + system_configuration: { enabled: false }, + custom_configuration: { + status: 'active', + available_credentials: [], + current_credential_usable: true, + has_custom_models: false, + }, +} satisfies ModelProviderSummaryResponse vi.mock('@/config', async (importOriginal) => { const actual = await importOriginal() @@ -23,23 +28,6 @@ vi.mock('@/config', async (importOriginal) => { } }) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - modelProviders: [ - { - provider: 'openai', - label: { en_US: 'OpenAI' }, - custom_configuration: { status: CustomConfigurationStatusEnum.active }, - system_configuration: { - enabled: false, - current_quota_type: CurrentSystemQuotaTypeEnum.free, - quota_configurations: [mockQuotaConfig], - }, - }, - ], - }), -})) - vi.mock('../hooks', () => ({ useDefaultModel: () => ({ data: null, isLoading: false }), useLanguage: () => 'en_US', @@ -116,8 +104,8 @@ vi.mock('@/app/components/plugins/reference-setting-modal', () => ({ default: () =>
, })) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() const originalWorkspaces = actual.consoleQuery.workspaces return { ...actual, @@ -128,6 +116,18 @@ vi.mock('@/service/client', async (importOriginal) => { ...originalWorkspaces, current: { ...originalWorkspaces.current, + modelProviders: { + summary: { + get: { + queryKey: () => + originalWorkspaces.current.modelProviders.summary.get.queryKey(), + queryOptions: () => ({ + ...originalWorkspaces.current.modelProviders.summary.get.queryOptions(), + queryFn: () => new Promise(() => {}), + }), + }, + }, + }, plugin: { ...originalWorkspaces.current.plugin, list: { @@ -176,9 +176,18 @@ vi.mock('@/service/client', async (importOriginal) => { } }) +const renderPage: typeof renderWithConsoleQuery = (ui, options) => { + const queryClient = createConsoleQueryClient() + queryClient.setQueryData(consoleQuery.workspaces.current.modelProviders.summary.get.queryKey(), { + data: [{ ...providerSummaryFixture } satisfies ModelProviderSummaryResponse], + plugins: {}, + }) + return renderWithConsoleQuery(ui, { ...options, queryClient }) +} + describe('ModelProviderPage non-cloud branch', () => { it('should skip the quota panel when cloud edition is disabled', () => { - renderWithConsoleQuery(, { + renderPage(, { systemFeatures: { enable_marketplace: false }, }) diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx index f87e5ed837e..04259f27d46 100644 --- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx +++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx @@ -1,3 +1,4 @@ +import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen' import type { PluginDeclaration, PluginDetail } from '@/app/components/plugins/types' import { act, fireEvent, screen } from '@testing-library/react' import { describe, expect, it, vi } from 'vite-plus/test' @@ -6,7 +7,8 @@ import { getStepByStepTourTargetSelector, STEP_BY_STEP_TOUR_TARGETS, } from '@/app/components/step-by-step-tour/target-registry' -import { renderWithConsoleQuery } from '@/test/console/query-data' +import { consoleQuery } from '@/service/console' +import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { CurrentSystemQuotaTypeEnum, CustomConfigurationStatusEnum, @@ -15,6 +17,23 @@ import { } from '../declarations' import ModelProviderPage from '../index' +const providerSummaryFixture = { + provider: 'openai', + plugin_id: 'langgenius/openai', + label: { en_US: 'OpenAI' }, + configurate_methods: ['predefined-model'], + supported_model_types: ['llm'], + preferred_provider_type: 'custom', + is_configured: true, + system_configuration: { enabled: false }, + custom_configuration: { + status: 'active', + available_credentials: [], + current_credential_usable: true, + has_custom_models: false, + }, +} satisfies ModelProviderSummaryResponse + type MockReferenceSetting = { permission: Record auto_upgrade?: { @@ -52,11 +71,10 @@ const { mockReferenceSetting, mockAutoUpgradeError } = vi.hoisted(() => ({ }, })) -const { mockProviderContextState, mockRefreshModelProviders } = vi.hoisted(() => ({ - mockProviderContextState: { - isLoadingModelProviders: false, - isSuccessModelProviders: true, - modelProviderPlugins: {} as Record< +const { mockSummaryState } = vi.hoisted(() => ({ + mockSummaryState: { + isLoading: false, + plugins: {} as Record< string, { installation_id: string @@ -68,7 +86,6 @@ const { mockProviderContextState, mockRefreshModelProviders } = vi.hoisted(() => } >, }, - mockRefreshModelProviders: vi.fn(), })) const { mockInstalledModelPlugins, mockUseInstalledPluginList } = vi.hoisted(() => ({ @@ -87,22 +104,6 @@ const mockQuotaConfig = { is_valid: true, } -const renderModelProviderPage = ( - props: { - enableMarketplace?: boolean - searchText?: string - stickyToolbar?: boolean - } = {}, -) => { - const { searchText = '', enableMarketplace = true, stickyToolbar = true } = props - return renderWithConsoleQuery( - , - { - systemFeatures: { enable_marketplace: enableMarketplace }, - }, - ) -} - const saveUpdateSettings = () => { fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' })) } @@ -214,20 +215,52 @@ const mockProviders: MockProvider[] = [ }, ] -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - modelProviders: mockProviders.map((provider) => ({ - ...provider, - is_configured: - provider.custom_configuration.status === CustomConfigurationStatusEnum.active || - provider.system_configuration.enabled, - })), - modelProviderPlugins: mockProviderContextState.modelProviderPlugins, - isLoadingModelProviders: mockProviderContextState.isLoadingModelProviders, - isSuccessModelProviders: mockProviderContextState.isSuccessModelProviders, - refreshModelProviders: mockRefreshModelProviders, - }), -})) +const renderModelProviderPage = ( + props: { + enableMarketplace?: boolean + searchText?: string + stickyToolbar?: boolean + } = {}, +) => { + const { searchText = '', enableMarketplace = true, stickyToolbar = true } = props + const queryClient = createConsoleQueryClient() + if (mockSummaryState.isLoading) { + queryClient.setQueryDefaults( + consoleQuery.workspaces.current.modelProviders.summary.get.queryKey(), + { queryFn: () => new Promise(() => {}) }, + ) + } else { + queryClient.setQueryData( + consoleQuery.workspaces.current.modelProviders.summary.get.queryKey(), + { + data: mockProviders.map( + (provider) => + ({ + ...providerSummaryFixture, + ...{ + ...provider, + is_configured: + provider.custom_configuration.status === CustomConfigurationStatusEnum.active || + provider.system_configuration.enabled, + }, + custom_configuration: { + ...providerSummaryFixture.custom_configuration, + ...provider.custom_configuration, + }, + }) satisfies ModelProviderSummaryResponse, + ), + plugins: mockSummaryState.plugins, + }, + ) + } + return renderWithConsoleQuery( + , + { + queryClient, + systemFeatures: { enable_marketplace: enableMarketplace }, + }, + ) +} const mockDefaultModels: Record = { llm: { data: null, isLoading: false }, @@ -329,8 +362,8 @@ vi.mock('nuqs', async (importOriginal) => { return { ...actual, useQueryState: () => [null, mockSetSettingsDestination] } }) -vi.mock('@/service/client', async (importOriginal) => { - const actual = await importOriginal() +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() const originalWorkspaces = actual.consoleQuery.workspaces return { ...actual, @@ -341,6 +374,18 @@ vi.mock('@/service/client', async (importOriginal) => { ...originalWorkspaces, current: { ...originalWorkspaces.current, + modelProviders: { + summary: { + get: { + queryKey: () => + originalWorkspaces.current.modelProviders.summary.get.queryKey(), + queryOptions: () => ({ + ...originalWorkspaces.current.modelProviders.summary.get.queryOptions(), + queryFn: () => new Promise(() => {}), + }), + }, + }, + }, plugin: { ...originalWorkspaces.current.plugin, list: { @@ -394,11 +439,9 @@ describe('ModelProviderPage', () => { vi.useFakeTimers() vi.clearAllMocks() mockUseInstalledPluginList.mockClear() - mockRefreshModelProviders.mockClear() mockInstalledModelPlugins.value = [] - mockProviderContextState.isLoadingModelProviders = false - mockProviderContextState.isSuccessModelProviders = true - mockProviderContextState.modelProviderPlugins = {} + mockSummaryState.isLoading = false + mockSummaryState.plugins = {} mockPluginSettingsAccess.canSetPluginPreferences = true mockAutoUpgradeError.value = undefined mockReferenceSetting.auto_upgrade = { @@ -608,7 +651,7 @@ describe('ModelProviderPage', () => { quota_configurations: [mockQuotaConfig], }, }) - mockProviderContextState.modelProviderPlugins = { + mockSummaryState.plugins = { 'langgenius/openai-marketplace': { installation_id: 'openai-installation', plugin_id: 'langgenius/openai-marketplace', @@ -652,7 +695,7 @@ describe('ModelProviderPage', () => { }) it('should not refresh providers when remote plugin metadata already comes from summary', () => { - mockProviderContextState.modelProviderPlugins = { + mockSummaryState.plugins = { 'langgenius/debug-model': { installation_id: 'debug-installation', plugin_id: 'langgenius/debug-model', @@ -664,8 +707,6 @@ describe('ModelProviderPage', () => { } renderModelProviderPage() - - expect(mockRefreshModelProviders).not.toHaveBeenCalled() }) it('should render remote source from the authoritative summary plugin entry', () => { @@ -680,7 +721,7 @@ describe('ModelProviderPage', () => { quota_configurations: [mockQuotaConfig], }, }) - mockProviderContextState.modelProviderPlugins = { + mockSummaryState.plugins = { 'langgenius/openai': { installation_id: 'openai-debug-installation', plugin_id: 'langgenius/openai', @@ -698,12 +739,10 @@ describe('ModelProviderPage', () => { 'langgenius/openai', ) expect(screen.getByTestId('provider-card')).toHaveAttribute('data-plugin-source', 'remote') - expect(mockRefreshModelProviders).not.toHaveBeenCalled() }) it('should show provider placeholders while model providers are loading', () => { - mockProviderContextState.isLoadingModelProviders = true - mockProviderContextState.isSuccessModelProviders = false + mockSummaryState.isLoading = true renderModelProviderPage() @@ -923,7 +962,7 @@ describe('ModelProviderPage', () => { }, }, ) - mockProviderContextState.modelProviderPlugins = { + mockSummaryState.plugins = { 'langgenius/debug-model': { installation_id: 'debug-installation', plugin_id: 'langgenius/debug-model', diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx index c2e6a8e7fe7..aa800e85f42 100644 --- a/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx +++ b/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx @@ -5,7 +5,7 @@ import { getStepByStepTourTargetSelector, STEP_BY_STEP_TOUR_TARGETS, } from '@/app/components/step-by-step-tour/target-registry' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { useMarketplaceAllPlugins } from '../hooks' import InstallFromMarketplace from '../install-from-marketplace' diff --git a/web/app/components/header/account-setting/model-provider-page/declarations.ts b/web/app/components/header/account-setting/model-provider-page/declarations.ts index 62a84bc953b..9f49e9a86a5 100644 --- a/web/app/components/header/account-setting/model-provider-page/declarations.ts +++ b/web/app/components/header/account-setting/model-provider-page/declarations.ts @@ -242,15 +242,6 @@ export type ModelProvider = { allow_custom_token?: boolean } -export type Model = { - provider: string - icon_small: TypeWithI18N - icon_small_dark?: TypeWithI18N - label: TypeWithI18N - models: ModelItem[] - status: ModelStatusEnum -} - export type DefaultModelResponse = { model: string model_type: ModelTypeEnum diff --git a/web/app/components/header/account-setting/model-provider-page/hooks.ts b/web/app/components/header/account-setting/model-provider-page/hooks.ts index 737bcf1aa4d..73386dc0e69 100644 --- a/web/app/components/header/account-setting/model-provider-page/hooks.ts +++ b/web/app/components/header/account-setting/model-provider-page/hooks.ts @@ -1,4 +1,7 @@ -import type { ModelType } from '@dify/contracts/api/console/workspaces/types.gen' +import type { + ModelType, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' import type { ConfigurationMethodEnum, Credential, @@ -6,7 +9,6 @@ import type { CustomModel, DefaultModel, DefaultModelResponse, - Model, ModelModalModeEnum, ModelProvider, } from './declarations' @@ -20,15 +22,15 @@ import { import { PluginCategoryEnum } from '@/app/components/plugins/types' import { useLocale } from '@/context/i18n' import { useModalContextSelector } from '@/context/modal-context' -import { consoleQuery } from '@/service/client' -import { fetchDefaultModal, fetchModelList } from '@/service/common' +import { fetchDefaultModal } from '@/service/common' +import { consoleQuery } from '@/service/console' import { commonQueryKeys, modelProviderDetailsQueryOptions } from '@/service/use-common' import { useExpandModelProviderList } from './atoms' import { CustomConfigurationStatusEnum, ModelStatusEnum, ModelTypeEnum } from './declarations' type UseDefaultModelAndModelList = ( defaultModel: DefaultModelResponse | undefined, - modelList: Model[], + modelList: ProviderWithModelsResponse[], ) => [DefaultModel | undefined, (model: DefaultModel) => void] export const useSystemDefaultModelAndModelList: UseDefaultModelAndModelList = ( defaultModel, @@ -79,26 +81,6 @@ type ModelQueryOptions = { enabled?: boolean } -export const useModelList = (type: ModelTypeEnum, { enabled = true }: ModelQueryOptions = {}) => { - const { data, refetch, isPending } = useQuery({ - queryKey: consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryKey({ - input: { - params: { - model_type: type, - }, - }, - }), - queryFn: () => fetchModelList(`/workspaces/current/models/model-types/${type}`), - enabled, - }) - - return { - data: data?.data || [], - mutate: refetch, - isLoading: isPending, - } -} - export const useDefaultModel = ( type: ModelTypeEnum, { enabled = true }: ModelQueryOptions = {}, @@ -116,10 +98,6 @@ export const useDefaultModel = ( } } -type ModelFromProvider = TProvider extends { models: Array } - ? TModel - : never - export const getCurrentProviderAndModel = < TProvider extends { models: Array<{ model: string }>; provider: string }, >( @@ -127,9 +105,9 @@ export const getCurrentProviderAndModel = < defaultModel?: DefaultModel, ) => { const currentProvider = modelList.find((provider) => provider.provider === defaultModel?.provider) - const currentModel = currentProvider?.models.find( + const currentModel: TProvider['models'][number] | undefined = currentProvider?.models.find( (model) => model.model === defaultModel?.model, - ) as ModelFromProvider | undefined + ) return { currentProvider, @@ -142,7 +120,12 @@ export { getCurrentProviderAndModel as useCurrentProviderAndModel } export const useTextGenerationCurrentProviderAndModelAndModelList = ( defaultModel?: DefaultModel, ) => { - const { data: textGenerationModelList } = useModelList(ModelTypeEnum.textGeneration) + const { data: textGenerationModelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) const activeTextGenerationModelList = textGenerationModelList.filter( (model) => model.status === ModelStatusEnum.active, ) @@ -160,7 +143,12 @@ export const useTextGenerationCurrentProviderAndModelAndModelList = ( } export const useModelListAndDefaultModel = (type: ModelTypeEnum) => { - const { data: modelList } = useModelList(type) + const { data: modelList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: type } }, + select: (response) => response.data, + }), + ) const { data: defaultModel } = useDefaultModel(type) return { diff --git a/web/app/components/header/account-setting/model-provider-page/index.tsx b/web/app/components/header/account-setting/model-provider-page/index.tsx index 097f2ab0d76..3565e3a3c19 100644 --- a/web/app/components/header/account-setting/model-provider-page/index.tsx +++ b/web/app/components/header/account-setting/model-provider-page/index.tsx @@ -1,5 +1,6 @@ import type { ModelProviderPluginSummaryResponse, + ModelProviderSummaryListResponse, ModelProviderSummaryResponse, } from '@dify/contracts/api/console/workspaces/types.gen' import type { ReactNode } from 'react' @@ -11,15 +12,17 @@ import { useTranslation } from 'react-i18next' import { SearchInput } from '@/app/components/base/search-input' import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting' import { PluginCategoryEnum } from '@/app/components/plugins/types' -import { useProviderContext } from '@/context/provider-context' import { systemFeaturesQueryOptions } from '@/features/system-features/client' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import UpdateSettingDialog from '../update-setting-dialog' import { ModelTypeEnum } from './declarations' import { useDefaultModel } from './hooks' import ModelProviderPageBody from './model-provider-page-body' import SystemModelSelector from './system-model-selector' +const EMPTY_MODEL_PROVIDERS: ModelProviderSummaryListResponse['data'] = [] +const EMPTY_MODEL_PROVIDER_PLUGINS: ModelProviderSummaryListResponse['plugins'] = {} + type SystemModelConfigStatus = | 'no-provider' | 'none-configured' @@ -68,11 +71,11 @@ const ModelProviderPage = ({ ModelTypeEnum.tts, defaultModelQueryOptions, ) - const { - modelProviders: providers, - modelProviderPlugins = {}, - isLoadingModelProviders, - } = useProviderContext() + const { data: providerSummary, isLoading: isLoadingModelProviders } = useQuery( + consoleQuery.workspaces.current.modelProviders.summary.get.queryOptions(), + ) + const providers = providerSummary?.data ?? EMPTY_MODEL_PROVIDERS + const modelProviderPlugins = providerSummary?.plugins ?? EMPTY_MODEL_PROVIDER_PLUGINS const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions()) const marketplacePluginIds = useMemo( diff --git a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx index 21d7b5e9fbb..9bf467f009d 100644 --- a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx +++ b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx @@ -12,7 +12,7 @@ import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/us import ProviderCard from '@/app/components/plugins/provider-card' import { PluginCategoryEnum } from '@/app/components/plugins/types' import Link from '@/next/link' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useMarketplaceAllPlugins } from './hooks' type InstallFromMarketplaceProps = { diff --git a/web/app/components/header/account-setting/model-provider-page/model-icon/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-icon/index.tsx index 5302f0aaa8b..72f9ea032c5 100644 --- a/web/app/components/header/account-setting/model-provider-page/model-icon/index.tsx +++ b/web/app/components/header/account-setting/model-provider-page/model-icon/index.tsx @@ -1,6 +1,9 @@ -import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen' +import type { + ModelProviderSummaryResponse, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' import type { FC } from 'react' -import type { Model, ModelProvider } from '../declarations' +import type { ModelProvider } from '../declarations' import type { ModelSelectorProvider } from '../model-selector/types' import { cn } from '@langgenius/dify-ui/cn' import { OpenaiYellow } from '@/app/components/base/icons/src/public/llm' @@ -10,7 +13,11 @@ import { Theme } from '@/types/app' import { useLanguage } from '../hooks' type ModelIconProps = { - provider?: Model | ModelProvider | ModelProviderSummaryResponse | ModelSelectorProvider + provider?: + | ProviderWithModelsResponse + | ModelProvider + | ModelProviderSummaryResponse + | ModelSelectorProvider modelName?: string className?: string iconClassName?: string diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsx index 3be0d8210e0..5da62eb4c50 100644 --- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsx +++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsx @@ -41,12 +41,6 @@ let activeTextGenerationModelList: Array> = [ }, ] -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - isAPIKeySet: true, - }), -})) - vi.mock('@/service/use-common', () => ({ useModelParameterRules: () => ({ data: { diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx index 2a3878ccfb6..45084128556 100644 --- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx +++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx @@ -1,15 +1,20 @@ -import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen' +import type { + ModelProviderSummaryResponse, + ProviderModelWithStatusEntity, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' import type { ReactNode } from 'react' -import type { Model, ModelItem } from '../../declarations' import { QueryClientProvider } from '@tanstack/react-query' import { fireEvent, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createConsoleQueryClient } from '@/test/console/query-data' import { ConfigurationMethodEnum, ModelStatusEnum, ModelTypeEnum } from '../../declarations' import { ModelSelector, SplitModelSelector } from '../index' -const makeModelItem = (overrides: Partial = {}): ModelItem => ({ +const makeModelItem = ( + overrides: Partial = {}, +): ProviderModelWithStatusEntity => ({ model: 'gpt-4', label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' }, model_type: ModelTypeEnum.textGeneration, @@ -20,7 +25,7 @@ const makeModelItem = (overrides: Partial = {}): ModelItem => ({ ...overrides, }) -const mockModelProviders = vi.hoisted(() => ({ current: [] as Model[] })) +const mockModelProviders = vi.hoisted(() => ({ current: [] as ProviderWithModelsResponse[] })) const mockSetSettingsDestination = vi.hoisted(() => vi.fn()) vi.mock('nuqs', async (importOriginal) => { @@ -31,9 +36,6 @@ vi.mock('nuqs', async (importOriginal) => { } }) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ modelProviders: mockModelProviders.current }), -})) vi.mock('../../provider-added-card/use-credential-panel-state', () => ({ useCredentialPanelState: () => ({ variant: 'credits-active', @@ -58,7 +60,7 @@ vi.mock('../popup', () => { onConfigureEmptyState?: () => void onHide: () => void onOpenProviderSettings?: () => void - onSelect: (provider: string, model: ModelItem) => void + onSelect: (provider: string, model: ProviderModelWithStatusEntity) => void }) => ( <> + + + ) +} + +function TrendingCard({ + banner, + card, + isMarketplacePlatform, + page, +}: { + banner: BannerRecommend + card: BannerRecommendCard + isMarketplacePlatform: boolean + page: MarketplaceBannerPage +}) { + const embeddedPlugin = isMarketplacePlatform ? null : pluginFromRecommendCard(card) + if (embeddedPlugin) { + return ( + + ) + } + + const href = getCardHref(card, isMarketplacePlatform) + if (!href) return null + const opensInNewTab = !isMarketplacePlatform && /^https?:\/\//.test(href) + + return ( + { + trackRecommendCardClick(banner, card, page, href) + }} + className={recommendCardClassName} + > + ) } diff --git a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx index 96aadc24f8d..3fd90d4366e 100644 --- a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx +++ b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx @@ -26,7 +26,7 @@ import { useEffect, useRef, useState } from 'react' import { useTranslation } from '#i18n' import { MARKETPLACE_API_PREFIX } from '@/config' import { renderI18nObject } from '@/i18n-config/index' -import { marketplaceQuery } from '@/service/client' +import { marketplaceQuery } from '@/service/marketplace' import { markMarketplaceSiteSearch } from '@/utils/marketplace-site-track' import { getPluginDetailLinkInMarketplace, diff --git a/web/app/components/plugins/marketplace/list/__tests__/search-results-layout.browser.spec.tsx b/web/app/components/plugins/marketplace/list/__tests__/search-results-layout.browser.spec.tsx new file mode 100644 index 00000000000..259bca8c64e --- /dev/null +++ b/web/app/components/plugins/marketplace/list/__tests__/search-results-layout.browser.spec.tsx @@ -0,0 +1,55 @@ +import type { Plugin } from '@/app/components/plugins/types' +import { page } from 'vite-plus/test/browser' +import { render } from 'vitest-browser-react' +import List from '../index' + +vi.mock('@/app/components/plugins/install-plugin/hooks/use-check-installed', () => ({ + default: () => ({ installedInfo: {} }), +})) + +const plugins = Array.from({ length: 5 }, (_, index) => ({ + plugin_id: `publisher/plugin-${index}`, + org: 'publisher', + name: `Plugin ${index + 1}`, +})) as Plugin[] + +describe('Marketplace search result layout', () => { + // Native grid layout determines whether the result cards remain readable; + // happy-dom cannot reproduce the four 75px columns seen on mobile. + it.each([ + { viewportWidth: 390, columns: 1 }, + { viewportWidth: 1280, columns: 4 }, + ])('keeps readable cards at $viewportWidth px', async ({ viewportWidth, columns }) => { + await page.viewport(viewportWidth, 844) + const screen = await render( + , + ) + + const first = screen.getByRole('link', { name: 'Plugin 1' }).element().getBoundingClientRect() + const nextRow = screen + .getByRole('link', { name: `Plugin ${columns + 1}` }) + .element() + .getBoundingClientRect() + + expect(first.width).toBeGreaterThanOrEqual(250) + expect(nextRow.top).toBeGreaterThanOrEqual(first.bottom) + if (columns > 1) { + const lastInRow = screen + .getByRole('link', { name: `Plugin ${columns}` }) + .element() + .getBoundingClientRect() + expect(lastInRow.top).toBe(first.top) + } + }) +}) diff --git a/web/app/components/plugins/marketplace/list/index.tsx b/web/app/components/plugins/marketplace/list/index.tsx index f6d94dddc0c..eec7c9d7577 100644 --- a/web/app/components/plugins/marketplace/list/index.tsx +++ b/web/app/components/plugins/marketplace/list/index.tsx @@ -8,6 +8,7 @@ import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use import { useOptionalPluginInstallPermission } from '@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission' import Empty from '../empty' import CardWrapper from './card-wrapper' +import { GRID_CLASS } from './collection-constants' import ListWithCollection from './list-with-collection' type ListProps = { @@ -77,7 +78,7 @@ const List = ({ /> )} {plugins && !!plugins.length && ( -
+
{plugins.map((plugin) => { if (cardRender) return cardRender(plugin) diff --git a/web/app/components/plugins/marketplace/prefetch-marketplace-dehydrated-state.ts b/web/app/components/plugins/marketplace/prefetch-marketplace-dehydrated-state.ts index 8ccfad85fe3..08d3774ba46 100644 --- a/web/app/components/plugins/marketplace/prefetch-marketplace-dehydrated-state.ts +++ b/web/app/components/plugins/marketplace/prefetch-marketplace-dehydrated-state.ts @@ -3,7 +3,7 @@ import type { MarketplaceSearchParams } from './search-params' import { dehydrate, noop } from '@tanstack/react-query' import { createLoader } from 'nuqs/server' import { getQueryClient } from '@/app/get-query-client' -import { marketplaceQuery } from '@/service/client' +import { marketplaceQuery } from '@/service/marketplace' import { PLUGIN_CATEGORY_WITH_COLLECTIONS } from './constants' import { getMarketplacePluginsInfiniteQueryOptions } from './query-options' import { diff --git a/web/app/components/plugins/marketplace/query-options.ts b/web/app/components/plugins/marketplace/query-options.ts index c9a8f5ba8ac..a8761440953 100644 --- a/web/app/components/plugins/marketplace/query-options.ts +++ b/web/app/components/plugins/marketplace/query-options.ts @@ -1,6 +1,6 @@ import type { PluginsSearchParams } from '@dify/contracts/marketplace' import { infiniteQueryOptions, keepPreviousData } from '@tanstack/react-query' -import { marketplaceQuery } from '@/service/client' +import { marketplaceQuery } from '@/service/marketplace' import { getMarketplacePlugins } from './utils' export const getMarketplacePluginsInfiniteQueryOptions = ( @@ -26,7 +26,9 @@ export const getMarketplacePluginsInfiniteQueryOptions = ( // the grid unmounts, the container collapses, and the scroll position jumps — // the "jitter" the Marketplace search is reported for. Consumers show a // quiet pending state off `isPlaceholderData` instead. - placeholderData: keepPreviousData, + // Returning to collections disables search; keeping its placeholder then + // leaves the last category visible and permanently marked as refreshing. + placeholderData: queryParams === undefined ? undefined : keepPreviousData, // Matches the autocomplete queries. Now that the fetcher propagates // failures, react-query's default of 3 retries would hold isFetching true // through ~7s of backoff — indistinguishable from a hang. Failing fast and diff --git a/web/app/components/plugins/marketplace/query.ts b/web/app/components/plugins/marketplace/query.ts index 17195d20efc..af10ed6de10 100644 --- a/web/app/components/plugins/marketplace/query.ts +++ b/web/app/components/plugins/marketplace/query.ts @@ -1,6 +1,6 @@ import type { MarketPlaceInputs, PluginsSearchParams } from '@dify/contracts/marketplace' import { useInfiniteQuery, useQuery } from '@tanstack/react-query' -import { marketplaceQuery } from '@/service/client' +import { marketplaceQuery } from '@/service/marketplace' import { getMarketplacePluginsInfiniteQueryOptions } from './query-options' import { getMarketplaceCollectionsAndPlugins } from './utils' diff --git a/web/app/components/plugins/marketplace/utils.ts b/web/app/components/plugins/marketplace/utils.ts index 5f1462e06e2..a55bbc59baf 100644 --- a/web/app/components/plugins/marketplace/utils.ts +++ b/web/app/components/plugins/marketplace/utils.ts @@ -8,7 +8,7 @@ import type { ActivePluginType } from './constants' import type { Plugin } from '@/app/components/plugins/types' import { PluginCategoryEnum } from '@/app/components/plugins/types' import { MARKETPLACE_API_PREFIX } from '@/config' -import { marketplaceClient } from '@/service/client' +import { marketplaceClient } from '@/service/marketplace' import { getMarketplaceUrl } from '@/utils/var' import { PLUGIN_TYPE_SEARCH_MAP } from './constants' diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsx index 1427c7c15f2..33b4a425a17 100644 --- a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsx +++ b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsx @@ -42,7 +42,7 @@ const apps = [ const mockAppDetailQuery = vi.hoisted(() => vi.fn()) const mockUseAppWorkflow = vi.hoisted(() => vi.fn()) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { apps: { get: { diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.ts b/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.ts index 38535e5635f..de3fa4869a6 100644 --- a/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.ts +++ b/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.ts @@ -9,7 +9,7 @@ import { useQuery } from '@tanstack/react-query' import { useMemo } from 'react' import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants' import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useFileUploadConfig } from '@/service/use-common' import { useAppWorkflow } from '@/service/use-workflow' import { AppModeEnum, Resolution } from '@/types/app' diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/index.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/index.tsx index d0cf2bc5f7a..f9271c971e2 100644 --- a/web/app/components/plugins/plugin-detail-panel/app-selector/index.tsx +++ b/web/app/components/plugins/plugin-detail-panel/app-selector/index.tsx @@ -9,7 +9,7 @@ import { useTranslation } from 'react-i18next' import AppInputsPanel from '@/app/components/plugins/plugin-detail-panel/app-selector/app-inputs-panel' import { AppPicker } from '@/app/components/plugins/plugin-detail-panel/app-selector/app-picker' import { AppTrigger } from '@/app/components/plugins/plugin-detail-panel/app-selector/app-trigger' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' const PAGE_SIZE = 20 diff --git a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx index 598c9471a21..851ef468771 100644 --- a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx +++ b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx @@ -1,7 +1,9 @@ import type { - Model, - ModelItem, -} from '@/app/components/header/account-setting/model-provider-page/declarations' + GetWorkspacesCurrentModelsModelTypesByModelTypeData, + ProviderModelWithStatusEntity, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' +import type { OperationKey } from '@orpc/tanstack-query' import { fireEvent, render, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' @@ -33,42 +35,14 @@ vi.mock('@langgenius/dify-ui/toast', () => ({ })) // Mock provider context -const mockProviderContextValue = { - isAPIKeySet: true, - modelProviders: [], -} -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockProviderContextValue, -})) // Mock model list hook -const mockTextGenerationList: Model[] = [] -const mockTextEmbeddingList: Model[] = [] -const mockRerankList: Model[] = [] -const mockModerationList: Model[] = [] -const mockSttList: Model[] = [] -const mockTtsList: Model[] = [] - -vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({ - useModelList: (type: ModelTypeEnum) => { - switch (type) { - case ModelTypeEnum.textGeneration: - return { data: mockTextGenerationList } - case ModelTypeEnum.textEmbedding: - return { data: mockTextEmbeddingList } - case ModelTypeEnum.rerank: - return { data: mockRerankList } - case ModelTypeEnum.moderation: - return { data: mockModerationList } - case ModelTypeEnum.speech2text: - return { data: mockSttList } - case ModelTypeEnum.tts: - return { data: mockTtsList } - default: - return { data: [] } - } - }, -})) +const mockTextGenerationList: ProviderWithModelsResponse[] = [] +const mockTextEmbeddingList: ProviderWithModelsResponse[] = [] +const mockRerankList: ProviderWithModelsResponse[] = [] +const mockModerationList: ProviderWithModelsResponse[] = [] +const mockSttList: ProviderWithModelsResponse[] = [] +const mockTtsList: ProviderWithModelsResponse[] = [] // Mock fetchAndMergeValidCompletionParams const mockFetchAndMergeValidCompletionParams = vi.fn() @@ -88,7 +62,7 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-selec onValueChange, }: { value?: { provider?: string; model?: string } - models?: Model[] + models?: ProviderWithModelsResponse[] scopeFeatures?: string[] surface?: 'default' | 'workflow' disabled?: boolean @@ -163,7 +137,7 @@ vi.mock('../tts-params-panel', () => ({ voice, onChange, }: { - currentModel?: ModelItem + currentModel?: ProviderModelWithStatusEntity language?: string voice?: string onChange?: (language: string, voice: string) => void @@ -183,9 +157,11 @@ vi.mock('../tts-params-panel', () => ({ // ==================== Test Utilities ==================== /** - * Factory function to create a ModelItem with defaults + * Factory function to create a ProviderModelWithStatusEntity with defaults */ -const createModelItem = (overrides: Partial = {}): ModelItem => ({ +const createModelItem = ( + overrides: Partial = {}, +): ProviderModelWithStatusEntity => ({ model: 'test-model', label: { en_US: 'Test Model', zh_Hans: 'Test Model' }, model_type: ModelTypeEnum.textGeneration, @@ -198,9 +174,12 @@ const createModelItem = (overrides: Partial = {}): ModelItem => ({ }) /** - * Factory function to create a Model (provider with models) with defaults + * Factory function to create a ProviderWithModelsResponse (provider with models) with defaults */ -const createModel = (overrides: Partial = {}): Model => ({ +const createModel = ( + overrides: Partial = {}, +): ProviderWithModelsResponse => ({ + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: 'icon-small.png', zh_Hans: 'icon-small.png' }, label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' }, @@ -226,12 +205,12 @@ const createDefaultProps = ( */ const setupModelLists = ( config: { - textGeneration?: Model[] - textEmbedding?: Model[] - rerank?: Model[] - moderation?: Model[] - stt?: Model[] - tts?: Model[] + textGeneration?: ProviderWithModelsResponse[] + textEmbedding?: ProviderWithModelsResponse[] + rerank?: ProviderWithModelsResponse[] + moderation?: ProviderWithModelsResponse[] + stt?: ProviderWithModelsResponse[] + tts?: ProviderWithModelsResponse[] } = {}, ) => { mockTextGenerationList.length = 0 @@ -257,8 +236,6 @@ describe('ModelParameterModal', () => { beforeEach(() => { vi.clearAllMocks() - mockProviderContextValue.isAPIKeySet = true - mockProviderContextValue.modelProviders = [] setupModelLists() mockFetchAndMergeValidCompletionParams.mockResolvedValue({ params: {}, removedDetails: {} }) }) @@ -674,7 +651,6 @@ describe('ModelParameterModal', () => { describe('Memoization - disabled', () => { it('should keep active TTS model settings available without an active text generation model', async () => { const user = userEvent.setup() - mockProviderContextValue.isAPIKeySet = false const ttsModel = createModel({ provider: 'tts-provider', models: [ @@ -707,7 +683,6 @@ describe('ModelParameterModal', () => { it('should keep model selection available when isAPIKeySet is false', () => { // Arrange - mockProviderContextValue.isAPIKeySet = false const model = createModel({ provider: 'openai', models: [createModelItem({ model: 'gpt-4', status: ModelStatusEnum.active })], @@ -751,7 +726,6 @@ describe('ModelParameterModal', () => { it('should set disabled to false when all conditions are met', () => { // Arrange - mockProviderContextValue.isAPIKeySet = true const model = createModel({ provider: 'openai', models: [createModelItem({ model: 'gpt-4', status: ModelStatusEnum.active })], @@ -1344,14 +1318,12 @@ describe('ModelParameterModal', () => { models: [createModelItem({ model: 'gpt-4', status: ModelStatusEnum.active })], }) setupModelLists({ textGeneration: [model] }) - mockProviderContextValue.isAPIKeySet = true const props = createDefaultProps({ value: { provider: 'openai', model: 'gpt-4' } }) // Act const { rerender } = render() expect(screen.getByTestId('trigger')).toHaveAttribute('data-disabled', 'false') - mockProviderContextValue.isAPIKeySet = false rerender() // Assert @@ -1374,3 +1346,37 @@ describe('ModelParameterModal', () => { }) }) }) + +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useQuery: (options: { + queryKey: OperationKey< + 'query', + { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] } + > + }) => { + if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options) + + const type = options.queryKey[1].input?.params?.model_type + if (!type) throw new Error('Missing model type in query') + switch (type) { + case ModelTypeEnum.textGeneration: + return { data: mockTextGenerationList } + case ModelTypeEnum.textEmbedding: + return { data: mockTextEmbeddingList } + case ModelTypeEnum.rerank: + return { data: mockRerankList } + case ModelTypeEnum.moderation: + return { data: mockModerationList } + case ModelTypeEnum.speech2text: + return { data: mockSttList } + case ModelTypeEnum.tts: + return { data: mockTtsList } + default: + return { data: [] } + } + }, + } +}) diff --git a/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx b/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx index 2940b791b7c..f19ffcb8ac3 100644 --- a/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx +++ b/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx @@ -7,15 +7,16 @@ import type { ModelSelectorValue } from '@/app/components/header/account-setting import { cn } from '@langgenius/dify-ui/cn' import { Popover, PopoverContent } from '@langgenius/dify-ui/popover' import { toast } from '@langgenius/dify-ui/toast' +import { useQuery } from '@tanstack/react-query' import { useMemo, useState } from 'react' import { useTranslation } from 'react-i18next' import { ModelStatusEnum, ModelTypeEnum, } from '@/app/components/header/account-setting/model-provider-page/declarations' -import { useModelList } from '@/app/components/header/account-setting/model-provider-page/hooks' import { ModelSettingsTrigger } from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/model-settings-trigger' import { SplitModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector' +import { consoleQuery } from '@/service/console' import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params' import LLMParamsPanel from './llm-params-panel' import TTSParamsPanel from './tts-params-panel' @@ -69,12 +70,42 @@ const ModelParameterModal: FC = ({ .map((item) => item as ModelFeatureEnum) }, [scopeArray]) - const { data: textGenerationList } = useModelList(ModelTypeEnum.textGeneration) - const { data: textEmbeddingList } = useModelList(ModelTypeEnum.textEmbedding) - const { data: rerankList } = useModelList(ModelTypeEnum.rerank) - const { data: moderationList } = useModelList(ModelTypeEnum.moderation) - const { data: sttList } = useModelList(ModelTypeEnum.speech2text) - const { data: ttsList } = useModelList(ModelTypeEnum.tts) + const { data: textGenerationList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textGeneration } }, + select: (response) => response.data, + }), + ) + const { data: textEmbeddingList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.textEmbedding } }, + select: (response) => response.data, + }), + ) + const { data: rerankList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.rerank } }, + select: (response) => response.data, + }), + ) + const { data: moderationList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.moderation } }, + select: (response) => response.data, + }), + ) + const { data: sttList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.speech2text } }, + select: (response) => response.data, + }), + ) + const { data: ttsList = [] } = useQuery( + consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({ + input: { params: { model_type: ModelTypeEnum.tts } }, + select: (response) => response.data, + }), + ) const scopedModelList = useMemo(() => { if (scopeArray.includes('all')) { diff --git a/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx index 22bd2bcd60d..4819938e550 100644 --- a/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx +++ b/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx @@ -28,7 +28,7 @@ vi.mock('next-themes', () => ({ useTheme: () => ({ theme: 'light' }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { workspaces: { current: { diff --git a/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx b/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx index d848c5a8168..e28ba2cfc82 100644 --- a/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx +++ b/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx @@ -17,7 +17,7 @@ import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/ import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting' import ProviderCard from '@/app/components/plugins/provider-card' import Link from '@/next/link' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { getCategoryMarketplaceId } from './category-marketplace' const MARKETPLACE_PAGE_SIZE = 30 diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx index e57afa364d1..99b3ea417ab 100644 --- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx +++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx @@ -4,7 +4,7 @@ import { act, fireEvent, screen, waitFor } from '@testing-library/react' import * as React from 'react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' import { seedAccountProfileQuery } from '@/test/console/account-profile' -import { seedSystemFeatures } from '@/test/console/query-data' +import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data' import { render } from '@/test/console/render' import Publisher from '../index' import { Popup } from '../popup' @@ -126,20 +126,7 @@ vi.mock('@/context/modal-context', () => ({ ): T => selector({ setShowPricingModal: mockSetShowPricingModal }), })) -const mockIsAllowPublishAsCustomKnowledgePipelineTemplate = vi.fn(() => true) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - isAllowPublishAsCustomKnowledgePipelineTemplate: - mockIsAllowPublishAsCustomKnowledgePipelineTemplate(), - }), - useProviderContextSelector: ( - selector: (s: { isAllowPublishAsCustomKnowledgePipelineTemplate: boolean }) => T, - ): T => - selector({ - isAllowPublishAsCustomKnowledgePipelineTemplate: - mockIsAllowPublishAsCustomKnowledgePipelineTemplate(), - }), -})) +let publishEnabled = true const toastMocks = vi.hoisted(() => ({ call: vi.fn(), @@ -246,6 +233,7 @@ const createQueryClient = () => defaultOptions: { queries: { retry: false, + staleTime: Infinity, }, }, }) @@ -254,6 +242,7 @@ const renderWithQueryClient = (ui: React.ReactElement) => { const queryClient = createQueryClient() seedAccountProfileQuery(queryClient, { id: 'user-1' }) seedSystemFeatures(queryClient, { deployment_edition: 'CLOUD' }) + seedFeatures(queryClient, { knowledge_pipeline: { publish_enabled: publishEnabled } }) return render({ui}) } @@ -265,7 +254,7 @@ describe('publisher', () => { mockPublishedAt.mockReturnValue(null) mockDraftUpdatedAt.mockReturnValue(1700000000) mockPipelineId.mockReturnValue('test-pipeline-id') - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true) + publishEnabled = true mockHandleCheckBeforePublish.mockResolvedValue(true) mockDatasetPermissionKeys = ['dataset.acl.use'] mockDatasetMaintainer = undefined @@ -360,7 +349,7 @@ describe('publisher', () => { it('should close the outer popover before opening publish-as follow-up flow', async () => { mockPublishedAt.mockReturnValue(1700000000) - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false) + publishEnabled = false renderWithQueryClient() fireEvent.click(screen.getByText('workflow.common.publish')) @@ -429,7 +418,7 @@ describe('publisher', () => { it('should show premium badge when publish as template is not allowed', () => { mockPublishedAt.mockReturnValue(1700000000) - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false) + publishEnabled = false renderWithQueryClient() @@ -438,7 +427,7 @@ describe('publisher', () => { it('should not show premium badge when publish as template is allowed', () => { mockPublishedAt.mockReturnValue(1700000000) - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true) + publishEnabled = true renderWithQueryClient() @@ -500,7 +489,7 @@ describe('publisher', () => { it('should show pricing modal when publish as template is clicked without permission', async () => { mockPublishedAt.mockReturnValue(1700000000) - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false) + publishEnabled = false renderWithQueryClient() const publishAsButton = screen @@ -513,7 +502,7 @@ describe('publisher', () => { it('should show publish as knowledge pipeline modal when permitted', async () => { mockPublishedAt.mockReturnValue(1700000000) - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true) + publishEnabled = true renderWithQueryClient() fireEvent.click(screen.getByText('workflow.common.publish')) @@ -530,7 +519,7 @@ describe('publisher', () => { it('should close publish as knowledge pipeline modal when cancel is clicked', async () => { mockPublishedAt.mockReturnValue(1700000000) - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true) + publishEnabled = true renderWithQueryClient() fireEvent.click(screen.getByText('workflow.common.publish')) @@ -851,7 +840,7 @@ describe('publisher', () => { describe('Prop Variations', () => { it('should display correct width when permission is allowed', () => { - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true) + publishEnabled = true const { container } = renderWithQueryClient() const popupDiv = container.firstChild as HTMLElement @@ -859,7 +848,7 @@ describe('publisher', () => { }) it('should display correct width when permission is not allowed', () => { - mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false) + publishEnabled = false const { container } = renderWithQueryClient() const popupDiv = container.firstChild as HTMLElement diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx index 88d1aefb459..0a7c4dfabd0 100644 --- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx +++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx @@ -4,9 +4,12 @@ import { createConsoleQueryWrapper } from '@/test/console/query-data' import { render as renderWithConsoleState } from '@/test/console/render' import { Popup } from '../popup' +let mockIsAllowPublishAsCustom = true + const render = (ui: React.ReactElement) => { const { wrapper } = createConsoleQueryWrapper({ systemFeatures: { deployment_edition: 'CLOUD' }, + features: { knowledge_pipeline: { publish_enabled: mockIsAllowPublishAsCustom } }, }) return renderWithConsoleState(ui, { wrapper }) } @@ -50,7 +53,6 @@ const mockInvalidCustomizedTemplateList = vi.fn() let mockPublishedAt: string | undefined = '2024-01-01T00:00:00Z' let mockDraftUpdatedAt: string | undefined = '2024-06-01T00:00:00Z' let mockPipelineId: string | undefined = 'pipeline-123' -let mockIsAllowPublishAsCustom = true let mockDatasetPermissionKeys = ['dataset.acl.use'] let mockDatasetMaintainer: string | undefined let mockCurrentUserId = 'user-1' @@ -154,10 +156,6 @@ vi.mock('@/context/modal-context', () => ({ ) => selector({ setShowPricingModal: mockSetShowPricingModal }), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContextSelector: () => mockIsAllowPublishAsCustom, -})) - vi.mock('@/hooks/use-api-access-url', () => ({ useDatasetApiAccessUrl: () => '/api/datasets/ds-123', })) diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx index 73158b9790a..48321d393ea 100644 --- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx +++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx @@ -14,7 +14,7 @@ import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd' import { toast } from '@langgenius/dify-ui/toast' import { RiArrowRightUpLine, RiPlayCircleLine, RiTerminalBoxLine } from '@remixicon/react' import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys' -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' import { useBoolean } from 'ahooks' import { useAtomValue } from 'jotai' import { useCallback, useState } from 'react' @@ -31,13 +31,13 @@ import { workspacePermissionKeysAtom, workspacePermissionKeysLoadingAtom, } from '@/context/permission-state' -import { useProviderContextSelector } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' import { systemFeaturesQueryOptions } from '@/features/system-features/client' import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url' import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now' import Link from '@/next/link' import { useParams } from '@/next/navigation' +import { consoleQuery } from '@/service/console' import { useInvalidDatasetList } from '@/service/knowledge/use-dataset' import { useInvalid } from '@/service/use-base' import { publishedPipelineInfoQueryKeyPrefix } from '@/service/use-pipeline' @@ -84,8 +84,10 @@ export function Popup({ const { handleCheckBeforePublish } = useChecklistBeforePublish() const { mutateAsync: publishWorkflow } = usePublishWorkflow() const workflowStore = useWorkflowStore() - const isAllowPublishAsCustomKnowledgePipelineTemplate = useProviderContextSelector( - (s) => s.isAllowPublishAsCustomKnowledgePipelineTemplate, + const { data: isAllowPublishAsCustomKnowledgePipelineTemplate } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.knowledge_pipeline.publish_enabled, + }), ) const setShowPricingModal = useModalContextSelector((s) => s.setShowPricingModal) const apiReferenceUrl = useDatasetApiAccessUrl() @@ -195,6 +197,8 @@ export function Popup({ preventDefault: true, }) const handleClickPublishAsKnowledgePipeline = useCallback(() => { + if (isAllowPublishAsCustomKnowledgePipelineTemplate === undefined) return + onRequestClose?.() if (!isAllowPublishAsCustomKnowledgePipelineTemplate) { if (deploymentEdition === 'CLOUD') setShowPricingModal() @@ -318,7 +322,11 @@ export function Popup({ className="w-full hover:bg-state-accent-hover hover:text-text-accent" variant="tertiary" onClick={handleClickPublishAsKnowledgePipeline} - disabled={!publishedAt || isPublishingAsCustomizedPipeline} + disabled={ + isAllowPublishAsCustomKnowledgePipelineTemplate === undefined || + !publishedAt || + isPublishingAsCustomizedPipeline + } >
@@ -328,17 +336,18 @@ export function Popup({ > {t(($) => $['common.publishAs'], { ns: 'pipeline' })} - {deploymentEdition === 'CLOUD' && !isAllowPublishAsCustomKnowledgePipelineTemplate && ( - - - )} + {deploymentEdition === 'CLOUD' && + isAllowPublishAsCustomKnowledgePipelineTemplate === false && ( + + + )}
diff --git a/web/app/components/snippet-list/__tests__/index.spec.tsx b/web/app/components/snippet-list/__tests__/index.spec.tsx index 758ecbcc5c5..23bf6333ca1 100644 --- a/web/app/components/snippet-list/__tests__/index.spec.tsx +++ b/web/app/components/snippet-list/__tests__/index.spec.tsx @@ -52,7 +52,7 @@ vi.mock('../hooks/use-snippets-query-state', () => ({ }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { systemFeatures: vi.fn(), }, @@ -77,7 +77,6 @@ vi.mock('@/service/client', () => ({ }, })) -const mockIsCurrentWorkspaceEditor = vi.fn(() => true) const mockIsCurrentWorkspaceDatasetOperator = vi.fn(() => false) const mockWorkspacePermissionKeys = vi.fn(() => ['snippets.create_and_modify']) @@ -263,7 +262,6 @@ describe('SnippetList', () => { mockQueryState.tagIDs = [] mockQueryState.keywords = '' mockQueryState.creatorIDs = [] - mockIsCurrentWorkspaceEditor.mockReturnValue(true) mockIsCurrentWorkspaceDatasetOperator.mockReturnValue(false) mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify']) mockUseInfiniteSnippetList.mockReturnValue({ @@ -428,8 +426,7 @@ describe('SnippetList', () => { expect(within(list).getByText('workflow.tabs.noSnippetsFound')).toBeInTheDocument() }) - it('shows the create button for users with snippet create permission even when they are not workspace editors', () => { - mockIsCurrentWorkspaceEditor.mockReturnValue(false) + it('shows the create button for users with snippet create permission', () => { mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify']) renderList() diff --git a/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsx b/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsx index 629c80c43ae..ce4d1497752 100644 --- a/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsx +++ b/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsx @@ -70,7 +70,7 @@ vi.mock('@/features/account-profile/client', () => ({ }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { snippets: { bySnippetId: { diff --git a/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx b/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx index d4d824a6c9d..5b36d04c8e1 100644 --- a/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx +++ b/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx @@ -9,7 +9,6 @@ const { mockExportMutateAsync, mockOnRefresh, mockRenderTagSelector, - mockIsCurrentWorkspaceEditor, mockWorkspacePermissionKeys, mockToastError, mockToastSuccess, @@ -18,7 +17,6 @@ const { mockDeleteMutate: vi.fn(), mockDownloadBlob: vi.fn(), mockExportMutateAsync: vi.fn(), - mockIsCurrentWorkspaceEditor: vi.fn(() => true), mockWorkspacePermissionKeys: vi.fn(() => ['snippets.create_and_modify', 'snippets.management']), mockOnRefresh: vi.fn(), mockRenderTagSelector: vi.fn(), @@ -30,14 +28,12 @@ const { vi.mock('@/context/workspace-state', async () => { const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture') return createWorkspaceStateModuleMock(() => ({ - isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor(), workspacePermissionKeys: mockWorkspacePermissionKeys(), })) }) vi.mock('@/context/permission-state', async () => { const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture') return createPermissionStateModuleMock(() => ({ - isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor(), workspacePermissionKeys: mockWorkspacePermissionKeys(), })) }) @@ -146,7 +142,6 @@ const createSnippet = (overrides: Partial = {}): SnippetListIte describe('SnippetCard', () => { beforeEach(() => { vi.clearAllMocks() - mockIsCurrentWorkspaceEditor.mockReturnValue(true) mockWorkspacePermissionKeys.mockReturnValue([ 'snippets.create_and_modify', 'snippets.management', @@ -222,7 +217,6 @@ describe('SnippetCard', () => { }) it('should show edit info with create-and-modify permission without management actions', async () => { - mockIsCurrentWorkspaceEditor.mockReturnValue(false) mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify']) render() @@ -245,7 +239,6 @@ describe('SnippetCard', () => { }) it('should show delete with snippet management permission without create-and-modify actions', async () => { - mockIsCurrentWorkspaceEditor.mockReturnValue(false) mockWorkspacePermissionKeys.mockReturnValue(['snippets.management']) render() diff --git a/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx b/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx index f61422e78a0..e9feb419425 100644 --- a/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx +++ b/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx @@ -57,7 +57,7 @@ vi.mock('@/service/use-snippets', () => ({ }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { snippets: { bySnippetId: { diff --git a/web/app/components/snippets/components/hooks/use-snippet-publish.ts b/web/app/components/snippets/components/hooks/use-snippet-publish.ts index c4d208d8cec..caa91089acd 100644 --- a/web/app/components/snippets/components/hooks/use-snippet-publish.ts +++ b/web/app/components/snippets/components/hooks/use-snippet-publish.ts @@ -5,7 +5,7 @@ import { useCallback } from 'react' import { useTranslation } from 'react-i18next' import { useChecklistBeforePublish } from '@/app/components/workflow/hooks/use-checklist' import { useWorkflowStore } from '@/app/components/workflow/store' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { usePublishSnippetWorkflowMutation } from '@/service/use-snippet-workflows' import { useResetWorkflowVersionHistory } from '@/service/use-workflow' diff --git a/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsx b/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsx index 4492464aaeb..4afcc49a849 100644 --- a/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsx +++ b/web/app/components/snippets/hooks/__tests__/use-create-snippet.spec.tsx @@ -30,7 +30,7 @@ vi.mock('@/service/use-snippets', () => ({ }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { snippets: { bySnippetId: { diff --git a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts index 3b1d4658c32..5a328dff6fe 100644 --- a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts +++ b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts @@ -58,7 +58,7 @@ vi.mock('@/app/components/workflow/store', () => ({ }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { snippets: { bySnippetId: { diff --git a/web/app/components/snippets/hooks/use-create-snippet.ts b/web/app/components/snippets/hooks/use-create-snippet.ts index 1e85eafbbb8..4d60e782db5 100644 --- a/web/app/components/snippets/hooks/use-create-snippet.ts +++ b/web/app/components/snippets/hooks/use-create-snippet.ts @@ -5,7 +5,7 @@ import { useState } from 'react' import { useTranslation } from 'react-i18next' import { workspacePermissionKeysAtom } from '@/context/permission-state' import { useRouter } from '@/next/navigation' -import { consoleClient } from '@/service/client' +import { consoleClient } from '@/service/console' import { useCreateSnippetMutation } from '@/service/use-snippets' import { canCreateAndModifySnippets } from '../utils/permission' diff --git a/web/app/components/snippets/hooks/use-nodes-sync-draft.ts b/web/app/components/snippets/hooks/use-nodes-sync-draft.ts index 80c7767392f..f3b69a03755 100644 --- a/web/app/components/snippets/hooks/use-nodes-sync-draft.ts +++ b/web/app/components/snippets/hooks/use-nodes-sync-draft.ts @@ -11,7 +11,7 @@ import { useStoreApi } from 'reactflow' import { useNodesReadOnlyByCanEdit } from '@/app/components/workflow/hooks/use-workflow' import { useWorkflowStore } from '@/app/components/workflow/store' import { API_PREFIX } from '@/config' -import { consoleClient } from '@/service/client' +import { consoleClient } from '@/service/console' // oxlint-disable-next-line no-restricted-imports import { postWithKeepalive } from '@/service/fetch' import { useSnippetDraftStore } from '../draft-store' diff --git a/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx b/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx index 9719aae9b0f..34bf115af72 100644 --- a/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx +++ b/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx @@ -226,7 +226,7 @@ vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: mockRouterPush }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { systemFeatures: { get: { diff --git a/web/app/components/step-by-step-tour/__tests__/state.spec.ts b/web/app/components/step-by-step-tour/__tests__/state.spec.ts index c0378899913..33aab751c60 100644 --- a/web/app/components/step-by-step-tour/__tests__/state.spec.ts +++ b/web/app/components/step-by-step-tour/__tests__/state.spec.ts @@ -84,7 +84,7 @@ vi.mock('@/features/system-features/state', async () => { return { deploymentEditionAtom: atom('CLOUD') } }) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { onboarding: { stepByStepTour: { diff --git a/web/app/components/step-by-step-tour/state.ts b/web/app/components/step-by-step-tour/state.ts index c960d09b067..594b4588c15 100644 --- a/web/app/components/step-by-step-tour/state.ts +++ b/web/app/components/step-by-step-tour/state.ts @@ -16,7 +16,7 @@ import { atomWithMutation, atomWithQuery, queryClientAtom } from 'jotai-tanstack import { selectAtom } from 'jotai/utils' import { currentWorkspaceIdAtom } from '@/context/workspace-state' import { deploymentEditionAtom } from '@/features/system-features/state' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' const stepByStepTourStateQueryKey = () => consoleQuery.onboarding.stepByStepTour.state.get.queryKey() diff --git a/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx b/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx index aa084bfaf38..8cdb13f4e36 100644 --- a/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx +++ b/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx @@ -1,5 +1,4 @@ import type { ModalContextState } from '@/context/modal-context' -import type { ProviderContextState } from '@/context/provider-context' import { toast } from '@langgenius/dify-ui/toast' import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vite-plus/test' @@ -35,11 +34,6 @@ vi.mock('@/context/modal-context', () => ({ }), })) -const mockUseProviderContext = vi.fn() -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockUseProviderContext(), -})) - vi.mock('@/context/i18n', async () => { const actual = await vi.importActual('@/context/i18n') return { @@ -62,13 +56,6 @@ describe('EditCustomCollectionModal', () => { parameters_schema: [], schema_type: 'openapi', }) - mockUseProviderContext.mockReturnValue({ - plan: { - type: 'sandbox', - }, - enableBilling: false, - webappCopyrightEnabled: true, - } as ProviderContextState) }) const renderModal = (props?: { diff --git a/web/app/components/tools/marketplace/__tests__/hooks.spec.ts b/web/app/components/tools/marketplace/__tests__/hooks.spec.ts index f1d734768ee..b191ca0ac44 100644 --- a/web/app/components/tools/marketplace/__tests__/hooks.spec.ts +++ b/web/app/components/tools/marketplace/__tests__/hooks.spec.ts @@ -26,7 +26,7 @@ vi.mock('@/app/components/plugins/marketplace/hooks', () => ({ useMarketplacePlugins: (...args: unknown[]) => mockUseMarketplacePlugins(...args), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { workspaces: { current: { diff --git a/web/app/components/tools/marketplace/hooks.ts b/web/app/components/tools/marketplace/hooks.ts index 2985e97dbc4..f79ea04057f 100644 --- a/web/app/components/tools/marketplace/hooks.ts +++ b/web/app/components/tools/marketplace/hooks.ts @@ -7,7 +7,7 @@ import { } from '@/app/components/plugins/marketplace/hooks' import { getMarketplaceListCondition } from '@/app/components/plugins/marketplace/utils' import { PluginCategoryEnum } from '@/app/components/plugins/types' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' export const useMarketplace = ( searchPluginText: string, diff --git a/web/app/components/tools/provider/__tests__/detail.spec.tsx b/web/app/components/tools/provider/__tests__/detail.spec.tsx index f86c32e2bfd..a5b21a1acb7 100644 --- a/web/app/components/tools/provider/__tests__/detail.spec.tsx +++ b/web/app/components/tools/provider/__tests__/detail.spec.tsx @@ -1,14 +1,42 @@ +import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen' import type { ReactElement } from 'react' import type { Collection } from '../../types' import { act, cleanup, fireEvent, screen, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test' +import { consoleQuery } from '@/service/console' import { commonQueryKeys } from '@/service/use-common' import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data' import { AuthType, CollectionType } from '../../types' import ProviderDetail from '../detail' +const providerSummaryFixture = { + provider: 'openai', + plugin_id: 'langgenius/openai', + label: { en_US: 'OpenAI' }, + configurate_methods: ['predefined-model'], + supported_model_types: ['llm'], + preferred_provider_type: 'custom', + is_configured: true, + system_configuration: { enabled: false }, + custom_configuration: { + status: 'active', + available_credentials: [], + current_credential_usable: true, + has_custom_models: false, + }, +} satisfies ModelProviderSummaryResponse + const render = (ui: ReactElement) => { const queryClient = createConsoleQueryClient() + queryClient.setQueryData(consoleQuery.workspaces.current.modelProviders.summary.get.queryKey(), { + data: [ + { + ...providerSummaryFixture, + ...{ provider: 'model-collection-id' }, + } satisfies ModelProviderSummaryResponse, + ], + plugins: {}, + }) queryClient.setQueryData(commonQueryKeys.modelProviderDetails, { data: [{ provider: 'model-collection-id' }], }) @@ -48,12 +76,6 @@ vi.mock('@/context/modal-context', () => ({ }), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - modelProviders: [{ provider: 'model-collection-id', name: 'TestModel' }], - }), -})) - const mockFetchBuiltInToolList = vi.fn().mockResolvedValue([]) const mockFetchCustomToolList = vi.fn().mockResolvedValue([]) const mockFetchModelToolList = vi.fn().mockResolvedValue([]) diff --git a/web/app/components/tools/provider/detail.tsx b/web/app/components/tools/provider/detail.tsx index 343d26aa948..44f16041351 100644 --- a/web/app/components/tools/provider/detail.tsx +++ b/web/app/components/tools/provider/detail.tsx @@ -1,4 +1,5 @@ 'use client' + import type { Collection, CustomCollectionBackend, @@ -29,7 +30,7 @@ import { IconButton } from '@langgenius/dify-ui/icon-button' import { StatusDot } from '@langgenius/dify-ui/status-dot' import { toast } from '@langgenius/dify-ui/toast' import { RiCloseLine } from '@remixicon/react' -import { useQueryClient } from '@tanstack/react-query' +import { useQuery, useQueryClient } from '@tanstack/react-query' import * as React from 'react' import { useCallback, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' @@ -45,9 +46,9 @@ import ConfigCredential from '@/app/components/tools/setting/build-in/config-cre import { WorkflowToolDrawer } from '@/app/components/tools/workflow-tool' import { useLocale } from '@/context/i18n' import { useModalContext } from '@/context/modal-context' -import { useProviderContext } from '@/context/provider-context' import { useCredentialPermissions } from '@/hooks/use-credential-permissions' import { getLanguage } from '@/i18n-config/language' +import { consoleQuery } from '@/service/console' import { deleteWorkflowTool, fetchBuiltInToolList, @@ -92,20 +93,23 @@ const ProviderDetail = ({ collection, onHide, onRefreshData }: Props) => { // built in provider const [showSettingAuth, setShowSettingAuth] = useState(false) const { setShowModelModal } = useModalContext() - const { modelProviders: providers } = useProviderContext() + const { data: modelProvider } = useQuery( + consoleQuery.workspaces.current.modelProviders.summary.get.queryOptions({ + select: (response) => response.data.find((provider) => provider.provider === collection?.id), + }), + ) const queryClient = useQueryClient() const showSettingAuthModal = async () => { if (!canOpenCredentialSettings) return if (isModel) { - const summary = providers.find((item) => item.provider === collection?.id) - if (!summary) return + if (!modelProvider) return try { const response = await queryClient.query({ ...modelProviderDetailsQueryOptions(), staleTime: 'static', }) - const provider = response.data.find((item) => item.provider === summary.provider) + const provider = response.data.find((item) => item.provider === modelProvider.provider) if (!provider) return setShowModelModal({ payload: { diff --git a/web/app/components/workflow-app/components/dify-builder/__tests__/flows.spec.tsx b/web/app/components/workflow-app/components/dify-builder/__tests__/flows.spec.tsx index da37d46f220..ff90ffccbd7 100644 --- a/web/app/components/workflow-app/components/dify-builder/__tests__/flows.spec.tsx +++ b/web/app/components/workflow-app/components/dify-builder/__tests__/flows.spec.tsx @@ -1,9 +1,9 @@ import type { DifyBuilderStreamEventResponse } from '@dify/contracts/api/console/dify-builder/types.gen' import type { ConversationItem, SessionView } from '../types' -import { act, render, screen, waitFor, within } from '@testing-library/react' +import { act, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useSetAtom } from 'jotai' -import { baseProviderContextValue, ProviderContext } from '@/context/provider-context' +import { renderWithConsoleQuery } from '@/test/console/query-data' import DifyBuilderPanel from '../panel' import { DifyBuilderProvider } from '../provider' import { difyBuilderStartRunFixAtom } from '../store' @@ -22,22 +22,27 @@ const mocks = vi.hoisted(() => ({ syncDraft: vi.fn(async () => undefined), })) -vi.mock('@/service/client', () => ({ - consoleClient: { - difyBuilder: { - sessions: { - post: mocks.create, - bySessionId: { - get: mocks.get, - conversation: { get: mocks.conversation }, - stream: { get: mocks.stream }, - actions: { post: mocks.action }, - messages: { post: mocks.message }, +vi.mock('@/service/console', async (importOriginal) => { + const actual = await importOriginal() + + return { + ...actual, + consoleClient: { + difyBuilder: { + sessions: { + post: mocks.create, + bySessionId: { + get: mocks.get, + conversation: { get: mocks.conversation }, + stream: { get: mocks.stream }, + actions: { post: mocks.action }, + messages: { post: mocks.message }, + }, }, }, }, - }, -})) + } +}) vi.mock('../model-selector', () => ({ default: () => , @@ -146,23 +151,21 @@ const FixEntry = () => { } const renderFlow = (edgeCount = 0) => - render( - // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its special provider. - - ({ nodes: [], edgeCount })} - onFocusCanvas={mocks.focusCanvas} - onRefreshCanvas={mocks.refreshCanvas} - onSyncDraft={mocks.syncDraft} - tenantId="workspace-1" - userId="user-1" - > - - - - , + renderWithConsoleQuery( + ({ nodes: [], edgeCount })} + onFocusCanvas={mocks.focusCanvas} + onRefreshCanvas={mocks.refreshCanvas} + onSyncDraft={mocks.syncDraft} + tenantId="workspace-1" + userId="user-1" + > + + + , + { features: { dify_builder_enabled: true } }, ) const getComposer = () => diff --git a/web/app/components/workflow-app/components/dify-builder/__tests__/provider.spec.tsx b/web/app/components/workflow-app/components/dify-builder/__tests__/provider.spec.tsx index 50f855c1bcb..650ba83ec26 100644 --- a/web/app/components/workflow-app/components/dify-builder/__tests__/provider.spec.tsx +++ b/web/app/components/workflow-app/components/dify-builder/__tests__/provider.spec.tsx @@ -1,7 +1,7 @@ -import { act, render, screen, waitFor } from '@testing-library/react' +import { act, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useAtomValue, useSetAtom } from 'jotai' -import { baseProviderContextValue, ProviderContext } from '@/context/provider-context' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { DifyBuilderProvider } from '../provider' import { difyBuilderActiveSessionIdAtom, @@ -192,22 +192,20 @@ const Probe = () => { } const renderProvider = (edgeCount = 0, difyBuilderEnabled = true, userId = 'user-1') => - render( - // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its special provider. - - ({ nodes: [], edgeCount })} - onFocusCanvas={mocks.focusCanvas} - onRefreshCanvas={mocks.refreshCanvas} - onSyncDraft={mocks.syncDraft} - tenantId="workspace-1" - userId={userId} - > - - - , + renderWithConsoleQuery( + ({ nodes: [], edgeCount })} + onFocusCanvas={mocks.focusCanvas} + onRefreshCanvas={mocks.refreshCanvas} + onSyncDraft={mocks.syncDraft} + tenantId="workspace-1" + userId={userId} + > + + , + { features: { dify_builder_enabled: difyBuilderEnabled } }, ) describe('DifyBuilderProvider', () => { diff --git a/web/app/components/workflow-app/components/dify-builder/provider/index.tsx b/web/app/components/workflow-app/components/dify-builder/provider/index.tsx index cac544983a6..f7f7ae2ce57 100644 --- a/web/app/components/workflow-app/components/dify-builder/provider/index.tsx +++ b/web/app/components/workflow-app/components/dify-builder/provider/index.tsx @@ -2,11 +2,12 @@ import type { ReactNode } from 'react' import type { DifyBuilderCanvasNode } from '../utils' +import { useQuery } from '@tanstack/react-query' import { ScopeProvider } from 'jotai-scope' import { useHydrateAtoms } from 'jotai/utils' import { useMemo } from 'react' import { useStore } from '@/app/components/workflow/store' -import { useProviderContextSelector } from '@/context/provider-context' +import { consoleQuery } from '@/service/console' import { difyBuilderSessionScopedAtoms } from '../session/state' import { useDifyBuilderSessionController } from '../session/use-session-controller' import { difyBuilderRuntimeAtom, difyBuilderScopedAtoms } from '../store' @@ -37,7 +38,11 @@ const DifyBuilderProviderContent = ({ tenantId, userId, }: DifyBuilderProviderProps) => { - const enabled = useProviderContextSelector((context) => context.difyBuilderEnabled) + const { data: enabled = false } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.dify_builder_enabled, + }), + ) const setShowPanel = useStore((state) => state.setShowDifyBuilderPanel) const session = useDifyBuilderSessionController() const runtime = useMemo( diff --git a/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.spec.tsx b/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.spec.tsx index b12a879b67c..6f3ff01cf1d 100644 --- a/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.spec.tsx +++ b/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.spec.tsx @@ -28,7 +28,7 @@ const clientMocks = vi.hoisted(() => ({ message: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { difyBuilder: { sessions: { diff --git a/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.streaming.spec.tsx b/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.streaming.spec.tsx index 27691d248c9..1e4e6ecac35 100644 --- a/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.streaming.spec.tsx +++ b/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.streaming.spec.tsx @@ -35,7 +35,7 @@ const clientMocks = vi.hoisted(() => ({ message: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { difyBuilder: { sessions: { diff --git a/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.trace.spec.tsx b/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.trace.spec.tsx index e41d9fc0749..64448296476 100644 --- a/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.trace.spec.tsx +++ b/web/app/components/workflow-app/components/dify-builder/session/__tests__/use-session-controller.trace.spec.tsx @@ -17,7 +17,7 @@ const clientMocks = vi.hoisted(() => ({ message: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { difyBuilder: { sessions: { diff --git a/web/app/components/workflow-app/components/dify-builder/session/client.ts b/web/app/components/workflow-app/components/dify-builder/session/client.ts index 6ec5d3fb775..5baa88dc564 100644 --- a/web/app/components/workflow-app/components/dify-builder/session/client.ts +++ b/web/app/components/workflow-app/components/dify-builder/session/client.ts @@ -1,5 +1,5 @@ import type { ChecklistErrorPayload, SessionModel } from '../types' -import { consoleClient } from '@/service/client' +import { consoleClient } from '@/service/console' export const createFixSession = ( appId: string, diff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx index 54ddf212a8f..461a220099a 100644 --- a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx +++ b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx @@ -1,13 +1,14 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' +import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen' import type { ReactElement } from 'react' import type { AppPublisherProps } from '@/app/components/app/app-publisher/types' import type { App } from '@/types/app' -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { render, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useStore as useAppStore } from '@/app/components/app/store' import { BlockEnum, InputVarType } from '@/app/components/workflow/types' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' +import { createConsoleQueryWrapper, seedFeatures } from '@/test/console/query-data' import FeaturesTrigger from '../features-trigger' const mockUseIsChatMode = vi.fn() @@ -17,7 +18,6 @@ const mockUseChecklist = vi.fn() const mockUseChecklistBeforePublish = vi.fn() const mockUseNodesSyncDraft = vi.fn() const mockUseFeatures = vi.fn() -const mockUseProviderContext = vi.fn() const mockUseNodes = vi.fn() const mockUseEdges = vi.fn() @@ -112,24 +112,10 @@ vi.mock('@/app/components/workflow/hooks-store', () => ({ }), })) -vi.mock('@tanstack/react-query', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - useQueryClient: () => ({ - invalidateQueries: mockInvalidateQueries, - }), - } -}) - vi.mock('@/app/components/base/features/hooks', () => ({ useFeatures: (selector: (state: Record) => unknown) => mockUseFeatures(selector), })) -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => mockUseProviderContext(), -})) - vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({ default: () => mockUseNodes(), })) @@ -253,23 +239,16 @@ vi.mock('@/hooks/use-theme', () => ({ // Use real app store - global zustand mock will auto-reset between tests -const createProviderContext = ({ - type = 'sandbox', - isFetchedPlan = true, -}: { - type?: CloudPlan - isFetchedPlan?: boolean -}) => ({ - plan: { type }, - isFetchedPlan, -}) - -const renderWithToast = (ui: ReactElement) => { - const queryClient = new QueryClient() - return { - queryClient, - ...render({ui}), - } +const renderWithToast = ( + ui: ReactElement, + { edition = 'CLOUD', plan = 'sandbox' }: { edition?: DeploymentEdition; plan?: CloudPlan } = {}, +) => { + const { queryClient, wrapper } = createConsoleQueryWrapper({ + systemFeatures: { deployment_edition: edition }, + }) + seedFeatures(queryClient, { billing: { subscription: { plan } } }) + vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries) + return { queryClient, ...render(ui, { wrapper }) } } describe('FeaturesTrigger', () => { @@ -295,7 +274,6 @@ describe('FeaturesTrigger', () => { mockUseFeatures.mockImplementation((selector: (state: Record) => unknown) => selector({ features: { file: {} } }), ) - mockUseProviderContext.mockReturnValue(createProviderContext({})) mockUseNodes.mockReturnValue([]) mockUseEdges.mockReturnValue([]) // Set up app store state @@ -467,24 +445,32 @@ describe('FeaturesTrigger', () => { }) }) - it('should set startNodeLimitExceeded when sandbox entry limit is exceeded', () => { - // Arrange - mockUseNodes.mockReturnValue([ - { id: 'start', data: { type: BlockEnum.Start } }, - { id: 'trigger-1', data: { type: BlockEnum.TriggerWebhook } }, - { id: 'trigger-2', data: { type: BlockEnum.TriggerSchedule } }, - { id: 'end', data: { type: BlockEnum.End } }, - ]) + it.each([ + { edition: 'CLOUD', plan: 'sandbox', restricted: true }, + { edition: 'CLOUD', plan: 'professional', restricted: false }, + { edition: 'COMMUNITY', plan: 'sandbox', restricted: false }, + { edition: 'ENTERPRISE', plan: 'sandbox', restricted: false }, + ] as const)( + 'should apply the entry limit for $edition / $plan', + ({ edition, plan, restricted }) => { + // Arrange + mockUseNodes.mockReturnValue([ + { id: 'start', data: { type: BlockEnum.Start } }, + { id: 'trigger-1', data: { type: BlockEnum.TriggerWebhook } }, + { id: 'trigger-2', data: { type: BlockEnum.TriggerSchedule } }, + { id: 'end', data: { type: BlockEnum.End } }, + ]) - // Act - renderWithToast() + // Act + renderWithToast(, { edition, plan }) - // Assert - const publisher = screen.getByTestId('app-publisher') - expect(publisher).toHaveAttribute('data-start-node-limit-exceeded', 'true') - expect(publisher).toHaveAttribute('data-publish-disabled', 'true') - expect(publisher).toHaveAttribute('data-has-trigger-node', 'true') - }) + // Assert + const publisher = screen.getByTestId('app-publisher') + expect(publisher).toHaveAttribute('data-start-node-limit-exceeded', String(restricted)) + expect(publisher).toHaveAttribute('data-publish-disabled', String(restricted)) + expect(publisher).toHaveAttribute('data-has-trigger-node', 'true') + }, + ) }) // Verifies callbacks wired from AppPublisher to stores and draft syncing. diff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/index.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/index.spec.tsx index b36687bc44a..0cf9ec989f3 100644 --- a/web/app/components/workflow-app/components/workflow-header/__tests__/index.spec.tsx +++ b/web/app/components/workflow-app/components/workflow-header/__tests__/index.spec.tsx @@ -1,8 +1,8 @@ import type { SessionView } from '../../dify-builder/types' import type { HeaderProps } from '@/app/components/workflow/header' -import { render, screen } from '@testing-library/react' +import { screen } from '@testing-library/react' import { createStore, Provider } from 'jotai' -import { baseProviderContextValue, ProviderContext } from '@/context/provider-context' +import { renderWithConsoleQuery } from '@/test/console/query-data' import { difyBuilderSessionViewAtom } from '../../dify-builder/session/state' import WorkflowHeader from '../index' @@ -57,13 +57,11 @@ const renderHeader = (difyBuilderEnabled: boolean, sessionView: SessionView | nu const store = createStore() store.set(difyBuilderSessionViewAtom, sessionView) - return render( + return renderWithConsoleQuery( - {/* oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its special provider. */} - - - + , + { features: { dify_builder_enabled: difyBuilderEnabled } }, ) } diff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx index 659936e4b08..5dab50d4e32 100644 --- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx +++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx @@ -9,7 +9,7 @@ import type { CommonEdgeType, Node } from '@/app/components/workflow/types' import { Button } from '@langgenius/dify-ui/button' import { cn } from '@langgenius/dify-ui/cn' import { toast } from '@langgenius/dify-ui/toast' -import { useQueryClient } from '@tanstack/react-query' +import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query' import { memo, useCallback, useMemo } from 'react' import { useTranslation } from 'react-i18next' import { useEdges } from 'reactflow' @@ -28,10 +28,10 @@ import { isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/type import { useStore, useWorkflowStore } from '@/app/components/workflow/store' import useNodes from '@/app/components/workflow/store/workflow/use-nodes' import { BlockEnum, InputVarType, isTriggerNode } from '@/app/components/workflow/types' -import { useProviderContext } from '@/context/provider-context' +import { systemFeaturesQueryOptions } from '@/features/system-features/client' import useTheme from '@/hooks/use-theme' import { fetchAppDetail } from '@/service/apps' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useInvalidateAppTriggers } from '@/service/use-tools' import { useInvalidateAppWorkflow, @@ -50,7 +50,16 @@ const FeaturesTrigger = () => { const appID = appDetail?.id const { nodesReadOnly, getNodesReadOnly } = useNodesReadOnly() const canReleaseAndVersion = useHooksStore((s) => s.accessControl.canReleaseAndVersion) - const { plan, isFetchedPlan } = useProviderContext() + const { data: deploymentEdition } = useSuspenseQuery({ + ...systemFeaturesQueryOptions(), + select: ({ deployment_edition }) => deployment_edition, + }) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (features) => features.billing.subscription.plan, + }), + ) const publishedAt = useStore((s) => s.publishedAt) const draftUpdatedAt = useStore((s) => s.draftUpdatedAt) const toolPublished = useStore((s) => s.toolPublished) @@ -135,8 +144,8 @@ const FeaturesTrigger = () => { if (nodeType === BlockEnum.Start || isTriggerNode(nodeType)) return count + 1 return count }, 0) - return isFetchedPlan && plan.type === 'sandbox' && entryCount > 2 - }, [nodes, plan.type, isFetchedPlan]) + return deploymentEdition === 'CLOUD' && plan === 'sandbox' && entryCount > 2 + }, [nodes, plan, deploymentEdition]) const hasHumanInputNode = useMemo(() => { return nodes.some((node) => node.data.type === BlockEnum.HumanInput) diff --git a/web/app/components/workflow-app/components/workflow-header/index.tsx b/web/app/components/workflow-app/components/workflow-header/index.tsx index 900ce03c893..8ae6c164491 100644 --- a/web/app/components/workflow-app/components/workflow-header/index.tsx +++ b/web/app/components/workflow-app/components/workflow-header/index.tsx @@ -1,10 +1,11 @@ import type { HeaderProps } from '@/app/components/workflow/header' +import { useQuery } from '@tanstack/react-query' import { useAtomValue } from 'jotai' import { memo, useCallback, useMemo } from 'react' import { useShallow } from 'zustand/react/shallow' import { useStore as useAppStore } from '@/app/components/app/store' import Header from '@/app/components/workflow/header' -import { useProviderContextSelector } from '@/context/provider-context' +import { consoleQuery } from '@/service/console' import { useResetWorkflowVersionHistory } from '@/service/use-workflow' import { useIsChatMode } from '../../hooks/use-is-chat-mode' import { difyBuilderHasSessionAtom } from '../dify-builder/store' @@ -21,7 +22,11 @@ const WorkflowHeader = () => { ) const resetWorkflowVersionHistory = useResetWorkflowVersionHistory() const isChatMode = useIsChatMode() - const difyBuilderEnabled = useProviderContextSelector((context) => context.difyBuilderEnabled) + const { data: difyBuilderEnabled = false } = useQuery( + consoleQuery.features.get.queryOptions({ + select: (features) => features.dify_builder_enabled, + }), + ) const hasDifyBuilderSession = useAtomValue(difyBuilderHasSessionAtom) const handleClearLogAndMessageModal = useCallback(() => { diff --git a/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts index 6ded926c890..8d105f403b7 100644 --- a/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts +++ b/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts @@ -4,6 +4,7 @@ import { useAvailableNodesMetaData } from '../use-available-nodes-meta-data' const mockUseIsChatMode = vi.fn() const mockIsAgentV2Enabled = vi.hoisted(() => vi.fn(() => true)) +const mockIsAgentV2InChatflowEnabled = vi.hoisted(() => vi.fn(() => false)) vi.mock('../use-is-chat-mode', () => ({ useIsChatMode: () => mockUseIsChatMode(), @@ -11,6 +12,7 @@ vi.mock('../use-is-chat-mode', () => ({ vi.mock('@/features/agent-v2/feature-flag', () => ({ isAgentV2Enabled: () => mockIsAgentV2Enabled(), + isAgentV2InChatflowEnabled: () => mockIsAgentV2InChatflowEnabled(), })) vi.mock('@/context/i18n', () => ({ @@ -21,6 +23,7 @@ describe('useAvailableNodesMetaData', () => { beforeEach(() => { vi.clearAllMocks() mockIsAgentV2Enabled.mockReturnValue(true) + mockIsAgentV2InChatflowEnabled.mockReturnValue(false) }) it('should include chat-specific nodes and make the start node undeletable in chat mode', () => { @@ -40,7 +43,7 @@ describe('useAvailableNodesMetaData', () => { ) }) - it('should expose only legacy Agent in chat mode while retaining Agent v2 metadata', () => { + it('should expose only legacy Agent in chat mode by default even when Agent v2 is enabled', () => { mockUseIsChatMode.mockReturnValue(true) const { result } = renderHook(() => useAvailableNodesMetaData()) @@ -52,6 +55,33 @@ describe('useAvailableNodesMetaData', () => { expect(result.current.nodesMap?.[BlockEnum.AgentV2]).toBeDefined() }) + it('should expose Agent v2 in chat mode when the Chatflow gate is enabled', () => { + mockUseIsChatMode.mockReturnValue(true) + mockIsAgentV2InChatflowEnabled.mockReturnValue(true) + + const { result } = renderHook(() => useAvailableNodesMetaData()) + const nodeTypes = result.current.nodes.map((node) => node.metaData.type) + + expect(nodeTypes).toContain(BlockEnum.AgentV2) + expect(nodeTypes).not.toContain(BlockEnum.Agent) + expect(result.current.nodesMap?.[BlockEnum.AgentV2]).toBeDefined() + expect(result.current.nodesMap?.[BlockEnum.Agent]).toBeDefined() + }) + + it('should expose only legacy Agent in chat mode when Agent v2 is disabled', () => { + mockUseIsChatMode.mockReturnValue(true) + mockIsAgentV2Enabled.mockReturnValue(false) + mockIsAgentV2InChatflowEnabled.mockReturnValue(true) + + const { result } = renderHook(() => useAvailableNodesMetaData()) + const nodeTypes = result.current.nodes.map((node) => node.metaData.type) + + expect(nodeTypes).toContain(BlockEnum.Agent) + expect(nodeTypes).not.toContain(BlockEnum.AgentV2) + expect(result.current.nodesMap?.[BlockEnum.Agent]).toBeDefined() + expect(result.current.nodesMap?.[BlockEnum.AgentV2]).toBeDefined() + }) + it('should include workflow-specific trigger and end nodes outside chat mode', () => { mockUseIsChatMode.mockReturnValue(false) diff --git a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts b/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts index efa4a219858..b1027598994 100644 --- a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts +++ b/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts @@ -13,7 +13,7 @@ import TriggerScheduleDefault from '@/app/components/workflow/nodes/trigger-sche import TriggerWebhookDefault from '@/app/components/workflow/nodes/trigger-webhook/default' import { BlockEnum } from '@/app/components/workflow/types' import { useDocLink } from '@/context/i18n' -import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag' +import { isAgentV2Enabled, isAgentV2InChatflowEnabled } from '@/features/agent-v2/feature-flag' import { isProductlessDocPathWithAnchor } from '@/types/doc-paths' import { useIsChatMode } from './use-is-chat-mode' @@ -29,7 +29,9 @@ export const useAvailableNodesMetaData = () => { const isChatMode = useIsChatMode() const docLink = useDocLink() const agentV2Enabled = isAgentV2Enabled() - const shouldUseAgentV2 = agentV2Enabled && !isChatMode + // Chatflow (advanced-chat) keeps Agent v2 hidden by default; opt in via + // NEXT_PUBLIC_ENABLE_AGENT_V2_IN_CHATFLOW. Pure workflows are unaffected. + const shouldUseAgentV2 = agentV2Enabled && (!isChatMode || isAgentV2InChatflowEnabled()) const startNodeMetaData = useMemo( () => ({ diff --git a/web/app/components/workflow/__tests__/model-provider-fixtures.ts b/web/app/components/workflow/__tests__/model-provider-fixtures.ts index 72095f025df..3a97fe551cf 100644 --- a/web/app/components/workflow/__tests__/model-provider-fixtures.ts +++ b/web/app/components/workflow/__tests__/model-provider-fixtures.ts @@ -1,7 +1,9 @@ +import type { + ProviderModelWithStatusEntity, + ProviderWithModelsResponse, +} from '@dify/contracts/api/console/workspaces/types.gen' import type { DefaultModel, - Model, - ModelItem, ModelProvider, } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { CredentialPanelState } from '@/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state' @@ -14,7 +16,9 @@ import { PreferredProviderTypeEnum, } from '@/app/components/header/account-setting/model-provider-page/declarations' -export function createModelItem(overrides: Partial = {}): ModelItem { +export function createModelItem( + overrides: Partial = {}, +): ProviderModelWithStatusEntity { return { model: 'text-embedding-3-large', label: { en_US: 'Text Embedding 3 Large', zh_Hans: 'Text Embedding 3 Large' }, @@ -27,8 +31,11 @@ export function createModelItem(overrides: Partial = {}): ModelItem { } } -export function createModel(overrides: Partial = {}): Model { +export function createModel( + overrides: Partial = {}, +): ProviderWithModelsResponse { return { + tenant_id: 'test-workspace', provider: 'openai', icon_small: { en_US: 'icon', zh_Hans: 'icon' }, icon_small_dark: { en_US: 'icon-dark', zh_Hans: 'icon-dark' }, diff --git a/web/app/components/workflow/__tests__/workflow-test-env.tsx b/web/app/components/workflow/__tests__/workflow-test-env.tsx index ea3a84d0302..caba2808b04 100644 --- a/web/app/components/workflow/__tests__/workflow-test-env.tsx +++ b/web/app/components/workflow/__tests__/workflow-test-env.tsx @@ -70,7 +70,7 @@ import type { Shape as HooksStoreShape } from '../hooks-store/store' import type { Shape } from '../store/workflow' import type { WorkflowHistoryState } from '../store/workflow/history-slice' import type { Edge, Node, WorkflowRunningData } from '../types' -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { QueryClient } from '@tanstack/react-query' import * as React from 'react' import ReactFlow, { ReactFlowProvider } from 'reactflow' import { seedAccountProfileQuery } from '@/test/console/account-profile' @@ -176,10 +176,7 @@ function createWorkflowWrapper( if (!externalQueryClient) seedSystemFeatures(queryClient) if (!externalQueryClient) seedAppDslVersion(queryClient) if (!externalQueryClient) seedAccountProfileQuery(queryClient) - const QueryClientWrapper = externalQueryClient - ? ({ children }: { children: React.ReactNode }) => - React.createElement(QueryClientProvider, { client: queryClient }, children) - : createQueryClientWrapper(queryClient) + const QueryClientWrapper = createQueryClientWrapper(queryClient) return ({ children }: { children: React.ReactNode }) => { let inner: React.ReactNode = children 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 3b264940f17..e24112c1d9a 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 @@ -16,7 +16,7 @@ vi.mock('@/app/components/workflow/hooks-store', () => ({ useHooksStore: () => undefined, })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { agent: { inviteOptions: { @@ -63,7 +63,7 @@ describe('AgentSelectorContent', () => { mocks.agents = [] }) - it('offers the Agent Console link with agent.manage', async () => { + it('offers the Agent Console link with agent.acl.preview', async () => { await renderSelector({ onStartFromScratch: vi.fn() }) const listbox = screen.getByRole('listbox') @@ -99,7 +99,7 @@ describe('AgentSelectorContent', () => { expect(listbox.querySelector('.overflow-y-auto')).not.toBeInTheDocument() }) - it('hides the Agent Console link without agent.manage', async () => { + it('hides the Agent Console link without agent.acl.preview', async () => { mocks.canManageAgents = false await renderSelector() @@ -107,7 +107,7 @@ describe('AgentSelectorContent', () => { expect(screen.queryByText(manageInConsoleLabel)).not.toBeInTheDocument() }) - it('keeps start from scratch without agent.manage', async () => { + it('keeps start from scratch without agent.acl.preview', async () => { mocks.canManageAgents = false await renderSelector({ onStartFromScratch: vi.fn() }) diff --git a/web/app/components/workflow/block-selector/agent-selector.tsx b/web/app/components/workflow/block-selector/agent-selector.tsx index 79ce1898f75..b140e910517 100644 --- a/web/app/components/workflow/block-selector/agent-selector.tsx +++ b/web/app/components/workflow/block-selector/agent-selector.tsx @@ -24,7 +24,7 @@ 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/client' +import { consoleQuery } from '@/service/console' import BlockIcon from '../block-icon' const AGENT_SELECTOR_PAGE_SIZE = 8 diff --git a/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx b/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx index cf0e7f97fac..c0efc32e307 100644 --- a/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx +++ b/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx @@ -14,7 +14,7 @@ vi.mock('next-themes', () => ({ }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/marketplace', () => ({ marketplaceQuery: { downloadPlugin: { mutationOptions: (options = {}) => ({ diff --git a/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx b/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx index 20d6f9aa50f..850780d2cb9 100644 --- a/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx +++ b/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx @@ -11,7 +11,7 @@ import { useMutation } from '@tanstack/react-query' import { useTheme } from 'next-themes' import { memo } from 'react' import { useTranslation } from 'react-i18next' -import { marketplaceQuery } from '@/service/client' +import { marketplaceQuery } from '@/service/marketplace' import { downloadBlob } from '@/utils/download' import { getMarketplaceUrl } from '@/utils/var' diff --git a/web/app/components/workflow/block-selector/snippets/__tests__/snippet-tags-filter.spec.tsx b/web/app/components/workflow/block-selector/snippets/__tests__/snippet-tags-filter.spec.tsx index f8ba189691f..4bef9e4a83e 100644 --- a/web/app/components/workflow/block-selector/snippets/__tests__/snippet-tags-filter.spec.tsx +++ b/web/app/components/workflow/block-selector/snippets/__tests__/snippet-tags-filter.spec.tsx @@ -7,7 +7,7 @@ vi.mock('@tanstack/react-query', () => ({ useQuery: vi.fn(), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleQuery: { tags: { get: { diff --git a/web/app/components/workflow/block-selector/snippets/__tests__/use-insert-snippet.spec.tsx b/web/app/components/workflow/block-selector/snippets/__tests__/use-insert-snippet.spec.tsx index d6f9026399d..d1d72b69e8e 100644 --- a/web/app/components/workflow/block-selector/snippets/__tests__/use-insert-snippet.spec.tsx +++ b/web/app/components/workflow/block-selector/snippets/__tests__/use-insert-snippet.spec.tsx @@ -1,7 +1,7 @@ import type { SnippetWorkflowResponse } from '@dify/contracts/api/console/snippets/types.gen' import type { QueryClient } from '@tanstack/react-query' import { act, renderHook } from '@testing-library/react' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { createQueryClientWrapper } from '@/test/console/query-client' import { createTestQueryClient } from '@/test/query-client' import { NESTED_ELEMENT_Z_INDEX } from '../../../constants' diff --git a/web/app/components/workflow/block-selector/snippets/snippet-tags-filter.tsx b/web/app/components/workflow/block-selector/snippets/snippet-tags-filter.tsx index 45650dd87b8..dc87e69d8f1 100644 --- a/web/app/components/workflow/block-selector/snippets/snippet-tags-filter.tsx +++ b/web/app/components/workflow/block-selector/snippets/snippet-tags-filter.tsx @@ -7,7 +7,7 @@ import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgeni import { useQuery } from '@tanstack/react-query' import { useMemo, useState } from 'react' import { useTranslation } from 'react-i18next' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' type SnippetTagsFilterProps = { embedded?: boolean diff --git a/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts b/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts index d4dbd266b6d..9797e9a998d 100644 --- a/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts +++ b/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts @@ -6,7 +6,7 @@ import { useQueryClient } from '@tanstack/react-query' import { useCallback } from 'react' import { useTranslation } from 'react-i18next' import { useStoreApi } from 'reactflow' -import { consoleQuery } from '@/service/client' +import { consoleQuery } from '@/service/console' import { useIncrementSnippetUseCountMutation } from '@/service/use-snippets' import { CUSTOM_EDGE, NESTED_ELEMENT_Z_INDEX, NODE_WIDTH_X_OFFSET, X_OFFSET } from '../../constants' import { useNodesSyncDraft } from '../../hooks/use-nodes-sync-draft' diff --git a/web/app/components/workflow/comment/mention-input.spec.tsx b/web/app/components/workflow/comment/mention-input.spec.tsx index 0483112c6f2..12569aa063e 100644 --- a/web/app/components/workflow/comment/mention-input.spec.tsx +++ b/web/app/components/workflow/comment/mention-input.spec.tsx @@ -23,7 +23,7 @@ vi.mock('@/next/navigation', () => ({ useParams: () => ({ appId: 'app-1' }), })) -vi.mock('@/service/client', () => ({ +vi.mock('@/service/console', () => ({ consoleClient: { apps: { byAppId: { diff --git a/web/app/components/workflow/comment/mention-input.tsx b/web/app/components/workflow/comment/mention-input.tsx index ab0c4d9d4c5..02fc0622d6b 100644 --- a/web/app/components/workflow/comment/mention-input.tsx +++ b/web/app/components/workflow/comment/mention-input.tsx @@ -22,7 +22,7 @@ import { useTranslation } from 'react-i18next' import Textarea from 'react-textarea-autosize' import EnterKey from '@/app/components/base/icons/src/public/common/EnterKey' import { useParams } from '@/next/navigation' -import { consoleClient } from '@/service/client' +import { consoleClient } from '@/service/console' import { useStore, useWorkflowStore } from '../store' type MentionInputProps = { diff --git a/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsx b/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsx index 2f225ebc99b..df2ab245422 100644 --- a/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsx +++ b/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsx @@ -1,8 +1,14 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen' import type { VersionHistory } from '@/types/workflow' import { fireEvent, screen } from '@testing-library/react' +import { + createConsoleQueryClient, + createConsoleQueryWrapper, + seedFeatures, + seedSystemFeatures, +} from '@/test/console/query-data' import { FlowType } from '@/types/common' -import { renderWorkflowComponent } from '../../__tests__/workflow-test-env' +import { renderWorkflowComponent as renderWorkflow } from '../../__tests__/workflow-test-env' import { WorkflowVersion } from '../../types' import HeaderInRestoring from '../header-in-restoring' @@ -12,14 +18,7 @@ const mockResetWorkflowVersionHistory = vi.fn() const mockHandleLoadBackupDraft = vi.fn() const mockHandleRefreshWorkflowDraft = vi.fn() let mockPlanType: CloudPlan = 'professional' -let mockEnableBilling = true - -vi.mock('@/context/provider-context', () => ({ - useProviderContext: () => ({ - plan: { type: mockPlanType }, - enableBilling: mockEnableBilling, - }), -})) +let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'CLOUD' vi.mock('@/hooks/use-theme', () => ({ default: () => ({ @@ -89,7 +88,7 @@ describe('HeaderInRestoring', () => { beforeEach(() => { vi.clearAllMocks() mockPlanType = 'professional' - mockEnableBilling = true + deploymentEdition = 'CLOUD' }) it('should disable restore when the flow id is not ready yet', () => { @@ -163,3 +162,14 @@ describe('HeaderInRestoring', () => { expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled() }) }) + +function renderWorkflowComponent( + ui: Parameters[0], + options: Parameters[1] = {}, +) { + const queryClient = createConsoleQueryClient() + createConsoleQueryWrapper({ queryClient }) + seedSystemFeatures(queryClient, { deployment_edition: deploymentEdition }) + seedFeatures(queryClient, { billing: { subscription: { plan: mockPlanType } } }) + return renderWorkflow(ui, { ...options, queryClient }) +} diff --git a/web/app/components/workflow/header/__tests__/header-layouts.spec.tsx b/web/app/components/workflow/header/__tests__/header-layouts.spec.tsx index ef4b4b80636..d70bc30ace2 100644 --- a/web/app/components/workflow/header/__tests__/header-layouts.spec.tsx +++ b/web/app/components/workflow/header/__tests__/header-layouts.spec.tsx @@ -2,6 +2,7 @@ import type { Shape } from '../../store/workflow' import { fireEvent, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { createAccountProfileQueryClient } from '@/test/console/account-profile' +import { seedSystemFeatures } from '@/test/console/query-data' import { FlowType } from '@/types/common' import { renderWorkflowComponent } from '../../__tests__/workflow-test-env' import { WorkflowVersion } from '../../types' @@ -384,6 +385,8 @@ describe('Header layout components', () => { const deleteAllInspectVars = vi.fn() const currentVersion = createCurrentVersion() const currentUser = { id: 'user-1', name: 'Alice' } + const queryClient = createAccountProfileQueryClient(currentUser) + seedSystemFeatures(queryClient) const { store } = renderWorkflowComponent( , @@ -402,7 +405,7 @@ describe('Header layout components', () => { fileSettings: {}, }, }, - queryClient: createAccountProfileQueryClient(currentUser), + queryClient, }, ) diff --git a/web/app/components/workflow/header/header-in-restoring.tsx b/web/app/components/workflow/header/header-in-restoring.tsx index 20a75844dc7..d7b50c68324 100644 --- a/web/app/components/workflow/header/header-in-restoring.tsx +++ b/web/app/components/workflow/header/header-in-restoring.tsx @@ -2,14 +2,16 @@ import { Button } from '@langgenius/dify-ui/button' import { cn } from '@langgenius/dify-ui/cn' import { toast } from '@langgenius/dify-ui/toast' import { RiHistoryLine } from '@remixicon/react' -import { useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' +import { useAtomValue } from 'jotai' import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal' import { getWorkflowVersionName } from '@/app/components/workflow/utils/version' -import { useProviderContext } from '@/context/provider-context' import { userProfileQueryOptions } from '@/features/account-profile/client' +import { deploymentEditionAtom } from '@/features/system-features/state' import useTheme from '@/hooks/use-theme' +import { consoleQuery } from '@/service/console' import { useInvalidAllLastRun, useResetWorkflowVersionHistory, @@ -30,7 +32,13 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => { const { t } = useTranslation() const { theme } = useTheme() const [isRestorePlanUpgradeModalOpen, setIsRestorePlanUpgradeModalOpen] = useState(false) - const { plan, enableBilling } = useProviderContext() + const deploymentEdition = useAtomValue(deploymentEditionAtom) + const { data: plan } = useQuery( + consoleQuery.features.get.queryOptions({ + enabled: deploymentEdition === 'CLOUD', + select: (data) => data.billing.subscription.plan, + }), + ) const workflowStore = useWorkflowStore() const { data: userProfile } = useSuspenseQuery({ ...userProfileQueryOptions(), @@ -48,7 +56,7 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => { const resetWorkflowVersionHistory = useResetWorkflowVersionHistory() const canRestore = !!currentVersion?.id && !!configsMap?.flowId && currentVersion.version !== WorkflowVersion.Draft - const canUseWorkflowVersionAction = !enableBilling || plan.type !== 'sandbox' + const isPlanUnavailable = deploymentEdition === 'CLOUD' && plan === undefined const canEmitCollaborationEvents = configsMap?.flowType === FlowType.appFlow const handleCancelRestore = useCallback(() => { @@ -115,9 +123,9 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => { }, [canEmitCollaborationEvents, configsMap?.flowId]) const handleRestore = useCallback(async () => { - if (!canRestore || !currentVersion) return + if (isPlanUnavailable || !canRestore || !currentVersion) return - if (!canUseWorkflowVersionAction) { + if (deploymentEdition === 'CLOUD' && plan === 'sandbox') { setIsRestorePlanUpgradeModalOpen(true) return } @@ -143,9 +151,11 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => { onRestoreSettled?.() } }, [ + isPlanUnavailable, canRestore, currentVersion, - canUseWorkflowVersionAction, + deploymentEdition, + plan, setShowWorkflowVersionHistoryPanel, emitRestoreIntent, restoreWorkflow, @@ -169,7 +179,7 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => {