Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat: app deployment v2 (#41444)
Wu Tianwei550196e3b868
diff --git a/api/.importlinter b/api/.importlinterindex 99bff19c96d..df3929e6f89 100644--- a/api/.importlinter+++ b/api/.importlinter@@ -423,6 +423,22 @@ forbidden_modules =sqlalchemywerkzeug+[importlinter:contract:file-grant-service-boundary]+name = File grant application service is framework and persistence neutral+type = forbidden+source_modules =+ services.file_grant_service+ services.entities.file_grant_entities+forbidden_modules =+ configs+ controllers+ extensions+ flask+ models+ repositories+ sqlalchemy+ werkzeug+[importlinter:contract:account-activation-service-boundary]name = Account activation application service is framework and persistence neutraltype = forbiddendiff --git a/api/controllers/console/socketio/workflow.py b/api/controllers/console/socketio/workflow.pyindex 545af703dda..4569310bbe4 100644--- a/api/controllers/console/socketio/workflow.py+++ b/api/controllers/console/socketio/workflow.py@@ -93,12 +93,10 @@ def handle_collaboration_event(sid, data):1. mouse_move2. vars_and_features_update3. sync_request (ask leader to update graph)- 4. app_state_update- 5. mcp_server_update- 6. workflow_update- 7. comments_update- 8. node_panel_presence- 9. graph_view_state (session reports tab visibility; drives leader election)+ 4. workflow_update+ 5. comments_update+ 6. node_panel_presence+ 7. graph_view_state (session reports tab visibility; drives leader election)"""return collaboration_service.relay_collaboration_event(sid, data)diff --git a/api/controllers/files/__init__.py b/api/controllers/files/__init__.pyindex f8976b86b9f..42b3761b92d 100644--- a/api/controllers/files/__init__.py+++ b/api/controllers/files/__init__.py@@ -14,12 +14,13 @@ api = ExternalApi(files_ns = Namespace("files", description="File operations", path="/")-from . import image_preview, tool_files, upload+from . import appdeploy_files, image_preview, tool_files, uploadapi.add_namespace(files_ns)__all__ = ["api",+ "appdeploy_files","bp","files_ns","image_preview",diff --git a/api/controllers/files/appdeploy_files.py b/api/controllers/files/appdeploy_files.pynew file mode 100644index 00000000000..265884cf7df--- /dev/null+++ b/api/controllers/files/appdeploy_files.py@@ -0,0 +1,401 @@+"""File endpoints reached with an AppDeploy file grant.++Upload, remote-upload, produce, and resolve authenticate with a Bearer grant;+content authenticates with a per-file token in the query string, because an+``<img src>`` cannot carry a header.++They stay on the public ``files`` blueprint rather than moving under+``inner_api``, whose contract is a fully trusted caller holding the master key.+None of the five meets it: ``content`` is a browser-facing surface, ``upload``+carries an end user's payload, and ``produced`` and ``resolve`` are called by+workers executing third-party plugin code. The one genuinely server-to-server+step, minting the grant, already lives in ``inner_api``.+"""++from __future__ import annotations++from typing import IO+from urllib.parse import quote+from uuid import UUID++from flask import Response, request+from flask_restx import Resource+from pydantic import BaseModel, Field, HttpUrl, ValidationError+from werkzeug.datastructures import FileStorage++import services+from controllers.common.errors import (+ BlockedFileExtensionError,+ FilenameNotExistsError,+ FileTooLargeError,+ NoFileUploadedError,+ RemoteFileUploadError,+ TooManyFilesError,+ UnsupportedFileTypeError,+)+from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models+from controllers.files import files_ns+from controllers.files.wraps import FileGrantInvalidError, GrantedFileNotFoundError, file_grant_required+from extensions.ext_application_services import application_services+from fields.base import ResponseModel+from fields.file_fields import FileResponse+from fields.file_grant_fields import ResolvedFileResponse+from libs.exception import BaseHTTPException+from libs.helper import dump_response+from services.entities.file_grant_entities import (+ FileContent,+ FileGrantClaims,+ FileGrantContext,+ FileGrantScope,+ FileKind,+ FileRef,+ StoredUpload,+)+from services.errors.file_grant import (+ EndUserNotFoundError,+ InvalidFileGrantError,+ RemoteFileUnavailableError,+ TooManyFileRefsError,+)+from services.file_grant_service import MAX_FILE_GRANT_REFS++# Everything outside this whitelist is served as an attachment. Produced files+# carry a plugin-declared MIME type, so SVG and the rest of the XML family must+# never render in the viewer's origin.+INLINE_MIME_TYPES = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"})+++class InvalidFileRequestError(BaseHTTPException):+ error_code = "invalid_request"+ description = "The file request is malformed."+ code = 400+++class FileRefPayload(BaseModel):+ id: str+ kind: FileKind+++class RemoteFileUploadPayload(BaseModel):+ url: HttpUrl = Field(description="Remote file URL to fetch and store")+++class FileResolvePayload(BaseModel):+ files: list[FileRefPayload] = Field(default_factory=list, max_length=MAX_FILE_GRANT_REFS)+++class FileContentQuery(BaseModel):+ token: str = Field(description="Signed content token scoped to this file")+++class RemoteFileUploadResponse(FileResponse):+ """Dify's upload shape plus the ``url`` key its remote-upload clients read.++ Dify has no service-api remote upload for this endpoint to stand in for, and+ the web and console one it does have answers under ``url``. Carrying both+ names lets a client of either move over untouched; they hold one URL.+ """++ url: str+++class ProducedFileResponse(ResponseModel):+ id: str+ name: str+ size: int+ mime_type: str | None = None+ url: str+ internal_url: str+++class FileResolveResponse(ResponseModel):+ files: list[ResolvedFileResponse]+++register_schema_models(files_ns, RemoteFileUploadPayload, FileResolvePayload)+register_response_schema_models(+ files_ns, FileResponse, RemoteFileUploadResponse, ProducedFileResponse, FileResolveResponse+)+++@files_ns.route("/appdeploy/upload")+class GrantedFileUploadApi(Resource):+ """Store one uploaded file against the grant's end user."""++ @file_grant_required(FileGrantScope.UPLOAD)+ @files_ns.doc("grant_upload_file")+ @files_ns.doc(+ responses={+ 201: "File uploaded",+ 400: "No file uploaded, the file has no name, or its extension is blocked",+ 401: "Invalid grant",+ 403: "Grant lacks the upload scope",+ 413: "File too large",+ 415: "Unsupported file type",+ }+ )+ @files_ns.response(201, "File uploaded", files_ns.models[FileResponse.__name__])+ def post(self, grant: FileGrantClaims):+ upload = _single_upload()+ upload_file = _store_upload(+ grant,+ filename=upload.filename or "",+ stream=upload.stream,+ mimetype=upload.mimetype,+ )+ return _granted_file_response(upload_file), 201+++@files_ns.route("/appdeploy/remote-upload")+class GrantedRemoteFileUploadApi(Resource):+ """Fetch a remote URL through the SSRF-safe fetcher and store it."""++ @file_grant_required(FileGrantScope.UPLOAD)+ @files_ns.doc("grant_upload_remote_file")+ @files_ns.expect(files_ns.models[RemoteFileUploadPayload.__name__])+ @files_ns.doc(+ responses={+ 201: "Remote file uploaded",+ 400: "Invalid URL, unfetchable remote file, or a blocked extension",+ 401: "Invalid grant",+ 403: "Grant lacks the upload scope",+ 413: "File too large",+ 415: "Unsupported file type",+ }+ )+ @files_ns.response(201, "Remote file uploaded", files_ns.models[RemoteFileUploadResponse.__name__])+ def post(self, grant: FileGrantClaims):+ try:+ payload = RemoteFileUploadPayload.model_validate(files_ns.payload or {})+ except ValidationError as exc:+ raise InvalidFileRequestError(str(exc)) from exc++ try:+ upload_file = application_services().file_grants.store_remote_upload(+ context=_grant_context(grant),+ url=str(payload.url),+ )+ except RemoteFileUnavailableError as exc:+ raise RemoteFileUploadError(f"Failed to fetch file from {payload.url}") from exc+ except EndUserNotFoundError as exc:+ raise GrantedFileNotFoundError() from exc+ except services.errors.file.FileTooLargeError as exc:+ raise FileTooLargeError(exc.description) from exc+ except services.errors.file.BlockedFileExtensionError as exc:+ raise BlockedFileExtensionError(exc.description) from exc+ except services.errors.file.UnsupportedFileTypeError:+ raise UnsupportedFileTypeError()+ return _remote_granted_file_response(upload_file), 201+++@files_ns.route("/appdeploy/produced")+class ProducedFileApi(Resource):+ """Store one file produced by a running workflow node."""++ @file_grant_required(FileGrantScope.PRODUCE)+ @files_ns.doc("grant_upload_produced_file")+ @files_ns.doc(+ responses={+ 201: "Produced file stored",+ 400: "No file uploaded",+ 401: "Invalid grant",+ 403: "Grant lacks the produce scope",+ 413: "File too large",+ }+ )+ @files_ns.response(201, "Produced file stored", files_ns.models[ProducedFileResponse.__name__])+ def post(self, grant: FileGrantClaims):+ upload = _single_upload()+ try:+ tool_file, access = application_services().file_grants.store_produced(+ context=_grant_context(grant),+ filename=upload.filename,+ stream=upload.stream,+ mimetype=upload.mimetype,+ )+ except services.errors.file.FileTooLargeError as exc:+ raise FileTooLargeError(exc.description)+ except EndUserNotFoundError as exc:+ raise GrantedFileNotFoundError() from exc++ return ProducedFileResponse(+ id=tool_file.id,+ name=tool_file.name,+ size=tool_file.size,+ mime_type=tool_file.mime_type,+ url=access.external_url,+ internal_url=access.internal_url,+ ).model_dump(mode="json"), 201+++@files_ns.route("/appdeploy/resolve")+class GrantedFileResolveApi(Resource):+ """Re-check ownership and sign fresh URLs at the moment of use."""++ @file_grant_required(FileGrantScope.RESOLVE)+ @files_ns.doc("grant_resolve_files")+ @files_ns.expect(files_ns.models[FileResolvePayload.__name__])+ @files_ns.doc(+ responses={+ 200: "Files resolved",+ 400: "Malformed request",+ 401: "Invalid grant",+ 403: "Grant lacks the resolve scope",+ }+ )+ @files_ns.response(200, "Files resolved", files_ns.models[FileResolveResponse.__name__])+ def post(self, grant: FileGrantClaims):+ try:+ payload = FileResolvePayload.model_validate(files_ns.payload or {})+ except ValidationError as exc:+ raise InvalidFileRequestError(str(exc)) from exc++ refs = [FileRef(id=ref.id, kind=ref.kind) for ref in payload.files]+ try:+ resolved = application_services().file_grants.resolve_file_access(+ context=_grant_context(grant),+ refs=refs,+ )+ except EndUserNotFoundError as exc:+ raise GrantedFileNotFoundError() from exc+ except TooManyFileRefsError as exc:+ raise InvalidFileRequestError(str(exc)) from exc++ return FileResolveResponse(+ files=[ResolvedFileResponse.from_resolved(ref.id, file) for ref, file in zip(refs, resolved, strict=True)]+ ).model_dump(mode="json")+++@files_ns.route("/appdeploy/<uuid:file_id>/content")+class GrantedFileContentApi(Resource):+ """Stream one file's bytes to a holder of its content token."""++ @files_ns.doc("grant_file_content")+ @files_ns.doc(params=query_params_from_model(FileContentQuery))+ @files_ns.doc(+ responses={+ 200: "File stream returned",+ 401: "Invalid or expired content token",+ 404: "File not found",+ }+ )+ def get(self, file_id: UUID):+ try:+ query = FileContentQuery.model_validate(request.args.to_dict(flat=True))+ except ValidationError as exc:+ raise FileGrantInvalidError() from exc++ try:+ content = application_services().file_grants.load_content(+ token=query.token,+ requested_file_id=str(file_id),+ )+ except InvalidFileGrantError as exc:+ raise FileGrantInvalidError() from exc+ if content is None:+ raise GrantedFileNotFoundError()++ return _content_response(content)+++def _content_response(content: FileContent) -> Response:+ mime_type = _normalized_mime_type(content.mime_type)+ inline = mime_type in INLINE_MIME_TYPES++ response = Response(+ content.stream,+ mimetype=mime_type if inline else "application/octet-stream",+ direct_passthrough=True,+ headers={},+ )+ response.headers["X-Content-Type-Options"] = "nosniff"+ if not inline:+ encoded_filename = quote(content.name or "")+ response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"+ response.headers["Content-Type"] = "application/octet-stream"+ # The sibling preview endpoints advertise `Accept-Ranges` for audio and video.+ # Every such type downloads here, so the hint could only ever ride on a+ # response no player will seek.+ if content.size > 0:+ response.headers["Content-Length"] = str(content.size)+ return response+++def _normalized_mime_type(mime_type: str | None) -> str:+ return mime_type.split(";", 1)[0].strip().lower() if mime_type else ""+++def _single_upload() -> FileStorage:+ if "file" not in request.files:+ raise NoFileUploadedError()+ if len(request.files) > 1:+ raise TooManyFilesError()++ upload = request.files["file"]+ if not upload.filename:+ raise FilenameNotExistsError()+ return upload+++def _store_upload(+ grant: FileGrantClaims,+ *,+ filename: str,+ stream: IO[bytes],+ mimetype: str,+) -> StoredUpload:+ try:+ return application_services().file_grants.store_upload(+ context=_grant_context(grant),+ filename=filename,+ stream=stream,+ mimetype=mimetype,+ )+ except EndUserNotFoundError as exc:+ raise GrantedFileNotFoundError() from exc+ except services.errors.file.FileTooLargeError as exc:+ raise FileTooLargeError(exc.description)+ except services.errors.file.BlockedFileExtensionError as exc:+ raise BlockedFileExtensionError(exc.description) from exc+ except services.errors.file.UnsupportedFileTypeError:+ raise UnsupportedFileTypeError()+++def _grant_context(grant: FileGrantClaims) -> FileGrantContext:+ return FileGrantContext(tenant_id=grant.tenant_id, app_id=grant.app_id, end_user_id=grant.sub)+++def _granted_file_response(upload_file: StoredUpload) -> dict[str, object]:+ """Answer an upload exactly as dify's own upload endpoints answer it.++ A client moving off ``POST /v1/files/upload`` must not have to read a second+ shape, so the same model reads the same ``upload_files`` row: every key dify+ leaves null for such a row is null here too. Only the value of ``source_url``+ is ours. Dify signs a ``file-preview`` URL there and this channel signs a+ content-token URL, which keeps that key's promise of a signed URL that+ retrieves the file while keeping the grant its only way in.+ """++ signed_url, _ = application_services().file_grants.content_urls(file_id=upload_file.id, kind=FileKind.UPLOAD)+ return dump_response(FileResponse, upload_file) | {"source_url": signed_url}+++def _remote_granted_file_response(upload_file: StoredUpload) -> dict[str, object]:+ """Answer a remote upload with the upload shape plus dify's ``url`` key.++ Reuses the URL already signed for ``source_url`` rather than signing a+ second one, so the two keys are one value under the two names dify's two+ kinds of client look for.+ """++ response = _granted_file_response(upload_file)+ return response | {"url": response["source_url"]}+++__all__ = [+ "GrantedFileContentApi",+ "GrantedFileResolveApi",+ "GrantedFileUploadApi",+ "GrantedRemoteFileUploadApi",+ "ProducedFileApi",+]diff --git a/api/controllers/files/wraps.py b/api/controllers/files/wraps.pynew file mode 100644index 00000000000..b72925028d8--- /dev/null+++ b/api/controllers/files/wraps.py@@ -0,0 +1,57 @@+"""Bearer authentication for the AppDeploy file grant endpoints."""++from collections.abc import Callable+from functools import wraps++from flask import request++from extensions.ext_application_services import application_services+from libs.exception import BaseHTTPException+from services.entities.file_grant_entities import FileGrantClaims, FileGrantScope+++class FileGrantInvalidError(BaseHTTPException):+ error_code = "grant_invalid"+ description = "The file grant is missing, malformed, or expired."+ code = 401+++class FileGrantScopeDeniedError(BaseHTTPException):+ error_code = "grant_scope_denied"+ description = "The file grant does not carry the required scope."+ code = 403+++class GrantedFileNotFoundError(BaseHTTPException):+ error_code = "file_not_found"+ description = "File not found."+ code = 404+++def file_grant_required[**P, R](scope: FileGrantScope) -> Callable[[Callable[P, R]], Callable[P, R]]:+ """Require a valid file grant carrying ``scope`` and inject its claims."""++ def decorator(view: Callable[P, R]) -> Callable[P, R]:+ @wraps(view)+ def decorated(*args: P.args, **kwargs: P.kwargs) -> R:+ kwargs["grant"] = _authenticated_claims(scope)+ return view(*args, **kwargs)++ return decorated++ return decorator+++def _authenticated_claims(scope: FileGrantScope) -> FileGrantClaims:+ scheme, _, token = request.headers.get("Authorization", "").partition(" ")+ if scheme.lower() != "bearer" or not token:+ raise FileGrantInvalidError()++ claims = application_services().file_grants.decode_grant(token)+ if claims is None:+ raise FileGrantInvalidError()++ if scope not in claims.scopes:+ raise FileGrantScopeDeniedError()++ return claimsdiff --git a/api/controllers/inner_api/__init__.py b/api/controllers/inner_api/__init__.pyindex cb7ddd7f107..1656df8aaff 100644--- a/api/controllers/inner_api/__init__.py+++ b/api/controllers/inner_api/__init__.py@@ -21,6 +21,7 @@ from .agent import files as _agent_filesfrom .agent import llm as _agent_llmfrom .agent import tools as _agent_toolsfrom .app import dsl as _app_dsl+from .app import file_grants as _app_file_grantsfrom .knowledge import retrieval as _knowledge_retrievalfrom .plugin import agent_config as _agent_configfrom .plugin import plugin as _plugin@@ -35,6 +36,7 @@ __all__ = ["_agent_llm","_agent_tools","_app_dsl",+ "_app_file_grants","_knowledge_retrieval","_mail","_plugin",diff --git a/api/controllers/inner_api/app/file_grants.py b/api/controllers/inner_api/app/file_grants.pynew file mode 100644index 00000000000..0acc9754c73--- /dev/null+++ b/api/controllers/inner_api/app/file_grants.py@@ -0,0 +1,203 @@+"""Mint AppDeploy file grants for the enterprise control plane.++This is the only endpoint that asserts an AppDeploy identity: the application+service upserts the subject's ``EndUser`` row, validates the files the caller+claims to reference, and signs a short-lived grant.+"""++from __future__ import annotations++from flask_restx import Resource+from pydantic import BaseModel, Field, ValidationError++from controllers.common.schema import register_response_schema_models, register_schema_models+from controllers.console.wraps import setup_required+from controllers.files.wraps import GrantedFileNotFoundError+from controllers.inner_api import inner_api_ns+from controllers.inner_api.wraps import enterprise_inner_api_only+from extensions.ext_application_services import application_services+from fields.base import ResponseModel+from fields.file_grant_fields import ResolvedFileResponse+from libs.exception import BaseHTTPException+from services.entities.file_grant_entities import FileGrantMintRequest, FileGrantScope, FileKind, FileRef+from services.file_grant_service import (+ AppNotFoundError,+ EndUserNotFoundError,+ TooManyFileRefsError,+)+from services.file_grant_service import (+ GrantedFileNotFoundError as ServiceGrantedFileNotFoundError,+)+from services.file_grant_service import (+ GrantTtlTooLongError as ServiceGrantTtlTooLongError,+)+from services.file_grant_service import (+ InvalidGrantRequestError as ServiceInvalidGrantRequestError,+)+from services.file_grant_service import (+ InvalidSubjectError as ServiceInvalidSubjectError,+)+++class InvalidGrantRequestError(BaseHTTPException):+ error_code = "invalid_request"+ description = "The file grant request is malformed."+ code = 400+++class GrantTtlTooLongError(BaseHTTPException):+ error_code = "grant_ttl_too_long"+ description = "The requested file grant lifetime exceeds its allowed window."+ code = 400+++class InvalidSubjectError(BaseHTTPException):+ error_code = "invalid_subject"+ description = "The subject is empty or contains a NUL byte."+ code = 400+++class GrantAppNotFoundError(BaseHTTPException):+ error_code = "app_not_found"+ description = "App not found."+ code = 404+++class FileGrantFileRef(BaseModel):+ id: str+ kind: FileKind+++class FileGrantMintPayload(BaseModel):+ tenant_id: str+ app_id: str+ subject: str+ is_anonymous: bool = False+ scopes: list[FileGrantScope]+ ttl_seconds: int = Field(gt=0)+ # Recorded by the enterprise caller's own audit log; it never enters the+ # grant because a rotated key must not strand the files it uploaded.+ actor_key_digest: str | None = None+ file_ids: list[FileGrantFileRef] = Field(default_factory=list)+ optional_file_ids: list[FileGrantFileRef] = Field(default_factory=list)+ run_deadline: int | None = None+++class FileGrantLimits(ResponseModel):+ file_size_limit: int+ image_file_size_limit: int+ audio_file_size_limit: int+ video_file_size_limit: int+ workflow_file_upload_limit: int+ batch_count_limit: int+++class FileGrantFileMetadata(ResponseModel):+ id: str+ kind: FileKind+ name: str+ size: int+ extension: str+ mime_type: str | None = None+++class FileGrantMintResponse(ResponseModel):+ grant: str+ expires_at: int+ limits: FileGrantLimits+ files: list[FileGrantFileMetadata]+ optional_files: list[ResolvedFileResponse]+++register_schema_models(inner_api_ns, FileGrantMintPayload)+register_response_schema_models(inner_api_ns, FileGrantMintResponse)+++@inner_api_ns.route("/enterprise/file-grants")+class EnterpriseFileGrantApi(Resource):+ """Assert one AppDeploy subject and sign a grant for it."""++ @setup_required+ @enterprise_inner_api_only+ @inner_api_ns.doc("enterprise_mint_file_grant")+ @inner_api_ns.expect(inner_api_ns.models[FileGrantMintPayload.__name__])+ @inner_api_ns.response(+ 200,+ "File grant minted",+ inner_api_ns.models[FileGrantMintResponse.__name__],+ )+ @inner_api_ns.doc(+ responses={+ 400: "Invalid request, subject, or grant TTL",+ 404: "App not found, or a required file is not owned by the subject",+ }+ )+ def post(self):+ try:+ payload = FileGrantMintPayload.model_validate(inner_api_ns.payload or {})+ except ValidationError as exc:+ raise InvalidGrantRequestError(str(exc)) from exc++ try:+ result = application_services().file_grants.mint(+ FileGrantMintRequest(+ tenant_id=payload.tenant_id,+ app_id=payload.app_id,+ subject=payload.subject,+ is_anonymous=payload.is_anonymous,+ scopes=tuple(payload.scopes),+ ttl_seconds=payload.ttl_seconds,+ file_refs=tuple(FileRef(id=ref.id, kind=ref.kind) for ref in payload.file_ids),+ optional_file_refs=tuple(FileRef(id=ref.id, kind=ref.kind) for ref in payload.optional_file_ids),+ run_deadline=payload.run_deadline,+ )+ )+ except AppNotFoundError as exc:+ raise GrantAppNotFoundError() from exc+ except ServiceGrantTtlTooLongError as exc:+ raise GrantTtlTooLongError() from exc+ except ServiceInvalidSubjectError as exc:+ raise InvalidSubjectError() from exc+ except (ServiceInvalidGrantRequestError, TooManyFileRefsError) as exc:+ raise InvalidGrantRequestError(str(exc)) from exc+ except (EndUserNotFoundError, ServiceGrantedFileNotFoundError) as exc:+ raise GrantedFileNotFoundError() from exc++ return FileGrantMintResponse(+ grant=result.grant,+ expires_at=result.expires_at,+ limits=FileGrantLimits(+ file_size_limit=result.limits.file_size_limit,+ image_file_size_limit=result.limits.image_file_size_limit,+ audio_file_size_limit=result.limits.audio_file_size_limit,+ video_file_size_limit=result.limits.video_file_size_limit,+ workflow_file_upload_limit=result.limits.workflow_file_upload_limit,+ batch_count_limit=result.limits.batch_count_limit,+ ),+ files=[+ FileGrantFileMetadata(+ id=file.id,+ kind=file.kind,+ name=file.name,+ size=file.size,+ extension=file.extension,+ mime_type=file.mime_type,+ )+ for file in result.files+ ],+ optional_files=[+ ResolvedFileResponse.from_resolved(ref.id, access)+ for ref, access in zip(+ payload.optional_file_ids,+ result.optional_files,+ strict=True,+ )+ ],+ ).model_dump(mode="json")+++__all__ = [+ "EnterpriseFileGrantApi",+ "FileGrantMintPayload",+ "FileGrantMintResponse",+]diff --git a/api/controllers/web/app.py b/api/controllers/web/app.pyindex 1e985b77cc1..929cd6ae51a 100644--- a/api/controllers/web/app.py+++ b/api/controllers/web/app.py@@ -26,6 +26,7 @@ from libs.passport import PassportServicefrom libs.token import extract_webapp_passportfrom models.model import App, EndUserfrom services.app_definition_query_service import AppDefinitionNotPublishedError, AppDefinitionUnavailableError+from services.web_passport_service import WebAppAuthTypefrom services.webapp_access_query_service import (WebAppAccessAppNotFoundError,WebAppAccessReferenceRequiredError,@@ -184,12 +185,16 @@ class AppWebAuthPermission(Resource):if not tk:raise Unauthorized("Access token is missing.")decoded = PassportService().verify(tk)- user_id = decoded.get("user_id", "visitor")except Unauthorized:raise WebAppAuthRequiredError() from Noneexcept Exception:logger.exception("Unexpected error during auth verification")raise+ if decoded.get("auth_type") != WebAppAuthType.INTERNAL:+ raise WebAppAuthRequiredError()+ user_id = decoded.get("user_id")+ if not user_id:+ raise WebAppAuthRequiredError()try:is_allowed = webapp_access.is_user_allowed(user_id=str(user_id), app_id=app_id)diff --git a/api/controllers/web/wraps.py b/api/controllers/web/wraps.pyindex 69e0edb059f..d6aac7e97c6 100644--- a/api/controllers/web/wraps.py+++ b/api/controllers/web/wraps.py@@ -19,6 +19,7 @@ from models.model import App, EndUser, Sitefrom services.app_service import AppServicefrom services.enterprise.enterprise_service import EnterpriseService, WebAppAccessMode, WebAppSettingsfrom services.system_feature_service import SystemFeatureService+from services.web_passport_gateways import resolve_web_app_auth_typefrom services.webapp_auth_service import WebAppAuthService@@ -133,6 +134,14 @@ def _validate_user_accessibility(if not webapp_settings:raise WebAppAuthRequiredError("Web app settings not found.")+ auth_type = decoded.get("auth_type")+ if not auth_type:+ raise WebAppAuthRequiredError("Missing auth_type in the token.")++ expected_auth_type = resolve_web_app_auth_type(webapp_settings.access_mode)+ if auth_type != expected_auth_type:+ raise WebAppAuthRequiredError()+if WebAppAuthService.is_app_require_permission_check(access_mode=webapp_settings.access_mode, session=db.session()):@@ -140,10 +149,7 @@ def _validate_user_accessibility(if not EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp(user_id, app_id):raise WebAppAuthAccessDeniedError()- auth_type = decoded.get("auth_type")granted_at = decoded.get("granted_at")- if not auth_type:- raise WebAppAuthAccessDeniedError("Missing auth_type in the token.")if not granted_at:raise WebAppAuthAccessDeniedError("Missing granted_at in the token.")# check if sso has been updateddiff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex d39a84c150c..7863e5a5b72 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -1,6 +1,7 @@"""Composition root for application services used by transport adapters."""import json+import timefrom collections.abc import Mappingfrom dataclasses import dataclassfrom datetime import UTC, datetime@@ -18,8 +19,10 @@ from constants.languages import languagesfrom core.db.session_factory import get_session_makerfrom core.helper.ssrf_proxy import ssrf_proxyfrom core.schemas.schema_manager import SchemaManager+from core.tools.tool_file_manager import ToolFileManagerfrom enums import DeploymentEdition, WebAppAccessModefrom extensions.ext_redis import RedisClientWrapper, redis_client+from extensions.ext_storage import storagefrom libs.datetime_utils import naive_utc_nowfrom libs.helper import RateLimiterfrom libs.oauth import GitHubOAuth, GoogleOAuth@@ -39,6 +42,7 @@ from repositories.data_source_api_key_auth_repository import SQLAlchemyDataSourcfrom repositories.data_source_oauth_binding_repository import SQLAlchemyDataSourceOAuthBindingRepositoryfrom repositories.explore_banner_query_repository import ExploreBannerQueryRepositoryfrom repositories.factory import DifyAPIRepositoryFactory+from repositories.file_grant_repository import FileGrantRepositoryfrom repositories.installation_state_repository import InstallationStateRepositoryfrom repositories.oauth_server_repository import RedisOAuthServerTokenRepository, SQLAlchemyOAuthServerRepositoryfrom repositories.recommended_app_catalog_repository import DatabaseRecommendedAppCatalogRepository@@ -132,10 +136,13 @@ from services.billing_service import BillingServicefrom services.compliance_download_service import ComplianceDownloadServicefrom services.data_source_oauth_service import DataSourceOAuthService, InvalidDataSourceOAuthProviderErrorfrom services.enterprise.enterprise_service import EnterpriseService+from services.entities.file_grant_entities import FileGrantLimitsfrom services.errors.enterprise import EnterpriseServiceErrorfrom services.explore_banner_query_service import ExploreBannerQueryServicefrom services.feature_query_service import FeatureQueryServicefrom services.feature_service_gateway import FeatureServiceGateway+from services.file_grant_gateways import FileGrantFileGateway, FileGrantRemoteFileGateway, FileGrantTokenGateway+from services.file_grant_service import FileGrantServicefrom services.file_service import FileServicefrom services.init_validation_service import InitValidationServicefrom services.inner_mail_service import InnerMailService@@ -235,6 +242,7 @@ class ApplicationServices:schema_definitions: SchemaDefinitionServicesetup: SetupServicefeature_queries: FeatureQueryService+ file_grants: FileGrantServicefiles: FileServiceoauth_server: OAuthServerServiceinit_validation: InitValidationService@@ -293,6 +301,37 @@ def _build_oauth_server_service()+def _build_file_grant_service(*, database_client: sessionmaker[Session]) -> FileGrantService:+ repository = FileGrantRepository(session_factory=database_client)+ return FileGrantService(+ repository=repository,+ files=FileGrantFileGateway(+ load_end_user=repository.get_end_user,+ subject_exists=repository.subject_exists,+ file_service=FileService(session_factory=database_client),+ tool_files=ToolFileManager(),+ storage=storage,+ ),+ remote_files=FileGrantRemoteFileGateway(),+ tokens=FileGrantTokenGateway(+ secret_key=dify_config.SECRET_KEY,+ external_files_url=dify_config.FILES_URL,+ internal_files_url=dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL,+ content_token_ttl_seconds=dify_config.FILES_ACCESS_TIMEOUT,+ now=lambda: int(time.time()),+ ),+ limits=FileGrantLimits(+ file_size_limit=dify_config.UPLOAD_FILE_SIZE_LIMIT,+ image_file_size_limit=dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT,+ audio_file_size_limit=dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT,+ video_file_size_limit=dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT,+ workflow_file_upload_limit=dify_config.WORKFLOW_FILE_UPLOAD_LIMIT,+ batch_count_limit=dify_config.UPLOAD_FILE_BATCH_LIMIT,+ ),+ now=lambda: int(time.time()),+ )++def _build_account_oauth_service(*,database_client: sessionmaker[Session],@@ -574,6 +613,7 @@ def build_application_services(features=feature_gateway,app_dsl_version=CURRENT_APP_DSL_VERSION,),+ file_grants=_build_file_grant_service(database_client=database_client),files=file_service,oauth_server=_build_oauth_server_service(database_client=database_client, redis=redis),init_validation=InitValidationService(diff --git a/api/fields/file_grant_fields.py b/api/fields/file_grant_fields.pynew file mode 100644index 00000000000..b0c550bb425--- /dev/null+++ b/api/fields/file_grant_fields.py@@ -0,0 +1,49 @@+"""Response DTOs shared by the AppDeploy file grant surfaces."""++from __future__ import annotations++from fields.base import ResponseModel+from services.entities.file_grant_entities import FileKind, ResolvedFileAccess+++class ResolvedFileResponse(ResponseModel):+ """One requested file reference, either resolved or accounted for.++ The resolve endpoint and optional mint references answer item by item so one+ missing history file cannot fail a whole run. A file that exists but belongs+ to another owner is reported exactly like one that never existed.+ """++ id: str+ ok: bool+ kind: FileKind | None = None+ name: str | None = None+ size: int | None = None+ extension: str | None = None+ mime_type: str | None = None+ url: str | None = None+ internal_url: str | None = None+ error: str | None = None++ @classmethod+ def from_resolved(cls, file_id: str, access: ResolvedFileAccess | None) -> ResolvedFileResponse:+ """Describe one resolved reference without performing infrastructure work."""++ if access is None:+ return cls(id=file_id, ok=False, error="not_found")++ file = access.file+ return cls(+ id=file.id,+ ok=True,+ kind=file.kind,+ name=file.name,+ size=file.size,+ extension=file.extension,+ mime_type=file.mime_type,+ url=access.external_url,+ internal_url=access.internal_url,+ )+++__all__ = ["ResolvedFileResponse"]diff --git a/api/models/enums.py b/api/models/enums.pyindex 4cdd46a4e12..944047d3ddd 100644--- a/api/models/enums.py+++ b/api/models/enums.py@@ -208,6 +208,7 @@ class InvokeFrom(StrEnum):class EndUserType(StrEnum):"""Persisted type values for the ``end_users.type`` column."""+ APP_DEPLOY = "app-deploy"BROWSER = "browser"MCP = "mcp"OPENAPI = "openapi"diff --git a/api/repositories/file_grant_repository.py b/api/repositories/file_grant_repository.pynew file mode 100644index 00000000000..98ff0fa8b16--- /dev/null+++ b/api/repositories/file_grant_repository.py@@ -0,0 +1,213 @@+from __future__ import annotations++import os+from collections.abc import Sequence++from sqlalchemy import select+from sqlalchemy.orm import Session, sessionmaker++from models.enums import CreatorUserRole, EndUserType+from models.model import App, EndUser, UploadFile+from models.tools import ToolFile+from services.entities.file_grant_entities import (+ FileContentRecord,+ FileGrantContext,+ FileKind,+ FileRef,+ ResolvedFile,+)+++class FileGrantRepository:+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ def get_or_create_subject(+ self,+ *,+ tenant_id: str,+ app_id: str,+ session_id: str,+ external_user_id: str,+ is_anonymous: bool,+ ) -> str | None:+ with self._session_factory() as session:+ end_user = session.scalar(+ self._subject_statement(+ tenant_id=tenant_id,+ app_id=app_id,+ session_id=session_id,+ require_app=True,+ ).limit(1)+ )+ if end_user is not None:+ return end_user.id++ with self._session_factory.begin() as session:+ app = session.scalar(select(App).where(App.id == app_id, App.tenant_id == tenant_id).with_for_update())+ if app is None:+ return None++ end_user = session.scalar(+ self._subject_statement(+ tenant_id=tenant_id,+ app_id=app_id,+ session_id=session_id,+ require_app=False,+ ).limit(1)+ )+ if end_user is None:+ end_user = EndUser(+ tenant_id=tenant_id,+ app_id=app_id,+ type=EndUserType.APP_DEPLOY,+ is_anonymous=is_anonymous,+ session_id=session_id,+ external_user_id=external_user_id,+ )+ session.add(end_user)+ session.flush()+ return end_user.id++ def subject_exists(self, context: FileGrantContext) -> bool:+ with self._session_factory() as session:+ return (+ session.scalar(+ select(EndUser.id)+ .where(+ EndUser.id == context.end_user_id,+ EndUser.tenant_id == context.tenant_id,+ EndUser.app_id == context.app_id,+ EndUser.type == EndUserType.APP_DEPLOY,+ )+ .limit(1)+ )+ is not None+ )++ def get_end_user(self, context: FileGrantContext) -> EndUser | None:+ with self._session_factory(expire_on_commit=False) as session:+ return session.scalar(+ select(EndUser)+ .where(+ EndUser.id == context.end_user_id,+ EndUser.tenant_id == context.tenant_id,+ EndUser.app_id == context.app_id,+ EndUser.type == EndUserType.APP_DEPLOY,+ )+ .limit(1)+ )++ def resolve_owned_files(+ self,+ *,+ context: FileGrantContext,+ refs: Sequence[FileRef],+ ) -> list[ResolvedFile | None]:+ upload_ids = {ref.id for ref in refs if ref.kind == FileKind.UPLOAD}+ tool_ids = {ref.id for ref in refs if ref.kind == FileKind.TOOL}++ with self._session_factory() as session:+ uploads = self._load_uploads(session, context=context, file_ids=upload_ids)+ tool_files = self._load_tool_files(session, context=context, file_ids=tool_ids)++ return [uploads.get(ref.id) if ref.kind == FileKind.UPLOAD else tool_files.get(ref.id) for ref in refs]++ def get_content_record(self, *, file_id: str, kind: FileKind) -> FileContentRecord | None:+ with self._session_factory() as session:+ match kind:+ case FileKind.UPLOAD:+ upload_file = session.scalar(select(UploadFile).where(UploadFile.id == file_id).limit(1))+ if upload_file is None:+ return None+ return FileContentRecord(+ name=upload_file.name,+ size=upload_file.size,+ mime_type=upload_file.mime_type,+ storage_key=upload_file.key,+ )+ case FileKind.TOOL:+ tool_file = session.scalar(select(ToolFile).where(ToolFile.id == file_id).limit(1))+ if tool_file is None:+ return None+ return FileContentRecord(+ name=tool_file.name or "",+ size=tool_file.size,+ mime_type=tool_file.mimetype,+ storage_key=tool_file.file_key,+ )++ @staticmethod+ def _subject_statement(*, tenant_id: str, app_id: str, session_id: str, require_app: bool):+ statement = select(EndUser)+ if require_app:+ statement = statement.join(App, App.id == EndUser.app_id)+ predicates = [+ EndUser.tenant_id == tenant_id,+ EndUser.app_id == app_id,+ EndUser.session_id == session_id,+ EndUser.type == EndUserType.APP_DEPLOY,+ ]+ if require_app:+ predicates.append(App.tenant_id == tenant_id)+ return statement.where(*predicates)++ @staticmethod+ def _load_uploads(+ session: Session,+ *,+ context: FileGrantContext,+ file_ids: set[str],+ ) -> dict[str, ResolvedFile]:+ if not file_ids:+ return {}+ rows = session.scalars(+ select(UploadFile).where(+ UploadFile.id.in_(file_ids),+ UploadFile.tenant_id == context.tenant_id,+ UploadFile.created_by_role == CreatorUserRole.END_USER,+ UploadFile.created_by == context.end_user_id,+ )+ ).all()+ return {+ row.id: ResolvedFile(+ id=row.id,+ kind=FileKind.UPLOAD,+ name=row.name,+ size=row.size,+ extension=row.extension,+ mime_type=row.mime_type,+ )+ for row in rows+ }++ @staticmethod+ def _load_tool_files(+ session: Session,+ *,+ context: FileGrantContext,+ file_ids: set[str],+ ) -> dict[str, ResolvedFile]:+ if not file_ids:+ return {}+ rows = session.scalars(+ select(ToolFile).where(+ ToolFile.id.in_(file_ids),+ ToolFile.tenant_id == context.tenant_id,+ ToolFile.user_id == context.end_user_id,+ )+ ).all()+ return {+ row.id: ResolvedFile(+ id=row.id,+ kind=FileKind.TOOL,+ name=row.name or "",+ size=row.size,+ extension=os.path.splitext(row.name or "")[1].lstrip(".").lower(),+ mime_type=row.mimetype,+ )+ for row in rows+ }+++__all__ = ["FileGrantRepository"]diff --git a/api/services/end_user_service.py b/api/services/end_user_service.pyindex c15e9949abb..a01d3a8128f 100644--- a/api/services/end_user_service.py+++ b/api/services/end_user_service.py@@ -63,6 +63,11 @@ class EndUserService:EndUser.tenant_id == tenant_id,EndUser.app_id == app_id,EndUser.session_id == user_id,+ # An AppDeploy row is never a legacy row this could upgrade:+ # the type was added after the split, and FileGrantService+ # reads its rows by type. Retyping one here would hide it+ # from that read and strand the files it owns.+ EndUser.type != EndUserType.APP_DEPLOY,).order_by(# Prioritize records with matching type (0 = match, 1 = no match)diff --git a/api/services/entities/file_grant_entities.py b/api/services/entities/file_grant_entities.pynew file mode 100644index 00000000000..5d7ffb44d7d--- /dev/null+++ b/api/services/entities/file_grant_entities.py@@ -0,0 +1,139 @@+from __future__ import annotations++from collections.abc import Iterable+from dataclasses import dataclass+from datetime import datetime+from enum import StrEnum++from pydantic import BaseModel+++class FileKind(StrEnum):+ UPLOAD = "upload"+ TOOL = "tool"+++class FileGrantScope(StrEnum):+ UPLOAD = "upload"+ RESOLVE = "resolve"+ PRODUCE = "produce"+++class FileGrantClaims(BaseModel):+ sub: str+ tenant_id: str+ app_id: str+ scopes: list[FileGrantScope]+ exp: int+++class FileContentClaims(BaseModel):+ kind: FileKind+ file_id: str+ exp: int+++@dataclass(frozen=True, slots=True)+class FileGrantContext:+ tenant_id: str+ app_id: str+ end_user_id: str+++@dataclass(frozen=True, slots=True)+class FileRef:+ id: str+ kind: FileKind+++@dataclass(frozen=True, slots=True)+class ResolvedFile:+ id: str+ kind: FileKind+ name: str+ size: int+ extension: str+ mime_type: str | None+++@dataclass(frozen=True, slots=True)+class ResolvedFileAccess:+ file: ResolvedFile+ external_url: str+ internal_url: str+++@dataclass(frozen=True, slots=True)+class FileContentRecord:+ name: str+ size: int+ mime_type: str | None+ storage_key: str+++@dataclass(frozen=True, slots=True)+class FileContent:+ name: str+ size: int+ mime_type: str | None+ stream: Iterable[bytes]+++@dataclass(frozen=True, slots=True)+class StoredUpload:+ id: str+ name: str+ size: int+ extension: str | None+ mime_type: str | None+ created_by: str | None+ created_at: datetime | None+ tenant_id: str | None+ source_url: str+++@dataclass(frozen=True, slots=True)+class StoredProducedFile:+ id: str+ name: str+ size: int+ mime_type: str | None+++@dataclass(frozen=True, slots=True)+class RemoteFile:+ filename: str+ mimetype: str+ content: bytes+++@dataclass(frozen=True, slots=True)+class FileGrantLimits:+ file_size_limit: int+ image_file_size_limit: int+ audio_file_size_limit: int+ video_file_size_limit: int+ workflow_file_upload_limit: int+ batch_count_limit: int+++@dataclass(frozen=True, slots=True)+class FileGrantMintRequest:+ tenant_id: str+ app_id: str+ subject: str+ is_anonymous: bool+ scopes: tuple[FileGrantScope, ...]+ ttl_seconds: int+ file_refs: tuple[FileRef, ...]+ optional_file_refs: tuple[FileRef, ...]+ run_deadline: int | None+++@dataclass(frozen=True, slots=True)+class FileGrantMintResult:+ grant: str+ expires_at: int+ limits: FileGrantLimits+ files: tuple[ResolvedFile, ...]+ optional_files: tuple[ResolvedFileAccess | None, ...]diff --git a/api/services/errors/file_grant.py b/api/services/errors/file_grant.pynew file mode 100644index 00000000000..17f08db9115--- /dev/null+++ b/api/services/errors/file_grant.py@@ -0,0 +1,34 @@+class AppNotFoundError(Exception):+ pass+++class EndUserNotFoundError(Exception):+ pass+++class InvalidGrantRequestError(Exception):+ pass+++class InvalidFileGrantError(Exception):+ pass+++class GrantTtlTooLongError(Exception):+ pass+++class GrantedFileNotFoundError(Exception):+ pass+++class InvalidSubjectError(Exception):+ pass+++class RemoteFileUnavailableError(Exception):+ pass+++class TooManyFileRefsError(Exception):+ passdiff --git a/api/services/file_grant_gateways.py b/api/services/file_grant_gateways.pynew file mode 100644index 00000000000..3fdf2493ee8--- /dev/null+++ b/api/services/file_grant_gateways.py@@ -0,0 +1,327 @@+from __future__ import annotations++import mimetypes+import os+import re+import urllib.parse+from collections.abc import Callable, Sequence+from typing import IO, cast+from uuid import uuid4++import httpx+import jwt+from pydantic import ValidationError++from core.file import remote_fetcher+from core.helper import ssrf_proxy+from core.tools.tool_file_manager import ToolFileManager, resolve_extension+from extensions.ext_storage import Storage+from models.model import EndUser+from services.entities.file_grant_entities import (+ FileContent,+ FileContentClaims,+ FileContentRecord,+ FileGrantClaims,+ FileGrantContext,+ FileGrantScope,+ FileKind,+ RemoteFile,+ StoredProducedFile,+ StoredUpload,+)+from services.errors.file import FileTooLargeError+from services.errors.file_grant import EndUserNotFoundError+from services.file_service import FileService++FILE_GRANT_AUDIENCE = "dify-files"+FILE_CONTENT_AUDIENCE = "dify-files-content"+_ALGORITHM = "HS256"+++class FileGrantTokenGateway:+ def __init__(+ self,+ *,+ secret_key: str,+ external_files_url: str,+ internal_files_url: str,+ content_token_ttl_seconds: int,+ now: Callable[[], int],+ ) -> None:+ self._secret_key = secret_key+ self._external_files_url = external_files_url+ self._internal_files_url = internal_files_url+ self._content_token_ttl_seconds = content_token_ttl_seconds+ self._now = now++ def issue_grant(+ self,+ *,+ context: FileGrantContext,+ scopes: Sequence[FileGrantScope],+ ttl_seconds: int,+ ) -> tuple[str, int]:+ expires_at = self._now() + ttl_seconds+ token = jwt.encode(+ {+ "aud": FILE_GRANT_AUDIENCE,+ "sub": context.end_user_id,+ "tenant_id": context.tenant_id,+ "app_id": context.app_id,+ "scopes": [str(scope) for scope in scopes],+ "exp": expires_at,+ },+ self._secret_key,+ algorithm=_ALGORITHM,+ )+ return token, expires_at++ def decode_grant(self, token: str) -> FileGrantClaims | None:+ payload = self._decode(+ token, audience=FILE_GRANT_AUDIENCE, required=["exp", "sub", "tenant_id", "app_id", "scopes"]+ )+ if payload is None:+ return None+ try:+ return FileGrantClaims.model_validate(payload)+ except ValidationError:+ return None++ def issue_content_urls(self, *, file_id: str, kind: FileKind) -> tuple[str, str]:+ external_token = self._issue_content_token(file_id=file_id, kind=kind)+ internal_token = self._issue_content_token(file_id=file_id, kind=kind)+ path = f"/files/appdeploy/{file_id}/content"+ return (+ f"{self._external_files_url}{path}?token={external_token}",+ f"{self._internal_files_url}{path}?token={internal_token}",+ )++ def decode_content_token(self, token: str) -> FileContentClaims | None:+ payload = self._decode(+ token,+ audience=FILE_CONTENT_AUDIENCE,+ required=["exp", "kind", "file_id"],+ )+ if payload is None:+ return None+ try:+ return FileContentClaims.model_validate(payload)+ except ValidationError:+ return None++ def _issue_content_token(self, *, file_id: str, kind: FileKind) -> str:+ return jwt.encode(+ {+ "aud": FILE_CONTENT_AUDIENCE,+ "kind": str(kind),+ "file_id": file_id,+ "nonce": os.urandom(8).hex(),+ "exp": self._now() + self._content_token_ttl_seconds,+ },+ self._secret_key,+ algorithm=_ALGORITHM,+ )++ def _decode(self, token: str, *, audience: str, required: list[str]) -> dict[str, object] | None:+ try:+ return cast(+ dict[str, object],+ jwt.decode(+ token,+ self._secret_key,+ algorithms=[_ALGORITHM],+ audience=audience,+ options={"require": ["aud", *required]},+ ),+ )+ except jwt.PyJWTError:+ return None+++class FileGrantFileGateway:+ def __init__(+ self,+ *,+ load_end_user: Callable[[FileGrantContext], EndUser | None],+ subject_exists: Callable[[FileGrantContext], bool],+ file_service: FileService,+ tool_files: ToolFileManager,+ storage: Storage,+ ) -> None:+ self._load_end_user = load_end_user+ self._subject_exists = subject_exists+ self._file_service = file_service+ self._tool_files = tool_files+ self._storage = storage++ def store_upload_stream(+ self,+ *,+ context: FileGrantContext,+ filename: str,+ stream: IO[bytes],+ mimetype: str,+ ) -> StoredUpload:+ if not self._subject_exists(context):+ raise EndUserNotFoundError(context.end_user_id)+ extension = os.path.splitext(filename)[1].lstrip(".").lower()+ limit = FileService.file_size_limit(extension=extension)+ content = stream.read(limit + 1)+ if len(content) > limit:+ raise FileTooLargeError(f"File size exceeded. The limit is {limit} bytes.")+ return self.store_upload(+ context=context,+ filename=filename,+ content=content,+ mimetype=mimetype,+ )++ def store_upload(+ self,+ *,+ context: FileGrantContext,+ filename: str,+ content: bytes,+ mimetype: str,+ source_url: str = "",+ ) -> StoredUpload:+ end_user = self._load_end_user(context)+ if end_user is None:+ raise EndUserNotFoundError(context.end_user_id)+ upload = self._file_service.upload_file(+ filename=filename,+ content=content,+ mimetype=mimetype,+ user=end_user,+ source_url=source_url,+ )+ return StoredUpload(+ id=upload.id,+ name=upload.name,+ size=upload.size,+ extension=upload.extension,+ mime_type=upload.mime_type,+ created_by=upload.created_by,+ created_at=upload.created_at,+ tenant_id=upload.tenant_id,+ source_url=upload.source_url,+ )++ def store_produced(+ self,+ *,+ context: FileGrantContext,+ filename: str | None,+ stream: IO[bytes],+ mimetype: str,+ ) -> StoredProducedFile:+ extension = resolve_extension(filename=filename, mimetype=mimetype).lstrip(".").lower()+ limit = FileService.file_size_limit(extension=extension)+ content = stream.read(limit + 1)+ if len(content) > limit:+ raise FileTooLargeError(f"File size exceeded. The limit is {limit} bytes.")+ stored = self._tool_files.create_file_by_raw(+ user_id=context.end_user_id,+ tenant_id=context.tenant_id,+ conversation_id=None,+ file_binary=content,+ mimetype=mimetype,+ filename=filename,+ )+ return StoredProducedFile(+ id=stored.id,+ name=stored.name or "",+ size=stored.size,+ mime_type=stored.mimetype,+ )++ def open_content(self, record: FileContentRecord) -> FileContent:+ return FileContent(+ name=record.name,+ size=record.size,+ mime_type=record.mime_type,+ stream=self._storage.load(record.storage_key, stream=True),+ )+++class FileGrantRemoteFileGateway:+ def fetch(self, url: str) -> RemoteFile | None:+ try:+ metadata = remote_fetcher.make_request("HEAD", url=url, follow_redirects=True)+ if metadata.status_code != httpx.codes.OK:+ metadata.close()+ metadata = remote_fetcher.make_request(+ "GET",+ url=url,+ timeout=3,+ follow_redirects=True,+ stream_response=True,+ )+ if metadata.status_code != httpx.codes.OK:+ metadata.close()+ return None++ filename, extension, mimetype = self._file_info(metadata)+ limit = FileService.file_size_limit(extension=extension)+ declared_size = self._declared_size(metadata)+ if declared_size is not None and declared_size > limit:+ metadata.close()+ raise FileTooLargeError(f"File size exceeded. The limit is {limit} bytes.")++ if metadata.request.method == "HEAD":+ metadata.close()+ response = remote_fetcher.make_request(+ "GET",+ url=url,+ timeout=3,+ follow_redirects=True,+ stream_response=True,+ )+ if response.status_code != httpx.codes.OK:+ response.close()+ return None+ else:+ response = metadata++ try:+ buffered = ssrf_proxy.buffer_response(response, max_response_bytes=limit)+ except ssrf_proxy.ResponseTooLargeError as exc:+ raise FileTooLargeError(f"File size exceeded. The limit is {limit} bytes.") from exc+ return RemoteFile(filename=filename, mimetype=mimetype, content=buffered.content)+ except (httpx.RequestError, ssrf_proxy.UnsupportedResponseEncodingError):+ return None++ @staticmethod+ def _file_info(response: httpx.Response) -> tuple[str, str, str]:+ parsed_url = urllib.parse.urlparse(str(response.url))+ filename = urllib.parse.unquote(os.path.basename(parsed_url.path))+ if not filename:+ content_disposition = response.headers.get("Content-Disposition", "")+ filename_match = re.search(r'filename="?([^";]+)', content_disposition)+ filename = filename_match.group(1) if filename_match else uuid4().hex+ extension = os.path.splitext(filename)[1].lstrip(".").lower()+ mimetype = (+ mimetypes.guess_type(filename)[0]+ or response.headers.get("Content-Type", "").split(";", 1)[0].strip()+ or "application/octet-stream"+ )+ return filename, extension, mimetype++ @staticmethod+ def _declared_size(response: httpx.Response) -> int | None:+ value = response.headers.get("Content-Length")+ if value is None:+ return None+ try:+ return int(value)+ except ValueError:+ return None+++__all__ = [+ "FILE_CONTENT_AUDIENCE",+ "FILE_GRANT_AUDIENCE",+ "FileGrantFileGateway",+ "FileGrantRemoteFileGateway",+ "FileGrantTokenGateway",+]diff --git a/api/services/file_grant_service.py b/api/services/file_grant_service.pynew file mode 100644index 00000000000..1cf542f278c--- /dev/null+++ b/api/services/file_grant_service.py@@ -0,0 +1,314 @@+from __future__ import annotations++import base64+import hashlib+from collections.abc import Callable, Sequence+from typing import IO, Protocol++from services.entities.file_grant_entities import (+ FileContent,+ FileContentClaims,+ FileContentRecord,+ FileGrantClaims,+ FileGrantContext,+ FileGrantLimits,+ FileGrantMintRequest,+ FileGrantMintResult,+ FileGrantScope,+ FileKind,+ FileRef,+ RemoteFile,+ ResolvedFile,+ ResolvedFileAccess,+ StoredProducedFile,+ StoredUpload,+)+from services.errors.file_grant import (+ AppNotFoundError,+ EndUserNotFoundError,+ GrantedFileNotFoundError,+ GrantTtlTooLongError,+ InvalidFileGrantError,+ InvalidGrantRequestError,+ InvalidSubjectError,+ RemoteFileUnavailableError,+ TooManyFileRefsError,+)++MAX_SESSION_GRANT_TTL_SECONDS = 7200+MAX_WORKFLOW_EXECUTION_SECONDS = 24 * 60 * 60+RUN_GRANT_EXPIRY_GRACE_SECONDS = 5 * 60+MAX_RUN_GRANT_TTL_SECONDS = MAX_WORKFLOW_EXECUTION_SECONDS + RUN_GRANT_EXPIRY_GRACE_SECONDS+MAX_FILE_GRANT_REFS = 100+++class FileGrantRepository(Protocol):+ def get_or_create_subject(+ self,+ *,+ tenant_id: str,+ app_id: str,+ session_id: str,+ external_user_id: str,+ is_anonymous: bool,+ ) -> str | None: ...++ def subject_exists(self, context: FileGrantContext) -> bool: ...++ def resolve_owned_files(+ self,+ *,+ context: FileGrantContext,+ refs: Sequence[FileRef],+ ) -> list[ResolvedFile | None]: ...++ def get_content_record(self, *, file_id: str, kind: FileKind) -> FileContentRecord | None: ...+++class FileGrantFiles(Protocol):+ def store_upload_stream(+ self,+ *,+ context: FileGrantContext,+ filename: str,+ stream: IO[bytes],+ mimetype: str,+ ) -> StoredUpload: ...++ def store_upload(+ self,+ *,+ context: FileGrantContext,+ filename: str,+ content: bytes,+ mimetype: str,+ source_url: str = "",+ ) -> StoredUpload: ...++ def store_produced(+ self,+ *,+ context: FileGrantContext,+ filename: str | None,+ stream: IO[bytes],+ mimetype: str,+ ) -> StoredProducedFile: ...++ def open_content(self, record: FileContentRecord) -> FileContent: ...+++class FileGrantTokens(Protocol):+ def issue_grant(+ self,+ *,+ context: FileGrantContext,+ scopes: Sequence[FileGrantScope],+ ttl_seconds: int,+ ) -> tuple[str, int]: ...++ def decode_grant(self, token: str) -> FileGrantClaims | None: ...++ def issue_content_urls(self, *, file_id: str, kind: FileKind) -> tuple[str, str]: ...++ def decode_content_token(self, token: str) -> FileContentClaims | None: ...+++class FileGrantRemoteFiles(Protocol):+ def fetch(self, url: str) -> RemoteFile | None: ...+++class FileGrantService:+ def __init__(+ self,+ *,+ repository: FileGrantRepository,+ files: FileGrantFiles,+ tokens: FileGrantTokens,+ remote_files: FileGrantRemoteFiles,+ limits: FileGrantLimits,+ now: Callable[[], int],+ ) -> None:+ self._repository = repository+ self._files = files+ self._tokens = tokens+ self._remote_files = remote_files+ self._limits = limits+ self._now = now++ @staticmethod+ def session_id_for_subject(subject: str) -> str:+ digest = hashlib.sha256(subject.encode()).digest()+ return base64.urlsafe_b64encode(digest).decode().rstrip("=")++ def mint(self, request: FileGrantMintRequest) -> FileGrantMintResult:+ self._validate_subject(request.subject)+ self._validate_ref_count((*request.file_refs, *request.optional_file_refs))+ ttl_seconds = self._effective_ttl_seconds(request)++ end_user_id = self._repository.get_or_create_subject(+ tenant_id=request.tenant_id,+ app_id=request.app_id,+ session_id=self.session_id_for_subject(request.subject),+ external_user_id=request.subject[:255],+ is_anonymous=request.is_anonymous,+ )+ if end_user_id is None:+ raise AppNotFoundError(request.app_id)++ context = FileGrantContext(request.tenant_id, request.app_id, end_user_id)+ strict_file_count = len(request.file_refs)+ resolved_files = self._repository.resolve_owned_files(+ context=context,+ refs=(*request.file_refs, *request.optional_file_refs),+ )+ strict_files = resolved_files[:strict_file_count]+ if any(file is None for file in strict_files):+ raise GrantedFileNotFoundError()+ optional_files = resolved_files[strict_file_count:]+ grant, expires_at = self._tokens.issue_grant(+ context=context,+ scopes=request.scopes,+ ttl_seconds=ttl_seconds,+ )+ return FileGrantMintResult(+ grant=grant,+ expires_at=expires_at,+ limits=self._limits,+ files=tuple(file for file in strict_files if file is not None),+ optional_files=tuple(self._with_access(file) if file is not None else None for file in optional_files),+ )++ def decode_grant(self, token: str) -> FileGrantClaims | None:+ return self._tokens.decode_grant(token)++ def store_upload(+ self,+ *,+ context: FileGrantContext,+ filename: str,+ stream: IO[bytes],+ mimetype: str,+ ) -> StoredUpload:+ return self._files.store_upload_stream(+ context=context,+ filename=filename,+ stream=stream,+ mimetype=mimetype,+ )++ def store_remote_upload(self, *, context: FileGrantContext, url: str) -> StoredUpload:+ if not self._repository.subject_exists(context):+ raise EndUserNotFoundError(context.end_user_id)+ remote_file = self._remote_files.fetch(url)+ if remote_file is None:+ raise RemoteFileUnavailableError(url)+ return self._files.store_upload(+ context=context,+ filename=remote_file.filename,+ content=remote_file.content,+ mimetype=remote_file.mimetype,+ source_url=url,+ )++ def store_produced(+ self,+ *,+ context: FileGrantContext,+ filename: str | None,+ stream: IO[bytes],+ mimetype: str,+ ) -> tuple[StoredProducedFile, ResolvedFileAccess]:+ if not self._repository.subject_exists(context):+ raise EndUserNotFoundError(context.end_user_id)+ stored = self._files.store_produced(+ context=context,+ filename=filename,+ stream=stream,+ mimetype=mimetype,+ )+ file = ResolvedFile(stored.id, FileKind.TOOL, stored.name, stored.size, "", stored.mime_type)+ return stored, self._with_access(file)++ def resolve_files(+ self,+ *,+ context: FileGrantContext,+ refs: Sequence[FileRef],+ ) -> list[ResolvedFile | None]:+ self._validate_ref_count(refs)+ if not self._repository.subject_exists(context):+ raise EndUserNotFoundError(context.end_user_id)+ return self._repository.resolve_owned_files(context=context, refs=refs)++ def resolve_file_access(+ self,+ *,+ context: FileGrantContext,+ refs: Sequence[FileRef],+ ) -> list[ResolvedFileAccess | None]:+ return [+ self._with_access(file) if file is not None else None+ for file in self.resolve_files(context=context, refs=refs)+ ]++ def load_content(self, *, token: str, requested_file_id: str) -> FileContent | None:+ claims = self._tokens.decode_content_token(token)+ if claims is None:+ raise InvalidFileGrantError()+ if claims.file_id != requested_file_id:+ return None+ record = self._repository.get_content_record(file_id=requested_file_id, kind=claims.kind)+ return self._files.open_content(record) if record is not None else None++ def content_urls(self, *, file_id: str, kind: FileKind) -> tuple[str, str]:+ return self._tokens.issue_content_urls(file_id=file_id, kind=kind)++ def _with_access(self, file: ResolvedFile) -> ResolvedFileAccess:+ external_url, internal_url = self._tokens.issue_content_urls(file_id=file.id, kind=file.kind)+ return ResolvedFileAccess(file=file, external_url=external_url, internal_url=internal_url)++ def _effective_ttl_seconds(self, request: FileGrantMintRequest) -> int:+ if request.run_deadline is None:+ if request.ttl_seconds > MAX_SESSION_GRANT_TTL_SECONDS:+ raise GrantTtlTooLongError()+ return request.ttl_seconds++ now = self._now()+ if FileGrantScope.PRODUCE not in request.scopes:+ raise InvalidGrantRequestError("A run deadline requires the produce scope.")+ if request.run_deadline <= now:+ raise InvalidGrantRequestError("The run deadline has expired.")+ if request.run_deadline > now + MAX_WORKFLOW_EXECUTION_SECONDS:+ raise InvalidGrantRequestError("The run deadline exceeds the workflow execution limit.")+ if request.ttl_seconds > MAX_RUN_GRANT_TTL_SECONDS:+ raise GrantTtlTooLongError()+ return min(request.ttl_seconds, request.run_deadline - now + RUN_GRANT_EXPIRY_GRACE_SECONDS)++ @staticmethod+ def _validate_subject(subject: str) -> None:+ if not subject.strip() or "\x00" in subject:+ raise InvalidSubjectError()++ @staticmethod+ def _validate_ref_count(refs: Sequence[FileRef]) -> None:+ if len(refs) > MAX_FILE_GRANT_REFS:+ raise TooManyFileRefsError(f"A file grant request may contain at most {MAX_FILE_GRANT_REFS} references.")+++__all__ = [+ "MAX_FILE_GRANT_REFS",+ "MAX_RUN_GRANT_TTL_SECONDS",+ "MAX_SESSION_GRANT_TTL_SECONDS",+ "MAX_WORKFLOW_EXECUTION_SECONDS",+ "RUN_GRANT_EXPIRY_GRACE_SECONDS",+ "AppNotFoundError",+ "EndUserNotFoundError",+ "FileGrantService",+ "GrantTtlTooLongError",+ "GrantedFileNotFoundError",+ "InvalidFileGrantError",+ "InvalidGrantRequestError",+ "InvalidSubjectError",+ "RemoteFileUnavailableError",+ "TooManyFileRefsError",+]diff --git a/api/services/file_service.py b/api/services/file_service.pyindex 4497639eb25..9c387720002 100644--- a/api/services/file_service.py+++ b/api/services/file_service.py@@ -131,21 +131,32 @@ class FileService:file_size: int,default_file_size_limit: int | None = None,) -> bool:+ return file_size <= FileService.file_size_limit(+ extension=extension,+ default_file_size_limit=default_file_size_limit,+ )++ @staticmethod+ def file_size_limit(+ *,+ extension: str,+ default_file_size_limit: int | None = None,+ ) -> int:+ """Return the size an extension is allowed, in bytes."""+if extension in IMAGE_EXTENSIONS:- file_size_limit = dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT * 1024 * 1024+ file_size_limit = dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMITelif extension in VIDEO_EXTENSIONS:- file_size_limit = dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT * 1024 * 1024+ file_size_limit = dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMITelif extension in AUDIO_EXTENSIONS:- file_size_limit = dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT * 1024 * 1024+ file_size_limit = dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMITelse:# Context-specific uploads may override the default limit without changing media-specific limits.file_size_limit = (- (default_file_size_limit if default_file_size_limit is not None else dify_config.UPLOAD_FILE_SIZE_LIMIT)- * 1024- * 1024+ default_file_size_limit if default_file_size_limit is not None else dify_config.UPLOAD_FILE_SIZE_LIMIT)- return file_size <= file_size_limit+ return file_size_limit * 1024 * 1024def get_file_base64(self, file_id: str) -> str:with self._session_maker(expire_on_commit=False) as session:diff --git a/api/services/web_passport_gateways.py b/api/services/web_passport_gateways.pyindex f6cf423302a..774a864e74a 100644--- a/api/services/web_passport_gateways.py+++ b/api/services/web_passport_gateways.py@@ -10,6 +10,16 @@ from services.enterprise.enterprise_service import PERMISSION_CHECK_MODES, WebApfrom services.web_passport_service import WebAppAuthType, WebPassportUnauthorizedError+def resolve_web_app_auth_type(access_mode: str) -> WebAppAuthType:+ if access_mode == WebAppAccessMode.PUBLIC:+ return WebAppAuthType.PUBLIC+ if access_mode in PERMISSION_CHECK_MODES:+ return WebAppAuthType.INTERNAL+ if access_mode == WebAppAccessMode.SSO_VERIFIED:+ return WebAppAuthType.EXTERNAL+ raise ValueError(f"Unsupported web app access mode: {access_mode}")++class DeploymentWebPassportAuthGateway:def __init__(self,@@ -25,13 +35,7 @@ class DeploymentWebPassportAuthGateway:def get_app_auth_type(self, app_id: str) -> WebAppAuthType:access_mode = self._get_app_access_mode(app_id).access_mode- if access_mode == WebAppAccessMode.PUBLIC:- return WebAppAuthType.PUBLIC- if access_mode in PERMISSION_CHECK_MODES:- return WebAppAuthType.INTERNAL- if access_mode == WebAppAccessMode.SSO_VERIFIED:- return WebAppAuthType.EXTERNAL- raise ValueError(f"Unsupported web app access mode: {access_mode}")+ return resolve_web_app_auth_type(access_mode)class PassportTokenGateway:diff --git a/api/tests/test_containers_integration_tests/controllers/web/test_wraps.py b/api/tests/test_containers_integration_tests/controllers/web/test_wraps.pyindex 9a143ab3bc3..5bda3738af5 100644--- a/api/tests/test_containers_integration_tests/controllers/web/test_wraps.py+++ b/api/tests/test_containers_integration_tests/controllers/web/test_wraps.py@@ -91,8 +91,8 @@ class TestValidateUserAccessibility:def test_missing_auth_type_raises(self) -> None:decoded = {"user_id": "u1", "granted_at": 1}- settings = SimpleNamespace(access_mode="public")- with pytest.raises(WebAppAuthAccessDeniedError, match="auth_type"):+ settings = SimpleNamespace(access_mode="private")+ with pytest.raises(WebAppAuthRequiredError, match="auth_type"):_validate_user_accessibility(decoded=decoded,app_code="code",@@ -103,7 +103,7 @@ class TestValidateUserAccessibility:def test_missing_granted_at_raises(self) -> None:decoded = {"user_id": "u1", "auth_type": "external"}- settings = SimpleNamespace(access_mode="public")+ settings = SimpleNamespace(access_mode="sso_verified")with pytest.raises(WebAppAuthAccessDeniedError, match="granted_at"):_validate_user_accessibility(decoded=decoded,@@ -121,7 +121,7 @@ class TestValidateUserAccessibility:mock_sso_time.return_value = datetime.now(UTC)old_granted = int((datetime.now(UTC) - timedelta(hours=1)).timestamp())decoded = {"user_id": "u1", "auth_type": "external", "granted_at": old_granted}- settings = SimpleNamespace(access_mode="public")+ settings = SimpleNamespace(access_mode="sso_verified")with pytest.raises(WebAppAuthAccessDeniedError, match="SSO settings"):_validate_user_accessibility(decoded=decoded,@@ -139,7 +139,7 @@ class TestValidateUserAccessibility:mock_workspace_sso.return_value = datetime.now(UTC)old_granted = int((datetime.now(UTC) - timedelta(hours=1)).timestamp())decoded = {"user_id": "u1", "auth_type": "internal", "granted_at": old_granted}- settings = SimpleNamespace(access_mode="public")+ settings = SimpleNamespace(access_mode="private")with pytest.raises(WebAppAuthAccessDeniedError, match="SSO settings"):_validate_user_accessibility(decoded=decoded,@@ -157,7 +157,7 @@ class TestValidateUserAccessibility:mock_sso_time.return_value = datetime.now(UTC) - timedelta(hours=2)recent_granted = int(datetime.now(UTC).timestamp())decoded = {"user_id": "u1", "auth_type": "external", "granted_at": recent_granted}- settings = SimpleNamespace(access_mode="public")+ settings = SimpleNamespace(access_mode="sso_verified")_validate_user_accessibility(decoded=decoded,app_code="code",@@ -172,8 +172,8 @@ class TestValidateUserAccessibility:def test_permission_check_denies_unauthorized_user(self, mock_perm: MagicMock, mock_app_id: MagicMock, mock_allowed: MagicMock) -> None:- decoded = {"user_id": "u1", "auth_type": "external", "granted_at": int(datetime.now(UTC).timestamp())}- settings = SimpleNamespace(access_mode="internal")+ decoded = {"user_id": "u1", "auth_type": "internal", "granted_at": int(datetime.now(UTC).timestamp())}+ settings = SimpleNamespace(access_mode="private")with pytest.raises(WebAppAuthAccessDeniedError):_validate_user_accessibility(decoded=decoded,@@ -183,6 +183,37 @@ class TestValidateUserAccessibility:webapp_settings=settings,)+ @pytest.mark.parametrize(+ ("access_mode", "auth_type"),+ [+ pytest.param("private", "external", id="private-rejects-external"),+ pytest.param("private_all", "external", id="private-all-rejects-external"),+ pytest.param("sso_verified", "internal", id="sso-verified-rejects-internal"),+ ],+ )+ @patch("controllers.web.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp")+ @patch("controllers.web.wraps.WebAppAuthService.is_app_require_permission_check")+ def test_auth_type_must_match_current_access_mode(+ self,+ mock_permission_check: MagicMock,+ mock_allowed: MagicMock,+ access_mode: str,+ auth_type: str,+ ) -> None:+ decoded = {"user_id": "u1", "auth_type": auth_type, "granted_at": int(datetime.now(UTC).timestamp())}++ with pytest.raises(WebAppAuthRequiredError):+ _validate_user_accessibility(+ decoded=decoded,+ app_code="code",+ app_web_auth_enabled=True,+ system_webapp_auth_enabled=True,+ webapp_settings=SimpleNamespace(access_mode=access_mode),+ )++ mock_permission_check.assert_not_called()+ mock_allowed.assert_not_called()+class TestDecodeJwtToken:@pytest.fixturediff --git a/api/tests/unit_tests/controllers/files/test_appdeploy_files.py b/api/tests/unit_tests/controllers/files/test_appdeploy_files.pynew file mode 100644index 00000000000..b9e7d6e289e--- /dev/null+++ b/api/tests/unit_tests/controllers/files/test_appdeploy_files.py@@ -0,0 +1,833 @@+"""Tests for the file endpoints reached with an AppDeploy file grant."""++import time+from collections.abc import Callable, Iterator+from datetime import datetime+from io import BytesIO+from types import SimpleNamespace+from typing import IO, cast+from unittest.mock import MagicMock, patch+from uuid import UUID++import jwt+import pytest+from flask import Flask+from sqlalchemy import update+from sqlalchemy.engine import Engine+from sqlalchemy.orm import Session, sessionmaker++from controllers.common.errors import (+ BlockedFileExtensionError,+ FilenameNotExistsError,+ FileTooLargeError,+ NoFileUploadedError,+ TooManyFilesError,+)+from controllers.files.appdeploy_files import (+ GrantedFileContentApi,+ GrantedFileResolveApi,+ GrantedFileUploadApi,+ GrantedRemoteFileUploadApi,+ InvalidFileRequestError,+ ProducedFileApi,+)+from controllers.files.wraps import FileGrantInvalidError, GrantedFileNotFoundError+from extensions.ext_application_services import _build_file_grant_service+from extensions.storage.storage_type import StorageType+from libs.datetime_utils import naive_utc_now+from models.enums import CreatorUserRole, EndUserType+from models.model import EndUser, UploadFile+from models.tools import ToolFile+from services.entities.file_grant_entities import FileGrantContext, FileGrantScope, FileKind, RemoteFile+from services.errors.file import FileTooLargeError as FileTooLargeServiceError+from services.file_grant_gateways import FILE_CONTENT_AUDIENCE, FileGrantFileGateway+from services.file_grant_service import MAX_FILE_GRANT_REFS, FileGrantService+from tests.unit_tests.file_grant_test_utils import issue_file_grant++CONTROLLER_MODULE = "controllers.files.appdeploy_files"++SECRET_KEY = "file-grant-test-secret-long-enough-for-hs256"+TENANT_ID = "11111111-1111-4111-8111-111111111111"+OTHER_TENANT_ID = "1a1a1a1a-1111-4111-8111-111111111111"+APP_ID = "22222222-2222-4222-8222-222222222222"+FILE_ID = UUID("66666666-6666-4666-8666-666666666666")+UPLOAD_FILE_ID = "77777777-7777-4777-8777-777777777777"+UPLOADED_AT = datetime(2026, 8, 20, 12, 0)++# What ``POST /v1/files/upload`` answers with. The grant channel is a drop-in+# for it, so the whole key set travels together and a key dify leaves null must+# still be present and null here.+DIFY_UPLOAD_RESPONSE_KEYS = frozenset(+ {+ "id",+ "reference",+ "name",+ "size",+ "extension",+ "mime_type",+ "created_by",+ "created_at",+ "preview_url",+ "source_url",+ "original_url",+ "user_id",+ "tenant_id",+ "conversation_id",+ "file_key",+ }+)++# The subset dify's own web upload client reads, from+# ``web/app/components/base/file-uploader/utils.ts``.+WEB_CLIENT_KEYS = frozenset(+ {+ "id",+ "name",+ "size",+ "extension",+ "mime_type",+ "created_by",+ "created_at",+ "preview_url",+ "source_url",+ }+)++[email protected](autouse=True)+def granted_config(config_overrides: Callable[..., None]) -> None:+ config_overrides(+ SECRET_KEY=SECRET_KEY,+ FILES_URL="https://files.example.com",+ INTERNAL_FILES_URL="http://dify-api.dify.svc:5001",+ FILES_ACCESS_TIMEOUT=300,+ )+++def sqlite_db(sqlite_engine: Engine) -> Iterator[FileGrantService]:+ service = _build_file_grant_service(database_client=sessionmaker(bind=sqlite_engine, expire_on_commit=False))+ services = SimpleNamespace(file_grants=service)+ with (+ patch(f"{CONTROLLER_MODULE}.application_services", return_value=services),+ patch("controllers.files.wraps.application_services", return_value=services),+ ):+ yield service+++def file_gateway(sqlite_db: FileGrantService) -> FileGrantFileGateway:+ return cast(FileGrantFileGateway, sqlite_db._files)+++def end_user(sqlite_session: Session) -> EndUser:+ record = EndUser(+ tenant_id=TENANT_ID,+ app_id=APP_ID,+ type=EndUserType.APP_DEPLOY,+ is_anonymous=True,+ session_id="seeded",+ external_user_id="adp1.seeded",+ )+ sqlite_session.add(record)+ sqlite_session.commit()+ return record+++def _bearer(*scopes: FileGrantScope, end_user_id: str, tenant_id: str = TENANT_ID) -> dict[str, str]:+ token, _ = issue_file_grant(+ end_user_id=end_user_id,+ tenant_id=tenant_id,+ app_id=APP_ID,+ scopes=scopes,+ ttl_seconds=600,+ )+ return {"Authorization": f"Bearer {token}"}+++def _content_token(*, file_id: str, kind: FileKind, expires_in: int = 300) -> str:+ return jwt.encode(+ {+ "aud": FILE_CONTENT_AUDIENCE,+ "kind": str(kind),+ "file_id": file_id,+ "nonce": "0011223344556677",+ "exp": int(time.time()) + expires_in,+ },+ SECRET_KEY,+ algorithm="HS256",+ )+++def _stub_upload_file(**overrides: object) -> SimpleNamespace:+ """Stand in for the ``upload_files`` row ``FileService`` hands back."""++ return SimpleNamespace(+ **{+ "id": UPLOAD_FILE_ID,+ "name": "report.pdf",+ "size": 2048,+ "extension": "pdf",+ "mime_type": "application/pdf",+ "tenant_id": TENANT_ID,+ "created_by": "99999999-9999-4999-8999-999999999999",+ "created_at": UPLOADED_AT,+ "source_url": "",+ **overrides,+ }+ )+++def _persist_upload_file(session: Session, *, owner_id: str, tenant_id: str = TENANT_ID) -> UploadFile:+ upload_file = UploadFile(+ tenant_id=tenant_id,+ storage_type=StorageType.OPENDAL,+ key="upload_files/report.pdf",+ name="report.pdf",+ size=2048,+ extension="pdf",+ mime_type="application/pdf",+ created_by=owner_id,+ created_by_role=CreatorUserRole.END_USER,+ created_at=naive_utc_now(),+ used=False,+ )+ session.add(upload_file)+ session.commit()+ return upload_file+++def _persist_tool_file(session: Session, *, owner_id: str, mimetype: str = "image/png") -> ToolFile:+ tool_file = ToolFile(+ user_id=owner_id,+ tenant_id=TENANT_ID,+ conversation_id=None,+ file_key="tools/chart.png",+ mimetype=mimetype,+ name="chart.png",+ size=64,+ )+ session.add(tool_file)+ session.commit()+ return tool_file+++def test_upload_stores_the_file_for_the_grant_end_user(+ app: Flask, end_user: EndUser, file_gateway: FileGrantFileGateway+) -> None:+ with (+ patch.object(file_gateway, "store_upload", wraps=file_gateway.store_upload) as store_upload,+ patch.object(file_gateway._file_service, "upload_file", return_value=_stub_upload_file()),+ ):+ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={"file": (BytesIO(b"pdf-bytes"), "report.pdf")},+ content_type="multipart/form-data",+ ):+ body, status = GrantedFileUploadApi().post()++ assert status == 201+ assert body["id"] == UPLOAD_FILE_ID+ assert body["extension"] == "pdf"+ assert store_upload.call_args.kwargs["context"].end_user_id == end_user.id+++def test_upload_answers_in_dify_s_own_upload_shape(+ app: Flask, end_user: EndUser, file_gateway: FileGrantFileGateway+) -> None:+ """A client moving off ``POST /v1/files/upload`` must not meet a second shape."""++ with patch.object(+ file_gateway._file_service,+ "upload_file",+ return_value=_stub_upload_file(created_by=end_user.id),+ ):+ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={"file": (BytesIO(b"pdf-bytes"), "report.pdf")},+ content_type="multipart/form-data",+ ):+ body, _ = GrantedFileUploadApi().post()++ source_url = body.pop("source_url")+ assert body == {+ "id": UPLOAD_FILE_ID,+ "reference": None,+ "name": "report.pdf",+ "size": 2048,+ "extension": "pdf",+ "mime_type": "application/pdf",+ "created_by": end_user.id,+ "created_at": int(UPLOADED_AT.timestamp()),+ "preview_url": None,+ "original_url": None,+ "user_id": None,+ "tenant_id": TENANT_ID,+ "conversation_id": None,+ "file_key": None,+ }+ assert source_url.startswith(f"https://files.example.com/files/appdeploy/{UPLOAD_FILE_ID}/content?token=")+++def test_upload_carries_every_key_dify_s_web_client_reads(+ app: Flask, end_user: EndUser, file_gateway: FileGrantFileGateway+) -> None:+ with patch.object(file_gateway._file_service, "upload_file", return_value=_stub_upload_file()):+ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={"file": (BytesIO(b"pdf-bytes"), "report.pdf")},+ content_type="multipart/form-data",+ ):+ body, _ = GrantedFileUploadApi().post()++ assert set(body) >= WEB_CLIENT_KEYS++[email protected]("sqlite_db")+def test_upload_rejects_a_grant_from_another_tenant(app: Flask, end_user: EndUser) -> None:+ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id, tenant_id=OTHER_TENANT_ID),+ data={"file": (BytesIO(b"pdf-bytes"), "report.pdf")},+ content_type="multipart/form-data",+ ):+ with pytest.raises(GrantedFileNotFoundError):+ GrantedFileUploadApi().post()++[email protected]("sqlite_db")+def test_upload_applies_the_shared_per_extension_size_limit(+ app: Flask, end_user: EndUser, config_overrides: Callable[..., None]+) -> None:+ config_overrides(UPLOAD_FILE_SIZE_LIMIT=1)++ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={"file": (BytesIO(b"0" * (1024 * 1024 + 1)), "big.bin")},+ content_type="multipart/form-data",+ ):+ with pytest.raises(FileTooLargeError):+ GrantedFileUploadApi().post()++[email protected]("sqlite_db")+def test_upload_rejects_a_blacklisted_extension(+ app: Flask, end_user: EndUser, config_overrides: Callable[..., None]+) -> None:+ config_overrides(inner_UPLOAD_FILE_EXTENSION_BLACKLIST="exe")++ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={"file": (BytesIO(b"MZ"), "payload.exe")},+ content_type="multipart/form-data",+ ):+ with pytest.raises(BlockedFileExtensionError):+ GrantedFileUploadApi().post()++[email protected]("sqlite_db")+def test_upload_rejects_a_request_carrying_no_file(app: Flask, end_user: EndUser) -> None:+ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={"note": "no file here"},+ content_type="multipart/form-data",+ ):+ with pytest.raises(NoFileUploadedError):+ GrantedFileUploadApi().post()++[email protected]("sqlite_db")+def test_upload_rejects_a_batch_of_files(app: Flask, end_user: EndUser) -> None:+ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={+ "file": (BytesIO(b"first"), "first.pdf"),+ "second": (BytesIO(b"second"), "second.pdf"),+ },+ content_type="multipart/form-data",+ ):+ with pytest.raises(TooManyFilesError):+ GrantedFileUploadApi().post()++[email protected]("sqlite_db")+def test_upload_rejects_a_file_without_a_name(app: Flask, end_user: EndUser) -> None:+ with app.test_request_context(+ "/files/appdeploy/upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ data={"file": (BytesIO(b"nameless"), "")},+ content_type="multipart/form-data",+ ):+ with pytest.raises(FilenameNotExistsError):+ GrantedFileUploadApi().post()+++def test_remote_upload_fetches_through_the_ssrf_safe_fetcher(+ app: Flask, end_user: EndUser, sqlite_db: FileGrantService, file_gateway: FileGrantFileGateway+) -> None:+ url = "https://example.com/docs/report.pdf"++ with (+ patch.object(+ sqlite_db._remote_files,+ "fetch",+ return_value=RemoteFile(filename="report.pdf", mimetype="application/pdf", content=b"pdf-bytes"),+ ) as fetch,+ patch.object(file_gateway._file_service, "upload_file", return_value=_stub_upload_file()) as upload_file,+ ):+ with app.test_request_context(+ "/files/appdeploy/remote-upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ json={"url": url},+ ):+ with patch(f"{CONTROLLER_MODULE}.files_ns") as files_ns:+ files_ns.payload = {"url": url}+ body, status = GrantedRemoteFileUploadApi().post()++ assert status == 201+ assert body["id"] == UPLOAD_FILE_ID+ fetch.assert_called_once_with(url)+ kwargs = upload_file.call_args.kwargs+ assert kwargs["source_url"] == url+ assert kwargs["content"] == b"pdf-bytes"+ assert kwargs["user"].id == end_user.id+++def test_remote_upload_answers_in_the_upload_shape_plus_dify_s_url_key(+ app: Flask, end_user: EndUser, sqlite_db: FileGrantService, file_gateway: FileGrantFileGateway+) -> None:+ """Dify's own remote upload answers under ``url``, so this one answers under both."""++ url = "https://example.com/docs/report.pdf"+ with (+ patch.object(+ sqlite_db._remote_files,+ "fetch",+ return_value=RemoteFile(filename="report.pdf", mimetype="application/pdf", content=b"pdf-bytes"),+ ),+ patch.object(+ file_gateway._file_service,+ "upload_file",+ return_value=_stub_upload_file(source_url=url),+ ),+ ):+ with app.test_request_context(+ "/files/appdeploy/remote-upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ json={"url": url},+ ):+ with patch(f"{CONTROLLER_MODULE}.files_ns") as files_ns:+ files_ns.payload = {"url": url}+ body, _ = GrantedRemoteFileUploadApi().post()++ assert set(body) == DIFY_UPLOAD_RESPONSE_KEYS | {"url"}+ # The row records where the bytes came from; the response hands back the+ # signed URL that fetches them, exactly as dify's own remote upload does.+ assert body["source_url"].startswith(f"https://files.example.com/files/appdeploy/{UPLOAD_FILE_ID}/content?token=")+ # One URL under both names, not two signings of the same file.+ assert body["url"] == body["source_url"]+++def test_remote_upload_honours_the_size_precheck(app: Flask, end_user: EndUser, sqlite_db: FileGrantService) -> None:+ url = "https://example.com/docs/huge.pdf"+ with patch.object(+ sqlite_db._remote_files,+ "fetch",+ side_effect=FileTooLargeServiceError("too large"),+ ):+ with app.test_request_context(+ "/files/appdeploy/remote-upload",+ method="POST",+ headers=_bearer(FileGrantScope.UPLOAD, end_user_id=end_user.id),+ json={"url": url},+ ):+ with patch(f"{CONTROLLER_MODULE}.files_ns") as files_ns:+ files_ns.payload = {"url": url}+ with pytest.raises(FileTooLargeError):+ GrantedRemoteFileUploadApi().post()+++def test_produced_stores_a_tool_file_and_returns_both_urls(+ app: Flask, end_user: EndUser, file_gateway: FileGrantFileGateway+) -> None:+ tool_file = SimpleNamespace(+ id="88888888-8888-4888-8888-888888888888",+ name="chart.png",+ size=64,+ mimetype="image/png",+ )++ with patch.object(file_gateway._tool_files, "create_file_by_raw", return_value=tool_file) as create_file:+ with app.test_request_context(+ "/files/appdeploy/produced",+ method="POST",+ headers=_bearer(FileGrantScope.PRODUCE, end_user_id=end_user.id),+ data={"file": (BytesIO(b"0" * 16), "chart.png")},+ content_type="multipart/form-data",+ ):+ body, status = ProducedFileApi().post()++ assert status == 201+ kwargs = create_file.call_args.kwargs+ assert kwargs["user_id"] == end_user.id+ assert kwargs["tenant_id"] == TENANT_ID+ assert kwargs["conversation_id"] is None+ assert body["url"].startswith(f"https://files.example.com/files/appdeploy/{tool_file.id}/content?token=")+ assert body["internal_url"].startswith(+ f"http://dify-api.dify.svc:5001/files/appdeploy/{tool_file.id}/content?token="+ )+++def test_produced_rejects_a_grant_whose_subject_was_deleted(app: Flask, file_gateway: FileGrantFileGateway) -> None:+ with patch.object(file_gateway._tool_files, "create_file_by_raw") as create_file:+ with app.test_request_context(+ "/files/appdeploy/produced",+ method="POST",+ headers=_bearer(+ FileGrantScope.PRODUCE,+ end_user_id="99999999-9999-4999-8999-999999999999",+ ),+ data={"file": (BytesIO(b"content"), "chart.png")},+ content_type="multipart/form-data",+ ):+ with pytest.raises(GrantedFileNotFoundError):+ ProducedFileApi().post()++ create_file.assert_not_called()+++def one_megabyte_image_limit(config_overrides: Callable[..., None]) -> int:+ """Hold images to one mebibyte while every other kind stays far above it."""++ config_overrides(+ UPLOAD_FILE_SIZE_LIMIT=64,+ UPLOAD_IMAGE_FILE_SIZE_LIMIT=1,+ UPLOAD_VIDEO_FILE_SIZE_LIMIT=64,+ UPLOAD_AUDIO_FILE_SIZE_LIMIT=64,+ )+ return 1024 * 1024+++def test_produced_accepts_a_file_of_exactly_the_per_extension_limit(+ app: Flask, end_user: EndUser, file_gateway: FileGrantFileGateway, one_megabyte_image_limit: int+) -> None:+ with patch.object(+ file_gateway._tool_files,+ "create_file_by_raw",+ return_value=SimpleNamespace(+ id="88888888-8888-4888-8888-888888888888",+ name="chart.png",+ size=one_megabyte_image_limit,+ mimetype="image/png",+ ),+ ) as create_file:+ with app.test_request_context(+ "/files/appdeploy/produced",+ method="POST",+ headers=_bearer(FileGrantScope.PRODUCE, end_user_id=end_user.id),+ data={"file": (BytesIO(b"0" * one_megabyte_image_limit), "chart.png")},+ content_type="multipart/form-data",+ ):+ _, status = ProducedFileApi().post()++ assert status == 201+ assert len(create_file.call_args.kwargs["file_binary"]) == one_megabyte_image_limit+++def test_produced_rejects_a_file_one_byte_over_the_per_extension_limit(+ app: Flask, end_user: EndUser, file_gateway: FileGrantFileGateway, one_megabyte_image_limit: int+) -> None:+ """``create_file_by_raw`` has no limit of its own, so nothing else would stop this."""++ with patch.object(file_gateway._tool_files, "create_file_by_raw") as create_file:+ with app.test_request_context(+ "/files/appdeploy/produced",+ method="POST",+ headers=_bearer(FileGrantScope.PRODUCE, end_user_id=end_user.id),+ data={"file": (BytesIO(b"0" * (one_megabyte_image_limit + 1)), "chart.png")},+ content_type="multipart/form-data",+ ):+ with pytest.raises(FileTooLargeError) as raised:+ ProducedFileApi().post()++ assert raised.value.code == 413+ create_file.assert_not_called()+++class _CountingStream:+ """A body that reports how much of itself a reader actually pulled."""++ def __init__(self, size: int) -> None:+ self._remaining = size+ self.bytes_read = 0++ def read(self, size: int = -1) -> bytes:+ served = self._remaining if size < 0 else min(size, self._remaining)+ self._remaining -= served+ self.bytes_read += served+ return b"0" * served+++def test_produced_stops_reading_an_oversized_body_at_the_per_extension_limit(+ end_user: EndUser,+ sqlite_db: FileGrantService,+ file_gateway: FileGrantFileGateway,+ one_megabyte_image_limit: int,+) -> None:+ """The caller is a worker running plugin code with no proxy body limit in front of it."""++ stream = _CountingStream(one_megabyte_image_limit * 64)++ with patch.object(file_gateway._tool_files, "create_file_by_raw") as create_file:+ with pytest.raises(FileTooLargeServiceError):+ sqlite_db.store_produced(+ context=FileGrantContext(TENANT_ID, APP_ID, end_user.id),+ filename="chart.png",+ stream=cast(IO[bytes], stream),+ mimetype="image/png",+ )++ assert stream.bytes_read == one_megabyte_image_limit + 1+ create_file.assert_not_called()++[email protected]("sqlite_db")+def test_resolve_signs_urls_per_item_and_hides_foreign_files(+ app: Flask, end_user: EndUser, sqlite_session: Session+) -> None:+ owned = _persist_upload_file(sqlite_session, owner_id=end_user.id)+ foreign = _persist_upload_file(sqlite_session, owner_id="00000000-0000-4000-8000-000000000000")+ payload = {+ "files": [+ {"id": owned.id, "kind": "upload"},+ {"id": foreign.id, "kind": "upload"},+ ]+ }++ with app.test_request_context(+ "/files/appdeploy/resolve",+ method="POST",+ headers=_bearer(FileGrantScope.RESOLVE, end_user_id=end_user.id),+ json=payload,+ ):+ with patch(f"{CONTROLLER_MODULE}.files_ns") as files_ns:+ files_ns.payload = payload+ body = GrantedFileResolveApi().post()++ resolved, hidden = body["files"]+ assert resolved["ok"] is True+ assert resolved["kind"] == "upload"+ assert resolved["extension"] == "pdf"+ assert resolved["url"].startswith(f"https://files.example.com/files/appdeploy/{owned.id}/content?token=")+ assert resolved["internal_url"].startswith(+ f"http://dify-api.dify.svc:5001/files/appdeploy/{owned.id}/content?token="+ )+ assert hidden == {+ "id": foreign.id,+ "ok": False,+ "kind": None,+ "name": None,+ "size": None,+ "extension": None,+ "mime_type": None,+ "url": None,+ "internal_url": None,+ "error": "not_found",+ }++[email protected]("sqlite_db")+def test_resolve_answers_a_mixed_batch_item_by_item(app: Flask, end_user: EndUser, sqlite_session: Session) -> None:+ owned_upload = _persist_upload_file(sqlite_session, owner_id=end_user.id)+ owned_tool = _persist_tool_file(sqlite_session, owner_id=end_user.id)+ missing_id = "44444444-4444-4444-8444-444444444444"+ payload = {+ "files": [+ {"id": owned_upload.id, "kind": "upload"},+ {"id": missing_id, "kind": "upload"},+ # A real file, but looked up in the wrong table.+ {"id": owned_upload.id, "kind": "tool"},+ {"id": owned_tool.id, "kind": "tool"},+ ]+ }++ with app.test_request_context(+ "/files/appdeploy/resolve",+ method="POST",+ headers=_bearer(FileGrantScope.RESOLVE, end_user_id=end_user.id),+ json=payload,+ ):+ with patch(f"{CONTROLLER_MODULE}.files_ns") as files_ns:+ files_ns.payload = payload+ body = GrantedFileResolveApi().post()++ assert [(file["id"], file["ok"], file["kind"], file["error"]) for file in body["files"]] == [+ (owned_upload.id, True, "upload", None),+ (missing_id, False, None, "not_found"),+ (owned_upload.id, False, None, "not_found"),+ (owned_tool.id, True, "tool", None),+ ]++[email protected]("sqlite_db")+def test_resolve_returns_an_empty_batch_unchanged(app: Flask, end_user: EndUser) -> None:+ payload: dict[str, object] = {"files": []}++ with app.test_request_context(+ "/files/appdeploy/resolve",+ method="POST",+ headers=_bearer(FileGrantScope.RESOLVE, end_user_id=end_user.id),+ json=payload,+ ):+ with patch(f"{CONTROLLER_MODULE}.files_ns") as files_ns:+ files_ns.payload = payload+ assert GrantedFileResolveApi().post() == {"files": []}+++def test_resolve_rejects_an_unbounded_batch(app: Flask, end_user: EndUser, sqlite_db: FileGrantService) -> None:+ del sqlite_db+ payload = {+ "files": [+ {"id": f"00000000-0000-4000-8000-{index:012d}", "kind": "upload"}+ for index in range(MAX_FILE_GRANT_REFS + 1)+ ]+ }+ with app.test_request_context(+ "/files/appdeploy/resolve",+ method="POST",+ headers=_bearer(FileGrantScope.RESOLVE, end_user_id=end_user.id),+ json=payload,+ ):+ with patch(f"{CONTROLLER_MODULE}.files_ns") as files_ns:+ files_ns.payload = payload+ with pytest.raises(InvalidFileRequestError):+ GrantedFileResolveApi().post()+++def stored_bytes(file_gateway: FileGrantFileGateway) -> Iterator[MagicMock]:+ with patch.object(file_gateway._storage, "load", return_value=iter([b"file-bytes"])) as load:+ yield load++[email protected]("sqlite_db", "stored_bytes")+ ("mime_type", "expected_content_type", "expects_attachment"),+ [+ ("image/png", "image/png", False),+ ("image/jpeg", "image/jpeg", False),+ ("image/gif", "image/gif", False),+ ("image/webp", "image/webp", False),+ # Case and parameters are normalized before the whitelist is consulted.+ ("IMAGE/PNG; charset=binary", "image/png", False),+ ("application/pdf", "application/octet-stream", True),+ ("image/svg+xml", "application/octet-stream", True),+ ("text/html", "application/octet-stream", True),+ ("application/xhtml+xml", "application/octet-stream", True),+ ("text/javascript", "application/octet-stream", True),+ ("audio/mpeg", "application/octet-stream", True),+ ("video/mp4", "application/octet-stream", True),+ ],+)+def test_content_disposition_follows_the_inline_whitelist(+ app: Flask,+ sqlite_session: Session,+ mime_type: str,+ expected_content_type: str,+ expects_attachment: bool,+) -> None:+ tool_file = _persist_tool_file(sqlite_session, owner_id="anyone", mimetype=mime_type)+ token = _content_token(file_id=tool_file.id, kind=FileKind.TOOL)++ with app.test_request_context(f"/files/appdeploy/{tool_file.id}/content", query_string={"token": token}):+ response = GrantedFileContentApi().get(UUID(tool_file.id))++ assert response.headers["X-Content-Type-Options"] == "nosniff"+ assert response.headers["Content-Type"].startswith(expected_content_type)+ assert ("Content-Disposition" in response.headers) is expects_attachment+ if expects_attachment:+ assert response.headers["Content-Disposition"] == "attachment; filename*=UTF-8''chart.png"+ # Range is never honoured here, so the hint must not be advertised either.+ assert "Accept-Ranges" not in response.headers+ assert response.headers["Content-Length"] == "64"++[email protected]("sqlite_db", "stored_bytes")+def test_content_downloads_a_file_with_no_recorded_mime_type(app: Flask, sqlite_session: Session) -> None:+ upload_file = _persist_upload_file(sqlite_session, owner_id="anyone")+ sqlite_session.execute(update(UploadFile).where(UploadFile.id == upload_file.id).values(mime_type=None))+ sqlite_session.commit()+ token = _content_token(file_id=upload_file.id, kind=FileKind.UPLOAD)++ with app.test_request_context(f"/files/appdeploy/{upload_file.id}/content", query_string={"token": token}):+ response = GrantedFileContentApi().get(UUID(upload_file.id))++ assert response.headers["X-Content-Type-Options"] == "nosniff"+ assert response.headers["Content-Type"].startswith("application/octet-stream")+ assert response.headers["Content-Disposition"] == "attachment; filename*=UTF-8''report.pdf"++[email protected]("sqlite_db", "stored_bytes")+def test_content_rejects_an_expired_token(app: Flask, sqlite_session: Session) -> None:+ tool_file = _persist_tool_file(sqlite_session, owner_id="anyone")+ token = _content_token(file_id=tool_file.id, kind=FileKind.TOOL, expires_in=-1)++ with app.test_request_context(f"/files/appdeploy/{tool_file.id}/content", query_string={"token": token}):+ with pytest.raises(FileGrantInvalidError):+ GrantedFileContentApi().get(UUID(tool_file.id))++[email protected]("sqlite_db", "stored_bytes")+def test_content_rejects_a_token_minted_for_another_file(app: Flask, sqlite_session: Session) -> None:+ tool_file = _persist_tool_file(sqlite_session, owner_id="anyone")+ token = _content_token(file_id=str(FILE_ID), kind=FileKind.TOOL)++ with app.test_request_context(f"/files/appdeploy/{tool_file.id}/content", query_string={"token": token}):+ with pytest.raises(GrantedFileNotFoundError):+ GrantedFileContentApi().get(UUID(tool_file.id))++[email protected]("sqlite_db", "stored_bytes")+def test_content_rejects_a_token_naming_the_wrong_table(app: Flask, sqlite_session: Session) -> None:+ tool_file = _persist_tool_file(sqlite_session, owner_id="anyone")+ token = _content_token(file_id=tool_file.id, kind=FileKind.UPLOAD)++ with app.test_request_context(f"/files/appdeploy/{tool_file.id}/content", query_string={"token": token}):+ with pytest.raises(GrantedFileNotFoundError):+ GrantedFileContentApi().get(UUID(tool_file.id))++[email protected]("sqlite_db", "stored_bytes")+def test_content_rejects_a_file_grant_replayed_as_a_content_token(app: Flask, sqlite_session: Session) -> None:+ tool_file = _persist_tool_file(sqlite_session, owner_id="anyone")+ grant, _ = issue_file_grant(+ end_user_id="anyone",+ tenant_id=TENANT_ID,+ app_id=APP_ID,+ scopes=[FileGrantScope.RESOLVE],+ ttl_seconds=600,+ )++ with app.test_request_context(f"/files/appdeploy/{tool_file.id}/content", query_string={"token": grant}):+ with pytest.raises(FileGrantInvalidError):+ GrantedFileContentApi().get(UUID(tool_file.id))diff --git a/api/tests/unit_tests/controllers/files/test_file_grant_wraps.py b/api/tests/unit_tests/controllers/files/test_file_grant_wraps.pynew file mode 100644index 00000000000..893001f54df--- /dev/null+++ b/api/tests/unit_tests/controllers/files/test_file_grant_wraps.py@@ -0,0 +1,151 @@+"""Tests for the Bearer file-grant decorator."""++import time+from collections.abc import Callable+from types import SimpleNamespace+from typing import cast++import jwt+import pytest+from flask import Flask++from controllers.files.wraps import FileGrantInvalidError, FileGrantScopeDeniedError, file_grant_required+from libs.passport import PassportService+from services.entities.file_grant_entities import FileGrantClaims, FileGrantScope+from services.file_grant_gateways import FILE_GRANT_AUDIENCE+from tests.unit_tests.file_grant_test_utils import issue_file_grant, token_gateway++SECRET_KEY = "file-grant-test-secret-long-enough-for-hs256"+TENANT_ID = "11111111-1111-4111-8111-111111111111"+APP_ID = "22222222-2222-4222-8222-222222222222"+END_USER_ID = "55555555-5555-4555-8555-555555555555"++[email protected](autouse=True)+def granted_config(config_overrides: Callable[..., None]) -> None:+ config_overrides(SECRET_KEY=SECRET_KEY)++[email protected](autouse=True)+def file_grant_service(granted_config: None, monkeypatch: pytest.MonkeyPatch) -> None:+ del granted_config+ service = SimpleNamespace(decode_grant=token_gateway().decode_grant)+ monkeypatch.setattr(+ "controllers.files.wraps.application_services",+ lambda: SimpleNamespace(file_grants=service),+ )+++@file_grant_required(FileGrantScope.UPLOAD)+def _view(grant: FileGrantClaims) -> FileGrantClaims:+ return grant+++def _call(app: Flask, authorization: str | None) -> FileGrantClaims:+ headers: dict[str, str] = {"Authorization": authorization} if authorization is not None else {}+ with app.test_request_context("/", method="POST", headers=headers):+ return cast(Callable[[], FileGrantClaims], _view)()+++def _grant(*scopes: FileGrantScope, ttl_seconds: int = 600) -> str:+ token, _ = issue_file_grant(+ end_user_id=END_USER_ID,+ tenant_id=TENANT_ID,+ app_id=APP_ID,+ scopes=scopes,+ ttl_seconds=ttl_seconds,+ )+ return token+++def test_valid_grant_is_injected_into_the_view(app: Flask) -> None:+ claims = _call(app, f"Bearer {_grant(FileGrantScope.UPLOAD, FileGrantScope.RESOLVE)}")++ assert claims.sub == END_USER_ID+ assert claims.tenant_id == TENANT_ID+ assert claims.app_id == APP_ID+ assert claims.scopes == [FileGrantScope.UPLOAD, FileGrantScope.RESOLVE]+++def test_missing_authorization_is_rejected(app: Flask) -> None:+ with pytest.raises(FileGrantInvalidError):+ _call(app, None)+++def test_non_bearer_authorization_is_rejected(app: Flask) -> None:+ with pytest.raises(FileGrantInvalidError):+ _call(app, f"Basic {_grant(FileGrantScope.UPLOAD)}")+++def test_webapp_passport_cannot_be_replayed_as_a_grant(app: Flask) -> None:+ """The passport is signed with the same key, so only ``aud`` separates them."""++ passport = PassportService().issue(+ {+ "iss": "SELF_HOSTED",+ "sub": "Web API Passport",+ "app_id": APP_ID,+ "end_user_id": END_USER_ID,+ "exp": int(time.time()) + 600,+ }+ )++ with pytest.raises(FileGrantInvalidError):+ _call(app, f"Bearer {passport}")+++def test_content_token_audience_is_not_accepted_as_a_grant(app: Flask) -> None:+ content_token = jwt.encode(+ {+ "aud": "dify-files-content",+ "kind": "upload",+ "file_id": "66666666-6666-4666-8666-666666666666",+ "exp": int(time.time()) + 600,+ },+ SECRET_KEY,+ algorithm="HS256",+ )++ with pytest.raises(FileGrantInvalidError):+ _call(app, f"Bearer {content_token}")+++def test_expired_grant_is_rejected(app: Flask) -> None:+ expired = jwt.encode(+ {+ "aud": FILE_GRANT_AUDIENCE,+ "sub": END_USER_ID,+ "tenant_id": TENANT_ID,+ "app_id": APP_ID,+ "scopes": ["upload"],+ "exp": int(time.time()) - 1,+ },+ SECRET_KEY,+ algorithm="HS256",+ )++ with pytest.raises(FileGrantInvalidError):+ _call(app, f"Bearer {expired}")+++def test_grant_signed_with_another_key_is_rejected(app: Flask) -> None:+ forged = jwt.encode(+ {+ "aud": FILE_GRANT_AUDIENCE,+ "sub": END_USER_ID,+ "tenant_id": TENANT_ID,+ "app_id": APP_ID,+ "scopes": ["upload"],+ "exp": int(time.time()) + 600,+ },+ "some-other-secret-long-enough-for-hs256-signing",+ algorithm="HS256",+ )++ with pytest.raises(FileGrantInvalidError):+ _call(app, f"Bearer {forged}")+++def test_grant_without_the_required_scope_is_denied(app: Flask) -> None:+ with pytest.raises(FileGrantScopeDeniedError):+ _call(app, f"Bearer {_grant(FileGrantScope.RESOLVE, FileGrantScope.PRODUCE)}")diff --git a/api/tests/unit_tests/controllers/inner_api/app/test_file_grants.py b/api/tests/unit_tests/controllers/inner_api/app/test_file_grants.pynew file mode 100644index 00000000000..97b5e1adffc--- /dev/null+++ b/api/tests/unit_tests/controllers/inner_api/app/test_file_grants.py@@ -0,0 +1,493 @@+"""Tests for the AppDeploy file grant minting endpoint."""++import inspect+import os+import time+from collections.abc import Callable, Iterator+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import jwt+import pytest+from flask import Flask+from sqlalchemy import select+from sqlalchemy.engine import Engine+from sqlalchemy.orm import Session, sessionmaker++from controllers.files.wraps import GrantedFileNotFoundError+from controllers.inner_api.app.file_grants import (+ EnterpriseFileGrantApi,+ GrantAppNotFoundError,+ GrantTtlTooLongError,+ InvalidGrantRequestError,+ InvalidSubjectError,+)+from extensions.ext_application_services import _build_file_grant_service+from extensions.storage.storage_type import StorageType+from libs.datetime_utils import naive_utc_now+from models.enums import CreatorUserRole, EndUserType+from models.model import App, EndUser, UploadFile+from models.tools import ToolFile+from services import end_user_service+from services.end_user_service import EndUserService+from services.file_grant_gateways import FILE_GRANT_AUDIENCE+from services.file_grant_service import (+ MAX_RUN_GRANT_TTL_SECONDS,+ MAX_SESSION_GRANT_TTL_SECONDS,+ MAX_WORKFLOW_EXECUTION_SECONDS,+ RUN_GRANT_EXPIRY_GRACE_SECONDS,+ FileGrantService,+)++CONTROLLER_MODULE = "controllers.inner_api.app.file_grants"++SECRET_KEY = "file-grant-test-secret-long-enough-for-hs256"+TENANT_ID = "11111111-1111-4111-8111-111111111111"+APP_ID = "22222222-2222-4222-8222-222222222222"+SUBJECT = "adp1.dGVzdC1zdWJqZWN0"+++def granted_config(config_overrides: Callable[..., None]) -> None:+ config_overrides(+ SECRET_KEY=SECRET_KEY,+ FILES_URL="https://files.example.com",+ INTERNAL_FILES_URL="http://dify-api.dify.svc:5001",+ FILES_ACCESS_TIMEOUT=300,+ )+++def seeded_app(sqlite_session: Session) -> App:+ app_model = App(+ id=APP_ID,+ tenant_id=TENANT_ID,+ name="deployed app",+ mode="workflow",+ enable_site=True,+ enable_api=True,+ )+ sqlite_session.add(app_model)+ sqlite_session.commit()+ return app_model+++def _mint(app: Flask, payload: dict[str, object]) -> dict[str, object]:+ handler = EnterpriseFileGrantApi()+ with app.test_request_context("/", method="POST", json=payload):+ with patch(f"{CONTROLLER_MODULE}.inner_api_ns") as mock_ns:+ mock_ns.payload = payload+ return inspect.unwrap(handler.post)(handler)+++def _subject_of(response: dict[str, object]) -> str:+ grant = response["grant"]+ assert isinstance(grant, str)+ return str(jwt.decode(grant, SECRET_KEY, algorithms=["HS256"], audience=FILE_GRANT_AUDIENCE)["sub"])+++def _payload(**overrides: object) -> dict[str, object]:+ return {+ "tenant_id": TENANT_ID,+ "app_id": APP_ID,+ "subject": SUBJECT,+ "is_anonymous": True,+ "scopes": ["upload"],+ "ttl_seconds": 600,+ } | overrides+++def _persist_upload_file(session: Session, *, owner_id: str, tenant_id: str = TENANT_ID) -> UploadFile:+ upload_file = UploadFile(+ tenant_id=tenant_id,+ storage_type=StorageType.OPENDAL,+ key="upload_files/report.pdf",+ name="report.pdf",+ size=2048,+ extension="pdf",+ mime_type="application/pdf",+ created_by=owner_id,+ created_by_role=CreatorUserRole.END_USER,+ created_at=naive_utc_now(),+ used=False,+ )+ session.add(upload_file)+ session.commit()+ return upload_file+++def _persist_tool_file(session: Session, *, owner_id: str, tenant_id: str = TENANT_ID) -> ToolFile:+ tool_file = ToolFile(+ user_id=owner_id,+ tenant_id=tenant_id,+ conversation_id=None,+ file_key="tools/chart.png",+ mimetype="image/png",+ name="chart.png",+ size=64,+ )+ session.add(tool_file)+ session.commit()+ return tool_file+++def sqlite_db(sqlite_engine: Engine, granted_config: None) -> Iterator[None]:+ del granted_config+ service = _build_file_grant_service(database_client=sessionmaker(bind=sqlite_engine, expire_on_commit=False))+ services = SimpleNamespace(file_grants=service)+ with patch(f"{CONTROLLER_MODULE}.application_services", return_value=services):+ yield++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_creates_exactly_one_end_user_and_reuses_it(app: Flask, sqlite_session: Session) -> None:+ first = _mint(app, _payload())+ second = _mint(app, _payload(ttl_seconds=900))++ end_users = list(sqlite_session.scalars(select(EndUser).where(EndUser.tenant_id == TENANT_ID)).all())+ assert len(end_users) == 1+ assert end_users[0].type == EndUserType.APP_DEPLOY+ assert end_users[0].session_id == FileGrantService.session_id_for_subject(SUBJECT)+ assert end_users[0].external_user_id == SUBJECT++ first_grant = first["grant"]+ second_grant = second["grant"]+ assert isinstance(first_grant, str)+ assert isinstance(second_grant, str)+ first_claims = jwt.decode(first_grant, SECRET_KEY, algorithms=["HS256"], audience=FILE_GRANT_AUDIENCE)+ second_claims = jwt.decode(second_grant, SECRET_KEY, algorithms=["HS256"], audience=FILE_GRANT_AUDIENCE)+ assert first_claims["sub"] == second_claims["sub"] == end_users[0].id+ assert first_claims["tenant_id"] == TENANT_ID+ assert first_claims["app_id"] == APP_ID+ assert first_claims["scopes"] == ["upload"]+ first_expires_at = first["expires_at"]+ second_expires_at = second["expires_at"]+ assert isinstance(first_expires_at, int)+ assert isinstance(second_expires_at, int)+ assert second_expires_at > first_expires_at++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_returns_dify_upload_limits(app: Flask, config_overrides: Callable[..., None]) -> None:+ config_overrides(+ UPLOAD_FILE_SIZE_LIMIT=15,+ UPLOAD_IMAGE_FILE_SIZE_LIMIT=10,+ UPLOAD_AUDIO_FILE_SIZE_LIMIT=50,+ UPLOAD_VIDEO_FILE_SIZE_LIMIT=100,+ WORKFLOW_FILE_UPLOAD_LIMIT=10,+ UPLOAD_FILE_BATCH_LIMIT=5,+ )++ response = _mint(app, _payload())++ assert response["limits"] == {+ "file_size_limit": 15,+ "image_file_size_limit": 10,+ "audio_file_size_limit": 50,+ "video_file_size_limit": 100,+ "workflow_file_upload_limit": 10,+ "batch_count_limit": 5,+ }++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_rejects_ttl_over_the_cap_before_touching_identity(app: Flask, sqlite_session: Session) -> None:+ with pytest.raises(GrantTtlTooLongError):+ _mint(app, _payload(ttl_seconds=MAX_SESSION_GRANT_TTL_SECONDS + 1))++ assert sqlite_session.scalars(select(EndUser)).all() == []++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_accepts_a_session_ttl_exactly_at_the_cap(app: Flask) -> None:+ before = int(time.time())++ response = _mint(app, _payload(ttl_seconds=MAX_SESSION_GRANT_TTL_SECONDS))++ expires_at = response["expires_at"]+ assert isinstance(expires_at, int)+ assert MAX_SESSION_GRANT_TTL_SECONDS <= expires_at - before <= MAX_SESSION_GRANT_TTL_SECONDS + 5++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_accepts_a_run_ttl_until_deadline_plus_grace(app: Flask) -> None:+ now = int(time.time())+ run_duration = MAX_RUN_GRANT_TTL_SECONDS - RUN_GRANT_EXPIRY_GRACE_SECONDS++ response = _mint(+ app,+ _payload(+ scopes=["resolve", "produce"],+ ttl_seconds=MAX_RUN_GRANT_TTL_SECONDS,+ run_deadline=now + run_duration,+ ),+ )++ expires_at = response["expires_at"]+ assert isinstance(expires_at, int)+ assert MAX_RUN_GRANT_TTL_SECONDS <= expires_at - now <= MAX_RUN_GRANT_TTL_SECONDS + 5++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_rejects_a_run_ttl_past_deadline_grace(app: Flask) -> None:+ now = int(time.time())++ with pytest.raises(GrantTtlTooLongError):+ _mint(+ app,+ _payload(+ scopes=["resolve", "produce"],+ ttl_seconds=MAX_RUN_GRANT_TTL_SECONDS + 1,+ run_deadline=now + MAX_WORKFLOW_EXECUTION_SECONDS,+ ),+ )++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_rejects_an_expired_run_deadline(app: Flask) -> None:+ with pytest.raises(InvalidGrantRequestError):+ _mint(+ app,+ _payload(scopes=["resolve", "produce"], ttl_seconds=1, run_deadline=int(time.time()) - 1),+ )++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_rejects_a_run_deadline_without_produce_scope(app: Flask) -> None:+ with pytest.raises(InvalidGrantRequestError):+ _mint(app, _payload(run_deadline=int(time.time()) + 60))++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_rejects_a_run_deadline_beyond_the_workflow_limit(app: Flask) -> None:+ with pytest.raises(InvalidGrantRequestError):+ _mint(+ app,+ _payload(+ scopes=["resolve", "produce"],+ run_deadline=int(time.time()) + MAX_WORKFLOW_EXECUTION_SECONDS + 1,+ ),+ )++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_caps_a_run_grant_at_deadline_plus_grace(app: Flask) -> None:+ now = int(time.time())+ run_deadline = now + 60++ response = _mint(+ app,+ _payload(+ scopes=["resolve", "produce"],+ ttl_seconds=1200,+ run_deadline=run_deadline,+ ),+ )++ expires_at = response["expires_at"]+ assert isinstance(expires_at, int)+ assert (+ run_deadline + RUN_GRANT_EXPIRY_GRACE_SECONDS+ <= expires_at+ <= (run_deadline + RUN_GRANT_EXPIRY_GRACE_SECONDS + 1)+ )++[email protected]("granted_config", "seeded_app", "sqlite_db")[email protected]("ttl_seconds", [0, -1])+def test_mint_rejects_a_non_positive_ttl(app: Flask, ttl_seconds: int) -> None:+ with pytest.raises(InvalidGrantRequestError):+ _mint(app, _payload(ttl_seconds=ttl_seconds))++[email protected]("granted_config", "seeded_app", "sqlite_db")[email protected]("subject", ["", " ", "\t\n", "adp1.with\x00nul", "\x00"])+def test_mint_rejects_an_unusable_subject(app: Flask, subject: str, sqlite_session: Session) -> None:+ """A NUL would reach ``external_user_id`` verbatim and blow up on PostgreSQL."""++ with pytest.raises(InvalidSubjectError):+ _mint(app, _payload(subject=subject))++ assert sqlite_session.scalars(select(EndUser)).all() == []++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_folds_an_oversized_subject_into_one_identity(app: Flask, sqlite_session: Session) -> None:+ """``external_user_id`` truncates at 255, so ``session_id`` is what keeps them apart."""++ long_subject = "adp1." + "s" * 4000+ sibling = long_subject[:-1] + "t"++ first = _mint(app, _payload(subject=long_subject))+ again = _mint(app, _payload(subject=long_subject))+ other = _mint(app, _payload(subject=sibling))++ end_users = sqlite_session.scalars(select(EndUser).order_by(EndUser.created_at)).all()+ assert len(end_users) == 2+ assert all(len(end_user.external_user_id) == 255 for end_user in end_users)+ assert _subject_of(first) == _subject_of(again) != _subject_of(other)++[email protected]("granted_config", "sqlite_db")+def test_mint_rejects_unknown_app(app: Flask) -> None:+ with pytest.raises(GrantAppNotFoundError):+ _mint(app, _payload())++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_returns_strict_metadata_without_urls(app: Flask, sqlite_session: Session) -> None:+ owner_id = _subject_of(_mint(app, _payload()))+ upload_file = _persist_upload_file(sqlite_session, owner_id=owner_id)+ tool_file = _persist_tool_file(sqlite_session, owner_id=owner_id)++ response = _mint(+ app,+ _payload(file_ids=[{"id": upload_file.id, "kind": "upload"}, {"id": tool_file.id, "kind": "tool"}]),+ )++ assert response["files"] == [+ {+ "id": upload_file.id,+ "kind": "upload",+ "name": "report.pdf",+ "size": 2048,+ "extension": "pdf",+ "mime_type": "application/pdf",+ },+ {+ "id": tool_file.id,+ "kind": "tool",+ "name": "chart.png",+ "size": 64,+ "extension": "png",+ "mime_type": "image/png",+ },+ ]++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_fails_the_whole_strict_batch_on_one_miss(app: Flask, sqlite_session: Session) -> None:+ owner_id = _subject_of(_mint(app, _payload()))+ upload_file = _persist_upload_file(sqlite_session, owner_id=owner_id)++ with pytest.raises(GrantedFileNotFoundError):+ _mint(+ app,+ _payload(+ file_ids=[+ {"id": upload_file.id, "kind": "upload"},+ {"id": "33333333-3333-4333-8333-333333333333", "kind": "upload"},+ ]+ ),+ )++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_hides_files_owned_by_another_subject(app: Flask, sqlite_session: Session) -> None:+ other_owner = _subject_of(_mint(app, _payload(subject="adp1.other")))+ foreign_file = _persist_upload_file(sqlite_session, owner_id=other_owner)++ with pytest.raises(GrantedFileNotFoundError):+ _mint(app, _payload(file_ids=[{"id": foreign_file.id, "kind": "upload"}]))++[email protected]("granted_config", "seeded_app", "sqlite_db")+def test_mint_reports_optional_files_item_by_item(app: Flask, sqlite_session: Session) -> None:+ owner_id = _subject_of(_mint(app, _payload()))+ upload_file = _persist_upload_file(sqlite_session, owner_id=owner_id)+ missing_id = "44444444-4444-4444-8444-444444444444"++ response = _mint(+ app,+ _payload(+ optional_file_ids=[+ {"id": upload_file.id, "kind": "upload"},+ {"id": missing_id, "kind": "tool"},+ ]+ ),+ )++ optional_files = response["optional_files"]+ assert isinstance(optional_files, list)+ present, absent = optional_files+ assert present["ok"] is True+ assert present["name"] == "report.pdf"+ assert present["url"].startswith(f"https://files.example.com/files/appdeploy/{upload_file.id}/content?token=")+ assert present["internal_url"].startswith(+ f"http://dify-api.dify.svc:5001/files/appdeploy/{upload_file.id}/content?token="+ )+ assert absent == {+ "id": missing_id,+ "ok": False,+ "kind": None,+ "name": None,+ "size": None,+ "extension": None,+ "mime_type": None,+ "url": None,+ "internal_url": None,+ "error": "not_found",+ }+ assert response["files"] == []++[email protected]("seeded_app")+def test_end_user_service_never_retypes_an_app_deploy_row(+ sqlite_engine: Engine,+ sqlite_session: Session,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Retyping would hide the row from the grant read and strand its files."""++ subject = "subject-that-also-reaches-the-service-api"+ session_id = FileGrantService.session_id_for_subject(subject)+ owner = EndUser(+ tenant_id=TENANT_ID,+ app_id=APP_ID,+ type=EndUserType.APP_DEPLOY,+ is_anonymous=True,+ session_id=session_id,+ external_user_id=session_id,+ )+ sqlite_session.add(owner)+ sqlite_session.commit()+ owner_id = owner.id+ monkeypatch.setattr(end_user_service, "db", SimpleNamespace(engine=sqlite_engine))++ EndUserService.get_or_create_end_user_by_type(EndUserType.SERVICE_API, TENANT_ID, APP_ID, session_id)++ sqlite_session.expire_all()+ persisted_owner = sqlite_session.get(EndUser, owner_id)+ assert persisted_owner is not None+ assert persisted_owner.type == EndUserType.APP_DEPLOY+++SKIPPED_DIRECTORY_NAMES = frozenset({".git", ".venv", "__pycache__", "migrations", "node_modules", "tests"})+++def test_app_deploy_end_users_have_exactly_one_writer() -> None:+ """``end_users`` has no unique constraint, so a second writer would fork identities.++ ``end_user_service`` names the type only to exclude it from the legacy retype;+ the behavioural guard above is what holds that exclusion in place.+ """++ api_root = Path(__file__).resolve().parents[5]+ assert api_root.name == "api"++ referencing_modules: set[str] = set()+ for directory, subdirectories, filenames in os.walk(api_root):+ subdirectories[:] = [name for name in subdirectories if name not in SKIPPED_DIRECTORY_NAMES]+ for filename in filenames:+ if not filename.endswith(".py"):+ continue+ path = Path(directory) / filename+ if "EndUserType.APP_DEPLOY" in path.read_text(encoding="utf-8"):+ referencing_modules.add(path.relative_to(api_root).as_posix())++ assert referencing_modules == {+ "repositories/file_grant_repository.py",+ "services/end_user_service.py",+ }diff --git a/api/tests/unit_tests/controllers/web/test_app.py b/api/tests/unit_tests/controllers/web/test_app.pyindex 005c23e7f25..9b1247bf431 100644--- a/api/tests/unit_tests/controllers/web/test_app.py+++ b/api/tests/unit_tests/controllers/web/test_app.py@@ -216,18 +216,17 @@ class TestAppWebAuthPermission:extract_passport.assert_not_called()@pytest.mark.parametrize(- ("decoded", "expected_user_id", "allowed"),+ ("user_id", "allowed"),[- pytest.param({"user_id": "user-1"}, "user-1", True, id="identified-user"),- pytest.param({}, "visitor", False, id="visitor-fallback"),+ pytest.param("user-1", True, id="allowed-user"),+ pytest.param("user-2", False, id="denied-user"),],)@patch("controllers.web.app.application_services")def test_checks_private_app_permission(self,application_services: MagicMock,- decoded: dict[str, str],- expected_user_id: str,+ user_id: str,allowed: bool,app: Flask,) -> None:@@ -241,14 +240,41 @@ class TestAppWebAuthPermission:patch("controllers.web.app.extract_webapp_passport", return_value="passport") as extract_passport,patch("controllers.web.app.PassportService") as passport_service,):- passport_service.return_value.verify.return_value = decoded+ passport_service.return_value.verify.return_value = {"user_id": user_id, "auth_type": "internal"}result = AppWebAuthPermission().get()assert result == {"result": allowed}webapp_access.requires_permission_check.assert_called_once_with("app-1")extract_passport.assert_called_once()passport_service.return_value.verify.assert_called_once_with("passport")- webapp_access.is_user_allowed.assert_called_once_with(user_id=expected_user_id, app_id="app-1")+ webapp_access.is_user_allowed.assert_called_once_with(user_id=user_id, app_id="app-1")++ @pytest.mark.parametrize(+ "decoded",+ [+ pytest.param({}, id="missing-auth-type"),+ pytest.param({"auth_type": "internal"}, id="missing-user-id"),+ pytest.param({"user_id": "sso_external_user", "auth_type": "external"}, id="external-auth-type"),+ ],+ )+ @patch("controllers.web.app.application_services")+ def test_private_app_requires_internal_identity(+ self, application_services: MagicMock, decoded: dict[str, str], app: Flask+ ) -> None:+ webapp_access = MagicMock()+ webapp_access.requires_permission_check.return_value = True+ application_services.return_value = SimpleNamespace(webapp_access=webapp_access)++ with (+ app.test_request_context("/webapp/permission?appId=app-1", headers={"X-App-Code": "code1"}),+ patch("controllers.web.app.extract_webapp_passport", return_value="passport"),+ patch("controllers.web.app.PassportService") as passport_service,+ ):+ passport_service.return_value.verify.return_value = decoded+ with pytest.raises(WebAppAuthRequiredError):+ AppWebAuthPermission().get()++ webapp_access.is_user_allowed.assert_not_called()@pytest.mark.parametrize("failing_method", ["requires_permission_check", "is_user_allowed"])@patch("controllers.web.app.application_services")@@ -264,7 +290,7 @@ class TestAppWebAuthPermission:application_services.return_value = SimpleNamespace(webapp_access=webapp_access)passport_service = MagicMock()- passport_service.return_value.verify.return_value = {"user_id": "user-1"}+ passport_service.return_value.verify.return_value = {"user_id": "user-1", "auth_type": "internal"}with (app.test_request_context("/webapp/permission?appId=app-1", headers={"X-App-Code": "code1"}),patch("controllers.web.app.extract_webapp_passport", return_value="passport"),diff --git a/api/tests/unit_tests/file_grant_test_utils.py b/api/tests/unit_tests/file_grant_test_utils.pynew file mode 100644index 00000000000..0fb7eae9408--- /dev/null+++ b/api/tests/unit_tests/file_grant_test_utils.py@@ -0,0 +1,31 @@+import time+from collections.abc import Sequence++from configs import dify_config+from services.entities.file_grant_entities import FileGrantContext, FileGrantScope+from services.file_grant_gateways import FileGrantTokenGateway+++def token_gateway() -> FileGrantTokenGateway:+ return FileGrantTokenGateway(+ secret_key=dify_config.SECRET_KEY,+ external_files_url=dify_config.FILES_URL,+ internal_files_url=dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL,+ content_token_ttl_seconds=dify_config.FILES_ACCESS_TIMEOUT,+ now=lambda: int(time.time()),+ )+++def issue_file_grant(+ *,+ end_user_id: str,+ tenant_id: str,+ app_id: str,+ scopes: Sequence[FileGrantScope],+ ttl_seconds: int,+) -> tuple[str, int]:+ return token_gateway().issue_grant(+ context=FileGrantContext(tenant_id=tenant_id, app_id=app_id, end_user_id=end_user_id),+ scopes=scopes,+ ttl_seconds=ttl_seconds,+ )diff --git a/api/tests/unit_tests/models/test_end_user_type.py b/api/tests/unit_tests/models/test_end_user_type.pyindex 222945814b4..af6407c7b7c 100644--- a/api/tests/unit_tests/models/test_end_user_type.py+++ b/api/tests/unit_tests/models/test_end_user_type.py@@ -15,6 +15,7 @@ API_ROOT = Path(__file__).resolve().parents[3]def test_end_user_type_covers_persisted_creation_values():assert {member.value for member in EndUserType} == {+ "app-deploy","browser","mcp","openapi",diff --git a/api/tests/unit_tests/repositories/test_file_grant_repository.py b/api/tests/unit_tests/repositories/test_file_grant_repository.pynew file mode 100644index 00000000000..b27353a622b--- /dev/null+++ b/api/tests/unit_tests/repositories/test_file_grant_repository.py@@ -0,0 +1,75 @@+from sqlalchemy import Engine, event+from sqlalchemy.orm import Session, sessionmaker++from extensions.storage.storage_type import StorageType+from libs.datetime_utils import naive_utc_now+from models.enums import CreatorUserRole+from models.model import UploadFile+from models.tools import ToolFile+from repositories.file_grant_repository import FileGrantRepository+from services.entities.file_grant_entities import FileGrantContext, FileKind, FileRef+++def test_resolve_owned_files_uses_one_query_per_file_kind(+ sqlite_engine: Engine,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ end_user_id = "11111111-1111-4111-8111-111111111111"+ tenant_id = "22222222-2222-4222-8222-222222222222"+ with sqlite_session_factory.begin() as session:+ upload = UploadFile(+ tenant_id=tenant_id,+ storage_type=StorageType.OPENDAL,+ key="upload_files/report.pdf",+ name="report.pdf",+ size=10,+ extension="pdf",+ mime_type="application/pdf",+ created_by=end_user_id,+ created_by_role=CreatorUserRole.END_USER,+ created_at=naive_utc_now(),+ used=False,+ )+ tool_file = ToolFile(+ user_id=end_user_id,+ tenant_id=tenant_id,+ conversation_id=None,+ file_key="tools/chart.png",+ mimetype="image/png",+ name="chart.png",+ size=20,+ )+ session.add_all([upload, tool_file])+ session.flush()+ upload_id = upload.id+ tool_file_id = tool_file.id++ statements: list[str] = []++ def record_statement(+ _connection: object,+ _cursor: object,+ statement: str,+ _parameters: object,+ _context: object,+ _executemany: object,+ ) -> None:+ statements.append(statement)++ event.listen(sqlite_engine, "before_cursor_execute", record_statement)+ try:+ refs = tuple(+ FileRef(id=upload_id, kind=FileKind.UPLOAD)+ if index % 2 == 0+ else FileRef(id=tool_file_id, kind=FileKind.TOOL)+ for index in range(100)+ )+ resolved = FileGrantRepository(session_factory=sqlite_session_factory).resolve_owned_files(+ context=FileGrantContext(tenant_id, "app-1", end_user_id),+ refs=refs,+ )+ finally:+ event.remove(sqlite_engine, "before_cursor_execute", record_statement)++ assert len(statements) == 2+ assert [file.kind if file is not None else None for file in resolved] == [ref.kind for ref in refs]diff --git a/api/tests/unit_tests/services/test_file_grant_gateways.py b/api/tests/unit_tests/services/test_file_grant_gateways.pynew file mode 100644index 00000000000..2b909f2ca03--- /dev/null+++ b/api/tests/unit_tests/services/test_file_grant_gateways.py@@ -0,0 +1,90 @@+from collections.abc import Callable+from unittest.mock import patch++import httpx+import pytest++from services.errors.file import FileTooLargeError+from services.file_grant_gateways import FileGrantRemoteFileGateway+++def test_remote_file_gateway_bounds_a_get_without_content_length(+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(UPLOAD_FILE_SIZE_LIMIT=1)+ url = "https://example.com/report.pdf"+ head = httpx.Response(200, request=httpx.Request("HEAD", url))+ download = httpx.Response(+ 200,+ content=b"0" * (1024 * 1024 + 1),+ request=httpx.Request("GET", url),+ )++ with patch("services.file_grant_gateways.remote_fetcher.make_request", side_effect=[head, download]) as request:+ with pytest.raises(FileTooLargeError):+ FileGrantRemoteFileGateway().fetch(url)++ assert request.call_args_list[1].kwargs["stream_response"] is True+ assert download.is_closed+++def test_remote_file_gateway_uses_the_actual_body_size_when_content_length_is_incorrect(+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(UPLOAD_FILE_SIZE_LIMIT=1)+ url = "https://example.com/report.pdf"+ head = httpx.Response(+ 200,+ headers={"Content-Length": "1"},+ request=httpx.Request("HEAD", url),+ )+ download = httpx.Response(+ 200,+ headers={"Content-Length": "1"},+ content=b"0" * (1024 * 1024 + 1),+ request=httpx.Request("GET", url),+ )++ with patch("services.file_grant_gateways.remote_fetcher.make_request", side_effect=[head, download]):+ with pytest.raises(FileTooLargeError):+ FileGrantRemoteFileGateway().fetch(url)++ assert download.is_closed+++def test_remote_file_gateway_rejects_encoded_content_that_cannot_be_safely_bounded(+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(UPLOAD_FILE_SIZE_LIMIT=1)+ url = "https://example.com/report.pdf"+ head = httpx.Response(200, request=httpx.Request("HEAD", url))+ download = httpx.Response(+ 200,+ headers={"Content-Encoding": "gzip"},+ stream=httpx.ByteStream(b"compressed"),+ request=httpx.Request("GET", url),+ )++ with patch("services.file_grant_gateways.remote_fetcher.make_request", side_effect=[head, download]):+ assert FileGrantRemoteFileGateway().fetch(url) is None++ assert download.is_closed+++def test_remote_file_gateway_returns_bounded_content(config_overrides: Callable[..., None]) -> None:+ config_overrides(UPLOAD_FILE_SIZE_LIMIT=1)+ url = "https://example.com/report.pdf"+ head = httpx.Response(+ 200,+ headers={"Content-Length": "9", "Content-Type": "application/pdf"},+ request=httpx.Request("HEAD", url),+ )+ download = httpx.Response(200, content=b"pdf-bytes", request=httpx.Request("GET", url))++ with patch("services.file_grant_gateways.remote_fetcher.make_request", side_effect=[head, download]):+ file = FileGrantRemoteFileGateway().fetch(url)++ assert file is not None+ assert file.filename == "report.pdf"+ assert file.mimetype == "application/pdf"+ assert file.content == b"pdf-bytes"diff --git a/api/tests/unit_tests/services/test_file_grant_service.py b/api/tests/unit_tests/services/test_file_grant_service.pynew file mode 100644index 00000000000..741eb9471d4--- /dev/null+++ b/api/tests/unit_tests/services/test_file_grant_service.py@@ -0,0 +1,147 @@+from io import BytesIO+from unittest.mock import MagicMock++import pytest++from services.entities.file_grant_entities import (+ FileGrantContext,+ FileGrantLimits,+ FileGrantMintRequest,+ FileGrantScope,+ FileKind,+ FileRef,+ ResolvedFile,+)+from services.errors.file_grant import EndUserNotFoundError, GrantTtlTooLongError+from services.file_grant_service import MAX_SESSION_GRANT_TTL_SECONDS, FileGrantService+++def _service() -> tuple[FileGrantService, MagicMock, MagicMock, MagicMock, MagicMock]:+ repository = MagicMock()+ repository.get_or_create_subject.return_value = "end-user-1"+ repository.subject_exists.return_value = True+ repository.resolve_owned_files.return_value = list[ResolvedFile | None]()+ files = MagicMock()+ tokens = MagicMock()+ tokens.issue_grant.return_value = ("grant", 1600)+ remote_files = MagicMock()+ service = FileGrantService(+ repository=repository,+ files=files,+ tokens=tokens,+ remote_files=remote_files,+ limits=FileGrantLimits(15, 10, 50, 100, 10, 5),+ now=lambda: 1000,+ )+ return service, repository, files, tokens, remote_files+++def _mint_request(+ *,+ ttl_seconds: int = 600,+ file_refs: tuple[FileRef, ...] = (),+ optional_file_refs: tuple[FileRef, ...] = (),+) -> FileGrantMintRequest:+ return FileGrantMintRequest(+ tenant_id="tenant-1",+ app_id="app-1",+ subject="subject-1",+ is_anonymous=True,+ scopes=(FileGrantScope.UPLOAD,),+ ttl_seconds=ttl_seconds,+ file_refs=file_refs,+ optional_file_refs=optional_file_refs,+ run_deadline=None,+ )+++def test_mint_rejects_an_invalid_ttl_before_persistence() -> None:+ service, repository, _files, tokens, _remote_files = _service()++ with pytest.raises(GrantTtlTooLongError):+ service.mint(_mint_request(ttl_seconds=MAX_SESSION_GRANT_TTL_SECONDS + 1))++ repository.get_or_create_subject.assert_not_called()+ tokens.issue_grant.assert_not_called()+++def test_mint_orchestrates_identity_resolution_and_token_issuance() -> None:+ service, repository, _files, tokens, _remote_files = _service()++ result = service.mint(_mint_request())++ assert result.grant == "grant"+ repository.get_or_create_subject.assert_called_once()+ tokens.issue_grant.assert_called_once_with(+ context=FileGrantContext("tenant-1", "app-1", "end-user-1"),+ scopes=(FileGrantScope.UPLOAD,),+ ttl_seconds=600,+ )+++def test_mint_resolves_required_and_optional_files_in_one_batch() -> None:+ service, repository, _files, tokens, _remote_files = _service()+ required_ref = FileRef(id="upload-1", kind=FileKind.UPLOAD)+ optional_ref = FileRef(id="tool-1", kind=FileKind.TOOL)+ required_file = ResolvedFile("upload-1", FileKind.UPLOAD, "report.pdf", 10, "pdf", "application/pdf")+ optional_file = ResolvedFile("tool-1", FileKind.TOOL, "chart.png", 20, "png", "image/png")+ repository.resolve_owned_files.return_value = [required_file, optional_file]+ tokens.issue_content_urls.return_value = ("https://files/tool-1", "http://files/tool-1")++ result = service.mint(+ _mint_request(+ file_refs=(required_ref,),+ optional_file_refs=(optional_ref,),+ )+ )++ repository.resolve_owned_files.assert_called_once_with(+ context=FileGrantContext("tenant-1", "app-1", "end-user-1"),+ refs=(required_ref, optional_ref),+ )+ assert result.files == (required_file,)+ assert result.optional_files[0] is not None+ assert result.optional_files[0].file == optional_file+++def test_store_produced_rejects_a_deleted_subject_before_reading_the_file() -> None:+ service, repository, files, _tokens, _remote_files = _service()+ repository.subject_exists.return_value = False+ stream = BytesIO(b"produced content")++ with pytest.raises(EndUserNotFoundError):+ service.store_produced(+ context=FileGrantContext("tenant-1", "app-1", "deleted-user"),+ filename="result.txt",+ stream=stream,+ mimetype="text/plain",+ )++ assert stream.tell() == 0+ files.store_produced.assert_not_called()+++def test_store_remote_upload_rejects_a_deleted_subject_before_fetching() -> None:+ service, repository, _files, _tokens, remote_files = _service()+ repository.subject_exists.return_value = False++ with pytest.raises(EndUserNotFoundError):+ service.store_remote_upload(+ context=FileGrantContext("tenant-1", "app-1", "deleted-user"),+ url="https://example.com/report.pdf",+ )++ remote_files.fetch.assert_not_called()+++def test_resolve_rejects_a_deleted_subject_before_querying_files() -> None:+ service, repository, _files, _tokens, _remote_files = _service()+ repository.subject_exists.return_value = False++ with pytest.raises(EndUserNotFoundError):+ service.resolve_files(+ context=FileGrantContext("tenant-1", "app-1", "deleted-user"),+ refs=(),+ )++ repository.resolve_owned_files.assert_not_called()diff --git a/api/tests/unit_tests/services/test_file_service.py b/api/tests/unit_tests/services/test_file_service.pyindex 49367183d9c..470235cf610 100644--- a/api/tests/unit_tests/services/test_file_service.py+++ b/api/tests/unit_tests/services/test_file_service.py@@ -258,6 +258,20 @@ class TestFileService:is False)+ def test_file_size_limit(self, config_overrides: Callable[..., None]):+ config_overrides(+ UPLOAD_IMAGE_FILE_SIZE_LIMIT=10,+ UPLOAD_VIDEO_FILE_SIZE_LIMIT=20,+ UPLOAD_AUDIO_FILE_SIZE_LIMIT=30,+ UPLOAD_FILE_SIZE_LIMIT=5,+ )++ assert FileService.file_size_limit(extension="jpg") == 10 * 1024 * 1024+ assert FileService.file_size_limit(extension="mp4") == 20 * 1024 * 1024+ assert FileService.file_size_limit(extension="mp3") == 30 * 1024 * 1024+ assert FileService.file_size_limit(extension="txt") == 5 * 1024 * 1024+ assert FileService.file_size_limit(extension="txt", default_file_size_limit=7) == 7 * 1024 * 1024+def test_get_file_base64_success(self, file_service: FileService, db_session: Session):self._persist_upload_file(db_session, key="test_key")diff --git a/e2e/features/step-definitions/agent-v2/access-point-helpers.ts b/e2e/features/step-definitions/agent-v2/access-point-helpers.tsindex 654455d1283..f0e5c01d776 100644--- a/e2e/features/step-definitions/agent-v2/access-point-helpers.ts+++ b/e2e/features/step-definitions/agent-v2/access-point-helpers.ts@@ -28,7 +28,7 @@ export const getAccessRegion = (world: DifyWorld) =>export type AccessSurfaceName = 'Web app' | 'Backend service API'export const getAccessSurfaceCard = (world: DifyWorld, surface: AccessSurfaceName) =>- getAccessRegion(world).getByRole('article', { name: surface }).first()+ getAccessRegion(world).getByRole('region', { name: surface }).first()export const getWebAppCard = (world: DifyWorld) => getAccessSurfaceCard(world, 'Web app')diff --git a/e2e/features/step-definitions/agent-v2/access-point-web-app.steps.ts b/e2e/features/step-definitions/agent-v2/access-point-web-app.steps.tsindex 53eba93fdae..a71d04f295d 100644--- a/e2e/features/step-definitions/agent-v2/access-point-web-app.steps.ts+++ b/e2e/features/step-definitions/agent-v2/access-point-web-app.steps.ts@@ -22,9 +22,9 @@ Then('I should see the Agent v2 Web app access URL', async function (this: DifyWconst webAppCard = getWebAppCard(this)await expect(webAppCard.getByRole('heading', { name: 'Web app' })).toBeVisible()- await expect(webAppCard.getByText('Web App URL')).toBeVisible()+ await expect(webAppCard.getByText('Access URL')).toBeVisible()await expect(webAppCard.getByLabel('Copy access URL')).toBeEnabled()- await expect(webAppCard.getByRole('link', { name: 'Launch' })).toBeVisible()+ await expect(webAppCard.getByRole('link', { name: 'Open' })).toBeVisible()})When('I copy the Agent v2 Web app access URL', async function (this: DifyWorld) {@@ -38,11 +38,11 @@ Then('the Agent v2 Web app access URL should show it was copied', async functionWhen('I launch the Agent v2 Web app', async function (this: DifyWorld) {await recordComposerDraftSnapshot(this)- const launchLink = getWebAppCard(this).getByRole('link', { name: 'Launch' })- const href = await launchLink.getAttribute('href')- if (!href) throw new Error('Agent v2 Web app Launch link does not expose an href.')+ const openLink = getWebAppCard(this).getByRole('link', { name: 'Open' })+ const href = await openLink.getAttribute('href')+ if (!href) throw new Error('Agent v2 Web app Open link does not expose an href.')- const [webAppPage] = await Promise.all([this.getPage().waitForEvent('popup'), launchLink.click()])+ const [webAppPage] = await Promise.all([this.getPage().waitForEvent('popup'), openLink.click()])this.agentBuilder.accessPoint.webAppURL = hrefthis.agentBuilder.accessPoint.webAppPage = webAppPage@@ -130,7 +130,7 @@ When('I close the Agent v2 Web app', async function (this: DifyWorld) {When('I open Agent v2 Embedded configuration', async function (this: DifyWorld) {await recordComposerDraftSnapshot(this)- await getWebAppCard(this).getByRole('button', { name: 'Embedded' }).click()+ await getWebAppCard(this).getByRole('button', { name: 'Embed Into Site' }).click()})Then('I should see the Agent v2 Embedded configuration dialog', async function (this: DifyWorld) {@@ -143,7 +143,7 @@ Then('I should see the Agent v2 Embedded configuration dialog', async function (When('I open Agent v2 Web app customization', async function (this: DifyWorld) {await recordComposerDraftSnapshot(this)- await getWebAppCard(this).getByRole('button', { name: 'Custom Frontend' }).click()+ await getWebAppCard(this).getByRole('button', { name: 'Custom frontend' }).click()})Then('I should see the Agent v2 Web app customization dialog', async function (this: DifyWorld) {@@ -156,7 +156,7 @@ Then('I should see the Agent v2 Web app customization dialog', async function (tWhen('I open Agent v2 Web app settings', async function (this: DifyWorld) {await recordComposerDraftSnapshot(this)- await getWebAppCard(this).getByRole('button', { name: 'Branding' }).click()+ await getWebAppCard(this).getByRole('button', { name: 'Settings' }).click()})Then('I should see the Agent v2 Web app settings dialog', async function (this: DifyWorld) {diff --git a/e2e/features/step-definitions/agent-v2/access-point.steps.ts b/e2e/features/step-definitions/agent-v2/access-point.steps.tsindex 38706e41a7d..956d4f0b776 100644--- a/e2e/features/step-definitions/agent-v2/access-point.steps.ts+++ b/e2e/features/step-definitions/agent-v2/access-point.steps.ts@@ -81,7 +81,7 @@ Then(await expect(webAppCard.getByText('Out of service')).toBeVisible({ timeout: 30_000 })await expect(webAppCard.getByLabel('Toggle Web app access')).toBeDisabled()- await expect(webAppCard.getByRole('button', { name: 'Launch' })).toBeDisabled()+ await expect(webAppCard.getByRole('button', { name: 'Open' })).toBeDisabled()await expect(serviceApiCard.getByText('Out of service')).toBeVisible()await expect(serviceApiCard.getByLabel('Toggle Backend service API access')).toBeDisabled()await expect(serviceApiCard.getByRole('button', { name: /^API Key\b/ })).toBeDisabled()@@ -94,9 +94,9 @@ When(const accessSurfaceCard = getAccessSurfaceCard(this, surface)if (surface === 'Web app') {- const launchLink = accessSurfaceCard.getByRole('link', { name: 'Launch' })- const href = await launchLink.getAttribute('href')- if (!href) throw new Error('Agent v2 Web app Launch link does not expose an href.')+ const openLink = accessSurfaceCard.getByRole('link', { name: 'Open' })+ const href = await openLink.getAttribute('href')+ if (!href) throw new Error('Agent v2 Web app Open link does not expose an href.')this.agentBuilder.accessPoint.webAppURL = href}@@ -122,7 +122,7 @@ Then(await expect(toggle).toBeEnabled()await expect(toggle).toHaveAttribute('aria-checked', 'false')if (surface === 'Web app')- await expect(accessSurfaceCard.getByRole('button', { name: 'Launch' })).toBeDisabled()+ await expect(accessSurfaceCard.getByRole('button', { name: 'Open' })).toBeDisabled()},)@@ -136,6 +136,6 @@ Then(await expect(toggle).toBeEnabled()await expect(toggle).toHaveAttribute('aria-checked', 'true')if (surface === 'Web app')- await expect(accessSurfaceCard.getByRole('link', { name: 'Launch' })).toBeVisible()+ await expect(accessSurfaceCard.getByRole('link', { name: 'Open' })).toBeVisible()},)diff --git a/e2e/features/step-definitions/apps/create-app.steps.ts b/e2e/features/step-definitions/apps/create-app.steps.tsindex 88113afa3fb..f632f310a33 100644--- a/e2e/features/step-definitions/apps/create-app.steps.ts+++ b/e2e/features/step-definitions/apps/create-app.steps.ts@@ -20,6 +20,10 @@ const getLatestCreatedAppId = (world: DifyWorld) => {return appId}+const expectAppEditorContent = async (world: DifyWorld) => {+ await expect(world.getPage().getByRole('link', { name: 'Orchestrate' })).toBeVisible()+}+When('I start creating a blank app', async function (this: DifyWorld) {await openBlankAppCreation(this.getPage())})@@ -78,14 +82,17 @@ Then('I should land on the app editor', async function (this: DifyWorld) {await expect(this.getPage()).toHaveURL(new RegExp(`/app/${appId}/(workflow|configuration)(?:\\?.*)?$`),)+ await expectAppEditorContent(this)})Then('I should land on the workflow editor', async function (this: DifyWorld) {const appId = getLatestCreatedAppId(this)await expect(this.getPage()).toHaveURL(new RegExp(`/app/${appId}/workflow(?:\\?.*)?$`))+ await expectAppEditorContent(this)})Then('I should land on the app configuration page', async function (this: DifyWorld) {const appId = getLatestCreatedAppId(this)await expect(this.getPage()).toHaveURL(new RegExp(`/app/${appId}/configuration(?:\\?.*)?$`))+ await expectAppEditorContent(this)})diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 8c87c9ae25d..d85da0688e3 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -4491,12 +4491,6 @@"eslint-react/set-state-in-effect": {"count": 4},- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- },"no-restricted-imports": {"count": 1}diff --git a/packages/contracts/generated/enterprise-app-deploy/types.gen.ts b/packages/contracts/generated/enterprise-app-deploy/types.gen.tsindex c64c433d4b6..f7c6aa4f4b9 100644--- a/packages/contracts/generated/enterprise-app-deploy/types.gen.ts+++ b/packages/contracts/generated/enterprise-app-deploy/types.gen.ts@@ -4,6 +4,8 @@ export type ClientOptions = {baseUrl: `${string}://${string}` | (string & {})}+export type GoogleProtobufValue = unknown+export const EnvironmentStatus = {ENVIRONMENT_STATUS_UNSPECIFIED: 'ENVIRONMENT_STATUS_UNSPECIFIED',ENVIRONMENT_STATUS_PENDING: 'ENVIRONMENT_STATUS_PENDING',@@ -21,11 +23,27 @@ export const ApplicationInteractionStatus = {APPLICATION_INTERACTION_STATUS_FAILED: 'APPLICATION_INTERACTION_STATUS_FAILED',APPLICATION_INTERACTION_STATUS_PARTIAL_SUCCEEDED:'APPLICATION_INTERACTION_STATUS_PARTIAL_SUCCEEDED',+ APPLICATION_INTERACTION_STATUS_STOPPED: 'APPLICATION_INTERACTION_STATUS_STOPPED',+ APPLICATION_INTERACTION_STATUS_PAUSED: 'APPLICATION_INTERACTION_STATUS_PAUSED',} as constexport type ApplicationInteractionStatus =(typeof ApplicationInteractionStatus)[keyof typeof ApplicationInteractionStatus]+export const ApplicationInteractionSource = {+ APPLICATION_INTERACTION_SOURCE_UNSPECIFIED: 'APPLICATION_INTERACTION_SOURCE_UNSPECIFIED',+ APPLICATION_INTERACTION_SOURCE_WEB_APP: 'APPLICATION_INTERACTION_SOURCE_WEB_APP',+ APPLICATION_INTERACTION_SOURCE_SERVICE_API: 'APPLICATION_INTERACTION_SOURCE_SERVICE_API',+ APPLICATION_INTERACTION_SOURCE_TRIGGER: 'APPLICATION_INTERACTION_SOURCE_TRIGGER',+ APPLICATION_INTERACTION_SOURCE_EXPLORE: 'APPLICATION_INTERACTION_SOURCE_EXPLORE',+ APPLICATION_INTERACTION_SOURCE_DEBUGGER: 'APPLICATION_INTERACTION_SOURCE_DEBUGGER',+ APPLICATION_INTERACTION_SOURCE_VALIDATION: 'APPLICATION_INTERACTION_SOURCE_VALIDATION',+ APPLICATION_INTERACTION_SOURCE_OPENAPI: 'APPLICATION_INTERACTION_SOURCE_OPENAPI',+} as const++export type ApplicationInteractionSource =+ (typeof ApplicationInteractionSource)[keyof typeof ApplicationInteractionSource]+export const EnvironmentMode = {ENVIRONMENT_MODE_UNSPECIFIED: 'ENVIRONMENT_MODE_UNSPECIFIED',ENVIRONMENT_MODE_SHARED: 'ENVIRONMENT_MODE_SHARED',@@ -124,36 +142,17 @@ export const EnvironmentBackend = {export type EnvironmentBackend = (typeof EnvironmentBackend)[keyof typeof EnvironmentBackend]-export const EnvironmentManagedBy = {- ENVIRONMENT_MANAGED_BY_UNSPECIFIED: 'ENVIRONMENT_MANAGED_BY_UNSPECIFIED',- ENVIRONMENT_MANAGED_BY_SYSTEM: 'ENVIRONMENT_MANAGED_BY_SYSTEM',- ENVIRONMENT_MANAGED_BY_USER: 'ENVIRONMENT_MANAGED_BY_USER',-} as const--export type EnvironmentManagedBy = (typeof EnvironmentManagedBy)[keyof typeof EnvironmentManagedBy]--export const EnvironmentDeployedAppStatus = {- ENVIRONMENT_DEPLOYED_APP_STATUS_UNSPECIFIED: 'ENVIRONMENT_DEPLOYED_APP_STATUS_UNSPECIFIED',- ENVIRONMENT_DEPLOYED_APP_STATUS_DEPLOYED: 'ENVIRONMENT_DEPLOYED_APP_STATUS_DEPLOYED',- ENVIRONMENT_DEPLOYED_APP_STATUS_DEPLOYING: 'ENVIRONMENT_DEPLOYED_APP_STATUS_DEPLOYING',- ENVIRONMENT_DEPLOYED_APP_STATUS_FAILED: 'ENVIRONMENT_DEPLOYED_APP_STATUS_FAILED',- ENVIRONMENT_DEPLOYED_APP_STATUS_UNDEPLOYED: 'ENVIRONMENT_DEPLOYED_APP_STATUS_UNDEPLOYED',+export const RuntimeState = {+ RUNTIME_STATE_UNSPECIFIED: 'RUNTIME_STATE_UNSPECIFIED',+ RUNTIME_STATE_UNDEPLOYED: 'RUNTIME_STATE_UNDEPLOYED',+ RUNTIME_STATE_RUNNING: 'RUNTIME_STATE_RUNNING',+ RUNTIME_STATE_STARTING: 'RUNTIME_STATE_STARTING',+ RUNTIME_STATE_STOPPING: 'RUNTIME_STATE_STOPPING',+ RUNTIME_STATE_ERROR: 'RUNTIME_STATE_ERROR',+ RUNTIME_STATE_UNKNOWN: 'RUNTIME_STATE_UNKNOWN',} as const-export type EnvironmentDeployedAppStatus =- (typeof EnvironmentDeployedAppStatus)[keyof typeof EnvironmentDeployedAppStatus]--export const DeploymentStatus = {- DEPLOYMENT_STATUS_UNSPECIFIED: 'DEPLOYMENT_STATUS_UNSPECIFIED',- DEPLOYMENT_STATUS_UNDEPLOYED: 'DEPLOYMENT_STATUS_UNDEPLOYED',- DEPLOYMENT_STATUS_DEPLOYING: 'DEPLOYMENT_STATUS_DEPLOYING',- DEPLOYMENT_STATUS_RUNNING: 'DEPLOYMENT_STATUS_RUNNING',- DEPLOYMENT_STATUS_UNDEPLOYING: 'DEPLOYMENT_STATUS_UNDEPLOYING',- DEPLOYMENT_STATUS_INVALID: 'DEPLOYMENT_STATUS_INVALID',- DEPLOYMENT_STATUS_FAILED: 'DEPLOYMENT_STATUS_FAILED',-} as const--export type DeploymentStatus = (typeof DeploymentStatus)[keyof typeof DeploymentStatus]+export type RuntimeState = (typeof RuntimeState)[keyof typeof RuntimeState]export const EnvVarValueSource = {ENV_VAR_VALUE_SOURCE_UNSPECIFIED: 'ENV_VAR_VALUE_SOURCE_UNSPECIFIED',@@ -169,6 +168,7 @@ export const EnvVarValueType = {ENV_VAR_VALUE_TYPE_STRING: 'ENV_VAR_VALUE_TYPE_STRING',ENV_VAR_VALUE_TYPE_NUMBER: 'ENV_VAR_VALUE_TYPE_NUMBER',ENV_VAR_VALUE_TYPE_SECRET: 'ENV_VAR_VALUE_TYPE_SECRET',+ ENV_VAR_VALUE_TYPE_LLM: 'ENV_VAR_VALUE_TYPE_LLM',} as constexport type EnvVarValueType = (typeof EnvVarValueType)[keyof typeof EnvVarValueType]@@ -203,22 +203,17 @@ export type AppEnvironment = {export type ApplicationInteraction = {id: stringtimestamp: string- workflowRunId: stringstatus: ApplicationInteractionStatusdurationSeconds: numbertotalTokens: stringworkspace: NamedRefenvironment: NamedRefapp: NamedRef- operator?: Operator- invokeFrom: string- traceId: string- difyTraceId: string- deploymentVersionId: string+ operator?: NamedRef+ source: ApplicationInteractionSource+ version?: WorkflowVersion+ traceId?: stringerror?: string- body?: string- attributesJson?: string- resourceAttributesJson?: string}export type BatchGetSourceVersionDeploymentsRequest = {@@ -262,7 +257,7 @@ export type CreateEnvironmentRequest = {displayName: stringdescription?: stringmode: EnvironmentMode- cpuPool: number+ cpuPoolMillicores: numbernamespace?: stringmaxMemoryMib?: string}@@ -292,12 +287,7 @@ export type CredentialSlot = {last_deployed_credential_id?: stringicon?: stringicon_dark?: string-}--export type DashboardApp = {- id: string- workspaceId: string- displayName: string+ workflow_as_tool_dependency?: WorkflowAsToolDependency}export type DeleteEnvironmentApiKeyResponse = {@@ -308,6 +298,15 @@ export type DeleteEnvironmentResponse = {[key: string]: unknown}+export type DeleteServiceApiConversationRequest = {+ conversationId: string+ user: string+}++export type DeleteServiceApiConversationResponse = {+ [key: string]: unknown+}+export type DeployWorkflowResponse = {operation: DeploymentOperationReceipt}@@ -358,8 +357,7 @@ export type Environment = {statusMessage: stringlastError?: Errornamespace?: string- managedBy?: EnvironmentManagedBy- cpuPool: number+ cpuPoolMillicores: numbercreatedAt: stringupdatedAt: stringmemory?: RunnerMemory@@ -381,6 +379,14 @@ export type EnvironmentAccess = {enable_api: boolean}+export type EnvironmentActivity = {+ environmentId: string+ invocationCount: string+ failedInvocationCount: string+ failedDeploymentCount: string+ deployedAppCount: string+}+export type EnvironmentApiKey = {id: stringtype: string@@ -393,13 +399,15 @@ export type EnvironmentDeployedApp = {deploymentId: stringworkspace: NamedRefapp: NamedRef- status: EnvironmentDeployedAppStatus+ runtimeState: RuntimeStatecurrentVersion?: WorkflowVersiondeployedAt?: stringdeployedBy?: OperatorlatestAttempt?: EnvironmentDeployedAppAttemptsizing?: RunnerSizingoccupiesPool?: boolean+ recentInvocationCount?: string+ versionsBehind?: number}export type EnvironmentDeployedAppAttempt = {@@ -412,13 +420,6 @@ export type EnvironmentDeployedAppAttempt = {finalizedAt?: string}-export type EnvironmentDeployedAppSummary = {- total: number- deployed: number- deploying: number- failed: number-}-export type EnvironmentDeployment = {environment: DeploymentEnvironmentdeployment?: EnvironmentDeploymentState@@ -435,7 +436,7 @@ export type EnvironmentDeploymentOperation = {}export type EnvironmentDeploymentState = {- status: DeploymentStatus+ runtimeState: RuntimeStatecurrent_version?: WorkflowVersionversions_behind?: numberdeployed_at?: number@@ -449,17 +450,17 @@ export type EnvironmentMcpServer = {export type EnvironmentPoolComposition = {topApps?: Array<EnvironmentPoolShare>- otherCpu?: number+ otherCpuMillicores?: numberotherAppCount?: number}export type EnvironmentPoolShare = {app: NamedRef- isolatedCpu: number+ isolatedCpuMillicores: number}export type EnvironmentPoolUsage = {- occupiedCpu: number+ occupiedCpuMillicores: numberappCount: number}@@ -478,10 +479,16 @@ export type EnvironmentTrigger = {[key: string]: unknown}+export type EnvironmentVariableGroup = {+ from_app?: WorkflowReference+ from_workflow_as_tool?: WorkflowAsToolSource+ environment_variable_slots: Array<EnvironmentVariableSlot>+}+export type EnvironmentVariableInput = {key: stringvalue_source: EnvVarValueSource- value?: string+ value?: GoogleProtobufValue}export type EnvironmentVariableSlot = {@@ -490,8 +497,8 @@ export type EnvironmentVariableSlot = {description: stringhas_configured_value: booleanhas_last_deployed_value: boolean- configured_value?: string- last_deployed_value?: string+ configured_value?: GoogleProtobufValue+ last_deployed_value?: GoogleProtobufValue}export type EnvironmentWebAppAccessModeUpdate = {@@ -540,7 +547,6 @@ export type Error = {| 'APPDEPLOY_APP_LOG_INVALID_TIME_RANGE'| 'APPDEPLOY_APP_LOG_INVALID_CURSOR'| 'APPDEPLOY_APP_LOG_CURSOR_FILTER_MISMATCH'- | 'APPDEPLOY_APP_LOG_ID_INVALID'| 'APPDEPLOY_UNSUPPORTED_NODE_TYPE'| 'APPDEPLOY_UNSUPPORTED_TOOL_PROVIDER_TYPE'| 'APPDEPLOY_TOOL_PROVIDER_TYPE_INVALID'@@ -552,15 +558,12 @@ export type Error = {| 'APPDEPLOY_INVALID_WORKFLOW_ID'| 'APPDEPLOY_INVALID_DEPLOYMENT_VERSION_ID'| 'APPDEPLOY_DEVELOPER_API_URL_NOT_CONFIGURED'- | 'APPDEPLOY_INVALID_DEPLOYMENT_OPERATION_ID'- | 'APPDEPLOY_APP_LOG_EXPORT_RANGE_TOO_WIDE'- | 'APPDEPLOY_APP_LOG_EXPORT_TOO_MANY_ROWS'- | 'APPDEPLOY_APP_LOG_EXPORT_TOO_LARGE'| 'APPDEPLOY_UNAUTHORIZED'| 'APPDEPLOY_FORBIDDEN'| 'APPDEPLOY_APP_RUNNER_AUTH_REQUIRED'| 'APPDEPLOY_APP_RUNNER_INVALID_JOIN_TOKEN'| 'APPDEPLOY_APP_RUNNER_INVALID_CONTROL_TOKEN'+ | 'APPDEPLOY_WEB_APP_ACCESS_DENIED'| 'APPDEPLOY_ENVIRONMENT_NOT_FOUND'| 'APPDEPLOY_DEPLOYMENT_NOT_FOUND'| 'APPDEPLOY_REVISION_NOT_FOUND'@@ -571,15 +574,15 @@ export type Error = {| 'APPDEPLOY_ACCESS_SUBJECT_NOT_FOUND'| 'APPDEPLOY_API_KEY_NOT_FOUND'| 'APPDEPLOY_SOURCE_VERSION_NOT_FOUND'- | 'APPDEPLOY_APP_LOG_NOT_FOUND'| 'APPDEPLOY_WORKSPACE_NOT_FOUND'| 'APPDEPLOY_APP_RUNNER_NOT_FOUND'| 'APPDEPLOY_WORKFLOW_NOT_FOUND'- | 'APPDEPLOY_DEPLOYMENT_OPERATION_NOT_FOUND'| 'APPDEPLOY_RUN_FILE_NOT_FOUND'| 'APPDEPLOY_APPLICATION_UNAVAILABLE'| 'APPDEPLOY_TARGET_ENVIRONMENT_REMOVED'| 'APPDEPLOY_VERSION_UNAVAILABLE'+ | 'APPDEPLOY_CONVERSATION_NOT_FOUND'+ | 'APPDEPLOY_CHAT_MESSAGE_NOT_FOUND'| 'APPDEPLOY_CONFLICT'| 'APPDEPLOY_DEPLOYMENT_IN_PROGRESS'| 'APPDEPLOY_ALREADY_UNDEPLOYED'@@ -618,10 +621,13 @@ export type Error = {| 'APPDEPLOY_ENVIRONMENT_CPU_POOL_EXHAUSTED'| 'APPDEPLOY_RESOURCE_NOT_APPLICABLE_FOR_MODE'| 'APPDEPLOY_ENVIRONMENT_CPU_POOL_BELOW_ALLOCATED'+ | 'APPDEPLOY_CHAT_CONTEXT_TOO_LARGE'+ | 'APPDEPLOY_FILE_GRANT_UNAVAILABLE'| 'APPDEPLOY_APP_RUNNER_CONTROL_NOT_CONFIGURED'| 'APPDEPLOY_RUNTIME_ASSIGNMENT_FAILED'| 'APPDEPLOY_REVISION_TIMEOUT'| 'APPDEPLOY_INTERNAL_ERROR'+ | 'APPDEPLOY_RECEIPT_RETRY'| 'APPDEPLOY_ENVIRONMENT_BOOTSTRAP_AUTH_REJECTED'| 'APPDEPLOY_ENVIRONMENT_BOOTSTRAP_NAMESPACE_MISSING'| 'APPDEPLOY_ENVIRONMENT_BOOTSTRAP_INSUFFICIENT_RBAC'@@ -640,12 +646,14 @@ export type Error = {detailCode?: string}-export type GetApplicationInteractionResponse = {- interaction: ApplicationInteraction+export type GetApplicationInteractionSummaryResponse = {+ totalCount: string+ failedCount: string+ lookbackStart: string}-export type GetDeploymentOperationResponse = {- operation: DeploymentOperation+export type GetEnvironmentActivityResponse = {+ data: Array<EnvironmentActivity>}export type GetEnvironmentCapabilitiesResponse = {@@ -673,12 +681,17 @@ export type GetWebAppAccessModeResponse = {accessMode?: string}+export type GetWebAppLoginStatusResponse = {+ logged_in?: boolean+ app_logged_in?: boolean+}+export type GetWebAppPermissionResponse = {result?: boolean}export type GetWorkflowDeploymentOptionsResponse = {- environment_variable_slots: Array<EnvironmentVariableSlot>+ environment_variable_groups: Array<EnvironmentVariableGroup>credential_slots: Array<CredentialSlot>}@@ -686,14 +699,15 @@ export type ListAppEnvironmentsResponse = {data: Array<AppEnvironment>}-export type ListApplicationInteractionsResponse = {- data: Array<ApplicationInteraction>+export type ListApplicationInteractionAppsResponse = {+ data: Array<NamedRef>pagination: Pagination}-export type ListAppsResponse = {- data: Array<DashboardApp>- pagination: Pagination+export type ListApplicationInteractionsResponse = {+ data: Array<ApplicationInteraction>+ nextPageToken?: string+ previousPageToken?: string}export type ListDeploymentOperationsResponse = {@@ -707,7 +721,6 @@ export type ListEnvironmentApiKeysResponse = {export type ListEnvironmentDeployedAppsResponse = {data: Array<EnvironmentDeployedApp>- summary: EnvironmentDeployedAppSummarypagination: Pagination}@@ -724,11 +737,34 @@ export type ListEnvironmentsResponse = {pagination: Pagination}+export type ListOperationAppsResponse = {+ data: Array<OperationApp>+ pagination: Pagination+}++export type MintServiceApiFileGrantRequest = {+ tenantId?: string+ appId?: string+ environmentId?: string+ user?: string+}++export type MintServiceApiFileGrantResponse = {+ grant?: string+ expiresAt?: string+}+export type NamedRef = {id: stringdisplayName: string}+export type OperationApp = {+ id?: string+ workspaceId?: string+ displayName?: string+}+export type Operator = {type: OperatorTypeid: string@@ -744,6 +780,20 @@ export type PrepareAppDeletionRequest = {appId?: string}+export type RenameServiceApiConversationRequest = {+ conversationId: string+ user: string+ name?: string+ autoGenerate?: boolean+}++export type RenameWebAppConversationRequest = {+ appCode: string+ conversationId: string+ name?: string+ autoGenerate?: boolean+}+export type ResolveApiTokenRouteRequest = {token?: string}@@ -753,17 +803,14 @@ export type ResolveApiTokenRouteResponse = {namespace?: stringserviceName?: stringservicePort?: number- environmentStatus?: EnvironmentStatusappId?: stringtenantId?: stringdeploymentId?: stringservingRevisionId?: string- deploymentStatus?: DeploymentStatus- revoked?: boolean- unavailableReason?: stringtargetKind?: RouteTargetKinddirectUpstream?: string- deploymentGeneration?: string+ assignmentGeneration?: string+ decision?: string}export type ResolveWebAppRouteRequest = {@@ -777,18 +824,18 @@ export type ResolveWebAppRouteResponse = {namespace?: stringserviceName?: stringservicePort?: number- environmentStatus?: EnvironmentStatusappId?: stringtenantId?: stringdeploymentId?: stringservingRevisionId?: string- deploymentStatus?: DeploymentStatus- unavailableReason?: stringtargetKind?: RouteTargetKinddirectUpstream?: string- deploymentGeneration?: string- endUserId?: string- authType?: string+ assignmentGeneration?: string+ userId?: string+ userFrom?: string+ userAuthType?: string+ fileGrant?: string+ fileGrantExpiresAt?: string}export type RetryEnvironmentBootstrapRequest = {@@ -806,7 +853,7 @@ export type RunnerMemory = {}export type RunnerSizing = {- isolatedCpu: number+ isolatedCpuMillicores: numbermemory: RunnerMemory}@@ -818,7 +865,12 @@ export type SimpleAccount = {export type SourceVersionDeployment = {sourceVersionId?: string- environments?: Array<WorkflowDeploymentEnvironment>+ environments?: Array<SourceVersionDeploymentEnvironment>+}++export type SourceVersionDeploymentEnvironment = {+ id?: string+ name?: string}export type TestConnectionRequest = {@@ -843,6 +895,7 @@ export type UnsupportedNode = {type: stringtitle: stringprovider?: UnsupportedNodeProvider+ workflow_as_tool_dependency?: WorkflowAsToolDependency}export type UnsupportedNodeProvider = {@@ -855,15 +908,15 @@ export type UnsupportedNodeProvider = {export type UpdateEnvironmentDeployedAppResourcesRequest = {environmentId: stringdeploymentId: string- isolatedCpu: number+ isolatedCpuMillicores: numbermaxMemoryMib?: string}export type UpdateEnvironmentDeployedAppResourcesResponse = {deploymentId: string- isolatedCpu: number- allocatedCpuCount: number- poolCpuCount: number+ isolatedCpuMillicores: number+ allocatedCpuMillicores: number+ poolCpuMillicores: numbermemory: RunnerMemory}@@ -871,7 +924,7 @@ export type UpdateEnvironmentRequest = {environmentId?: stringdisplayName?: stringdescription?: string- cpuPool?: number+ cpuPoolMillicores?: numbermaxMemoryMib?: string}@@ -879,16 +932,46 @@ export type UpdateEnvironmentResponse = {environment: Environment}-export type WorkflowDeploymentEnvironment = {- id?: string- name?: string+export type UpdateServiceApiConversationVariableRequest = {+ conversationId: string+ variableId: string+ user: string+ value: GoogleProtobufValue+}++export type WorkflowAsToolDependency = {+ paths: Array<WorkflowPath>+}++export type WorkflowAsToolSource = {+ workflow: WorkflowReference+ paths: Array<WorkflowPath>}export type WorkflowDeploymentInput = {- environment_variables?: Array<EnvironmentVariableInput>+ environment_variable_groups: Array<WorkflowEnvironmentVariableInputGroup>credentials?: Array<CredentialSelectionInput>}+export type WorkflowEnvironmentVariableInputGroup = {+ workflow_id: string+ environment_variables: Array<EnvironmentVariableInput>+}++export type WorkflowPath = {+ workflows: Array<WorkflowReference>+}++export type WorkflowReference = {+ app_id: string+ workflow_id: string+ name: string+ icon: string+ icon_background: string+ icon_type: string+ icon_url?: string+}+export type WorkflowVersion = {version?: stringmarked_name?: string@@ -898,7 +981,6 @@ export type WorkflowVersion = {created_at?: numbercreated_by?: SimpleAccountdsl_hash?: string- deleted?: boolean}export type Pagination = {@@ -920,6 +1002,10 @@ export type DeleteEnvironmentResponseWritable = {[key: string]: unknown}+export type DeleteServiceApiConversationResponseWritable = {+ [key: string]: unknown+}+export type EnvironmentWritable = {id: stringdisplayName: string@@ -930,8 +1016,7 @@ export type EnvironmentWritable = {statusMessage: stringlastError?: Errornamespace?: string- managedBy?: EnvironmentManagedBy- cpuPool: number+ cpuPoolMillicores: numbercreatedAt: stringupdatedAt: stringmemory?: RunnerMemoryWritable@@ -942,13 +1027,15 @@ export type EnvironmentDeployedAppWritable = {deploymentId: stringworkspace: NamedRefapp: NamedRef- status: EnvironmentDeployedAppStatus+ runtimeState: RuntimeStatecurrentVersion?: WorkflowVersiondeployedAt?: stringdeployedBy?: OperatorlatestAttempt?: EnvironmentDeployedAppAttemptsizing?: RunnerSizingWritableoccupiesPool?: boolean+ recentInvocationCount?: string+ versionsBehind?: number}export type EnvironmentMcpServerWritable = {@@ -966,7 +1053,6 @@ export type GetEnvironmentResponseWritable = {export type ListEnvironmentDeployedAppsResponseWritable = {data: Array<EnvironmentDeployedAppWritable>- summary: EnvironmentDeployedAppSummarypagination: Pagination}@@ -984,15 +1070,15 @@ export type RunnerMemoryWritable = {}export type RunnerSizingWritable = {- isolatedCpu: number+ isolatedCpuMillicores: numbermemory: RunnerMemoryWritable}export type UpdateEnvironmentDeployedAppResourcesResponseWritable = {deploymentId: string- isolatedCpu: number- allocatedCpuCount: number- poolCpuCount: number+ isolatedCpuMillicores: number+ allocatedCpuMillicores: number+ poolCpuMillicores: numbermemory: RunnerMemoryWritable}diff --git a/packages/contracts/generated/enterprise-app-deploy/zod.gen.ts b/packages/contracts/generated/enterprise-app-deploy/zod.gen.tsindex c823bce2015..ae2591ffbf2 100644--- a/packages/contracts/generated/enterprise-app-deploy/zod.gen.ts+++ b/packages/contracts/generated/enterprise-app-deploy/zod.gen.ts@@ -2,6 +2,11 @@import * as z from 'zod'+/**+ * Represents a dynamically typed value which can be either null, a number, a string, a boolean, a recursive struct value, or a list of values.+ */+export const zGoogleProtobufValue = z.unknown()+export const zEnvironmentStatus = z.enum(['ENVIRONMENT_STATUS_UNSPECIFIED','ENVIRONMENT_STATUS_PENDING',@@ -16,6 +21,19 @@ export const zApplicationInteractionStatus = z.enum(['APPLICATION_INTERACTION_STATUS_SUCCEEDED','APPLICATION_INTERACTION_STATUS_FAILED','APPLICATION_INTERACTION_STATUS_PARTIAL_SUCCEEDED',+ 'APPLICATION_INTERACTION_STATUS_STOPPED',+ 'APPLICATION_INTERACTION_STATUS_PAUSED',+])++export const zApplicationInteractionSource = z.enum([+ 'APPLICATION_INTERACTION_SOURCE_UNSPECIFIED',+ 'APPLICATION_INTERACTION_SOURCE_WEB_APP',+ 'APPLICATION_INTERACTION_SOURCE_SERVICE_API',+ 'APPLICATION_INTERACTION_SOURCE_TRIGGER',+ 'APPLICATION_INTERACTION_SOURCE_EXPLORE',+ 'APPLICATION_INTERACTION_SOURCE_DEBUGGER',+ 'APPLICATION_INTERACTION_SOURCE_VALIDATION',+ 'APPLICATION_INTERACTION_SOURCE_OPENAPI',])export const zEnvironmentMode = z.enum([@@ -79,28 +97,14 @@ export const zEnvironmentBackend = z.enum(['ENVIRONMENT_BACKEND_EXTERNAL',])-export const zEnvironmentManagedBy = z.enum([- 'ENVIRONMENT_MANAGED_BY_UNSPECIFIED',- 'ENVIRONMENT_MANAGED_BY_SYSTEM',- 'ENVIRONMENT_MANAGED_BY_USER',-])--export const zEnvironmentDeployedAppStatus = z.enum([- 'ENVIRONMENT_DEPLOYED_APP_STATUS_UNSPECIFIED',- 'ENVIRONMENT_DEPLOYED_APP_STATUS_DEPLOYED',- 'ENVIRONMENT_DEPLOYED_APP_STATUS_DEPLOYING',- 'ENVIRONMENT_DEPLOYED_APP_STATUS_FAILED',- 'ENVIRONMENT_DEPLOYED_APP_STATUS_UNDEPLOYED',-])--export const zDeploymentStatus = z.enum([- 'DEPLOYMENT_STATUS_UNSPECIFIED',- 'DEPLOYMENT_STATUS_UNDEPLOYED',- 'DEPLOYMENT_STATUS_DEPLOYING',- 'DEPLOYMENT_STATUS_RUNNING',- 'DEPLOYMENT_STATUS_UNDEPLOYING',- 'DEPLOYMENT_STATUS_INVALID',- 'DEPLOYMENT_STATUS_FAILED',+export const zRuntimeState = z.enum([+ 'RUNTIME_STATE_UNSPECIFIED',+ 'RUNTIME_STATE_UNDEPLOYED',+ 'RUNTIME_STATE_RUNNING',+ 'RUNTIME_STATE_STARTING',+ 'RUNTIME_STATE_STOPPING',+ 'RUNTIME_STATE_ERROR',+ 'RUNTIME_STATE_UNKNOWN',])export const zEnvVarValueSource = z.enum([@@ -115,6 +119,7 @@ export const zEnvVarValueType = z.enum(['ENV_VAR_VALUE_TYPE_STRING','ENV_VAR_VALUE_TYPE_NUMBER','ENV_VAR_VALUE_TYPE_SECRET',+ 'ENV_VAR_VALUE_TYPE_LLM',])export const zOperatorType = z.enum([@@ -173,7 +178,10 @@ export const zCreateEnvironmentRequest = z.object({displayName: z.string(),description: z.string().optional(),mode: zEnvironmentMode,- cpuPool: z.number(),+ cpuPoolMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),namespace: z.string().optional(),maxMemoryMib: z.string().optional(),})@@ -192,25 +200,17 @@ export const zCredentialSelectionInput = z.object({credential_id: z.string(),})-export const zCredentialSlot = z.object({- provider_id: z.string(),- category: zPluginCategory,- candidates: z.array(zCredentialCandidate),- last_deployed_credential_id: z.string().optional(),- icon: z.string().optional(),- icon_dark: z.string().optional(),-})--export const zDashboardApp = z.object({- id: z.string(),- workspaceId: z.string(),- displayName: z.string(),-})-export const zDeleteEnvironmentApiKeyResponse = z.record(z.string(), z.unknown())export const zDeleteEnvironmentResponse = z.record(z.string(), z.unknown())+export const zDeleteServiceApiConversationRequest = z.object({+ conversationId: z.string(),+ user: z.string(),+})++export const zDeleteServiceApiConversationResponse = z.record(z.string(), z.unknown())+export const zDeploymentEnvironment = z.object({id: z.string(),display_name: z.string(),@@ -257,6 +257,18 @@ export const zEnvironmentAccess = z.object({enable_api: z.boolean(),})+/**+ * EnvironmentActivity reports a numerator and a denominator rather than a rate,+ * so a caller can tell a healthy environment from one nothing has called.+ */+export const zEnvironmentActivity = z.object({+ environmentId: z.string(),+ invocationCount: z.string(),+ failedInvocationCount: z.string(),+ failedDeploymentCount: z.string(),+ deployedAppCount: z.string(),+})+export const zEnvironmentApiKey = z.object({id: z.string(),type: z.string(),@@ -275,29 +287,13 @@ export const zEnvironmentDeployedAppAttempt = z.object({finalizedAt: z.iso.datetime().optional(),})-export const zEnvironmentDeployedAppSummary = z.object({- total: z- .int()- .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })- .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),- deployed: z- .int()- .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })- .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),- deploying: z- .int()- .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })- .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),- failed: z- .int()- .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })- .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),-})-export const zEnvironmentMcpServer = z.record(z.string(), z.unknown())export const zEnvironmentPoolUsage = z.object({- occupiedCpu: z.number(),+ occupiedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),appCount: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })@@ -320,7 +316,7 @@ export const zEnvironmentTrigger = z.record(z.string(), z.unknown())export const zEnvironmentVariableInput = z.object({key: z.string(),value_source: zEnvVarValueSource,- value: z.string().optional(),+ value: zGoogleProtobufValue.optional(),})export const zEnvironmentVariableSlot = z.object({@@ -329,8 +325,8 @@ export const zEnvironmentVariableSlot = z.object({description: z.string(),has_configured_value: z.boolean(),has_last_deployed_value: z.boolean(),- configured_value: z.string().optional(),- last_deployed_value: z.string().optional(),+ configured_value: zGoogleProtobufValue.optional(),+ last_deployed_value: zGoogleProtobufValue.optional(),})export const zEnvironmentWebAppSubjectAccountData = z.object({@@ -384,7 +380,6 @@ export const zError = z.object({'APPDEPLOY_APP_LOG_INVALID_TIME_RANGE','APPDEPLOY_APP_LOG_INVALID_CURSOR','APPDEPLOY_APP_LOG_CURSOR_FILTER_MISMATCH',- 'APPDEPLOY_APP_LOG_ID_INVALID','APPDEPLOY_UNSUPPORTED_NODE_TYPE','APPDEPLOY_UNSUPPORTED_TOOL_PROVIDER_TYPE','APPDEPLOY_TOOL_PROVIDER_TYPE_INVALID',@@ -396,15 +391,12 @@ export const zError = z.object({'APPDEPLOY_INVALID_WORKFLOW_ID','APPDEPLOY_INVALID_DEPLOYMENT_VERSION_ID','APPDEPLOY_DEVELOPER_API_URL_NOT_CONFIGURED',- 'APPDEPLOY_INVALID_DEPLOYMENT_OPERATION_ID',- 'APPDEPLOY_APP_LOG_EXPORT_RANGE_TOO_WIDE',- 'APPDEPLOY_APP_LOG_EXPORT_TOO_MANY_ROWS',- 'APPDEPLOY_APP_LOG_EXPORT_TOO_LARGE','APPDEPLOY_UNAUTHORIZED','APPDEPLOY_FORBIDDEN','APPDEPLOY_APP_RUNNER_AUTH_REQUIRED','APPDEPLOY_APP_RUNNER_INVALID_JOIN_TOKEN','APPDEPLOY_APP_RUNNER_INVALID_CONTROL_TOKEN',+ 'APPDEPLOY_WEB_APP_ACCESS_DENIED','APPDEPLOY_ENVIRONMENT_NOT_FOUND','APPDEPLOY_DEPLOYMENT_NOT_FOUND','APPDEPLOY_REVISION_NOT_FOUND',@@ -415,15 +407,15 @@ export const zError = z.object({'APPDEPLOY_ACCESS_SUBJECT_NOT_FOUND','APPDEPLOY_API_KEY_NOT_FOUND','APPDEPLOY_SOURCE_VERSION_NOT_FOUND',- 'APPDEPLOY_APP_LOG_NOT_FOUND','APPDEPLOY_WORKSPACE_NOT_FOUND','APPDEPLOY_APP_RUNNER_NOT_FOUND','APPDEPLOY_WORKFLOW_NOT_FOUND',- 'APPDEPLOY_DEPLOYMENT_OPERATION_NOT_FOUND','APPDEPLOY_RUN_FILE_NOT_FOUND','APPDEPLOY_APPLICATION_UNAVAILABLE','APPDEPLOY_TARGET_ENVIRONMENT_REMOVED','APPDEPLOY_VERSION_UNAVAILABLE',+ 'APPDEPLOY_CONVERSATION_NOT_FOUND',+ 'APPDEPLOY_CHAT_MESSAGE_NOT_FOUND','APPDEPLOY_CONFLICT','APPDEPLOY_DEPLOYMENT_IN_PROGRESS','APPDEPLOY_ALREADY_UNDEPLOYED',@@ -462,10 +454,13 @@ export const zError = z.object({'APPDEPLOY_ENVIRONMENT_CPU_POOL_EXHAUSTED','APPDEPLOY_RESOURCE_NOT_APPLICABLE_FOR_MODE','APPDEPLOY_ENVIRONMENT_CPU_POOL_BELOW_ALLOCATED',+ 'APPDEPLOY_CHAT_CONTEXT_TOO_LARGE',+ 'APPDEPLOY_FILE_GRANT_UNAVAILABLE','APPDEPLOY_APP_RUNNER_CONTROL_NOT_CONFIGURED','APPDEPLOY_RUNTIME_ASSIGNMENT_FAILED','APPDEPLOY_REVISION_TIMEOUT','APPDEPLOY_INTERNAL_ERROR',+ 'APPDEPLOY_RECEIPT_RETRY','APPDEPLOY_ENVIRONMENT_BOOTSTRAP_AUTH_REJECTED','APPDEPLOY_ENVIRONMENT_BOOTSTRAP_NAMESPACE_MISSING','APPDEPLOY_ENVIRONMENT_BOOTSTRAP_INSUFFICIENT_RBAC',@@ -486,6 +481,16 @@ export const zError = z.object({detailCode: z.string().optional(),})+export const zGetApplicationInteractionSummaryResponse = z.object({+ totalCount: z.string(),+ failedCount: z.string(),+ lookbackStart: z.iso.datetime(),+})++export const zGetEnvironmentActivityResponse = z.object({+ data: z.array(zEnvironmentActivity),+})+export const zGetEnvironmentCapabilitiesResponse = z.object({backend: zEnvironmentBackend,supportedModes: z.array(@@ -506,13 +511,13 @@ export const zGetWebAppAccessModeResponse = z.object({accessMode: z.string().optional(),})-export const zGetWebAppPermissionResponse = z.object({- result: z.boolean().optional(),+export const zGetWebAppLoginStatusResponse = z.object({+ logged_in: z.boolean().optional(),+ app_logged_in: z.boolean().optional(),})-export const zGetWorkflowDeploymentOptionsResponse = z.object({- environment_variable_slots: z.array(zEnvironmentVariableSlot),- credential_slots: z.array(zCredentialSlot),+export const zGetWebAppPermissionResponse = z.object({+ result: z.boolean().optional(),})export const zListAppEnvironmentsResponse = z.object({@@ -527,6 +532,18 @@ export const zListEnvironmentTriggersResponse = z.object({data: z.array(zEnvironmentTrigger),})+export const zMintServiceApiFileGrantRequest = z.object({+ tenantId: z.string().optional(),+ appId: z.string().optional(),+ environmentId: z.string().optional(),+ user: z.string().optional(),+})++export const zMintServiceApiFileGrantResponse = z.object({+ grant: z.string().optional(),+ expiresAt: z.string().optional(),+})+export const zNamedRef = z.object({id: z.string(),displayName: z.string(),@@ -534,7 +551,10 @@ export const zNamedRef = z.object({export const zEnvironmentPoolShare = z.object({app: zNamedRef,- isolatedCpu: z.number(),+ isolatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),})/**@@ -544,7 +564,11 @@ export const zEnvironmentPoolShare = z.object({*/export const zEnvironmentPoolComposition = z.object({topApps: z.array(zEnvironmentPoolShare).optional(),- otherCpu: z.number().optional(),+ otherCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),otherAppCount: z.int().min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })@@ -552,40 +576,35 @@ export const zEnvironmentPoolComposition = z.object({.optional(),})+export const zOperationApp = z.object({+ id: z.string().optional(),+ workspaceId: z.string().optional(),+ displayName: z.string().optional(),+})+export const zOperator = z.object({type: zOperatorType,id: z.string(),display_name: z.string(),})-export const zApplicationInteraction = z.object({- id: z.string(),- timestamp: z.iso.datetime(),- workflowRunId: z.string(),- status: zApplicationInteractionStatus,- durationSeconds: z.number(),- totalTokens: z.string(),- workspace: zNamedRef,- environment: zNamedRef,- app: zNamedRef,- operator: zOperator.optional(),- invokeFrom: z.string(),- traceId: z.string(),- difyTraceId: z.string(),- deploymentVersionId: z.string(),- error: z.string().optional(),- body: z.string().optional(),- attributesJson: z.string().optional(),- resourceAttributesJson: z.string().optional(),+export const zPrepareAppDeletionRequest = z.object({+ tenantId: z.string().optional(),+ appId: z.string().optional(),})-export const zGetApplicationInteractionResponse = z.object({- interaction: zApplicationInteraction,+export const zRenameServiceApiConversationRequest = z.object({+ conversationId: z.string(),+ user: z.string(),+ name: z.string().optional(),+ autoGenerate: z.boolean().optional(),})-export const zPrepareAppDeletionRequest = z.object({- tenantId: z.string().optional(),- appId: z.string().optional(),+export const zRenameWebAppConversationRequest = z.object({+ appCode: z.string(),+ conversationId: z.string(),+ name: z.string().optional(),+ autoGenerate: z.boolean().optional(),})export const zResolveApiTokenRouteRequest = z.object({@@ -601,17 +620,14 @@ export const zResolveApiTokenRouteResponse = z.object({.min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(),- environmentStatus: zEnvironmentStatus.optional(),appId: z.string().optional(),tenantId: z.string().optional(),deploymentId: z.string().optional(),servingRevisionId: z.string().optional(),- deploymentStatus: zDeploymentStatus.optional(),- revoked: z.boolean().optional(),- unavailableReason: z.string().optional(),targetKind: zRouteTargetKind.optional(),directUpstream: z.string().optional(),- deploymentGeneration: z.string().optional(),+ assignmentGeneration: z.string().optional(),+ decision: z.string().optional(),})export const zResolveWebAppRouteRequest = z.object({@@ -629,18 +645,18 @@ export const zResolveWebAppRouteResponse = z.object({.min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' }).max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }).optional(),- environmentStatus: zEnvironmentStatus.optional(),appId: z.string().optional(),tenantId: z.string().optional(),deploymentId: z.string().optional(),servingRevisionId: z.string().optional(),- deploymentStatus: zDeploymentStatus.optional(),- unavailableReason: z.string().optional(),targetKind: zRouteTargetKind.optional(),directUpstream: z.string().optional(),- deploymentGeneration: z.string().optional(),- endUserId: z.string().optional(),- authType: z.string().optional(),+ assignmentGeneration: z.string().optional(),+ userId: z.string().optional(),+ userFrom: z.string().optional(),+ userAuthType: z.string().optional(),+ fileGrant: z.string().optional(),+ fileGrantExpiresAt: z.string().optional(),})export const zRetryEnvironmentBootstrapRequest = z.object({@@ -667,8 +683,10 @@ export const zEnvironment = z.object({statusMessage: z.string(),lastError: zError.optional(),namespace: z.string().optional(),- managedBy: zEnvironmentManagedBy.optional(),- cpuPool: z.number(),+ cpuPoolMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),createdAt: z.iso.datetime(),updatedAt: z.iso.datetime(),memory: zRunnerMemory.optional(),@@ -693,7 +711,10 @@ export const zRetryEnvironmentBootstrapResponse = z.object({* in an isolated environment; elsewhere the runner belongs to the environment.*/export const zRunnerSizing = z.object({- isolatedCpu: z.number(),+ isolatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),memory: zRunnerMemory,})@@ -707,6 +728,20 @@ export const zSimpleAccount = z.object({email: z.string().optional(),})+export const zSourceVersionDeploymentEnvironment = z.object({+ id: z.string().optional(),+ name: z.string().optional(),+})++export const zSourceVersionDeployment = z.object({+ sourceVersionId: z.string().optional(),+ environments: z.array(zSourceVersionDeploymentEnvironment).optional(),+})++export const zBatchGetSourceVersionDeploymentsResponse = z.object({+ items: z.array(zSourceVersionDeployment).optional(),+})+export const zTestConnectionRequest = z.object({environmentId: z.string().optional(),})@@ -731,29 +766,30 @@ export const zUnsupportedNodeProvider = z.object({provider_name: z.string(),})-export const zUnsupportedNode = z.object({- id: z.string(),- type: z.string(),- title: z.string(),- provider: zUnsupportedNodeProvider.optional(),-})--export const zPrecheckWorkflowDeploymentResponse = z.object({- unsupported_nodes: z.array(zUnsupportedNode),-})-export const zUpdateEnvironmentDeployedAppResourcesRequest = z.object({environmentId: z.string(),deploymentId: z.string(),- isolatedCpu: z.number(),+ isolatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),maxMemoryMib: z.string().optional(),})export const zUpdateEnvironmentDeployedAppResourcesResponse = z.object({deploymentId: z.string(),- isolatedCpu: z.number(),- allocatedCpuCount: z.number(),- poolCpuCount: z.number(),+ isolatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+ allocatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+ poolCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),memory: zRunnerMemory,})@@ -761,7 +797,11 @@ export const zUpdateEnvironmentRequest = z.object({environmentId: z.string().optional(),displayName: z.string().optional(),description: z.string().optional(),- cpuPool: z.number().optional(),+ cpuPoolMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),maxMemoryMib: z.string().optional(),})@@ -769,25 +809,79 @@ export const zUpdateEnvironmentResponse = z.object({environment: zEnvironment,})-export const zWorkflowDeploymentEnvironment = z.object({- id: z.string().optional(),- name: z.string().optional(),+export const zUpdateServiceApiConversationVariableRequest = z.object({+ conversationId: z.string(),+ variableId: z.string(),+ user: z.string(),+ value: zGoogleProtobufValue,})-export const zSourceVersionDeployment = z.object({- sourceVersionId: z.string().optional(),- environments: z.array(zWorkflowDeploymentEnvironment).optional(),-})--export const zBatchGetSourceVersionDeploymentsResponse = z.object({- items: z.array(zSourceVersionDeployment).optional(),+export const zWorkflowEnvironmentVariableInputGroup = z.object({+ workflow_id: z.string(),+ environment_variables: z.array(zEnvironmentVariableInput),})export const zWorkflowDeploymentInput = z.object({- environment_variables: z.array(zEnvironmentVariableInput).optional(),+ environment_variable_groups: z.array(zWorkflowEnvironmentVariableInputGroup),credentials: z.array(zCredentialSelectionInput).optional(),})+export const zWorkflowReference = z.object({+ app_id: z.string(),+ workflow_id: z.string(),+ name: z.string(),+ icon: z.string(),+ icon_background: z.string(),+ icon_type: z.string(),+ icon_url: z.string().optional(),+})++export const zWorkflowPath = z.object({+ workflows: z.array(zWorkflowReference),+})++export const zWorkflowAsToolDependency = z.object({+ paths: z.array(zWorkflowPath),+})++export const zCredentialSlot = z.object({+ provider_id: z.string(),+ category: zPluginCategory,+ candidates: z.array(zCredentialCandidate),+ last_deployed_credential_id: z.string().optional(),+ icon: z.string().optional(),+ icon_dark: z.string().optional(),+ workflow_as_tool_dependency: zWorkflowAsToolDependency.optional(),+})++export const zUnsupportedNode = z.object({+ id: z.string(),+ type: z.string(),+ title: z.string(),+ provider: zUnsupportedNodeProvider.optional(),+ workflow_as_tool_dependency: zWorkflowAsToolDependency.optional(),+})++export const zPrecheckWorkflowDeploymentResponse = z.object({+ unsupported_nodes: z.array(zUnsupportedNode),+})++export const zWorkflowAsToolSource = z.object({+ workflow: zWorkflowReference,+ paths: z.array(zWorkflowPath),+})++export const zEnvironmentVariableGroup = z.object({+ from_app: zWorkflowReference.optional(),+ from_workflow_as_tool: zWorkflowAsToolSource.optional(),+ environment_variable_slots: z.array(zEnvironmentVariableSlot),+})++export const zGetWorkflowDeploymentOptionsResponse = z.object({+ environment_variable_groups: z.array(zEnvironmentVariableGroup),+ credential_slots: z.array(zCredentialSlot),+})+export const zWorkflowVersion = z.object({version: z.string().optional(),marked_name: z.string().optional(),@@ -801,7 +895,22 @@ export const zWorkflowVersion = z.object({created_at: z.number().optional(),created_by: zSimpleAccount.optional(),dsl_hash: z.string().optional(),- deleted: z.boolean().optional(),+})++export const zApplicationInteraction = z.object({+ id: z.string(),+ timestamp: z.iso.datetime(),+ status: zApplicationInteractionStatus,+ durationSeconds: z.number(),+ totalTokens: z.string(),+ workspace: zNamedRef,+ environment: zNamedRef,+ app: zNamedRef,+ operator: zNamedRef.optional(),+ source: zApplicationInteractionSource,+ version: zWorkflowVersion.optional(),+ traceId: z.string().optional(),+ error: z.string().optional(),})export const zDeploymentOperation = z.object({@@ -824,13 +933,19 @@ export const zEnvironmentDeployedApp = z.object({deploymentId: z.string(),workspace: zNamedRef,app: zNamedRef,- status: zEnvironmentDeployedAppStatus,+ runtimeState: zRuntimeState,currentVersion: zWorkflowVersion.optional(),deployedAt: z.iso.datetime().optional(),deployedBy: zOperator.optional(),latestAttempt: zEnvironmentDeployedAppAttempt.optional(),sizing: zRunnerSizing.optional(),occupiesPool: z.boolean().optional(),+ recentInvocationCount: z.string().optional(),+ versionsBehind: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),})export const zEnvironmentDeploymentOperation = z.object({@@ -843,7 +958,7 @@ export const zEnvironmentDeploymentOperation = z.object({})export const zEnvironmentDeploymentState = z.object({- status: zDeploymentStatus,+ runtimeState: zRuntimeState,current_version: zWorkflowVersion.optional(),versions_behind: z.int()@@ -861,14 +976,16 @@ export const zEnvironmentDeployment = z.object({access: zEnvironmentAccess,})-export const zGetDeploymentOperationResponse = z.object({- operation: zDeploymentOperation,-})-export const zGetEnvironmentDeploymentResponse = z.object({environment_deployment: zEnvironmentDeployment,})+export const zListApplicationInteractionsResponse = z.object({+ data: z.array(zApplicationInteraction),+ nextPageToken: z.string().optional(),+ previousPageToken: z.string().optional(),+})+export const zListEnvironmentDeploymentsResponse = z.object({environment_deployments: z.array(zEnvironmentDeployment),})@@ -899,13 +1016,8 @@ export const zPagination = z.object({.optional(),})-export const zListApplicationInteractionsResponse = z.object({- data: z.array(zApplicationInteraction),- pagination: zPagination,-})--export const zListAppsResponse = z.object({- data: z.array(zDashboardApp),+export const zListApplicationInteractionAppsResponse = z.object({+ data: z.array(zNamedRef),pagination: zPagination,})@@ -916,7 +1028,6 @@ export const zListDeploymentOperationsResponse = z.object({export const zListEnvironmentDeployedAppsResponse = z.object({data: z.array(zEnvironmentDeployedApp),- summary: zEnvironmentDeployedAppSummary,pagination: zPagination,})@@ -925,10 +1036,17 @@ export const zListEnvironmentsResponse = z.object({pagination: zPagination,})+export const zListOperationAppsResponse = z.object({+ data: z.array(zOperationApp),+ pagination: zPagination,+})+export const zDeleteEnvironmentApiKeyResponseWritable = z.record(z.string(), z.unknown())export const zDeleteEnvironmentResponseWritable = z.record(z.string(), z.unknown())+export const zDeleteServiceApiConversationResponseWritable = z.record(z.string(), z.unknown())+export const zEnvironmentMcpServerWritable = z.record(z.string(), z.unknown())export const zEnvironmentTriggerWritable = z.record(z.string(), z.unknown())@@ -951,8 +1069,10 @@ export const zEnvironmentWritable = z.object({statusMessage: z.string(),lastError: zError.optional(),namespace: z.string().optional(),- managedBy: zEnvironmentManagedBy.optional(),- cpuPool: z.number(),+ cpuPoolMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),createdAt: z.iso.datetime(),updatedAt: z.iso.datetime(),memory: zRunnerMemoryWritable.optional(),@@ -982,7 +1102,10 @@ export const zRetryEnvironmentBootstrapResponseWritable = z.object({* in an isolated environment; elsewhere the runner belongs to the environment.*/export const zRunnerSizingWritable = z.object({- isolatedCpu: z.number(),+ isolatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),memory: zRunnerMemoryWritable,})@@ -990,26 +1113,40 @@ export const zEnvironmentDeployedAppWritable = z.object({deploymentId: z.string(),workspace: zNamedRef,app: zNamedRef,- status: zEnvironmentDeployedAppStatus,+ runtimeState: zRuntimeState,currentVersion: zWorkflowVersion.optional(),deployedAt: z.iso.datetime().optional(),deployedBy: zOperator.optional(),latestAttempt: zEnvironmentDeployedAppAttempt.optional(),sizing: zRunnerSizingWritable.optional(),occupiesPool: z.boolean().optional(),+ recentInvocationCount: z.string().optional(),+ versionsBehind: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' })+ .optional(),})export const zListEnvironmentDeployedAppsResponseWritable = z.object({data: z.array(zEnvironmentDeployedAppWritable),- summary: zEnvironmentDeployedAppSummary,pagination: zPagination,})export const zUpdateEnvironmentDeployedAppResourcesResponseWritable = z.object({deploymentId: z.string(),- isolatedCpu: z.number(),- allocatedCpuCount: z.number(),- poolCpuCount: z.number(),+ isolatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+ allocatedCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),+ poolCpuMillicores: z+ .int()+ .min(-2147483648, { error: 'Invalid value: Expected int32 to be >= -2147483648' })+ .max(2147483647, { error: 'Invalid value: Expected int32 to be <= 2147483647' }),memory: zRunnerMemoryWritable,})diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsxindex c56c8ac546c..e37f124dd9a 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx@@ -166,7 +166,9 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {(routeAppDetail.mode === AppModeEnum.AGENT || !appACLCapabilities.canAccessConfig)) ||(isAccessPointPath && !appACLCapabilities.canViewAccessPoint) ||(isDeployPath &&- (routeAppDetail.mode !== AppModeEnum.WORKFLOW || !appACLCapabilities.canDeploy))+ ((routeAppDetail.mode !== AppModeEnum.WORKFLOW &&+ routeAppDetail.mode !== AppModeEnum.ADVANCED_CHAT) ||+ !appACLCapabilities.canDeploy))) {router.replace(getRedirectionPath(routeAppDetail, {diff --git a/web/app/(shareLayout)/components/__tests__/splash.spec.tsx b/web/app/(shareLayout)/components/__tests__/splash.spec.tsxindex 1287b47fa79..c9b5582b030 100644--- a/web/app/(shareLayout)/components/__tests__/splash.spec.tsx+++ b/web/app/(shareLayout)/components/__tests__/splash.spec.tsx@@ -46,6 +46,8 @@ describe('Splash', () => {beforeEach(() => {vi.clearAllMocks()webAppState.shareCode = 'share-app'+ webAppState.webAppAccessMode = 'public'+ webAppState.embeddedUserId = 'embedded-user'navigationMocks.pathname = '/chatbot/share-app'window.history.replaceState({}, '', navigationMocks.pathname)navigationMocks.searchParams = new URLSearchParams({@@ -140,6 +142,74 @@ describe('Splash', () => {expect(await screen.findByText('share.common.appUnavailable')).toBeInTheDocument()})+ it('should redirect an unauthenticated sso verified environment to the sign-in page', async () => {+ navigationMocks.searchParams = new URLSearchParams()+ navigationMocks.pathname = '/environment/chat/environment-app'+ window.history.replaceState({}, '', navigationMocks.pathname)+ webAppState.shareCode = 'environment-app'+ webAppState.webAppAccessMode = 'sso_verified'++ render(+ <Splash>+ <div>share application</div>+ </Splash>,+ )++ await waitFor(() => {+ expect(navigationMocks.replace).toHaveBeenCalledWith(+ '/webapp-signin?redirect_url=%2Fenvironment%2Fchat%2Fenvironment-app',+ )+ })+ expect(fetchAccessTokenMock).not.toHaveBeenCalled()+ expect(screen.queryByText('share application')).not.toBeInTheDocument()+ })++ it('should redirect an sso verified environment when its passport cannot be issued', async () => {+ navigationMocks.searchParams = new URLSearchParams({+ query: 'keep-me',+ web_sso_token: 'expired-token',+ })+ navigationMocks.pathname = '/environment/chat/environment-app'+ window.history.replaceState({}, '', navigationMocks.pathname)+ webAppState.shareCode = 'environment-app'+ webAppState.webAppAccessMode = 'sso_verified'+ webAppAuthMocks.webAppLoginStatus.mockResolvedValue({+ userLoggedIn: true,+ appLoggedIn: false,+ })+ fetchAccessTokenMock.mockRejectedValue(new Response(null, { status: 401 }))++ render(+ <Splash>+ <div>share application</div>+ </Splash>,+ )++ await waitFor(() => {+ expect(navigationMocks.replace).toHaveBeenCalledWith(+ '/webapp-signin?redirect_url=%2Fenvironment%2Fchat%2Fenvironment-app%3Fquery%3Dkeep-me',+ )+ })+ expect(webAppAuthMocks.webAppLogout).toHaveBeenCalledWith({+ kind: 'environment',+ code: 'environment-app',+ })+ expect(screen.queryByText('share application')).not.toBeInTheDocument()+ })++ it('should keep the existing authentication surface for an ordinary Web App', async () => {+ navigationMocks.searchParams = new URLSearchParams()++ render(+ <Splash>+ <div>share application</div>+ </Splash>,+ )++ expect(await screen.findByText('share application')).toBeInTheDocument()+ expect(navigationMocks.replace).not.toHaveBeenCalled()+ })+it('should expose the unavailable-state action as a button', () => {navigationMocks.searchParams = new URLSearchParams({code: '404',diff --git a/web/app/(shareLayout)/components/splash.tsx b/web/app/(shareLayout)/components/splash.tsxindex 9558c6acaa4..eaede783da1 100644--- a/web/app/(shareLayout)/components/splash.tsx+++ b/web/app/(shareLayout)/components/splash.tsx@@ -4,11 +4,13 @@ import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import {isWebAppSigninPath,+ navigateAfterWebAppLogin,resolveWebAppLoginRedirect,} from '@/app/(shareLayout)/webapp-signin/login-redirect'import AppUnavailable from '@/app/components/base/app-unavailable'import Loading from '@/app/components/base/loading'import { useWebAppStore } from '@/context/web-app-context'+import { AccessMode } from '@/models/access-control'import { usePathname, useRouter, useSearchParams } from '@/next/navigation'import { fetchAccessToken } from '@/service/share'import { resolveWebAppAddress } from '@/service/webapp-address'@@ -76,11 +78,25 @@ function Splash({ children }: PropsWithChildren) {if (tokenFromUrl) setWebAppAccessToken(tokenFromUrl)const redirectOrFinish = () => {- if (loginRedirect) replaceLoginRedirect(loginRedirect.target, router.replace, basePath)+ if (loginRedirect) navigateAfterWebAppLogin(loginRedirect, router.replace, basePath)else setIsLoading(false)}- const proceedToAuth = () => {+ const proceedToAuth = (authenticationRequired: boolean) => {+ if (+ authenticationRequired &&+ address.kind === 'environment' &&+ webAppAccessMode !== AccessMode.PUBLIC &&+ !isSigninRoute+ ) {+ const redirectSearchParams = new URLSearchParams(searchParams)+ redirectSearchParams.delete('web_sso_token')+ const redirectSearch = redirectSearchParams.toString()+ const redirectTarget = redirectSearch ? `${pathname}?${redirectSearch}` : pathname+ const signinSearchParams = new URLSearchParams({ redirect_url: redirectTarget })+ router.replace(`/webapp-signin?${signinSearchParams.toString()}`)+ return+ }setIsLoading(false)}@@ -88,13 +104,12 @@ function Splash({ children }: PropsWithChildren) {// if access mode is public, user login is always true, but the app login(passport) may be expiredconst { userLoggedIn, appLoggedIn } = await webAppLoginStatus(effectiveShareCode,- webAppAccessMode,embeddedUserId || undefined,)if (userLoggedIn && appLoggedIn) {redirectOrFinish()} else if (!userLoggedIn && !appLoggedIn) {- proceedToAuth()+ proceedToAuth(true)} else if (!userLoggedIn && appLoggedIn) {redirectOrFinish()} else if (userLoggedIn && !appLoggedIn) {@@ -112,7 +127,7 @@ function Splash({ children }: PropsWithChildren) {return}await webAppLogout(address)- proceedToAuth()+ proceedToAuth(error instanceof Response && error.status === 401)}}})()diff --git a/web/app/(shareLayout)/environment/chat/[token]/page.tsx b/web/app/(shareLayout)/environment/chat/[token]/page.tsxnew file mode 100644index 00000000000..fc55ec54af5--- /dev/null+++ b/web/app/(shareLayout)/environment/chat/[token]/page.tsx@@ -0,0 +1,14 @@+'use client'+import * as React from 'react'+import ChatWithHistoryWrap from '@/app/components/base/chat/chat-with-history'+import AuthenticatedLayout from '../../../components/authenticated-layout'++const EnvironmentChat = () => {+ return (+ <AuthenticatedLayout>+ <ChatWithHistoryWrap />+ </AuthenticatedLayout>+ )+}++export default React.memo(EnvironmentChat)diff --git a/web/app/(shareLayout)/env/workflow/[token]/page.tsx b/web/app/(shareLayout)/environment/workflow/[token]/page.tsxsimilarity index 100%rename from web/app/(shareLayout)/env/workflow/[token]/page.tsxrename to web/app/(shareLayout)/environment/workflow/[token]/page.tsxdiff --git a/web/app/(shareLayout)/webapp-signin/__tests__/login-redirect.spec.ts b/web/app/(shareLayout)/webapp-signin/__tests__/login-redirect.spec.tsindex 94e0872c01e..ada96f415d9 100644--- a/web/app/(shareLayout)/webapp-signin/__tests__/login-redirect.spec.ts+++ b/web/app/(shareLayout)/webapp-signin/__tests__/login-redirect.spec.ts@@ -1,4 +1,4 @@-import { resolveWebAppLoginRedirect } from '../login-redirect'+import { navigateAfterWebAppLogin, resolveWebAppLoginRedirect } from '../login-redirect'describe('resolveWebAppLoginRedirect', () => {// Covers the canonical relative redirect shape used by share applications.@@ -27,14 +27,14 @@ describe('resolveWebAppLoginRedirect', () => {it('should resolve an environment workflow redirect', () => {const result = resolveWebAppLoginRedirect(- '/env/workflow/workflow-app',+ '/environment/workflow/workflow-app','https://self-hosted.example.com',)expect(result).toEqual({appCode: 'workflow-app',address: { kind: 'environment', code: 'workflow-app' },- target: { kind: 'internal', href: '/env/workflow/workflow-app' },+ target: { kind: 'internal', href: '/environment/workflow/workflow-app' },})})})@@ -84,3 +84,68 @@ describe('resolveWebAppLoginRedirect', () => {})})})++describe('navigateAfterWebAppLogin', () => {+ const routerReplace = vi.fn()+ const locationReplace = vi.fn()++ beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('location', {+ ...window.location,+ replace: locationReplace,+ } as unknown as Location)+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it('reloads the document after an environment login', () => {+ navigateAfterWebAppLogin(+ {+ appCode: 'environment-app',+ address: { kind: 'environment', code: 'environment-app' },+ target: { kind: 'internal', href: '/environment/chat/environment-app' },+ },+ routerReplace,+ '',+ )++ expect(locationReplace).toHaveBeenCalledWith('/environment/chat/environment-app')+ expect(routerReplace).not.toHaveBeenCalled()+ })++ it.each([+ ['/environment/chat/environment-app', '/console/environment/chat/environment-app'],+ ['/console/environment/chat/environment-app', '/console/environment/chat/environment-app'],+ ])('keeps the deployment base path when reloading %s', (href, expected) => {+ navigateAfterWebAppLogin(+ {+ appCode: 'environment-app',+ address: { kind: 'environment', code: 'environment-app' },+ target: { kind: 'internal', href },+ },+ routerReplace,+ '/console',+ )++ expect(locationReplace).toHaveBeenCalledWith(expected)+ expect(routerReplace).not.toHaveBeenCalled()+ })++ it('keeps client navigation for an ordinary Web App login', () => {+ navigateAfterWebAppLogin(+ {+ appCode: 'share-app',+ address: { kind: 'default', code: 'share-app' },+ target: { kind: 'internal', href: '/chatbot/share-app' },+ },+ routerReplace,+ '',+ )++ expect(routerReplace).toHaveBeenCalledWith('/chatbot/share-app')+ expect(locationReplace).not.toHaveBeenCalled()+ })+})diff --git a/web/app/(shareLayout)/webapp-signin/__tests__/page.spec.tsx b/web/app/(shareLayout)/webapp-signin/__tests__/page.spec.tsxindex 2459bf07329..89fc70c051a 100644--- a/web/app/(shareLayout)/webapp-signin/__tests__/page.spec.tsx+++ b/web/app/(shareLayout)/webapp-signin/__tests__/page.spec.tsx@@ -84,7 +84,7 @@ describe('WebSSOForm environment access modes', () => {beforeEach(() => {vi.clearAllMocks()navigationMocks.searchParams = new URLSearchParams({- redirect_url: '/env/workflow/workflow-app',+ redirect_url: '/environment/workflow/workflow-app',})})@@ -105,7 +105,7 @@ describe('WebSSOForm environment access modes', () => {await waitFor(() => {expect(serviceMocks.fetchWebSAMLSSOUrl).toHaveBeenCalledWith('workflow-app',- '/env/workflow/workflow-app',+ '/environment/workflow/workflow-app',)})expect(navigationMocks.push).toHaveBeenCalledWith('https://idp.example/authorize')diff --git a/web/app/(shareLayout)/webapp-signin/check-code/page.tsx b/web/app/(shareLayout)/webapp-signin/check-code/page.tsxindex 6a408735326..a17c95678af 100644--- a/web/app/(shareLayout)/webapp-signin/check-code/page.tsx+++ b/web/app/(shareLayout)/webapp-signin/check-code/page.tsx@@ -3,10 +3,12 @@ import type { FormEvent } from 'react'import { Button } from '@langgenius/dify-ui/button'import { Input } from '@langgenius/dify-ui/input'import { toast } from '@langgenius/dify-ui/toast'-import { RiArrowLeftLine, RiMailSendFill } from '@remixicon/react'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { resolveWebAppLoginRedirect } from '@/app/(shareLayout)/webapp-signin/login-redirect'+import {+ navigateAfterWebAppLogin,+ resolveWebAppLoginRedirect,+} from '@/app/(shareLayout)/webapp-signin/login-redirect'import Countdown from '@/app/components/signin/countdown'import { useLocale } from '@/context/i18n'import { useWebAppStore } from '@/context/web-app-context'@@ -67,7 +69,7 @@ export default function CheckCode() {userId: embeddedUserId || undefined,})setWebAppPassport(loginRedirect.address, access_token)- replaceLoginRedirect(loginRedirect.target, router.replace, basePath)+ navigateAfterWebAppLogin(loginRedirect, router.replace, basePath)}} catch (error) {console.error(error)@@ -107,7 +109,10 @@ export default function CheckCode() {return (<div className="flex w-100 flex-col gap-3"><div className="inline-flex size-14 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge shadow-lg">- <RiMailSendFill className="size-6 text-2xl text-text-accent-light-mode-only" />+ <span+ aria-hidden+ className="i-ri-mail-send-fill size-6 text-2xl text-text-accent-light-mode-only"+ /></div><div className="pt-2 pb-4"><h1 className="title-4xl-semi-bold text-text-primary">@@ -160,7 +165,7 @@ export default function CheckCode() {className="flex h-9 cursor-pointer appearance-none items-center justify-center text-text-tertiary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"><span className="bg-background-default-dimm inline-block rounded-full p-1">- <RiArrowLeftLine aria-hidden size={12} />+ <span aria-hidden className="i-ri-arrow-left-line block size-3" /></span><span className="ml-2 system-xs-regular">{t(($) => $.back, { ns: 'login' })}</span></button>diff --git a/web/app/(shareLayout)/webapp-signin/components/mail-and-password-auth.tsx b/web/app/(shareLayout)/webapp-signin/components/mail-and-password-auth.tsxindex 0c741a89a12..2fc180f80bb 100644--- a/web/app/(shareLayout)/webapp-signin/components/mail-and-password-auth.tsx+++ b/web/app/(shareLayout)/webapp-signin/components/mail-and-password-auth.tsx@@ -8,7 +8,10 @@ import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-uimport { toast } from '@langgenius/dify-ui/toast'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import { resolveWebAppLoginRedirect } from '@/app/(shareLayout)/webapp-signin/login-redirect'+import {+ navigateAfterWebAppLogin,+ resolveWebAppLoginRedirect,+} from '@/app/(shareLayout)/webapp-signin/login-redirect'import { emailRegex } from '@/config'import { useWebAppStore } from '@/context/web-app-context'import Link from '@/next/link'@@ -84,7 +87,7 @@ export default function MailAndPasswordAuth({ isEmailSetup }: MailAndPasswordAutuserId: embeddedUserId || undefined,})setWebAppPassport(loginRedirect.address, access_token)- replaceLoginRedirect(loginRedirect.target, router.replace, basePath)+ navigateAfterWebAppLogin(loginRedirect, router.replace, basePath)} else {toast.error(res.data)}diff --git a/web/app/(shareLayout)/webapp-signin/login-redirect.ts b/web/app/(shareLayout)/webapp-signin/login-redirect.tsindex 216e61f338c..26a29d0d1f5 100644--- a/web/app/(shareLayout)/webapp-signin/login-redirect.ts+++ b/web/app/(shareLayout)/webapp-signin/login-redirect.ts@@ -2,6 +2,7 @@ import type { WebAppAddress } from '@/service/webapp-address'import type { LoginRedirectTarget } from '@/utils/login-redirect'import { parseWebAppAddress } from '@/service/webapp-address'import { resolveLoginRedirectTarget } from '@/utils/login-redirect'+import { replaceLoginRedirect } from '@/utils/login-redirect.client'const INTERNAL_PATH_PARSE_BASE = 'https://login-redirect.invalid'@@ -11,6 +12,34 @@ export type WebAppLoginRedirect = {target: LoginRedirectTarget}+function addBasePathOnce(href: string, basePath: string) {+ const normalizedBasePath = basePath === '/' ? '' : basePath.replace(/\/+$/, '')+ if (!normalizedBasePath) return href++ const url = new URL(href, INTERNAL_PATH_PARSE_BASE)+ if (url.pathname === normalizedBasePath || url.pathname.startsWith(`${normalizedBasePath}/`))+ return href++ return `${normalizedBasePath}${url.pathname}${url.search}${url.hash}`+}++export function navigateAfterWebAppLogin(+ loginRedirect: WebAppLoginRedirect,+ routerReplace: (href: string) => void,+ basePath: string,+) {+ if (loginRedirect.address.kind === 'environment') {+ const href =+ loginRedirect.target.kind === 'internal'+ ? addBasePathOnce(loginRedirect.target.href, basePath)+ : loginRedirect.target.href+ globalThis.location.replace(href)+ return+ }++ replaceLoginRedirect(loginRedirect.target, routerReplace, basePath)+}+export function isWebAppSigninPath(pathname: string): boolean {let candidate = pathnamediff --git a/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx b/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsxindex ae31b4c5ed2..27546c4eb51 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@@ -210,20 +210,23 @@ describe('AppDetailSection', () => {).not.toBeInTheDocument()})- it('should render deploy navigation with app deploy ACL regardless of the legacy workspace role', () => {- // Arrange- mockAppMode = 'workflow'- mockAppPermissionKeys = [AppACLPermission.Deploy]+ it.each(['workflow', 'advanced-chat'])(+ 'should render deploy navigation for a %s app with app deploy ACL regardless of the legacy workspace role',+ (mode) => {+ // Arrange+ mockAppMode = mode+ mockAppPermissionKeys = [AppACLPermission.Deploy]- // Act- render(<AppDetailSection />)+ // Act+ render(<AppDetailSection />)- // Assert- expect(screen.getByRole('link', { name: 'common.appMenus.deploy' })).toHaveAttribute(- 'href',- '/app/app-1/deploy',- )- })+ // Assert+ expect(screen.getByRole('link', { name: 'common.appMenus.deploy' })).toHaveAttribute(+ 'href',+ '/app/app-1/deploy',+ )+ },+ )it.each([{diff --git a/web/app/components/app-sidebar/app-detail-section.tsx b/web/app/components/app-sidebar/app-detail-section.tsxindex 3b2035b23a3..3cd1d813912 100644--- a/web/app/components/app-sidebar/app-detail-section.tsx+++ b/web/app/components/app-sidebar/app-detail-section.tsx@@ -98,7 +98,6 @@ const AppDetailSection = ({ expand = true }: AppDetailSectionProps) => {const appId = appDetail.idconst isWorkflowApp =appDetail.mode === AppModeEnum.WORKFLOW || appDetail.mode === AppModeEnum.ADVANCED_CHAT- const supportsAppDeploy = appDetail.mode === AppModeEnum.WORKFLOWconst supportsAnnotations =appDetail.mode !== AppModeEnum.WORKFLOW && appDetail.mode !== AppModeEnum.COMPLETIONconst supportsResourceAccess = appDetail.mode !== AppModeEnum.AGENT@@ -130,7 +129,7 @@ const AppDetailSection = ({ expand = true }: AppDetailSectionProps) => {},]: []),- ...(supportsAppDeploy && appACLCapabilities.canDeploy+ ...(isWorkflowApp && appACLCapabilities.canDeploy? [{name: t(($) => $['appMenus.deploy'], { ns: 'common' }),diff --git a/web/app/components/app/access-point/__tests__/access-point-card.spec.tsx b/web/app/components/app/access-point/__tests__/access-point-card.spec.tsxindex 38d88d3a5af..1d08a65fbb0 100644--- a/web/app/components/app/access-point/__tests__/access-point-card.spec.tsx+++ b/web/app/components/app/access-point/__tests__/access-point-card.spec.tsx@@ -1,7 +1,8 @@-import type { AccessPointStatus } from '../shared/access-point-status'+import type { AccessPointStatus } from '@/app/components/base/access-point/status'import { screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { AccessPointCard } from '@/app/components/base/access-point/card'import { render } from '@/test/console/render'-import { AccessPointCard } from '../shared/access-point-card'describe('AccessPointCard', () => {it('marks the card when it is the highlighted access point', () => {@@ -11,6 +12,7 @@ describe('AccessPointCard', () => {description="Web application access"icon="i-ri-robot-2-line"status="inService"+ statusLabel="In service"highlighted>Access URL@@ -39,6 +41,7 @@ describe('AccessPointCard', () => {description="Web application access"icon="i-ri-robot-2-line"status={status}+ statusLabel={label}onEnabledChange={vi.fn()}>Access URL@@ -51,4 +54,34 @@ describe('AccessPointCard', () => {else expect(card).not.toHaveAttribute('aria-busy')expect(screen.queryByRole('switch')).not.toBeInTheDocument()})++ it('keeps an unavailable switch focusable and explains why it is disabled', async () => {+ const user = userEvent.setup()+ const onEnabledChange = vi.fn()+ render(+ <AccessPointCard+ title="Web App"+ description="Web application access"+ icon="i-ri-robot-2-line"+ status="disabled"+ statusLabel="Disabled"+ switchDisabled+ switchDisabledReason="Publish first"+ switchLabel="Toggle Web App"+ onEnabledChange={onEnabledChange}+ >+ Access URL+ </AccessPointCard>,+ )++ const accessSwitch = screen.getByRole('switch', { name: 'Toggle Web App' })+ expect(accessSwitch).toHaveAttribute('aria-disabled', 'true')++ await user.tab()+ expect(accessSwitch).toHaveFocus()+ expect(await screen.findByRole('tooltip')).toHaveTextContent('Publish first')++ await user.click(accessSwitch)+ expect(onEnabledChange).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/app/access-point/__tests__/access-point-url.spec.tsx b/web/app/components/app/access-point/__tests__/access-point-url.spec.tsxindex 56461a8aa52..af58acf2416 100644--- a/web/app/components/app/access-point/__tests__/access-point-url.spec.tsx+++ b/web/app/components/app/access-point/__tests__/access-point-url.spec.tsx@@ -1,6 +1,7 @@import { screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { AccessPointUrl } from '@/app/components/base/access-point/url'import { render } from '@/test/console/render'-import { AccessPointUrl } from '../shared/access-point-url'const endpointProps = {label: 'Access URL',@@ -34,6 +35,22 @@ describe('AccessPointUrl', () => {expect(openLink).toHaveAttribute('rel', 'noopener noreferrer')})+ it('explains why the open action is disabled', async () => {+ const user = userEvent.setup()+ render(+ <AccessPointUrl+ {...endpointProps}+ enabled={false}+ showOpen+ openLabel="Open"+ openDisabledReason="Publish first"+ />,+ )++ await user.hover(screen.getByRole('button', { name: 'Open' }))+ expect(await screen.findByRole('tooltip')).toHaveTextContent('Publish first')+ })+it('shows an unavailable endpoint without replacing it with a loading skeleton', () => {render(<AccessPointUrl {...endpointProps} enabled={false} unavailable />)diff --git a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsxindex f4bc42f1d7f..c4ba3dd2d24 100644--- a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx+++ b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx@@ -57,7 +57,6 @@ vi.mock('@/service/use-workflow', () => ({vi.mock('../shared/use-access-point-actions', () => ({useAccessPointActions: () => ({- handleAppStateChanged: vi.fn(),handleResult: vi.fn(),refreshAppDetail: vi.fn(),saveSiteConfig: vi.fn(),diff --git a/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsx b/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsxindex d203cb47af7..663731e5e60 100644--- a/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsx+++ b/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsx@@ -1,4 +1,4 @@-import type { AccessPoint } from '@/app/components/app/deploy/access-point'+import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'import { screen, within } from '@testing-library/react'import { render } from '@/test/console/render'import { DeployedEnvironmentAccessPoints } from '../deployed-environment-access-points'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.tsxindex 9f35888e191..8a9f11c2444 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@@ -1,6 +1,7 @@import type { ReactElement } from 'react'+import { toast } from '@langgenius/dify-ui/toast'import { QueryClientProvider } from '@tanstack/react-query'-import { screen, waitFor } from '@testing-library/react'+import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { render } from '@/test/console/render'import { createTestQueryClient } from '@/test/query-client'@@ -84,6 +85,8 @@ vi.mock('@/features/system-features/client', () => ({}),}))+let mockAppMode = 'workflow'+vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.example.test/en${path}`,}))@@ -93,11 +96,13 @@ vi.mock('@/app/components/app/store', () => ({selector({appDetail: {id: 'app-1',+ get mode() {+ return mockAppMode+ },icon: '🤖',icon_background: '#FFEAD5',icon_type: 'emoji',icon_url: null,- mode: 'workflow',site: {access_token: 'built-in-code',app_base_url: 'https://built-in.example.test',@@ -195,6 +200,17 @@ function renderCard(ui: ReactElement) {return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)}+function createDeferredPromise<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((promiseResolve, promiseReject) => {+ resolve = promiseResolve+ reject = promiseReject+ })++ return { promise, reject, resolve }+}+describe('environment access point cards', () => {beforeEach(() => {vi.clearAllMocks()@@ -227,6 +243,25 @@ describe('environment access point cards', () => {})})+ it('sends a chatflow app to the chat web app shell', async () => {+ mockAppMode = 'advanced-chat'++ renderCard(+ <EnvironmentWebAppCard+ appId="app-1"+ environmentId="staging"+ canManageAccessPoint+ canReleaseAndVersion+ />,+ )++ 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 () => {renderCard(<EnvironmentWebAppCard@@ -237,8 +272,8 @@ describe('environment access point cards', () => {/>,)- expect(await screen.findByText(/env\/workflow\/site-code/)).toHaveTextContent(- 'https://site.example.test/env/workflow/site-code',+ expect(await screen.findByText(/environment\/workflow\/site-code/)).toHaveTextContent(+ 'https://site.example.test/environment/workflow/site-code',)expect(await screen.findByRole('button', {@@ -292,6 +327,23 @@ describe('environment access point cards', () => {).not.toBeInTheDocument()})+ it('does not announce the access control placeholder as loading after the Site query fails', async () => {+ mocks.getSite.mockRejectedValueOnce(new Error('Site unavailable'))++ renderCard(+ <EnvironmentWebAppCard+ appId="app-1"+ environmentId="staging"+ canManageAccessPoint+ canReleaseAndVersion+ />,+ )++ const card = screen.getByRole('region', { name: /webApp\.title/ })+ await screen.findAllByText('deployments.health.ENVIRONMENT_STATUS_FAILED')+ expect(within(card).queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()+ })+it('uses environment Site mutations for status and URL reset, and opens its access container', async () => {const user = userEvent.setup()renderCard(@@ -339,6 +391,49 @@ describe('environment access point cards', () => {})})+ it('optimistically serializes environment Web app changes without a success toast', async () => {+ const user = userEvent.setup()+ const firstToggle = createDeferredPromise<typeof site>()+ const secondToggle = createDeferredPromise<typeof site>()+ mocks.updateSite+ .mockReturnValueOnce(firstToggle.promise)+ .mockReturnValueOnce(secondToggle.promise)+ renderCard(+ <EnvironmentWebAppCard+ appId="app-1"+ environmentId="staging"+ canManageAccessPoint+ canReleaseAndVersion+ />,+ )++ const accessSwitch = await screen.findByRole('switch')+ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'false')+ expect(mocks.updateSite).toHaveBeenCalledTimes(1)++ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ expect(mocks.updateSite).toHaveBeenCalledTimes(1)++ firstToggle.resolve({ ...site, enabled: false })++ await waitFor(() => {+ expect(mocks.updateSite).toHaveBeenCalledTimes(2)+ })+ expect(mocks.updateSite.mock.calls[1]?.[0]).toEqual({+ body: { enabled: true },+ params: environmentParams,+ })++ secondToggle.resolve({ ...site, enabled: true })++ await screen.findByRole('link', { name: /studio\.accessPoint\.open/ })+ expect(toast.success).not.toHaveBeenCalled()+ })+it('opens Customize and Settings with environment endpoint data', async () => {const user = userEvent.setup()renderCard(@@ -350,7 +445,7 @@ describe('environment access point cards', () => {/>,)- await screen.findByText(/env\/workflow\/site-code/)+ await screen.findByText(/environment\/workflow\/site-code/)await user.click(screen.getByRole('button', { name: /customize\.entry/ }))expect(screen.getByRole('dialog', { name: 'environment customize' })).toHaveTextContent('https://api.example.test/v1',@@ -452,6 +547,29 @@ describe('environment access point cards', () => {})})+ it('rolls back a failed environment Service API change and shows only an error toast', async () => {+ const user = userEvent.setup()+ const toggle = createDeferredPromise<typeof api>()+ mocks.updateApi.mockReturnValueOnce(toggle.promise)+ renderCard(+ <EnvironmentServiceApiCard appId="app-1" environmentId="staging" canManageAccessPoint />,+ )++ await screen.findByText(api.base_url)+ const accessSwitch = screen.getByRole('switch')+ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'false')++ toggle.reject(new Error('request failed'))++ await waitFor(() => {+ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ })+ expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')+ expect(toast.success).not.toHaveBeenCalled()+ })+it('keeps environment API keys and external documentation available when the API is stopped', async () => {mocks.getApi.mockResolvedValue({...api,diff --git a/web/app/components/app/access-point/__tests__/index.spec.tsx b/web/app/components/app/access-point/__tests__/index.spec.tsxindex 4cfdb2c5637..493216c0316 100644--- a/web/app/components/app/access-point/__tests__/index.spec.tsx+++ b/web/app/components/app/access-point/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import type { AppEnvironment } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { ReactNode } from 'react'-import type { AccessPoint as AccessPointType } from '@/app/components/app/deploy/access-point'+import type { AccessPoint as AccessPointType } from '@/app/components/app/deploy/utils/access-point'import { EnvironmentStatus } from '@dify/contracts/enterprise-app-deploy/types.gen'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'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.tsxindex e4704b39979..1f96c4a5429 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@@ -1,8 +1,11 @@import type { AccessPointAppInfo, PublishedWorkflow } from '../shared/utils'-import { screen } from '@testing-library/react'+import { toast } from '@langgenius/dify-ui/toast'+import { QueryClientProvider } from '@tanstack/react-query'+import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { BlockEnum } from '@/app/components/workflow/types'import { render } from '@/test/console/render'+import { createTestQueryClient } from '@/test/query-client'import { AppModeEnum } from '@/types/app'import { MCPAccessPointCard } from '../built-in-access-points/mcp-card'@@ -17,6 +20,30 @@ const mocks = vi.hoisted(() => ({updateServer: vi.fn(),}))+vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ error: vi.fn(),+ success: vi.fn(),+ },+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ apps: {+ byAppId: {+ server: {+ put: {+ mutationOptions: (options = {}) => ({+ mutationFn: mocks.updateServer,+ ...options,+ }),+ },+ },+ },+ },+ },+}))+vi.mock('@/service/use-tools', () => ({useInvalidateMCPServerDetail: () => mocks.invalidateServerDetail,useMCPServerDetail: () => mocks.serverDetail,@@ -24,10 +51,6 @@ vi.mock('@/service/use-tools', () => ({isPending: false,mutateAsync: mocks.refreshServerCode,}),- useUpdateMCPServer: () => ({- isPending: false,- mutateAsync: mocks.updateServer,- }),}))vi.mock('@/app/components/tools/mcp/mcp-server-modal', () => ({@@ -74,11 +97,39 @@ const publishedWorkflow = {},} as unknown as PublishedWorkflow+function createDeferredPromise<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((promiseResolve, promiseReject) => {+ resolve = promiseResolve+ reject = promiseReject+ })++ return { promise, reject, resolve }+}++function renderCard(cardAppInfo: AccessPointAppInfo = appInfo, workflow?: PublishedWorkflow) {+ const queryClient = createTestQueryClient()++ return render(+ <QueryClientProvider client={queryClient}>+ <MCPAccessPointCard+ appInfo={cardAppInfo}+ canManageAccessPoint+ triggerModeDisabled={false}+ workflow={workflow}+ workflowLoading={false}+ />+ </QueryClientProvider>,+ )+}+describe('MCPAccessPointCard', () => {beforeEach(() => {vi.clearAllMocks()mocks.serverDetail.data = undefinedmocks.serverDetail.isPending = false+ mocks.updateServer.mockResolvedValue(undefined)})afterEach(() => {@@ -91,15 +142,7 @@ describe('MCPAccessPointCard', () => {.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}', { status: 200 }))- render(- <MCPAccessPointCard- appInfo={appInfo}- canManageAccessPoint- triggerModeDisabled={false}- workflow={undefined}- workflowLoading={false}- />,- )+ renderCard()await user.click(screen.getByRole('button', { name: /addDescription/ }))@@ -122,15 +165,7 @@ describe('MCPAccessPointCard', () => {it('uses workflow inputs when the app model config is null', async () => {const user = userEvent.setup()- render(- <MCPAccessPointCard- appInfo={workflowAppInfo}- canManageAccessPoint- triggerModeDisabled={false}- workflow={publishedWorkflow}- workflowLoading={false}- />,- )+ renderCard(workflowAppInfo, publishedWorkflow)await user.click(screen.getByRole('button', { name: /addDescription/ }))@@ -144,15 +179,7 @@ describe('MCPAccessPointCard', () => {it('shows loading without reporting an environment failure', () => {mocks.serverDetail.isPending = true- render(- <MCPAccessPointCard- appInfo={workflowAppInfo}- canManageAccessPoint- triggerModeDisabled={false}- workflow={publishedWorkflow}- workflowLoading={false}- />,- )+ renderCard(workflowAppInfo, publishedWorkflow)const card = screen.getByRole('region', { name: /mcp\.server\.title/ })expect(card).toHaveAttribute('aria-busy', 'true')@@ -161,4 +188,68 @@ describe('MCPAccessPointCard', () => {screen.queryByText('deployments.health.ENVIRONMENT_STATUS_FAILED'),).not.toBeInTheDocument()})++ it('rolls back a failed status change and shows only an error toast', async () => {+ const user = userEvent.setup()+ const toggle = createDeferredPromise<void>()+ mocks.serverDetail.data = {+ id: 'server-1',+ server_code: 'server-code',+ status: 'active',+ }+ mocks.updateServer.mockReturnValueOnce(toggle.promise)+ renderCard()++ const accessSwitch = screen.getByRole('switch')+ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'false')++ toggle.reject(new Error('request failed'))++ await waitFor(() => {+ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ })+ expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')+ expect(toast.success).not.toHaveBeenCalled()+ })++ it('optimistically serializes rapid status changes without a busy switch', async () => {+ const user = userEvent.setup()+ const firstToggle = createDeferredPromise<void>()+ const secondToggle = createDeferredPromise<void>()+ mocks.serverDetail.data = {+ id: 'server-1',+ server_code: 'server-code',+ status: 'active',+ }+ mocks.updateServer+ .mockReturnValueOnce(firstToggle.promise)+ .mockReturnValueOnce(secondToggle.promise)+ renderCard()++ const accessSwitch = screen.getByRole('switch')+ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'false')+ expect(accessSwitch).toBeEnabled()++ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ expect(mocks.updateServer).toHaveBeenCalledTimes(1)++ firstToggle.resolve()++ await waitFor(() => {+ expect(mocks.updateServer).toHaveBeenCalledTimes(2)+ })++ secondToggle.resolve()++ await waitFor(() => {+ expect(mocks.invalidateServerDetail).toHaveBeenCalledTimes(2)+ })+ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ })})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.tsxindex 4fc9bf3913e..3fac29c2f3d 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@@ -1,8 +1,9 @@-import type { ReactElement } from 'react'import type { AccessPointAppInfo } from '../shared/utils'+import { toast } from '@langgenius/dify-ui/toast'+import { QueryClientProvider } from '@tanstack/react-query'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { createQueryClientWrapper } from '@/test/console/query-client'+import { useStore as useAppStore } from '@/app/components/app/store'import { render } from '@/test/console/render'import { createTestQueryClient } from '@/test/query-client'import { AppModeEnum } from '@/types/app'@@ -10,13 +11,13 @@ import { ServiceApiAccessPointCard } from '../built-in-access-points/service-apiconst mocks = vi.hoisted(() => ({apiSecretKeyButtonProps: vi.fn(),- toastError: vi.fn(),- updateApiStatus: vi.fn().mockResolvedValue({}),+ apiEnable: vi.fn(),}))vi.mock('@langgenius/dify-ui/toast', () => ({toast: {- error: mocks.toastError,+ error: vi.fn(),+ success: vi.fn(),},}))@@ -27,7 +28,7 @@ vi.mock('@/service/client', () => ({apiEnable: {post: {mutationOptions: (options = {}) => ({- mutationFn: mocks.updateApiStatus,+ mutationFn: mocks.apiEnable,...options,}),},@@ -65,13 +66,58 @@ function createAppInfo(} as AccessPointAppInfo}-function renderWithQueryClient(ui: ReactElement) {- return render(ui, { wrapper: createQueryClientWrapper(createTestQueryClient()) })+function renderCard(+ mode: AppModeEnum,+ availability: 'available' | 'loading' | 'unavailable' = 'available',+ canManage = true,+ overrides: Partial<AccessPointAppInfo> = {},+) {+ useAppStore.setState({ appDetail: createAppInfo(mode, overrides) })+ const queryClient = createTestQueryClient()++ return render(+ <QueryClientProvider client={queryClient}>+ <StoreConnectedServiceApiCard availability={availability} canManage={canManage} />+ </QueryClientProvider>,+ )+}++function StoreConnectedServiceApiCard({+ availability,+ canManage,+}: {+ availability: 'available' | 'loading' | 'unavailable'+ canManage: boolean+}) {+ const appInfo = useAppStore((state) => state.appDetail)+ if (!appInfo) return null++ return (+ <ServiceApiAccessPointCard+ appInfo={appInfo}+ availability={availability}+ canManage={canManage}+ />+ )+}++function createDeferredPromise<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((promiseResolve, promiseReject) => {+ resolve = promiseResolve+ reject = promiseReject+ })++ return { promise, reject, resolve }}describe('ServiceApiAccessPointCard', () => {beforeEach(() => {vi.clearAllMocks()+ mocks.apiEnable.mockResolvedValue({+ enable_api: true,+ })})it.each([@@ -81,14 +127,7 @@ describe('ServiceApiAccessPointCard', () => {[AppModeEnum.AGENT_CHAT, '/api-reference/guides/chat'],[AppModeEnum.COMPLETION, '/api-reference/guides/completion'],])('links %s apps to the matching external API reference', (mode, path) => {- renderWithQueryClient(- <ServiceApiAccessPointCard- appInfo={createAppInfo(mode)}- availability="available"- canManage- onAppStateChanged={vi.fn()}- />,- )+ renderCard(mode)const apiReferenceLink = screen.getByRole('link', { name: /apiInfo\.doc/ })@@ -99,36 +138,20 @@ describe('ServiceApiAccessPointCard', () => {it('updates API status through the generated contract', async () => {const user = userEvent.setup()- const onAppStateChanged = vi.fn()- renderWithQueryClient(- <ServiceApiAccessPointCard- appInfo={createAppInfo(AppModeEnum.WORKFLOW)}- availability="available"- canManage- onAppStateChanged={onAppStateChanged}- />,- )+ renderCard(AppModeEnum.WORKFLOW)await user.click(screen.getByRole('switch'))await waitFor(() => {- expect(mocks.updateApiStatus.mock.calls[0]?.[0]).toEqual({+ expect(mocks.apiEnable.mock.calls[0]?.[0]).toEqual({params: { app_id: 'app-1' },body: { enable_api: false },})- expect(onAppStateChanged).toHaveBeenCalledTimes(1)})})it('shows loading without reporting an environment failure', () => {- renderWithQueryClient(- <ServiceApiAccessPointCard- appInfo={createAppInfo(AppModeEnum.WORKFLOW)}- availability="loading"- canManage- onAppStateChanged={vi.fn()}- />,- )+ renderCard(AppModeEnum.WORKFLOW, 'loading')const card = screen.getByRole('region', { name: /serviceApi\.title/ })expect(card).toHaveAttribute('aria-busy', 'true')@@ -139,14 +162,7 @@ describe('ServiceApiAccessPointCard', () => {})it('keeps API keys and external documentation available when the API is stopped', () => {- renderWithQueryClient(- <ServiceApiAccessPointCard- appInfo={createAppInfo(AppModeEnum.WORKFLOW, { enable_api: false })}- availability="available"- canManage- onAppStateChanged={vi.fn()}- />,- )+ renderCard(AppModeEnum.WORKFLOW, 'available', true, { enable_api: false })expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeEnabled()const apiReferenceLink = screen.getByRole('link', { name: /apiInfo\.doc/ })@@ -157,30 +173,51 @@ describe('ServiceApiAccessPointCard', () => {})it('disables API management without Access Point management permission', () => {- renderWithQueryClient(- <ServiceApiAccessPointCard- appInfo={createAppInfo(AppModeEnum.WORKFLOW)}- availability="available"- canManage={false}- onAppStateChanged={vi.fn()}- />,- )+ renderCard(AppModeEnum.WORKFLOW, 'available', false)expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeDisabled()expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')})it('disables API keys and external documentation when the access point is unavailable', () => {- renderWithQueryClient(- <ServiceApiAccessPointCard- appInfo={createAppInfo(AppModeEnum.WORKFLOW)}- availability="unavailable"- canManage- onAppStateChanged={vi.fn()}- />,- )+ renderCard(AppModeEnum.WORKFLOW, 'unavailable')expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeDisabled()expect(screen.getByRole('button', { name: /apiInfo\.doc/ })).toBeDisabled()})++ it('rolls back a failed status change and shows only an error toast', async () => {+ const user = userEvent.setup()+ const toggle = createDeferredPromise<{ enable_api: boolean }>()+ mocks.apiEnable.mockReturnValueOnce(toggle.promise)+ renderCard(AppModeEnum.WORKFLOW)++ const accessSwitch = screen.getByRole('switch')+ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'false')++ toggle.reject(new Error('request failed'))++ await waitFor(() => {+ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ })+ expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')+ expect(toast.success).not.toHaveBeenCalled()+ })++ it('keeps successful status changes silent', async () => {+ const user = userEvent.setup()+ mocks.apiEnable.mockResolvedValueOnce({ enable_api: false })+ renderCard(AppModeEnum.WORKFLOW)++ const accessSwitch = screen.getByRole('switch')+ await user.click(accessSwitch)++ await waitFor(() => {+ expect(useAppStore.getState().appDetail?.enable_api).toBe(false)+ })+ expect(accessSwitch).toHaveAttribute('aria-checked', 'false')+ expect(toast.success).not.toHaveBeenCalled()+ })})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.tsxindex 32120bfe8d8..aeac874d8ba 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@@ -1,13 +1,16 @@import type { AccessPointAppInfo } from '../shared/utils'import type { AppTrigger } from '@/service/use-tools'-import { screen } from '@testing-library/react'+import { toast } from '@langgenius/dify-ui/toast'+import { QueryClientProvider } from '@tanstack/react-query'+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import { render } from '@/test/console/render'+import { createTestQueryClient } from '@/test/query-client'import { AppModeEnum } from '@/types/app'import { TriggerAccessPointCard } from '../built-in-access-points/trigger-card'const mocks = vi.hoisted(() => ({invalidateTriggers: vi.fn(),- setTriggerStatus: vi.fn(),setTriggerStatuses: vi.fn(),triggerQuery: {data: undefined as { data: AppTrigger[] } | undefined,@@ -16,24 +19,46 @@ const mocks = vi.hoisted(() => ({updateTriggerStatus: vi.fn(),}))+vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ error: vi.fn(),+ success: vi.fn(),+ },+}))+vi.mock('@/app/components/workflow/store/trigger-status', () => ({- useTriggerStatusStore: () => ({- setTriggerStatus: mocks.setTriggerStatus,- setTriggerStatuses: mocks.setTriggerStatuses,- }),+ useTriggerStatusStore: (+ selector: (state: { setTriggerStatuses: typeof mocks.setTriggerStatuses }) => unknown,+ ) =>+ selector({+ setTriggerStatuses: mocks.setTriggerStatuses,+ }),}))vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.example.test/en${path}`,}))+vi.mock('@/service/client', () => ({+ consoleQuery: {+ apps: {+ byAppId: {+ triggerEnable: {+ post: {+ mutationOptions: (options = {}) => ({+ mutationFn: mocks.updateTriggerStatus,+ ...options,+ }),+ },+ },+ },+ },+ },+}))+vi.mock('@/service/use-tools', () => ({useAppTriggers: () => mocks.triggerQuery,useInvalidateAppTriggers: () => mocks.invalidateTriggers,- useUpdateTriggerStatus: () => ({- isPending: false,- mutateAsync: mocks.updateTriggerStatus,- }),}))vi.mock('@/service/use-triggers', () => ({@@ -64,21 +89,32 @@ function createTrigger(id: string, status: AppTrigger['status']): AppTrigger {}function renderCard(availability: 'available' | 'loading' | 'unavailable') {+ const queryClient = createTestQueryClient()+render(- <TriggerAccessPointCard- appInfo={appInfo}- availability={availability}- canManageAccessPoint- onToggleResult={vi.fn()}- />,+ <QueryClientProvider client={queryClient}>+ <TriggerAccessPointCard appInfo={appInfo} availability={availability} canManageAccessPoint />+ </QueryClientProvider>,)}+function createDeferredPromise<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((promiseResolve, promiseReject) => {+ resolve = promiseResolve+ reject = promiseReject+ })++ return { promise, reject, resolve }+}+describe('TriggerAccessPointCard', () => {beforeEach(() => {vi.clearAllMocks()mocks.triggerQuery.data = undefinedmocks.triggerQuery.isLoading = false+ mocks.updateTriggerStatus.mockResolvedValue(undefined)})it('shows loading without reporting an environment failure', () => {@@ -145,4 +181,84 @@ describe('TriggerAccessPointCard', () => {screen.queryByText('deployments.studio.accessPoint.noTriggerNodes'),).not.toBeInTheDocument()})++ it('keeps successful trigger changes silent', async () => {+ const user = userEvent.setup()+ mocks.triggerQuery.data = {+ data: [createTrigger('disabled', 'disabled')],+ }+ renderCard('available')++ await user.click(screen.getByRole('switch', { name: 'Trigger disabled' }))++ await waitFor(() => {+ expect(mocks.updateTriggerStatus).toHaveBeenCalledWith(+ {+ params: {+ app_id: 'app-1',+ },+ body: {+ trigger_id: 'disabled',+ enable_trigger: true,+ },+ },+ expect.any(Object),+ )+ expect(mocks.invalidateTriggers).toHaveBeenCalledWith('app-1')+ })+ expect(toast.success).not.toHaveBeenCalled()+ })++ it('shows an error toast when a trigger change fails', async () => {+ const user = userEvent.setup()+ mocks.triggerQuery.data = {+ data: [createTrigger('enabled', 'enabled')],+ }+ mocks.updateTriggerStatus.mockRejectedValueOnce(new Error('request failed'))+ renderCard('available')++ await user.click(screen.getByRole('switch', { name: 'Trigger enabled' }))++ await waitFor(() => {+ expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')+ })+ expect(toast.success).not.toHaveBeenCalled()+ })++ it('optimistically serializes rapid changes for each trigger without disabling its switch', async () => {+ const user = userEvent.setup()+ const firstToggle = createDeferredPromise<void>()+ const secondToggle = createDeferredPromise<void>()+ mocks.triggerQuery.data = {+ data: [createTrigger('enabled', 'enabled')],+ }+ mocks.updateTriggerStatus+ .mockReturnValueOnce(firstToggle.promise)+ .mockReturnValueOnce(secondToggle.promise)+ renderCard('available')++ const triggerSwitch = screen.getByRole('switch', { name: 'Trigger enabled' })+ await user.click(triggerSwitch)++ expect(triggerSwitch).toHaveAttribute('aria-checked', 'false')+ expect(triggerSwitch).toBeEnabled()++ await user.click(triggerSwitch)++ expect(triggerSwitch).toHaveAttribute('aria-checked', 'true')+ expect(mocks.updateTriggerStatus).toHaveBeenCalledTimes(1)++ firstToggle.resolve()++ await waitFor(() => {+ expect(mocks.updateTriggerStatus).toHaveBeenCalledTimes(2)+ })++ secondToggle.resolve()++ await waitFor(() => {+ expect(mocks.invalidateTriggers).toHaveBeenCalledTimes(2)+ })+ expect(triggerSwitch).toHaveAttribute('aria-checked', 'true')+ })})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.tsindex 7d25007c40f..3d192055cce 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@@ -5,10 +5,7 @@ import { createTestQueryClient } from '@/test/query-client'import { useAccessPointActions } from '../shared/use-access-point-actions'const mocks = vi.hoisted(() => ({- emit: vi.fn(),fetchAppDetail: vi.fn().mockResolvedValue({ id: 'app-1' }),- getSocket: vi.fn(),- onAppStateUpdate: vi.fn(() => vi.fn()),setAppDetail: vi.fn(),toast: vi.fn(),updateAppSiteConfig: vi.fn().mockResolvedValue({}),@@ -21,14 +18,6 @@ vi.mock('@/app/components/app/store', () => ({selector({ setAppDetail: mocks.setAppDetail }),}))-vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', () => ({- collaborationManager: { onAppStateUpdate: mocks.onAppStateUpdate },-}))--vi.mock('@/app/components/workflow/collaboration/core/websocket-manager', () => ({- webSocketClient: { getSocket: mocks.getSocket },-}))-vi.mock('@/service/apps', () => ({fetchAppDetail: mocks.fetchAppDetail,updateAppSiteConfig: mocks.updateAppSiteConfig,@@ -81,10 +70,9 @@ function renderActions(appId = 'app-1', canManageAccessPoint = true) {describe('useAccessPointActions', () => {beforeEach(() => {vi.clearAllMocks()- mocks.getSocket.mockReturnValue({ emit: mocks.emit })})- it('refreshes and broadcasts a successful access point result', async () => {+ it('refreshes after a successful access point result', async () => {const { result } = renderActions()act(() => result.current.handleResult(null))@@ -93,25 +81,17 @@ describe('useAccessPointActions', () => {expect(mocks.fetchAppDetail).toHaveBeenCalledWith({ url: '/apps', id: 'app-1' })expect(mocks.setAppDetail).toHaveBeenCalledWith({ id: 'app-1' })})- expect(mocks.emit).toHaveBeenCalledWith(- 'collaboration_event',- expect.objectContaining({- type: 'app_state_update',- timestamp: expect.any(Number),- }),- )expect(mocks.toast).toHaveBeenCalledWith('common.actionMsg.modifiedSuccessfully', {type: 'success',})})- it('reports a failed result without refreshing or broadcasting stale state', () => {+ it('reports a failed result without refreshing stale state', () => {const { result } = renderActions()act(() => result.current.handleResult(new Error('request failed')))expect(mocks.fetchAppDetail).not.toHaveBeenCalled()- expect(mocks.getSocket).not.toHaveBeenCalled()expect(mocks.toast).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully', {type: 'error',})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.tsxindex c1be2f4f69a..aa96922b3d6 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@@ -1,10 +1,12 @@import type { AccessPointAppInfo, PublishedWorkflow } from '../shared/utils'import type { InputVar, Node } from '@/app/components/workflow/types'-import { screen, waitFor } from '@testing-library/react'+import { toast } from '@langgenius/dify-ui/toast'+import { QueryClientProvider } from '@tanstack/react-query'+import { screen, waitFor, within } 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 { AccessMode } from '@/models/access-control'-import { createQueryClientWrapper } from '@/test/console/query-client'import { render } from '@/test/console/render'import { createTestQueryClient } from '@/test/query-client'import { AppModeEnum } from '@/types/app'@@ -12,14 +14,14 @@ import { basePath } from '@/utils/var'import { WebAppAccessPointCard } from '../built-in-access-points/web-app-card'const mocks = vi.hoisted(() => ({+ siteEnable: vi.fn(),resetSiteAccessToken: vi.fn().mockResolvedValue({}),- toastError: vi.fn(),- updateSiteStatus: vi.fn().mockResolvedValue({}),}))vi.mock('@langgenius/dify-ui/toast', () => ({toast: {- error: mocks.toastError,+ error: vi.fn(),+ success: vi.fn(),},}))@@ -30,7 +32,7 @@ vi.mock('@/service/client', () => ({siteEnable: {post: {mutationOptions: (options = {}) => ({- mutationFn: mocks.updateSiteStatus,+ mutationFn: mocks.siteEnable,...options,}),},@@ -111,30 +113,67 @@ function renderCard(workflow?: PublishedWorkflow,{canManageAccessPoint = true,- onAppStateChanged = vi.fn().mockResolvedValue(undefined),+ onRefreshApp = vi.fn().mockResolvedValue(undefined),}: {canManageAccessPoint?: boolean- onAppStateChanged?: () => Promise<void>+ onRefreshApp?: () => Promise<void>} = {},) {+ useAppStore.setState({ appDetail: createAppInfo(mode) })const queryClient = createTestQueryClient()- render(++ return render(+ <QueryClientProvider client={queryClient}>+ <StoreConnectedWebAppCard+ availability={availability}+ canManageAccessPoint={canManageAccessPoint}+ onRefreshApp={onRefreshApp}+ workflow={workflow}+ />+ </QueryClientProvider>,+ )+}++function StoreConnectedWebAppCard({+ availability,+ canManageAccessPoint,+ onRefreshApp,+ workflow,+}: {+ availability: 'available' | 'loading' | 'unavailable'+ canManageAccessPoint: boolean+ onRefreshApp: () => Promise<void>+ workflow?: PublishedWorkflow+}) {+ const appInfo = useAppStore((state) => state.appDetail)+ if (!appInfo) return null++ return (<WebAppAccessPointCard- appInfo={createAppInfo(mode)}+ appInfo={appInfo}availability={availability}canDeploycanManageAccesscanManageAccessPoint={canManageAccessPoint}showAccessControl- onAppStateChanged={onAppStateChanged}- onRefreshApp={vi.fn().mockResolvedValue(undefined)}+ onRefreshApp={onRefreshApp}onSaveSiteConfig={vi.fn().mockResolvedValue(undefined)}workflow={workflow}- />,- { wrapper: createQueryClientWrapper(queryClient) },+ />)}+function createDeferredPromise<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((promiseResolve, promiseReject) => {+ resolve = promiseResolve+ reject = promiseReject+ })++ return { promise, reject, resolve }+}+const startNode: Node<{ variables: InputVar[] }> = {id: 'start',position: { x: 0, y: 0 },@@ -179,6 +218,10 @@ const workflowWithHiddenInput: NonNullable<PublishedWorkflow> = {describe('WebAppAccessPointCard', () => {beforeEach(() => {vi.clearAllMocks()+ mocks.siteEnable.mockResolvedValue({+ enable_site: true,+ })+ mocks.resetSiteAccessToken.mockResolvedValue({})})afterEach(() => {@@ -216,43 +259,15 @@ describe('WebAppAccessPointCard', () => {it('updates site status through the generated contract', async () => {const user = userEvent.setup()- const onAppStateChanged = vi.fn().mockResolvedValue(undefined)- renderCard(AppModeEnum.CHAT, 'available', undefined, { onAppStateChanged })+ renderCard(AppModeEnum.CHAT)await user.click(screen.getByRole('switch'))await waitFor(() => {- expect(mocks.updateSiteStatus.mock.calls[0]?.[0]).toEqual({+ expect(mocks.siteEnable.mock.calls[0]?.[0]).toEqual({params: { app_id: 'app-1' },body: { enable_site: false },})- expect(onAppStateChanged).toHaveBeenCalledTimes(1)- })- })-- it('keeps the status switch pending until the app state refresh completes', async () => {- const user = userEvent.setup()- let resolveRefresh: (() => void) | undefined- const refresh = new Promise<void>((resolve) => {- resolveRefresh = resolve- })- const onAppStateChanged = vi.fn(() => refresh)- renderCard(AppModeEnum.CHAT, 'available', undefined, { onAppStateChanged })-- const statusSwitch = screen.getByRole('switch')- await user.click(statusSwitch)-- await waitFor(() => {- expect(onAppStateChanged).toHaveBeenCalledTimes(1)- expect(statusSwitch).toHaveAttribute('aria-busy', 'true')- expect(statusSwitch).toHaveAttribute('aria-disabled', 'true')- })-- resolveRefresh?.()-- await waitFor(() => {- expect(statusSwitch).not.toHaveAttribute('aria-busy', 'true')- expect(statusSwitch).not.toHaveAttribute('aria-disabled', 'true')})})@@ -262,13 +277,13 @@ describe('WebAppAccessPointCard', () => {await user.click(screen.getByRole('switch'))- expect(mocks.updateSiteStatus).not.toHaveBeenCalled()+ expect(mocks.siteEnable).not.toHaveBeenCalled()})it('resets the site access token through the generated contract', async () => {const user = userEvent.setup()- const onAppStateChanged = vi.fn().mockResolvedValue(undefined)- renderCard(AppModeEnum.CHAT, 'available', undefined, { onAppStateChanged })+ const onRefreshApp = vi.fn().mockResolvedValue(undefined)+ renderCard(AppModeEnum.CHAT, 'available', undefined, { onRefreshApp })await user.click(screen.getByRole('button', { name: /overview\.appInfo\.regenerate/ }))await user.click(screen.getByRole('button', { name: /operation\.confirm/ }))@@ -277,23 +292,21 @@ describe('WebAppAccessPointCard', () => {expect(mocks.resetSiteAccessToken.mock.calls[0]?.[0]).toEqual({params: { app_id: 'app-1' },})- expect(onAppStateChanged).toHaveBeenCalledTimes(1)+ expect(onRefreshApp).toHaveBeenCalledTimes(1)})})it('keeps generated mutation failures inside the card owner', async () => {const user = userEvent.setup()const error = new Error('request failed')- const onAppStateChanged = vi.fn().mockResolvedValue(undefined)- mocks.updateSiteStatus.mockRejectedValueOnce(error)- renderCard(AppModeEnum.CHAT, 'available', undefined, { onAppStateChanged })+ mocks.siteEnable.mockRejectedValueOnce(error)+ renderCard(AppModeEnum.CHAT)await user.click(screen.getByRole('switch'))await waitFor(() => {- expect(mocks.toastError).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')+ expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')})- expect(onAppStateChanged).not.toHaveBeenCalled()})it('passes hidden Chatflow inputs to the embed dialog', async () => {@@ -333,6 +346,53 @@ describe('WebAppAccessPointCard', () => {).not.toBeInTheDocument()})+ it('does not announce an unavailable access control entry as loading', () => {+ renderCard(AppModeEnum.WORKFLOW, 'unavailable')++ const card = screen.getByRole('region', { name: /webApp\.title/ })+ expect(within(card).queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()+ })++ it('optimistically serializes status changes without a success toast', async () => {+ const user = userEvent.setup()+ const firstToggle = createDeferredPromise<{ enable_site: boolean }>()+ const secondToggle = createDeferredPromise<{ enable_site: boolean }>()+ mocks.siteEnable+ .mockReturnValueOnce(firstToggle.promise)+ .mockReturnValueOnce(secondToggle.promise)+ renderCard(AppModeEnum.CHAT)++ const accessSwitch = screen.getByRole('switch')+ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'false')+ expect(mocks.siteEnable).toHaveBeenCalledTimes(1)++ await user.click(accessSwitch)++ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ expect(mocks.siteEnable).toHaveBeenCalledTimes(1)+ expect(+ screen.queryByRole('link', { name: /studio\.accessPoint\.open/ }),+ ).not.toBeInTheDocument()++ firstToggle.resolve({ enable_site: false })++ await waitFor(() => {+ expect(mocks.siteEnable).toHaveBeenCalledTimes(2)+ })+ expect(mocks.siteEnable.mock.calls[1]?.[0]).toEqual({+ body: { enable_site: true },+ params: { app_id: 'app-1' },+ })++ secondToggle.resolve({ enable_site: true })++ await screen.findByRole('link', { name: /studio\.accessPoint\.open/ })+ expect(accessSwitch).toHaveAttribute('aria-checked', 'true')+ expect(toast.success).not.toHaveBeenCalled()+ })+it('disables Web App management actions without Access Point management', () => {renderCard(AppModeEnum.CHAT, 'available', undefined, { canManageAccessPoint: false })diff --git a/web/app/components/app/access-point/built-in-access-points/index.tsx b/web/app/components/app/access-point/built-in-access-points/index.tsxindex b516f0d5b45..1713f41cdbd 100644--- a/web/app/components/app/access-point/built-in-access-points/index.tsx+++ b/web/app/components/app/access-point/built-in-access-points/index.tsx@@ -1,6 +1,6 @@'use client'-import type { AccessPoint } from '@/app/components/app/deploy/access-point'+import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'import { Button, buttonVariants } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { useSuspenseQuery } from '@tanstack/react-query'@@ -112,7 +112,6 @@ export function BuiltInAccessPoints({canManageAccess={canReleaseAndVersion}canManageAccessPoint={canManageAccessPoint}showAccessControl={systemFeatures.webapp_auth.enabled}- onAppStateChanged={actions.handleAppStateChanged}onRefreshApp={actions.refreshAppDetail}onSaveSiteConfig={actions.saveSiteConfig}workflow={workflow}@@ -122,7 +121,6 @@ export function BuiltInAccessPoints({appInfo={appInfo}availability={appCardAvailability}canManage={canManageAccessPoint}- onAppStateChanged={actions.handleAppStateChanged}highlighted={highlightedAccessPoint === 'serviceApi'}/><MCPAccessPointCard@@ -138,7 +136,6 @@ export function BuiltInAccessPoints({appInfo={appInfo}availability={triggerAvailability}canManageAccessPoint={canManageAccessPoint}- onToggleResult={actions.handleResult}highlighted={highlightedAccessPoint === 'trigger'}/>)}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.tsxindex dbca8400485..a3cd201d887 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@@ -11,19 +11,22 @@ import {AlertDialogTitle,} from '@langgenius/dify-ui/alert-dialog'import { Button } from '@langgenius/dify-ui/button'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+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 {useInvalidateMCPServerDetail,useMCPServerDetail,useRefreshMCPServerCode,- useUpdateMCPServer,} from '@/service/use-tools'import { AppModeEnum } from '@/types/app'-import { AccessPointCard } from '../shared/access-point-card'-import { AccessPointUrl } from '../shared/access-point-url'+import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'import { getPublishedWorkflowNodes, isAdvancedApp } from '../shared/utils'type MCPAccessPointCardProps = {@@ -49,20 +52,33 @@ export function MCPAccessPointCard({const workflowApp = appInfo.mode === AppModeEnum.WORKFLOWconst [showServerModal, setShowServerModal] = useState(false)const [showRegenerate, setShowRegenerate] = useState(false)- const [pendingStatus, setPendingStatus] = useState<boolean | null>(null)const basicConfig = appInfo.model_configconst basicAppInputForm = basicConfig?.user_input_formconst { data: detail, isPending: serverDetailLoading } = useMCPServerDetail(appInfo.id,Boolean(appInfo.id),)- const { mutateAsync: updateServer, isPending: statusUpdating } = useUpdateMCPServer()- const { mutateAsync: refreshServerCode, isPending: regenerating } = useRefreshMCPServerCode()const invalidateServerDetail = useInvalidateMCPServerDetail()+ const updateServerMutation = useMutation(+ consoleQuery.apps.byAppId.server.put.mutationOptions({+ scope: {+ id: `app-mcp-toggle:${appInfo.id}`,+ },+ onSuccess: () => invalidateServerDetail(appInfo.id),+ onError: () => {+ toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))+ },+ }),+ )+ const { mutateAsync: refreshServerCode, isPending: regenerating } = useRefreshMCPServerCode()const serverPublished = Boolean(detail?.id)const serverActivated = detail?.status === 'active'- const activated = pendingStatus ?? serverActivated+ const pendingStatus = updateServerMutation.variables?.body.status+ const activated =+ updateServerMutation.isPending && pendingStatus != null+ ? pendingStatus === 'active'+ : serverActivatedconst serverUrl = serverPublished? `${appInfo.api_base_url.replace(/\/v1$/, '')}/mcp/server/${detail?.server_code}/mcp`: '***********'@@ -98,26 +114,24 @@ export function MCPAccessPointCard({)}, [advancedApp, basicAppInputs, workflowNodes])- const handleStatusChange = async (enabled: boolean) => {+ const handleStatusChange = (enabled: boolean) => {if (!canManageAccessPoint || loading || unavailable) returnif (enabled && !serverPublished) {setShowServerModal(true)return}- setPendingStatus(enabled)- try {- await updateServer({- appID: appInfo.id,+ updateServerMutation.mutate({+ params: {+ app_id: appInfo.id,+ },+ body: {id: detail?.id || '',description: detail?.description || '',parameters: detail?.parameters || {},status: enabled ? 'active' : 'inactive',- })- invalidateServerDetail(appInfo.id)- } finally {- setPendingStatus(null)- }+ },+ })}const handleRegenerate = async () => {@@ -134,6 +148,7 @@ export function MCPAccessPointCard({: activated? 'inService': 'disabled'+ const statusLabel = useAccessPointStatusLabel(status)return (<>@@ -144,10 +159,10 @@ export function MCPAccessPointCard({})}icon="i-custom-vender-integrations-mcp"status={status}+ statusLabel={statusLabel}highlighted={highlighted}switchDisabled={!canManageAccessPoint}switchLabel={t(($) => $['mcp.server.title'], { ns: 'tools' })}- switchLoading={statusUpdating}onEnabledChange={loading || unavailable ? undefined : handleStatusChange}actions={<Button@@ -191,7 +206,6 @@ export function MCPAccessPointCard({latestParams={latestParams}onHide={() => {setShowServerModal(false)- setPendingStatus(null)invalidateServerDetail(appInfo.id)}}appInfo={appInfo}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.tsxindex 414003d9bc3..fb47f578ea3 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@@ -1,12 +1,13 @@'use client'-import type { AccessPointAvailability } from '../shared/access-point-status'import type { AccessPointAppInfo } from '../shared/utils'+import type { AccessPointAvailability } from '@/app/components/base/access-point/status'import { toast } from '@langgenius/dify-ui/toast'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 { getAccessPointStatus } from '../shared/access-point-status'import { ServiceApiCardView } from '../shared/service-api-card-view'import { getBuiltInAccessUrls } from '../shared/utils'@@ -15,7 +16,6 @@ type ServiceApiAccessPointCardProps = {availability: AccessPointAvailabilitycanManage: booleanhighlighted?: boolean- onAppStateChanged: () => Promise<void>}export function ServiceApiAccessPointCard({@@ -23,27 +23,48 @@ export function ServiceApiAccessPointCard({availability,canManage,highlighted,- onAppStateChanged,}: ServiceApiAccessPointCardProps) {const { t } = useTranslation()- const updateApiStatus = useMutation(+ const setAppDetail = useAppStore((state) => state.setAppDetail)+ const toggleApiMutation = useMutation(consoleQuery.apps.byAppId.apiEnable.post.mutationOptions({- onSuccess: onAppStateChanged,+ scope: {+ id: `app-service-api-toggle:${appInfo.id}`,+ },+ onSuccess: (updatedApp) => {+ const currentAppDetail = useAppStore.getState().appDetail+ if (!currentAppDetail || currentAppDetail.id !== appInfo.id) return++ setAppDetail({+ ...currentAppDetail,+ enable_api: updatedApp.enable_api,+ updated_at: updatedApp.updated_at ?? currentAppDetail.updated_at,+ })+ },onError: () => {toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))},}),)const { api: apiUrl } = getBuiltInAccessUrls(appInfo)- const running = availability === 'available' && appInfo.enable_api+ const pendingEnabled = toggleApiMutation.variables?.body.enable_api+ const optimisticEnabled =+ toggleApiMutation.isPending && pendingEnabled !== undefined+ ? pendingEnabled+ : appInfo.enable_api+ const running = availability === 'available' && optimisticEnabledconst status = getAccessPointStatus(availability, running)- const handleStatusChange = (enabled: boolean) => {+ const handleEnabledChange = (enabled: boolean) => {if (!canManage) return- updateApiStatus.mutate({- params: { app_id: appInfo.id },- body: { enable_api: enabled },+ toggleApiMutation.mutate({+ params: {+ app_id: appInfo.id,+ },+ body: {+ enable_api: enabled,+ },})}@@ -60,8 +81,7 @@ export function ServiceApiAccessPointCard({status={status}highlighted={highlighted}switchDisabled={!canManage}- switchLoading={updateApiStatus.isPending}- onEnabledChange={availability === 'available' ? handleStatusChange : undefined}+ onEnabledChange={availability === 'available' ? handleEnabledChange : undefined}/>)}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.tsxindex 634a2e09ce5..ad57d3252fe 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@@ -5,21 +5,21 @@ import type { TriggerWithProvider } from '@/app/components/workflow/block-selectimport type { AppTrigger } from '@/service/use-tools'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'import { useEffect, useMemo } from 'react'import { useTranslation } from 'react-i18next'+import { AccessPointCard, AccessPointEmptyContent } from '@/app/components/base/access-point/card'import BlockIcon from '@/app/components/workflow/block-icon'import { useTriggerStatusStore } from '@/app/components/workflow/store/trigger-status'import { BlockEnum } from '@/app/components/workflow/types'import { useDocLink } from '@/context/i18n'import Link from '@/next/link'-import {- useAppTriggers,- useInvalidateAppTriggers,- useUpdateTriggerStatus,-} from '@/service/use-tools'+import { consoleQuery } from '@/service/client'+import { useAppTriggers, useInvalidateAppTriggers } from '@/service/use-tools'import { useAllTriggerPlugins } from '@/service/use-triggers'import { canFindTool } from '@/utils'-import { AccessPointCard, AccessPointEmptyContent } from '../shared/access-point-card'+import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'function TriggerIcon({trigger,@@ -52,12 +52,89 @@ function TriggerIcon({)}+function TriggerAccessPointItem({+ appId,+ canManageAccessPoint,+ trigger,+ triggerPlugins,+}: {+ appId: string+ canManageAccessPoint: boolean+ trigger: AppTrigger+ triggerPlugins: TriggerWithProvider[]+}) {+ const { t } = useTranslation()+ const invalidateTriggers = useInvalidateAppTriggers()+ const updateTriggerMutation = useMutation(+ consoleQuery.apps.byAppId.triggerEnable.post.mutationOptions({+ scope: {+ id: `app-trigger-toggle:${appId}:${trigger.id}`,+ },+ onSuccess: () => invalidateTriggers(appId),+ onError: () => {+ toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))+ },+ }),+ )+ const pendingEnabled = updateTriggerMutation.variables?.body.enable_trigger+ const enabled =+ updateTriggerMutation.isPending && pendingEnabled !== undefined+ ? pendingEnabled+ : trigger.status === 'enabled'+ const statusLabel = enabled+ ? t(($) => $['agentDetail.access.status.inService'], {+ ns: 'agentV2',+ })+ : t(($) => $['overview.status.disable'], {+ ns: 'appOverview',+ })++ const handleEnabledChange = (nextEnabled: boolean) => {+ if (!canManageAccessPoint) return++ updateTriggerMutation.mutate({+ params: {+ app_id: appId,+ },+ body: {+ trigger_id: trigger.id,+ enable_trigger: nextEnabled,+ },+ })+ }++ return (+ <div className="flex min-h-11 items-center gap-3 rounded-lg px-2 py-1.5 hover:bg-state-base-hover">+ <TriggerIcon trigger={trigger} triggerPlugins={triggerPlugins} />+ <span className="w-28 shrink-0 truncate system-sm-medium text-text-secondary">+ {trigger.title}+ </span>+ <span className="min-w-0 flex-1 truncate system-xs-regular text-text-tertiary">+ {trigger.provider_name}+ </span>+ <span+ className={`flex shrink-0 items-center gap-1 system-xs-semibold-uppercase ${+ enabled ? 'text-text-success' : 'text-text-tertiary'+ }`}+ >+ <StatusDot size="small" status={enabled ? 'success' : 'disabled'} />+ {statusLabel}+ </span>+ <Switch+ checked={enabled}+ disabled={!canManageAccessPoint}+ aria-label={trigger.title}+ onCheckedChange={handleEnabledChange}+ />+ </div>+ )+}+type TriggerAccessPointCardProps = {appInfo: AccessPointAppInfoavailability: 'available' | 'loading' | 'unavailable'canManageAccessPoint: booleanhighlighted?: boolean- onToggleResult: (error: Error | null) => void}export function TriggerAccessPointCard({@@ -65,19 +142,17 @@ export function TriggerAccessPointCard({availability,canManageAccessPoint,highlighted,- onToggleResult,}: TriggerAccessPointCardProps) {const { t } = useTranslation()const docLink = useDocLink()const { data: response, isLoading } = useAppTriggers(appInfo.id)const { data: triggerPlugins = [] } = useAllTriggerPlugins()- const { mutateAsync: updateTriggerStatus, isPending: statusUpdating } = useUpdateTriggerStatus()- const invalidateTriggers = useInvalidateAppTriggers()- const { setTriggerStatus, setTriggerStatuses } = useTriggerStatusStore()+ const setTriggerStatuses = useTriggerStatusStore((state) => state.setTriggerStatuses)const triggers = useMemo(() => response?.data ?? [], [response?.data])const loading = availability === 'loading' || isLoadingconst active = availability === 'available' && !loadingconst status = loading ? 'loading' : active ? 'inService' : 'unavailable'+ const statusLabel = useAccessPointStatusLabel(status)const enabledCount = triggers.filter((trigger) => trigger.status === 'enabled').lengthuseEffect(() => {@@ -94,25 +169,6 @@ export function TriggerAccessPointCard({)}, [setTriggerStatuses, triggers])- const toggleTrigger = async (trigger: AppTrigger, enabled: boolean) => {- if (!canManageAccessPoint) return- const status = enabled ? 'enabled' : 'disabled'- setTriggerStatus(trigger.node_id, status)-- try {- await updateTriggerStatus({- appId: appInfo.id,- triggerId: trigger.id,- enableTrigger: enabled,- })- invalidateTriggers(appInfo.id)- onToggleResult(null)- } catch (error) {- setTriggerStatus(trigger.node_id, enabled ? 'disabled' : 'enabled')- onToggleResult(error as Error)- }- }-return (<AccessPointCardtitle={t(($) => $['settings.trigger'], { ns: 'common' })}@@ -121,6 +177,7 @@ export function TriggerAccessPointCard({})}icon="i-custom-vender-integrations-trigger"status={status}+ statusLabel={statusLabel}highlighted={highlighted}showStatus={!active}>@@ -160,45 +217,15 @@ export function TriggerAccessPointCard({})}</div><div className="mt-1 flex flex-col gap-1">- {triggers.map((trigger) => {- const enabled = trigger.status === 'enabled'- const statusLabel = enabled- ? t(($) => $['agentDetail.access.status.inService'], {- ns: 'agentV2',- })- : t(($) => $['overview.status.disable'], {- ns: 'appOverview',- })-- return (- <div- key={trigger.id}- className="flex min-h-11 items-center gap-3 rounded-lg px-2 py-1.5 hover:bg-state-base-hover"- >- <TriggerIcon trigger={trigger} triggerPlugins={triggerPlugins} />- <span className="w-28 shrink-0 truncate system-sm-medium text-text-secondary">- {trigger.title}- </span>- <span className="min-w-0 flex-1 truncate system-xs-regular text-text-tertiary">- {trigger.provider_name}- </span>- <span- className={`flex shrink-0 items-center gap-1 system-xs-semibold-uppercase ${- enabled ? 'text-text-success' : 'text-text-tertiary'- }`}- >- <StatusDot size="small" status={enabled ? 'success' : 'disabled'} />- {statusLabel}- </span>- <Switch- checked={enabled}- disabled={!canManageAccessPoint || statusUpdating}- aria-label={trigger.title}- onCheckedChange={(nextEnabled) => void toggleTrigger(trigger, nextEnabled)}- />- </div>- )- })}+ {triggers.map((trigger) => (+ <TriggerAccessPointItem+ key={trigger.id}+ appId={appInfo.id}+ canManageAccessPoint={canManageAccessPoint}+ trigger={trigger}+ triggerPlugins={triggerPlugins}+ />+ ))}</div></div>)}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.tsxindex a1183897442..787db1dc263 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@@ -1,9 +1,9 @@'use client'import type { SelectorParam } from 'i18next'-import type { AccessPointAvailability } from '../shared/access-point-status'import type { AccessPointAppInfo, PublishedWorkflow } from '../shared/utils'import type { ConfigParams } from '@/app/components/app/overview/settings'+import type { AccessPointAvailability } from '@/app/components/base/access-point/status'import {AlertDialog,AlertDialogActions,@@ -23,16 +23,21 @@ import CustomizeModal from '@/app/components/app/overview/customize'import EmbeddedModal from '@/app/components/app/overview/embedded'import SettingsModal from '@/app/components/app/overview/settings'import { WorkflowLaunchDialog } from '@/app/components/app/overview/workflow-launch-dialog'+import { useStore as useAppStore } from '@/app/components/app/store'+import { AccessPointCard } from '@/app/components/base/access-point/card'+import { getAccessPointStatus } from '@/app/components/base/access-point/status'+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 { AppModeEnum } from '@/types/app'-import { AccessPointCard } from '../shared/access-point-card'-import { getAccessPointStatus } from '../shared/access-point-status'-import { AccessPointUrl } from '../shared/access-point-url'+import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'import { getBuiltInAccessUrls, getHiddenStartInputs } from '../shared/utils'-import { WebAppAccessControlEntry } from '../shared/web-app-access-control'+import {+ WebAppAccessControlEntry,+ WebAppAccessControlEntrySkeleton,+} from '../shared/web-app-access-control'const ACCESS_MODE_ICON_MAP: Record<AccessMode, string> = {[AccessMode.ORGANIZATION]: 'i-ri-building-line',@@ -56,7 +61,6 @@ type WebAppAccessPointCardProps = {canManageAccessPoint: booleanhighlighted?: booleanshowAccessControl: boolean- onAppStateChanged: () => Promise<void>onRefreshApp: () => Promise<void>onSaveSiteConfig: (params: ConfigParams) => Promise<void>workflow: PublishedWorkflow@@ -69,22 +73,34 @@ export function WebAppAccessPointCard({canManageAccess,canManageAccessPoint,highlighted,- onAppStateChanged,onRefreshApp,onSaveSiteConfig,showAccessControl,workflow,}: WebAppAccessPointCardProps) {const { t } = useTranslation()+ const setAppDetail = useAppStore((state) => state.setAppDetail)const [showSettings, setShowSettings] = useState(false)const [showEmbedded, setShowEmbedded] = useState(false)const [showCustomize, setShowCustomize] = useState(false)const [showAccess, setShowAccess] = useState(false)const [showRegenerate, setShowRegenerate] = useState(false)const [showWorkflowLaunch, setShowWorkflowLaunch] = useState(false)- const updateSiteStatus = useMutation(+ const toggleSiteMutation = useMutation(consoleQuery.apps.byAppId.siteEnable.post.mutationOptions({- onSuccess: onAppStateChanged,+ scope: {+ id: `app-web-app-toggle:${appInfo.id}`,+ },+ onSuccess: (updatedApp) => {+ const currentAppDetail = useAppStore.getState().appDetail+ if (!currentAppDetail || currentAppDetail.id !== appInfo.id) return++ setAppDetail({+ ...currentAppDetail,+ enable_site: updatedApp.enable_site,+ updated_at: updatedApp.updated_at ?? currentAppDetail.updated_at,+ })+ },onError: () => {toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))},@@ -93,7 +109,7 @@ export function WebAppAccessPointCard({const resetSiteAccessToken = useMutation(consoleQuery.apps.byAppId.site.accessTokenReset.post.mutationOptions({onSuccess: async () => {- await onAppStateChanged()+ await onRefreshApp()setShowRegenerate(false)},onError: () => {@@ -103,7 +119,13 @@ export function WebAppAccessPointCard({}),)const { webApp: webAppUrl } = getBuiltInAccessUrls(appInfo)- const running = availability === 'available' && appInfo.enable_site+ const pendingEnabled = toggleSiteMutation.variables?.body.enable_site+ const optimisticEnabled =+ toggleSiteMutation.isPending && pendingEnabled !== undefined+ ? pendingEnabled+ : appInfo.enable_site+ const running = availability === 'available' && optimisticEnabled+ const actionsAvailable = running && !toggleSiteMutation.isPendingconst supportsEmbedded =appInfo.mode !== AppModeEnum.COMPLETION && appInfo.mode !== AppModeEnum.WORKFLOWconst hiddenLaunchVariables = getHiddenStartInputs(workflow)@@ -120,22 +142,27 @@ export function WebAppAccessPointCard({appInfo.access_mode !== AccessMode.SPECIFIC_GROUPS_MEMBERS ||Boolean(accessSubjects?.groups?.length || accessSubjects?.members?.length)- const handleStatusChange = (enabled: boolean) => {- if (!canManageAccessPoint) return-- updateSiteStatus.mutate({- params: { app_id: appInfo.id },- body: { enable_site: enabled },- })- }-const handleRegenerate = () => {if (!canManageAccessPoint || resetSiteAccessToken.isPending) returnresetSiteAccessToken.mutate({ params: { app_id: appInfo.id } })}+ const handleEnabledChange = (enabled: boolean) => {+ if (!canManageAccessPoint) return++ toggleSiteMutation.mutate({+ params: {+ app_id: appInfo.id,+ },+ body: {+ enable_site: enabled,+ },+ })+ }+const status = getAccessPointStatus(availability, running)+ const statusLabel = useAccessPointStatusLabel(status)return (<>@@ -154,18 +181,18 @@ export function WebAppAccessPointCard({/>}status={status}+ statusLabel={statusLabel}highlighted={highlighted}switchDisabled={!canManageAccessPoint}switchLabel={t(($) => $['overview.appInfo.title'], { ns: 'appOverview' })}- switchLoading={updateSiteStatus.isPending}- onEnabledChange={availability === 'available' ? handleStatusChange : undefined}+ onEnabledChange={availability === 'available' ? handleEnabledChange : undefined}actions={<>{hiddenLaunchVariables.length > 0 && (<ButtonclassName="flex items-center gap-1 px-3"variant="secondary"- disabled={!running}+ disabled={!actionsAvailable || !canManageAccessPoint}onClick={() => setShowWorkflowLaunch(true)}><span aria-hidden className="i-ri-settings-2-line size-4" />@@ -176,7 +203,7 @@ export function WebAppAccessPointCard({<ButtonclassName="flex items-center gap-1 px-3"variant="secondary"- disabled={!running || !canManageAccessPoint}+ disabled={!actionsAvailable || !canManageAccessPoint}onClick={() => setShowEmbedded(true)}><span aria-hidden className="i-ri-window-line size-4" />@@ -186,7 +213,7 @@ export function WebAppAccessPointCard({<ButtonclassName="flex items-center gap-1 px-3"variant="secondary"- disabled={!running || !canManageAccessPoint}+ disabled={!actionsAvailable || !canManageAccessPoint}onClick={() => setShowCustomize(true)}><span aria-hidden className="i-custom-vender-deploy-code-block size-4" />@@ -219,7 +246,7 @@ export function WebAppAccessPointCard({showQrCodeshowRegenerateopenLabel={t(($) => $['studio.accessPoint.open'], { ns: 'deployments' })}- openUrl={webAppUrl}+ openUrl={appInfo.enable_site && !toggleSiteMutation.isPending ? webAppUrl : undefined}regenerateLabel={t(($) => $['overview.appInfo.regenerate'], {ns: 'appOverview',})}@@ -227,16 +254,18 @@ export function WebAppAccessPointCard({regenerating={resetSiteAccessToken.isPending}onRegenerate={() => setShowRegenerate(true)}/>- {showAccessControl && (- <WebAppAccessControlEntry- accessConfigured={accessConfigured}- accessIcon={accessIcon}- accessLabel={t(accessLabel, { ns: 'app' })}- available={availability === 'available'}- disabled={!canManageAccess}- onClick={() => setShowAccess(true)}- />- )}+ {showAccessControl &&+ (availability === 'available' ? (+ <WebAppAccessControlEntry+ accessConfigured={accessConfigured}+ accessIcon={accessIcon}+ accessLabel={t(accessLabel, { ns: 'app' })}+ disabled={!canManageAccess}+ onClick={() => setShowAccess(true)}+ />+ ) : (+ <WebAppAccessControlEntrySkeleton loading={availability === 'loading'} />+ ))}</AccessPointCard><SettingsModaldiff --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.tsxindex ca284d456c8..9641b96b81a 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@@ -1,7 +1,7 @@'use client'import { toast } from '@langgenius/dify-ui/toast'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+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'@@ -21,7 +21,6 @@ export function EnvironmentServiceApiCard({highlighted,}: EnvironmentServiceApiCardProps) {const { t } = useTranslation()- const queryClient = useQueryClient()const appMode = useAppStore((state) => state.appDetail?.mode)const params = {app_id: appId,@@ -35,16 +34,18 @@ export function EnvironmentServiceApiCard({const api = apiQuery.dataconst apiMutation = useMutation(consoleQuery.enterprise.appDeploy.accessService.updateEnvironmentApi.mutationOptions({- onSuccess: (updatedApi) => {- queryClient.setQueryData(apiQueryOptions.queryKey, updatedApi)- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))+ scope: {+ id: `environment-service-api-toggle:${appId}:${environmentId}`,},onError: () => {toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))},}),)- const running = Boolean(apiQuery.isSuccess && api?.enabled)+ const pendingEnabled = apiMutation.variables?.body.enabled+ const optimisticEnabled =+ apiMutation.isPending && pendingEnabled !== undefined ? pendingEnabled : Boolean(api?.enabled)+ const running = apiQuery.isSuccess && optimisticEnabledconst status = apiQuery.isPending? 'loading': apiQuery.isError@@ -78,7 +79,6 @@ export function EnvironmentServiceApiCard({highlighted={highlighted}switchDisabled={!canManageAccessPoint}onEnabledChange={apiQuery.isSuccess ? handleEnabledChange : undefined}- switchLoading={apiMutation.isPending}/>)}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.tsxindex 0066fac4ca2..cf6651a67ab 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@@ -18,14 +18,18 @@ import { useTranslation } from 'react-i18next'import CustomizeModal from '@/app/components/app/overview/customize'import SettingsModal from '@/app/components/app/overview/settings'import { useStore as useAppStore } from '@/app/components/app/store'+import { AccessPointCard } from '@/app/components/base/access-point/card'+import { AccessPointUrl } from '@/app/components/base/access-point/url'import AppIcon from '@/app/components/base/app-icon'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AccessMode, isAccessMode } from '@/models/access-control'import { consoleQuery } from '@/service/client'-import { AccessPointCard } from '../shared/access-point-card'-import { AccessPointUrl } from '../shared/access-point-url'import { useAccessPointActions } from '../shared/use-access-point-actions'-import { WebAppAccessControlEntry } from '../shared/web-app-access-control'+import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'+import {+ WebAppAccessControlEntry,+ WebAppAccessControlEntrySkeleton,+} from '../shared/web-app-access-control'import { EnvironmentAccessControl } from './environment-access-control'import { getEnvironmentWebAppUrl } from './environment-web-app-utils'@@ -94,9 +98,8 @@ export function EnvironmentWebAppCard({subjectsQuery.data.subjects.length > 0const siteMutation = useMutation(consoleQuery.enterprise.appDeploy.accessService.updateEnvironmentSite.mutationOptions({- onSuccess: (updatedSite) => {- queryClient.setQueryData(siteQueryOptions.queryKey, updatedSite)- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))+ scope: {+ id: `environment-web-app-toggle:${appId}:${environmentId}`,},onError: () => {toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))@@ -117,8 +120,12 @@ export function EnvironmentWebAppCard({},),)- const webAppUrl = getEnvironmentWebAppUrl(site)- const running = Boolean(siteQuery.isSuccess && site?.enabled)+ const webAppUrl = getEnvironmentWebAppUrl(site, appInfo?.mode)+ const pendingEnabled = siteMutation.variables?.body.enabled+ const optimisticEnabled =+ siteMutation.isPending && pendingEnabled !== undefined ? pendingEnabled : Boolean(site?.enabled)+ const running = siteQuery.isSuccess && optimisticEnabled+ const actionsAvailable = running && !siteMutation.isPendingconst status = siteQuery.isPending? 'loading': siteQuery.isError@@ -126,6 +133,7 @@ export function EnvironmentWebAppCard({: running? 'inService': 'disabled'+ const statusLabel = useAccessPointStatusLabel(status)const accessLabel =accessMode === AccessMode.ORGANIZATION? t(($) => $['accessControlDialog.accessItems.organization'], { ns: 'app' })@@ -170,17 +178,17 @@ export function EnvironmentWebAppCard({)}status={status}+ statusLabel={statusLabel}highlighted={highlighted}switchDisabled={!canManageAccessPoint}switchLabel={t(($) => $['overview.appInfo.title'], { ns: 'appOverview' })}onEnabledChange={siteQuery.isSuccess ? handleEnabledChange : undefined}- switchLoading={siteMutation.isPending}actions={<><ButtonclassName="flex items-center gap-1 px-3"variant="secondary"- disabled={!running || !apiQuery.isSuccess || !canManageAccessPoint}+ disabled={!actionsAvailable || !apiQuery.isSuccess || !canManageAccessPoint}onClick={() => setShowCustomize(true)}><span aria-hidden className="i-custom-vender-deploy-code-block size-4" />@@ -213,7 +221,7 @@ export function EnvironmentWebAppCard({showQrCodeshowRegenerateopenLabel={t(($) => $['studio.accessPoint.open'], { ns: 'deployments' })}- openUrl={webAppUrl}+ openUrl={site?.enabled && !siteMutation.isPending ? webAppUrl : undefined}regenerateLabel={t(($) => $['overview.appInfo.regenerate'], {ns: 'appOverview',})}@@ -221,16 +229,18 @@ export function EnvironmentWebAppCard({regenerating={resetAccessTokenMutation.isPending}onRegenerate={() => setShowRegenerate(true)}/>- {systemFeatures.webapp_auth.enabled && (- <WebAppAccessControlEntry- accessConfigured={accessConfigured}- accessIcon={ACCESS_MODE_ICON_MAP[accessMode]}- accessLabel={accessLabel}- available={siteQuery.isSuccess}- disabled={!canReleaseAndVersion}- onClick={() => setShowAccess(true)}- />- )}+ {systemFeatures.webapp_auth.enabled &&+ (siteQuery.isSuccess ? (+ <WebAppAccessControlEntry+ accessConfigured={accessConfigured}+ accessIcon={ACCESS_MODE_ICON_MAP[accessMode]}+ accessLabel={accessLabel}+ disabled={!canReleaseAndVersion}+ onClick={() => setShowAccess(true)}+ />+ ) : (+ <WebAppAccessControlEntrySkeleton loading={siteQuery.isPending} />+ ))}</AccessPointCard>{appInfo && (diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.ts b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.tsindex cf1224e091a..0f11f208586 100644--- a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.ts+++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.ts@@ -1,8 +1,10 @@import type { EnvironmentSite } from '@dify/contracts/enterprise-app-deploy/types.gen'+import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'-export function getEnvironmentWebAppUrl(site?: EnvironmentSite) {+export function getEnvironmentWebAppUrl(site?: EnvironmentSite, mode?: string) {if (!site?.app_base_url || !site.code) return ''- return `${site.app_base_url.replace(/\/$/, '')}${basePath}/env/workflow/${site.code}`+ const route = mode === AppModeEnum.ADVANCED_CHAT ? 'chat' : 'workflow'+ return `${site.app_base_url.replace(/\/$/, '')}${basePath}/environment/${route}/${site.code}`}diff --git a/web/app/components/app/access-point/deployed-environment-access-points/index.tsx b/web/app/components/app/access-point/deployed-environment-access-points/index.tsxindex 172574e439c..f585e35aaf4 100644--- a/web/app/components/app/access-point/deployed-environment-access-points/index.tsx+++ b/web/app/components/app/access-point/deployed-environment-access-points/index.tsx@@ -1,8 +1,9 @@'use client'-import type { AccessPoint } from '@/app/components/app/deploy/access-point'+import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'import { useTranslation } from 'react-i18next'-import { AccessPointCard, AccessPointEmptyContent } from '../shared/access-point-card'+import { AccessPointCard, AccessPointEmptyContent } from '@/app/components/base/access-point/card'+import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'import { EnvironmentServiceApiCard } from './environment-service-api-card'import { EnvironmentWebAppCard } from './environment-web-app-card'@@ -44,6 +45,7 @@ export function DeployedEnvironmentAccessPoints({highlightedAccessPoint,}: DeployedEnvironmentAccessPointsProps) {const { t } = useTranslation()+ const unsupportedStatusLabel = useAccessPointStatusLabel('unsupported')const title = (accessPoint: (typeof UNSUPPORTED_ACCESS_POINTS)[number]) => {const key = ACCESS_POINT_CONFIG[accessPoint].title@@ -85,6 +87,7 @@ export function DeployedEnvironmentAccessPoints({description={description(accessPoint)}icon={ACCESS_POINT_CONFIG[accessPoint].icon}status="unsupported"+ statusLabel={unsupportedStatusLabel}highlighted={highlightedAccessPoint === accessPoint}><AccessPointEmptyContent>diff --git a/web/app/components/app/access-point/index.tsx b/web/app/components/app/access-point/index.tsxindex effb64ad4b9..cda649d7c58 100644--- a/web/app/components/app/access-point/index.tsx+++ b/web/app/components/app/access-point/index.tsx@@ -1,11 +1,18 @@'use client'+import {+ ScrollArea,+ ScrollAreaContent,+ ScrollAreaScrollbar,+ ScrollAreaThumb,+ ScrollAreaViewport,+} from '@langgenius/dify-ui/scroll-area'import { Tabs, TabsList, TabsTab } from '@langgenius/dify-ui/tabs'import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { parseAsString, parseAsStringLiteral, useQueryStates } from 'nuqs'import { useTranslation } from 'react-i18next'-import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/access-point'+import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'import { useStore as useAppStore } from '@/app/components/app/store'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'@@ -64,7 +71,7 @@ function AccessPointContent({<header className="flex shrink-0 flex-col gap-3 px-6 pt-3 pb-2"><div className="flex flex-col gap-0.5"><div className="flex h-6 items-center">- <h1 className="title-xl-semi-bold text-text-primary">+ <h1 id="access-point-title" className="title-xl-semi-bold text-text-primary">{t(($) => $['appMenus.accessPoint'], { ns: 'common' })}</h1></div>@@ -103,28 +110,41 @@ function AccessPointContent({)}</header>- <div- className="min-h-0 flex-1 overflow-y-auto px-6 py-2"- data-environment={selectedEnvironment}- >- {selectedEnvironment === BUILT_IN_ENVIRONMENT_ID ? (- <BuiltInAccessPoints- appId={appId}- canDeploy={canDeploy}- canManageAccessPoint={canManageAccessPoint}- canReleaseAndVersion={canReleaseAndVersion}- highlightedAccessPoint={selectedHighlightedAccessPoint}- />- ) : (- <DeployedEnvironmentAccessPoints- appId={appId}- environmentId={selectedEnvironment}- canManageAccessPoint={canManageAccessPoint}- canReleaseAndVersion={canReleaseAndVersion}- highlightedAccessPoint={selectedHighlightedAccessPoint}- />- )}- </div>+ <ScrollArea className="relative min-h-0 flex-1 overflow-hidden">+ <ScrollAreaViewport+ aria-labelledby="access-point-title"+ className="overscroll-contain"+ data-environment={selectedEnvironment}+ role="region"+ style={{ overflowX: 'hidden' }}+ >+ <ScrollAreaContent+ className="min-h-full w-full max-w-full px-6 py-2"+ style={{ minWidth: 0 }}+ >+ {selectedEnvironment === BUILT_IN_ENVIRONMENT_ID ? (+ <BuiltInAccessPoints+ appId={appId}+ canDeploy={canDeploy}+ canManageAccessPoint={canManageAccessPoint}+ canReleaseAndVersion={canReleaseAndVersion}+ highlightedAccessPoint={selectedHighlightedAccessPoint}+ />+ ) : (+ <DeployedEnvironmentAccessPoints+ appId={appId}+ environmentId={selectedEnvironment}+ canManageAccessPoint={canManageAccessPoint}+ canReleaseAndVersion={canReleaseAndVersion}+ highlightedAccessPoint={selectedHighlightedAccessPoint}+ />+ )}+ </ScrollAreaContent>+ </ScrollAreaViewport>+ <ScrollAreaScrollbar>+ <ScrollAreaThumb />+ </ScrollAreaScrollbar>+ </ScrollArea></main>)}@@ -142,7 +162,8 @@ export default function AccessPoint({ appId }: AccessPointProps) {workspacePermissionKeys,})const showEnvironmentTabs =- appDetail?.mode === AppModeEnum.WORKFLOW && capabilities.canViewAccessPoint+ (appDetail?.mode === AppModeEnum.WORKFLOW || appDetail?.mode === AppModeEnum.ADVANCED_CHAT) &&+ capabilities.canViewAccessPointreturn (<AccessPointStateBoundary appId={appId} environmentQueryEnabled={showEnvironmentTabs}>diff --git a/web/app/components/app/access-point/shared/service-api-card-view.tsx b/web/app/components/app/access-point/shared/service-api-card-view.tsxindex c5f708ddd41..5ff7f941e87 100644--- a/web/app/components/app/access-point/shared/service-api-card-view.tsx+++ b/web/app/components/app/access-point/shared/service-api-card-view.tsx@@ -1,16 +1,17 @@'use client'import type { ComponentProps } from 'react'-import type { AccessPointStatus } from './access-point-status'+import type { AccessPointStatus } from '@/app/components/base/access-point/status'import type { AppModeEnum } from '@/types/app'import { Button, buttonVariants } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { useTranslation } from 'react-i18next'+import { AccessPointCard } from '@/app/components/base/access-point/card'+import { AccessPointUrl } from '@/app/components/base/access-point/url'import { useDocLink } from '@/context/i18n'import Link from '@/next/link'-import { AccessPointCard } from './access-point-card'-import { AccessPointUrl } from './access-point-url'import { ApiSecretKeyButton } from './api-secret-key-button'+import { useAccessPointStatusLabel } from './use-access-point-status-label'import { getAppApiReferencePath } from './utils'type ServiceApiCardViewProps = {@@ -40,6 +41,7 @@ export function ServiceApiCardView({const docLink = useDocLink()const apiReferencePath = appMode ? getAppApiReferencePath(appMode) : undefinedconst apiReferenceUrl = apiReferencePath ? docLink(apiReferencePath) : undefined+ const statusLabel = useAccessPointStatusLabel(status)return (<AccessPointCard@@ -49,6 +51,7 @@ export function ServiceApiCardView({})}icon="i-custom-vender-knowledge-api-aggregate"status={status}+ statusLabel={statusLabel}highlighted={highlighted}switchDisabled={switchDisabled}switchLabel={t(($) => $['overview.apiInfo.title'], { ns: 'appOverview' })}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.tsindex cc26e7ec678..c82373dea0b 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@@ -5,11 +5,9 @@ import type { App } from '@/types/app'import type { I18nKeysByPrefix } from '@/types/i18n'import { toast } from '@langgenius/dify-ui/toast'import { useQueryClient } from '@tanstack/react-query'-import { useCallback, useEffect } from 'react'+import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { useStore as useAppStore } from '@/app/components/app/store'-import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'-import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'import { fetchAppDetail, updateAppSiteConfig } from '@/service/apps'import { consoleQuery } from '@/service/client'import { asyncRunSafe } from '@/utils'@@ -27,41 +25,21 @@ export function useAccessPointActions(appId: string, canManageAccessPoint: boole}}, [appId, setAppDetail])- const handleAppStateChanged = useCallback(async () => {- const refresh = refreshAppDetail()- const socket = webSocketClient.getSocket(appId)- if (socket) {- const timestamp = Date.now()- socket.emit('collaboration_event', {- type: 'app_state_update',- data: { timestamp },- timestamp,- })- }-- await refresh- }, [appId, refreshAppDetail])-const handleResult = useCallback((error: Error | null, message?: I18nKeysByPrefix<'common', 'actionMsg.'>) => {const type = error ? 'error' : 'success'const resolvedMessage = message ?? (error ? 'modifiedUnsuccessfully' : 'modifiedSuccessfully')- if (!error) void handleAppStateChanged()+ if (!error) {+ void refreshAppDetail()+ }toast(t(($) => $[`actionMsg.${resolvedMessage}`], { ns: 'common' }) as string, {type,})},- [handleAppStateChanged, t],+ [refreshAppDetail, t],)-- useEffect(() => {- if (!appId) return-- return collaborationManager.onAppStateUpdate(refreshAppDetail)- }, [appId, refreshAppDetail])-const saveSiteConfig = useCallback(async (params: ConfigParams) => {if (!canManageAccessPoint) return@@ -87,7 +65,6 @@ export function useAccessPointActions(appId: string, canManageAccessPoint: boole)return {- handleAppStateChanged,handleResult,refreshAppDetail,saveSiteConfig,diff --git a/web/app/components/app/access-point/shared/use-access-point-status-label.ts b/web/app/components/app/access-point/shared/use-access-point-status-label.tsnew file mode 100644index 00000000000..52a6b727661--- /dev/null+++ b/web/app/components/app/access-point/shared/use-access-point-status-label.ts@@ -0,0 +1,17 @@+'use client'++import type { AccessPointStatus } from '@/app/components/base/access-point/status'+import { useTranslation } from 'react-i18next'++export function useAccessPointStatusLabel(status: AccessPointStatus) {+ const { t } = useTranslation()+ const labels: Record<AccessPointStatus, string> = {+ disabled: t(($) => $['overview.status.disable'], { ns: 'appOverview' }),+ inService: t(($) => $['agentDetail.access.status.inService'], { ns: 'agentV2' }),+ loading: t(($) => $.loading, { ns: 'common' }),+ unavailable: t(($) => $['health.ENVIRONMENT_STATUS_FAILED'], { ns: 'deployments' }),+ unsupported: t(($) => $['studio.accessPoint.notSupported'], { ns: 'deployments' }),+ }++ return labels[status]+}diff --git a/web/app/components/app/access-point/shared/web-app-access-control.tsx b/web/app/components/app/access-point/shared/web-app-access-control.tsxindex 8c97d0074a3..c17eb11a0a5 100644--- a/web/app/components/app/access-point/shared/web-app-access-control.tsx+++ b/web/app/components/app/access-point/shared/web-app-access-control.tsx@@ -6,16 +6,36 @@ type WebAppAccessControlEntryProps = {accessConfigured: booleanaccessIcon: stringaccessLabel: string- available: booleandisabled: booleanonClick: () => void}+export function WebAppAccessControlEntrySkeleton({ loading }: { loading: boolean }) {+ const { t } = useTranslation()++ return (+ <div className="-mt-1 px-4 pb-3">+ <div+ role={loading ? 'status' : undefined}+ aria-label={loading ? t(($) => $.loading, { ns: 'common' }) : undefined}+ aria-hidden={loading ? undefined : true}+ className="flex h-9 w-full items-center gap-2 rounded-lg border-[0.5px] border-divider-subtle bg-background-section px-2.5"+ >+ <span aria-hidden className="i-ri-global-line size-4 shrink-0 text-text-disabled" />+ <span aria-hidden className="h-2 w-[42%] rounded-full bg-text-quaternary opacity-10" />+ <span+ aria-hidden+ className="ml-auto i-ri-arrow-right-s-line size-4 shrink-0 text-text-disabled"+ />+ </div>+ </div>+ )+}+export function WebAppAccessControlEntry({accessConfigured,accessIcon,accessLabel,- available,disabled,onClick,}: WebAppAccessControlEntryProps) {@@ -23,38 +43,27 @@ export function WebAppAccessControlEntry({return (<div className="-mt-1 px-4 pb-3">- {available ? (- <button- type="button"- className="flex h-9 w-full cursor-pointer items-center gap-x-0.5 rounded-lg border-[0.5px] border-divider-subtle bg-background-section py-1 pr-2 pl-2.5 text-left outline-hidden hover:bg-state-base-hover-alt focus-visible:ring-2 focus-visible:ring-state-accent-solid disabled:cursor-not-allowed disabled:hover:bg-background-section"- disabled={disabled}- onClick={onClick}- >- <div className="flex grow items-center gap-x-1.5 overflow-hidden pr-1">- <span aria-hidden className={`${accessIcon} size-4 shrink-0 text-text-secondary`} />- <div className="grow truncate">- <span className="system-sm-regular text-text-secondary">{accessLabel}</span>- </div>+ <button+ type="button"+ className="flex h-9 w-full cursor-pointer items-center gap-x-0.5 rounded-lg border-[0.5px] border-divider-subtle bg-background-section py-1 pr-2 pl-2.5 text-left outline-hidden hover:bg-state-base-hover-alt focus-visible:ring-2 focus-visible:ring-state-accent-solid disabled:cursor-not-allowed disabled:hover:bg-background-section"+ disabled={disabled}+ onClick={onClick}+ >+ <div className="flex grow items-center gap-x-1.5 overflow-hidden pr-1">+ <span aria-hidden className={`${accessIcon} size-4 shrink-0 text-text-secondary`} />+ <div className="grow truncate">+ <span className="system-sm-regular text-text-secondary">{accessLabel}</span></div>- {!accessConfigured && (- <span className="shrink-0 system-xs-regular text-text-tertiary">- {t(($) => $['publishApp.notSet'], { ns: 'app' })}- </span>- )}- <div className="flex size-4 shrink-0 items-center justify-center">- <span aria-hidden className="i-ri-arrow-right-s-line size-4 text-text-quaternary" />- </div>- </button>- ) : (- <div className="flex h-9 w-full items-center gap-2 rounded-lg border-[0.5px] border-divider-subtle bg-background-section px-2.5">- <span aria-hidden className="i-ri-global-line size-4 shrink-0 text-text-disabled" />- <span className="h-2 w-[42%] rounded-full bg-text-quaternary opacity-10" />- <span- aria-hidden- className="ml-auto i-ri-arrow-right-s-line size-4 shrink-0 text-text-disabled"- /></div>- )}+ {!accessConfigured && (+ <span className="shrink-0 system-xs-regular text-text-tertiary">+ {t(($) => $['publishApp.notSet'], { ns: 'app' })}+ </span>+ )}+ <div className="flex size-4 shrink-0 items-center justify-center">+ <span aria-hidden className="i-ri-arrow-right-s-line size-4 text-text-quaternary" />+ </div>+ </button></div>)}diff --git a/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx b/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsxindex d41d63422eb..688ea7212fa 100644--- a/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/add-member-or-group-pop.spec.tsx@@ -1,10 +1,12 @@import type { AccessControlSubjects } from '../specific-groups-or-members'import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'+import { RadioGroup } from '@langgenius/dify-ui/radio-group'import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'-import { SubjectType } from '@/models/access-control'+import { AccessMode, SubjectType } from '@/models/access-control'import { renderWithAccountProfile as render } from '@/test/console/account-profile'+import AccessControlItem from '../access-control-item'import AddMemberOrGroupDialog from '../add-member-or-group-pop'const mockUseSearchForWhiteListCandidates = vi.fn()@@ -50,6 +52,20 @@ function ControlledDialog({return <AddMemberOrGroupDialog subjects={subjects} onChange={handleChange} />}+function DialogInsideAccessOption() {+ return (+ <RadioGroup+ aria-label="Access"+ value={AccessMode.SPECIFIC_GROUPS_MEMBERS}+ onValueChange={() => {}}+ >+ <AccessControlItem type={AccessMode.SPECIFIC_GROUPS_MEMBERS}>+ <ControlledDialog />+ </AccessControlItem>+ </RadioGroup>+ )+}+describe('AddMemberOrGroupDialog', () => {const baseGroup = createGroup()const baseMember = createMember()@@ -142,6 +158,25 @@ describe('AddMemberOrGroupDialog', () => {expect(memberToggle).toHaveAttribute('aria-pressed', 'true')})+ it('should stay open when expanding a group inside an access option', async () => {+ const user = userEvent.setup()+ render(<DialogInsideAccessOption />)++ const addButton = screen.getByRole('button', { name: 'common.operation.add' })+ await user.click(addButton)+ await user.click(+ screen.getByRole('button', {+ name: 'app.accessControlDialog.operateGroupAndMember.expand',+ }),+ )++ expect(addButton).toHaveAttribute('aria-expanded', 'true')+ expect(mockUseSearchForWhiteListCandidates).toHaveBeenLastCalledWith(+ expect.objectContaining({ groupId: baseGroup.id }),+ true,+ )+ })+it('should show the empty state when no candidates are returned', async () => {mockUseSearchForWhiteListCandidates.mockReturnValue({isLoading: false,diff --git a/web/app/components/app/app-access-control/add-member-or-group-pop/index.tsx b/web/app/components/app/app-access-control/add-member-or-group-pop/index.tsxindex 455e223057e..ebd3b76327a 100644--- a/web/app/components/app/app-access-control/add-member-or-group-pop/index.tsx+++ b/web/app/components/app/app-access-control/add-member-or-group-pop/index.tsx@@ -113,11 +113,7 @@ export default function AddMemberOrGroupDialog({? selectedAccessSubjects.groups.some((group) => group.id === subject.subjectId): selectedAccessSubjects.members.some((member) => member.id === subject.subjectId)- const statusText = isLoading- ? t(($) => $.loading, { ns: 'common' })- : hasResults- ? null- : noResultLabel+ const statusText = hasResults ? null : noResultLabelreturn (<Popover open={open} onOpenChange={handleOpenChange}>@@ -137,14 +133,16 @@ export default function AddMemberOrGroupDialog({<PopoverContentplacement="bottom-end"alignOffset={300}- className="relative flex max-h-100 w-100 flex-col overflow-hidden bg-components-panel-bg-blur p-0 backdrop-blur-[5px]"+ className="relative w-100 overflow-hidden bg-components-panel-bg-blur p-0 backdrop-blur-[5px]"+ onClick={(event) => event.stopPropagation()}><PopoverTitle className="sr-only">{searchLabel}</PopoverTitle>- <ScrollArea className="min-h-0 flex-1 overflow-hidden">+ <ScrollArea className="max-h-100 overflow-hidden"><ScrollAreaViewportref={scrollRootRef}role="region"aria-label={searchLabel}+ className="max-h-100 overscroll-contain"style={{ overflowX: 'hidden' }}><ScrollAreaContent style={{ minWidth: 0 }}>@@ -184,16 +182,15 @@ export default function AddMemberOrGroupDialog({aria-live="polite"aria-atomic="true"className={- statusText ? 'flex min-h-7 items-center justify-center px-2 py-0.5' : 'h-0'+ isLoading || statusText+ ? 'flex min-h-7 items-center justify-center px-2 py-0.5 system-sm-regular text-text-tertiary'+ : 'h-0'}>{isLoading ? (- <>- <span className="sr-only">{statusText}</span>- <div className="w-full" aria-hidden="true">- <Loading />- </div>- </>+ <div className="w-full" aria-hidden="true">+ <Loading />+ </div>) : (statusText)}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.tsxindex 4337890d40e..e151473db72 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@@ -4,10 +4,10 @@ import type { QueryClient } from '@tanstack/react-query'import {DeploymentOperationStatus,DeploymentOperationType,- DeploymentStatus,EnvironmentStatus,EnvVarValueType,OperatorType,+ RuntimeState,} from '@dify/contracts/enterprise-app-deploy/types.gen'import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -140,11 +140,11 @@ const latestVersion = {function createDeployment({deployed = true,latest = false,- status = DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState = RuntimeState.RUNTIME_STATE_RUNNING,}: {deployed?: booleanlatest?: boolean- status?: NonNullable<EnvironmentDeployment['deployment']>['status']+ runtimeState?: NonNullable<EnvironmentDeployment['deployment']>['runtimeState']} = {}): EnvironmentDeployment {const currentVersion = latest? {@@ -173,7 +173,7 @@ function createDeployment({id: 'user-1',type: OperatorType.OPERATOR_TYPE_ACCOUNT,},- status,+ runtimeState,versions_behind: latest ? 0 : 1,},environment: {@@ -219,7 +219,7 @@ function createFlowQueryClient(environmentId: string, environmentInUse = false)queryClient.setQueryDefaults(deploymentOptionsQuery.queryKey, { staleTime: Infinity })queryClient.setQueryData(deploymentOptionsQuery.queryKey, {credential_slots: [],- environment_variable_slots: [],+ environment_variable_groups: [],})})@@ -291,7 +291,12 @@ function renderFlow({canViewAccessPoint = true,isDeploymentError = false,- }: { canViewAccessPoint?: boolean; isDeploymentError?: boolean } = {},+ onConfigurationOpenChange = vi.fn(),+ }: {+ canViewAccessPoint?: boolean+ isDeploymentError?: boolean+ onConfigurationOpenChange?: (open: boolean) => void+ } = {},) {const queryClient = createFlowQueryClient(deployment.environment.id)@@ -307,6 +312,7 @@ function renderFlow(isDeploymentError={isDeploymentError}isDeploymentLoading={false}latestVersion={latestVersion}+ onConfigurationOpenChange={onConfigurationOpenChange}onGoToPublish={vi.fn()}/>,{ queryClient },@@ -461,11 +467,31 @@ async function expectDeploymentRequest()expect(await deployRequest.json()).toEqual({credentials: [],- environment_variables: [],+ environment_variable_groups: [],})}describe('PublisherEnvironmentFlow', () => {+ it('shows the shared loading state while deployment details load', () => {+ render(+ <PublisherEnvironmentFlow+ appId="app-1"+ canViewAccessPoint+ environmentId="development"+ environmentName="Development"+ environmentTabs={<div>Environment tabs</div>}+ isEnvironmentInUse={false}+ isDeploymentError={false}+ isDeploymentLoading+ latestVersion={null}+ onGoToPublish={vi.fn()}+ />,+ )++ expect(screen.getByText('Environment tabs')).toBeInTheDocument()+ expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()+ })+it('formats deployed_at as a Unix timestamp in seconds', () => {const deployment = createDeployment()const deployedAt = deployment.deployment?.deployed_at@@ -554,6 +580,7 @@ describe('PublisherEnvironmentFlow', () => {await user.click(screen.getByRole('button', { name: 'All versions' }))expect(screen.getByRole('heading', { name: 'Deploy to Staging' })).toBeInTheDocument()+ expect(screen.getByRole('region', { name: 'Deploy to Staging' })).toBeInTheDocument()await user.click(screen.getByRole('button', { name: 'Back' }))@@ -561,17 +588,12 @@ describe('PublisherEnvironmentFlow', () => {expect(screen.getByRole('button', { name: 'All versions' })).toBeInTheDocument()})- it.each([- DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,- DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYING,- ])(- 'disables deployment triggers but keeps environment navigation available while the status is %s',- (status) => {- renderFlow(createDeployment({ deployed: false, status }))-- const deployButtonName =- status === DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING ? 'Deploying...' : 'Deploy latest'- expect(screen.getByRole('button', { name: deployButtonName })).toBeDisabled()+ it.each([RuntimeState.RUNTIME_STATE_STARTING, RuntimeState.RUNTIME_STATE_STOPPING])(+ 'disables deployment triggers but keeps environment navigation available while the state is %s',+ (runtimeState) => {+ renderFlow(createDeployment({ deployed: false, runtimeState }))++ expect(screen.getByRole('button', { name: 'Deploy latest' })).toBeDisabled()expect(screen.getByRole('button', { name: 'All versions' })).toBeDisabled()expect(screen.getByRole('link', { name: 'Access Point' })).toHaveAttribute('href',@@ -596,7 +618,7 @@ describe('PublisherEnvironmentFlow', () => {it('keeps the deployment target and progress controls when a deploying status refresh fails', () => {const deployment = createDeployment({- status: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,})deployment.deployment!.latest_operation = {activity_at: 1_785_456_000,@@ -638,16 +660,16 @@ describe('PublisherEnvironmentFlow', () => {expect(screen.queryByRole('alert')).not.toBeInTheDocument()})- it.each([- DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYED,- DeploymentStatus.DEPLOYMENT_STATUS_FAILED,- ])('shows the undeployed state when terminal status %s has no current version', (status) => {- renderFlow(createDeployment({ deployed: false, status }))+ it.each([RuntimeState.RUNTIME_STATE_UNDEPLOYED, RuntimeState.RUNTIME_STATE_ERROR])(+ 'shows the undeployed state when terminal state %s has no current version',+ (runtimeState) => {+ renderFlow(createDeployment({ deployed: false, runtimeState }))- expect(screen.getByText('Not deployed yet')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Deploy latest' })).toBeEnabled()- expect(screen.getByRole('button', { name: 'All versions' })).toBeEnabled()- })+ expect(screen.getByText('Not deployed yet')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Deploy latest' })).toBeEnabled()+ expect(screen.getByRole('button', { name: 'All versions' })).toBeEnabled()+ },+ )it('deploys the latest version directly and goes back to version selection', async () => {const user = userEvent.setup()@@ -663,6 +685,29 @@ describe('PublisherEnvironmentFlow', () => {expect(screen.getByRole('heading', { name: 'Deploy to Staging' })).toBeInTheDocument()})+ it('reports whether deployment configuration is active', async () => {+ const user = userEvent.setup()+ const onConfigurationOpenChange = vi.fn()+ const view = renderFlow(createDeployment(), { onConfigurationOpenChange })++ await user.click(screen.getByRole('button', { name: 'Deploy latest' }))+ expect(onConfigurationOpenChange).toHaveBeenLastCalledWith(true)++ await user.click(screen.getByRole('button', { name: 'Back' }))+ expect(onConfigurationOpenChange).toHaveBeenLastCalledWith(false)++ await user.click(screen.getByRole('button', { name: /Release 6/ }))+ expect(onConfigurationOpenChange).toHaveBeenLastCalledWith(true)++ await user.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(onConfigurationOpenChange).toHaveBeenLastCalledWith(false)++ await user.click(screen.getByRole('button', { name: 'Deploy latest' }))+ expect(onConfigurationOpenChange).toHaveBeenLastCalledWith(true)+ view.unmount()+ expect(onConfigurationOpenChange).toHaveBeenLastCalledWith(false)+ })+it('hides the environment variables section when deployment options have no slots', async () => {const user = userEvent.setup()renderFlow()@@ -691,14 +736,26 @@ describe('PublisherEnvironmentFlow', () => {)view.queryClient.setQueryData(deploymentOptionsQuery.queryKey, {credential_slots: [],- environment_variable_slots: [+ environment_variable_groups: [{- configured_value: 'production',- description: '',- has_configured_value: true,- has_last_deployed_value: false,- key: 'ENVIRONMENT',- value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING,+ environment_variable_slots: [+ {+ configured_value: 'production',+ description: '',+ has_configured_value: true,+ has_last_deployed_value: false,+ key: 'ENVIRONMENT',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING,+ },+ ],+ from_app: {+ app_id: 'app-1',+ icon: '💰',+ icon_background: '#FDF2FA',+ icon_type: 'emoji',+ name: 'Finance APP',+ workflow_id: latestVersion.id,+ },},],})diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsxindex d318a19802f..bb9766c54fd 100644--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx@@ -1,8 +1,5 @@/* oxlint-disable typescript/no-explicit-any */-import {- DeploymentStatus,- EnvironmentStatus,-} from '@dify/contracts/enterprise-app-deploy/types.gen'+import { EnvironmentStatus, RuntimeState } from '@dify/contracts/enterprise-app-deploy/types.gen'import { act, fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'@@ -458,6 +455,8 @@ describe('AppPublisher', () => {expect(mockUpdateWorkflow).toHaveBeenCalledWith({+ appId: 'app-1',+ appMode: AppModeEnum.WORKFLOW,url: '/apps/app-1/workflows/workflow-version-5',title: 'Release 6',releaseNotes: 'Updated notes',@@ -726,7 +725,7 @@ describe('AppPublisher', () => {marked_name: 'Release 5',version: 'v5',},- status: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,},environment: {description: '',diff --git a/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx b/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsxnew file mode 100644index 00000000000..5f3a9d7ffd5--- /dev/null+++ b/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx@@ -0,0 +1,118 @@+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { useState } from 'react'+import { PublisherPanel } from '../publisher-content/publisher-panel'++vi.mock('../environment-deployment-flow', () => ({+ PublisherEnvironmentFlow: ({+ onConfigurationOpenChange,+ }: {+ onConfigurationOpenChange?: (open: boolean) => void+ }) => (+ <div>+ Environment publisher+ <button type="button" onClick={() => onConfigurationOpenChange?.(true)}>+ Configure deployment+ </button>+ </div>+ ),+}))++function PublisherPanelHarness() {+ const [open, setOpen] = useState(true)++ return (+ <>+ <button type="button">Outside control</button>+ <PublisherPanel+ builtInPublisher={{+ actions: {+ appDetail: null,+ appURL: '',+ canViewAccessPoint: false,+ disabledFunctionButton: false,+ workflowToolIsLoading: false,+ onConfigureWorkflowTool: vi.fn(),+ },+ summary: {+ formatTimeFromNow: () => '',+ handlePublish: vi.fn(),+ handleRestore: vi.fn(),+ isChatApp: false,+ published: false,+ upgradeHighlightStyle: {},+ },+ }}+ environmentPublisher={{+ appId: 'app-1',+ canViewAccessPoint: false,+ environmentId: 'staging',+ environmentName: 'Staging',+ environmentTabs: null,+ isEnvironmentInUse: true,+ isDeploymentError: false,+ isDeploymentLoading: false,+ onGoToPublish: vi.fn(),+ }}+ environmentPublisherKey="staging"+ open={open}+ showBuiltInPublisher={false}+ workflowLaunch={{+ hiddenVariables: [],+ open: false,+ targetUrl: '',+ onOpenChange: vi.fn(),+ }}+ onOpenChange={setOpen}+ />+ </>+ )+}++describe('PublisherPanel', () => {+ it('keeps the publisher open after an outside press when dismissal is prevented', async () => {+ const user = userEvent.setup()+ render(<PublisherPanelHarness />)++ await user.click(screen.getByRole('button', { name: 'Configure deployment' }))++ await user.click(screen.getByRole('button', { name: 'Outside control' }))++ expect(screen.getByText('Environment publisher')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /common\.publish/ })).toHaveAttribute(+ 'aria-expanded',+ 'true',+ )+ })++ it('keeps the default outside-press dismissal outside deployment configuration', async () => {+ const user = userEvent.setup()+ render(<PublisherPanelHarness />)++ await user.click(screen.getByRole('button', { name: 'Outside control' }))++ expect(screen.queryByText('Environment publisher')).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: /common\.publish/ })).toHaveAttribute(+ 'aria-expanded',+ 'false',+ )+ })++ it('still closes from the trigger and Escape when outside dismissal is prevented', async () => {+ const user = userEvent.setup()+ render(<PublisherPanelHarness />)+ const publishButton = screen.getByRole('button', { name: /common\.publish/ })++ await user.click(screen.getByRole('button', { name: 'Configure deployment' }))+ await user.click(publishButton)+ expect(screen.queryByText('Environment publisher')).not.toBeInTheDocument()++ await user.click(publishButton)+ expect(screen.getByText('Environment publisher')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Configure deployment' }))++ await user.keyboard('{Escape}')++ expect(screen.queryByText('Environment publisher')).not.toBeInTheDocument()+ })+})diff --git a/web/app/components/app/app-publisher/__tests__/state.spec.tsx b/web/app/components/app/app-publisher/__tests__/state.spec.tsxindex 5cdba042d59..624205f869a 100644--- a/web/app/components/app/app-publisher/__tests__/state.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/state.spec.tsx@@ -1,6 +1,6 @@import {DeploymentOperationStatus,- DeploymentStatus,+ RuntimeState,} from '@dify/contracts/enterprise-app-deploy/types.gen'import { QueryClientProvider } from '@tanstack/react-query'import { screen, render as testingLibraryRender, waitFor } from '@testing-library/react'@@ -32,7 +32,7 @@ type QueryOptions = {id: stringstatus: string}- status: string+ runtimeState: string}}}@@ -204,11 +204,11 @@ function renderState(initialOpen = true) {}function environmentDeploymentResponse({- deploymentStatus,+ runtimeState,operationId,operationStatus,}: {- deploymentStatus: string+ runtimeState: stringoperationId: stringoperationStatus: string}) {@@ -220,7 +220,7 @@ function environmentDeploymentResponse({},deployment: {current_version:- deploymentStatus === DeploymentStatus.DEPLOYMENT_STATUS_RUNNING+ runtimeState === RuntimeState.RUNTIME_STATE_RUNNING? {id: 'version-development',marked_comment: '',@@ -239,7 +239,7 @@ function environmentDeploymentResponse({status: operationStatus,type: 'DEPLOYMENT_OPERATION_TYPE_DEPLOY',},- status: deploymentStatus,+ runtimeState,},environment: {description: '',@@ -316,7 +316,7 @@ describe('app publisher environment state', () => {marked_name: `Release ${input.params.environment_id}`,version: `2026-07-31.${input.params.environment_id}`,},- status: 'DEPLOYMENT_STATUS_RUNNING',+ runtimeState: 'RUNTIME_STATE_RUNNING',},environment: {description: '',@@ -361,7 +361,7 @@ describe('app publisher environment state', () => {it('discovers and resumes polling a first deployment while the environment remains not in use', async () => {const user = userEvent.setup()const response = environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,operationId: 'operation-development',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,})@@ -394,7 +394,7 @@ describe('app publisher environment state', () => {it('stops automatic status polling while the deployment query is failing', async () => {const user = userEvent.setup()const response = environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,operationId: 'operation-staging',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,})@@ -465,7 +465,7 @@ describe('app publisher environment state', () => {.mockResolvedValue(appEnvironments(true))queryMocks.deploymentRequest.mockResolvedValue(environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,operationId: 'operation-development',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_SUCCEEDED,}),@@ -497,7 +497,7 @@ describe('app publisher environment state', () => {deploymentQueryOptions?.refetchInterval?.({state: {data: environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,operationId: 'operation-development',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,}),@@ -508,7 +508,7 @@ describe('app publisher environment state', () => {deploymentQueryOptions?.refetchInterval?.({state: {data: environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,operationId: 'operation-development',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_SUCCEEDED,}),@@ -525,12 +525,12 @@ describe('app publisher environment state', () => {async (input: { params: { environment_id: string } }) =>input.params.environment_id === 'staging'? environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,operationId: 'operation-staging',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,}): environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,operationId: 'operation-development',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_SUCCEEDED,}),@@ -551,7 +551,7 @@ describe('app publisher environment state', () => {getDeploymentQueryOptions('staging')?.refetchInterval?.({state: {data: environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,operationId: 'operation-staging',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,}),@@ -577,7 +577,7 @@ describe('app publisher environment state', () => {getDeploymentQueryOptions('development')?.refetchInterval?.({state: {data: environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,operationId: 'operation-development',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_SUCCEEDED,}),@@ -608,7 +608,7 @@ describe('app publisher environment state', () => {queryMocks.environmentRequest.mockResolvedValue(appEnvironments(true))queryMocks.deploymentRequest.mockResolvedValue(environmentDeploymentResponse({- deploymentStatus: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,operationId: 'operation-staging',operationStatus: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,}),diff --git a/web/app/components/app/app-publisher/environment-deployment-flow/index.tsx b/web/app/components/app/app-publisher/environment-deployment-flow/index.tsxindex 995f412b27d..4916eb37320 100644--- a/web/app/components/app/app-publisher/environment-deployment-flow/index.tsx+++ b/web/app/components/app/app-publisher/environment-deployment-flow/index.tsx@@ -2,10 +2,11 @@import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { ReactNode } from 'react'-import type { DeploymentVersion } from '@/app/components/app/deploy/version'+import type { DeploymentVersion } from '@/app/components/app/deploy/utils/version'import { useAtomValue, useSetAtom } from 'jotai'import { useTranslation } from 'react-i18next'-import { EnvironmentDeploymentFlow } from '@/app/components/app/deploy/environment-deployment-flow'+import { EnvironmentDeploymentFlow } from '@/app/components/app/deploy/shared/environment-deployment-flow'+import Loading from '@/app/components/base/loading'import {publisherEnvironmentDeploymentPollingAtom,startPublisherEnvironmentDeploymentPollingAtom,@@ -24,6 +25,7 @@ type PublisherEnvironmentFlowProps = {isDeploymentError: booleanisDeploymentLoading: booleanlatestVersion?: DeploymentVersion | null+ onConfigurationOpenChange?: (open: boolean) => voidonGoToPublish: () => void}@@ -38,6 +40,7 @@ export function PublisherEnvironmentFlow({isDeploymentError,isDeploymentLoading,latestVersion,+ onConfigurationOpenChange,onGoToPublish,}: PublisherEnvironmentFlowProps) {const { t } = useTranslation()@@ -48,19 +51,16 @@ export function PublisherEnvironmentFlow({return (<div aria-busy={isDeploymentLoading} className="flex min-h-40 flex-col gap-3 p-4">{environmentTabs}- <div- role={isDeploymentError ? 'alert' : 'status'}- className="flex flex-1 items-center justify-center gap-2 system-sm-regular text-text-tertiary"- >- {isDeploymentLoading ? (- <>- <span aria-hidden className="i-ri-loader-2-line size-4 animate-spin" />- {t(($) => $.loading, { ns: 'common' })}- </>- ) : (- t(($) => $['common.loadFailed'], { ns: 'deployments' })- )}- </div>+ {isDeploymentLoading ? (+ <Loading className="flex-1" />+ ) : (+ <div+ role="alert"+ className="flex flex-1 items-center justify-center system-sm-regular text-text-tertiary"+ >+ {t(($) => $['common.loadFailed'], { ns: 'deployments' })}+ </div>+ )}</div>)}@@ -72,6 +72,7 @@ export function PublisherEnvironmentFlow({disabled={deploymentPolling?.environmentId === environmentId}environmentId={environmentId}environmentName={environmentName}+ onConfigurationOpenChange={onConfigurationOpenChange}onDeploymentStarted={(operationId) => {startDeploymentPolling({ environmentId, operationId })}}diff --git a/web/app/components/app/app-publisher/environment-deployment-flow/latest-version-row.tsx b/web/app/components/app/app-publisher/environment-deployment-flow/latest-version-row.tsxindex e8d8c8f9e36..cd2e7580353 100644--- a/web/app/components/app/app-publisher/environment-deployment-flow/latest-version-row.tsx+++ b/web/app/components/app/app-publisher/environment-deployment-flow/latest-version-row.tsx@@ -1,4 +1,4 @@-import type { DeploymentVersion } from '@/app/components/app/deploy/version'+import type { DeploymentVersion } from '@/app/components/app/deploy/utils/version'import { cn } from '@langgenius/dify-ui/cn'import { useTranslation } from 'react-i18next'import { PublisherDeployingMarker } from '../publisher-deploying-marker'diff --git a/web/app/components/app/app-publisher/environment-deployment-flow/summary-section.tsx b/web/app/components/app/app-publisher/environment-deployment-flow/summary-section.tsxindex 051d2d8f5e3..8d7685a69eb 100644--- a/web/app/components/app/app-publisher/environment-deployment-flow/summary-section.tsx+++ b/web/app/components/app/app-publisher/environment-deployment-flow/summary-section.tsx@@ -1,7 +1,10 @@import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { ReactNode } from 'react'-import type { DeploymentVersion } from '@/app/components/app/deploy/version'-import { DeploymentStatus } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { DeploymentVersion } from '@/app/components/app/deploy/utils/version'+import {+ DeploymentOperationStatus,+ DeploymentOperationType,+} from '@dify/contracts/enterprise-app-deploy/types.gen'import { Button } from '@langgenius/dify-ui/button'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useTranslation } from 'react-i18next'@@ -35,8 +38,11 @@ export function PublisherEnvironmentSummarySection({const { formatTimeFromNow } = useFormatTimeFromNow()const deploymentState = deployment?.deploymentconst deployedVersion = deploymentState?.current_version- const isDeploying = deploymentState?.status === DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING- const deployingVersion = deploymentState?.latest_operation?.target_version+ const latestOperation = deploymentState?.latest_operation+ const isDeploying =+ latestOperation?.type === DeploymentOperationType.DEPLOYMENT_OPERATION_TYPE_DEPLOY &&+ latestOperation.status === DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS+ const deployingVersion = latestOperation?.target_versionconst deployingVersionName = deployingVersion? getWorkflowVersionName(deployingVersion,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.tsindex 64f0a45db2e..de262d0263d 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@@ -4,7 +4,7 @@ import { DeploymentOperationStatus } from '@dify/contracts/enterprise-app-deployimport { useQueryClient } from '@tanstack/react-query'import { useAtomValue, useSetAtom } from 'jotai'import { useEffect, useRef } from 'react'-import { isEnvironmentDeploymentInProgress } from '@/app/components/app/deploy/state'+import { shouldPollEnvironmentDeployment } from '@/app/components/app/deploy/utils/environment-deployment'import { consoleQuery } from '@/service/client'import {appPublisherOpenAtom,@@ -44,7 +44,7 @@ export function useRefreshAppEnvironmentsAfterPublisherDeploymentPolling(appId?:polling.environmentId !== environment.id ||operation?.id !== polling.operationId ||!isDeploymentOperationTerminal(operation.status) ||- isEnvironmentDeploymentInProgress(deployment)+ shouldPollEnvironmentDeployment(deployment))return@@ -72,7 +72,7 @@ export function useRefreshAppEnvironmentsAfterPublisherDeploymentPolling(appId?:return}- if (isEnvironmentDeploymentInProgress(deployment)) {+ if (shouldPollEnvironmentDeployment(deployment)) {if (operationKey) operationsNeedingEnvironmentRefreshRef.current.add(operationKey)return}diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsxindex 465e22a4500..49d626233ed 100644--- a/web/app/components/app/app-publisher/index.tsx+++ b/web/app/components/app/app-publisher/index.tsx@@ -22,7 +22,9 @@ export function AppPublisher(props: AppPublisherProps) {resourceMaintainer: appDetail?.maintainer,workspacePermissionKeys,})- const supportsMultiEnvironment = appDetail?.mode === AppModeEnum.WORKFLOW && canDeploy+ const supportsMultiEnvironment =+ (appDetail?.mode === AppModeEnum.WORKFLOW || appDetail?.mode === AppModeEnum.ADVANCED_CHAT) &&+ canDeployreturn (<AppPublisherStateBoundarydiff --git a/web/app/components/app/app-publisher/publisher-content/index.tsx b/web/app/components/app/app-publisher/publisher-content/index.tsxindex bf6fd7cbb22..82641a214cc 100644--- a/web/app/components/app/app-publisher/publisher-content/index.tsx+++ b/web/app/components/app/app-publisher/publisher-content/index.tsx@@ -2,7 +2,7 @@ import type { AppPublisherProps } from '../types'import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue, useSetAtom } from 'jotai'import { useTranslation } from 'react-i18next'-import { toDeploymentVersion } from '@/app/components/app/deploy/version'+import { toDeploymentVersion } from '@/app/components/app/deploy/utils/version'import { useStore as useAppStore } from '@/app/components/app/store'import { WorkflowToolDrawer } from '@/app/components/tools/workflow-tool'import { systemFeaturesQueryOptions } from '@/features/system-features/client'@@ -115,6 +115,7 @@ export function PublisherContent({const marketplace = useMarketplacePublish(appDetail?.id)const versionInfo = useVersionInfo({appId: appDetail?.id,+ appMode: appDetail?.mode,publishedWorkflow: publish.publishedWorkflow,onClosePublisher: closePublisher,})diff --git a/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsx b/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsxindex e106fee9c28..98e199a1dc7 100644--- a/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsx+++ b/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsx@@ -1,7 +1,9 @@+import type { PopoverProps } from '@langgenius/dify-ui/popover'import type { ComponentProps } from 'react'import type { AppPublisherProps } from '../../types'import { Button } from '@langgenius/dify-ui/button'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'+import { useState } from 'react'import { useTranslation } from 'react-i18next'import { WorkflowLaunchDialog } from '@/app/components/app/overview/workflow-launch-dialog'import { BuiltInPublisher } from '../../built-in-publisher'@@ -9,7 +11,10 @@ import { PublisherEnvironmentFlow } from '../../environment-deployment-flow'type PublisherPanelProps = Pick<AppPublisherProps, 'crossAxisOffset' | 'disabled'> & {builtInPublisher: ComponentProps<typeof BuiltInPublisher>- environmentPublisher: ComponentProps<typeof PublisherEnvironmentFlow>+ environmentPublisher: Omit<+ ComponentProps<typeof PublisherEnvironmentFlow>,+ 'onConfigurationOpenChange'+ >environmentPublisherKey: stringopen: booleanshowBuiltInPublisher: boolean@@ -29,9 +34,21 @@ export function PublisherPanel({workflowLaunch,}: PublisherPanelProps) {const { t } = useTranslation()+ const [deploymentConfigurationOpen, setDeploymentConfigurationOpen] = useState(false)+ const handleOpenChange: NonNullable<PopoverProps['onOpenChange']> = (nextOpen, eventDetails) => {+ const isOutsideDismiss =+ eventDetails.reason === 'outside-press' || eventDetails.reason === 'focus-out'+ if (!nextOpen && deploymentConfigurationOpen && isOutsideDismiss) {+ eventDetails.cancel()+ return+ }++ if (!nextOpen) setDeploymentConfigurationOpen(false)+ onOpenChange(nextOpen)+ }return (- <Popover open={open} onOpenChange={onOpenChange}>+ <Popover open={open} onOpenChange={handleOpenChange}><PopoverTriggerrender={<Button variant="primary" className="py-2 pr-2 pl-3" disabled={disabled}>@@ -50,7 +67,11 @@ export function PublisherPanel({{showBuiltInPublisher ? (<BuiltInPublisher {...builtInPublisher} />) : (- <PublisherEnvironmentFlow key={environmentPublisherKey} {...environmentPublisher} />+ <PublisherEnvironmentFlow+ key={environmentPublisherKey}+ {...environmentPublisher}+ onConfigurationOpenChange={setDeploymentConfigurationOpen}+ />)}</div></PopoverContent>diff --git a/web/app/components/app/app-publisher/publisher-content/use-version-info.ts b/web/app/components/app/app-publisher/publisher-content/use-version-info.tsindex a9a23b42d9a..25f2ee00cba 100644--- a/web/app/components/app/app-publisher/publisher-content/use-version-info.ts+++ b/web/app/components/app/app-publisher/publisher-content/use-version-info.ts@@ -1,4 +1,5 @@import type { WorkflowResponse } from '@dify/contracts/api/console/apps/types.gen'+import type { AppModeEnum } from '@/types/app'import { toast } from '@langgenius/dify-ui/toast'import { useState } from 'react'import { useTranslation } from 'react-i18next'@@ -12,10 +13,12 @@ type VersionInfoUpdate = {export function useVersionInfo({appId,+ appMode,publishedWorkflow,onClosePublisher,}: {appId?: string+ appMode?: AppModeEnumpublishedWorkflow?: WorkflowResponse | nullonClosePublisher: () => void}) {@@ -36,6 +39,8 @@ export function useVersionInfo({updateWorkflow({+ appId,+ appMode,url: `/apps/${appId}/workflows/${params.id}`,title: params.title,releaseNotes: params.releaseNotes,diff --git a/web/app/components/app/app-publisher/state.ts b/web/app/components/app/app-publisher/state.tsindex bf8937f705d..87bbf47eb44 100644--- a/web/app/components/app/app-publisher/state.ts+++ b/web/app/components/app/app-publisher/state.ts@@ -6,7 +6,7 @@ import { skipToken } from '@tanstack/react-query'import { atom } from 'jotai'import { atomWithQuery } from 'jotai-tanstack-query'import { selectAtom, useHydrateAtoms } from 'jotai/utils'-import { isEnvironmentDeploymentInProgress } from '@/app/components/app/deploy/state'+import { shouldPollEnvironmentDeployment } from '@/app/components/app/deploy/utils/environment-deployment'import { consoleQuery } from '@/service/client'export const BUILT_IN_ENVIRONMENT_ID = 'built-in'@@ -316,7 +316,7 @@ const selectedEnvironmentDeploymentQueryAtom = atomWithQuery((get) => {const deployment = query.state.data?.environment_deploymentif (polling?.environmentId !== environmentId)- return isEnvironmentDeploymentInProgress(deployment)+ return shouldPollEnvironmentDeployment(deployment)? PUBLISHER_DEPLOYMENT_POLLING_INTERVAL: false@@ -324,7 +324,7 @@ const selectedEnvironmentDeploymentQueryAtom = atomWithQuery((get) => {const operationFinished =operation?.id === polling.operationId && isDeploymentOperationTerminal(operation.status)- return operationFinished && !isEnvironmentDeploymentInProgress(deployment)+ return operationFinished && !shouldPollEnvironmentDeployment(deployment)? false: PUBLISHER_DEPLOYMENT_POLLING_INTERVAL},diff --git a/web/app/components/app/deploy/__tests__/index.spec.tsx b/web/app/components/app/deploy/__tests__/index.spec.tsxindex 1f1c8f77862..9a60a3b97b3 100644--- a/web/app/components/app/deploy/__tests__/index.spec.tsx+++ b/web/app/components/app/deploy/__tests__/index.spec.tsx@@ -4,19 +4,20 @@ import type {EnvironmentDeployment,EnvironmentDeploymentOperation,GetWorkflowDeploymentOptionsResponse,+ WorkflowReference,WorkflowVersion,} from '@dify/contracts/enterprise-app-deploy/types.gen'import type { QueryClient } from '@tanstack/react-query'-import type { ReactElement } from 'react'+import type { ComponentProps, ReactElement } from 'react'import {DeploymentOperationStatus,DeploymentOperationType,- DeploymentStatus,EnvironmentStatus,EnvVarValueSource,EnvVarValueType,OperatorType,PluginCategory,+ RuntimeState,} from '@dify/contracts/enterprise-app-deploy/types.gen'import { toast } from '@langgenius/dify-ui/toast'import { act, screen, waitFor, within } from '@testing-library/react'@@ -30,7 +31,12 @@ import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/consoleimport { AppACLPermission } from '@/utils/permission'import AppDeploy from '..'import { EnvironmentTable } from '../environment-table'-import { AppDeployStateBoundary, getEnvironmentDeploymentActions } from '../state'+import { RuntimeStateIndicator } from '../shared/runtime-state'+import { AppDeployStateBoundary } from '../state'+import {+ getEnvironmentDeploymentActions,+ shouldPollEnvironmentDeployment,+} from '../utils/environment-deployment'const APP_ID = 'app-1'const ACTIVITY_AT = 1_784_941_200@@ -115,6 +121,24 @@ const SUCCESSFUL_WORKFLOW_DEPLOYMENT_PRECHECK = {unsupported_nodes: [],}+const ROOT_WORKFLOW_REFERENCE: WorkflowReference = {+ app_id: APP_ID,+ icon: '💰',+ icon_background: '#FDF2FA',+ icon_type: 'emoji',+ name: 'Finance APP',+ workflow_id: 'workflow-version-6',+}++const SUBWORKFLOW_REFERENCE: WorkflowReference = {+ app_id: 'app-workflow-tool',+ icon: '🐍',+ icon_background: '#F3FEE7',+ icon_type: 'emoji',+ name: 'Workflow as Tool',+ workflow_id: 'workflow-tool',+}+const WORKFLOW_DEPLOYMENT_OPTIONS: GetWorkflowDeploymentOptionsResponse = {credential_slots: [{@@ -151,32 +175,64 @@ const WORKFLOW_DEPLOYMENT_OPTIONS: GetWorkflowDeploymentOptionsResponse = {category: PluginCategory.PLUGIN_CATEGORY_TOOL,last_deployed_credential_id: 'github-oauth',provider_id: 'github',+ workflow_as_tool_dependency: {+ paths: [{ workflows: [ROOT_WORKFLOW_REFERENCE, SUBWORKFLOW_REFERENCE] }],+ },},],- environment_variable_slots: [- {- configured_value: '2',- description: 'Server port',- has_configured_value: true,- has_last_deployed_value: true,- key: 'PORT',- value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER,- },+ environment_variable_groups: [{- configured_value: 'sk-123************bc',- description: 'API credential',- has_configured_value: true,- has_last_deployed_value: true,- key: 'API_KEY',- value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET,+ environment_variable_slots: [+ {+ configured_value: 2,+ description: 'Server port',+ has_configured_value: true,+ has_last_deployed_value: true,+ key: 'PORT',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER,+ },+ {+ configured_value: 'sk-123************bc',+ description: 'API credential',+ has_configured_value: true,+ has_last_deployed_value: true,+ key: 'API_KEY',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET,+ },+ {+ description: '',+ has_configured_value: false,+ has_last_deployed_value: true,+ key: 'name',+ last_deployed_value: 'environment variable 01',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING,+ },+ ],+ from_app: ROOT_WORKFLOW_REFERENCE,},{- description: '',- has_configured_value: false,- has_last_deployed_value: true,- key: 'name',- last_deployed_value: 'environment variable 01',- value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING,+ environment_variable_slots: [+ {+ configured_value: 8080,+ description: 'Workflow tool port',+ has_configured_value: true,+ has_last_deployed_value: false,+ key: 'PORT',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER,+ },+ {+ configured_value: 'sk-child********bc',+ description: 'Workflow tool API credential',+ has_configured_value: true,+ has_last_deployed_value: false,+ key: 'API_KEY',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET,+ },+ ],+ from_workflow_as_tool: {+ paths: [{ workflows: [ROOT_WORKFLOW_REFERENCE, SUBWORKFLOW_REFERENCE] }],+ workflow: SUBWORKFLOW_REFERENCE,+ },},],}@@ -208,7 +264,7 @@ function environmentDeployment({id,latestOperation,name,- status,+ runtimeState,versionsBehind,}: {access?: EnvironmentDeployment['access']@@ -216,7 +272,7 @@ function environmentDeployment({id: stringlatestOperation?: EnvironmentDeploymentOperationname: string- status: NonNullable<EnvironmentDeployment['deployment']>['status']+ runtimeState: NonNullable<EnvironmentDeployment['deployment']>['runtimeState']versionsBehind?: number}): EnvironmentDeployment {return {@@ -226,7 +282,7 @@ function environmentDeployment({deployed_at: currentVersion ? ACTIVITY_AT : undefined,deployed_by: currentVersion ? OPERATOR : undefined,latest_operation: latestOperation,- status,+ runtimeState,versions_behind: versionsBehind,},environment: {@@ -247,7 +303,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.sprint42,}),name: 'Staging',- status: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,}),environmentDeployment({currentVersion: VERSIONS.sprint42,@@ -257,7 +313,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.sprint42,}),name: 'Canary',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 0,}),environmentDeployment({@@ -268,7 +324,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.version02,}),name: 'Pre-release',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 1,}),environmentDeployment({@@ -279,7 +335,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.hotfix,}),name: 'Prod',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 1,}),environmentDeployment({@@ -292,7 +348,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.sprint42,}),name: 'EU-Prod',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 2,}),environmentDeployment({@@ -304,7 +360,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.qa,}),name: 'QA',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 0,}),environmentDeployment({@@ -316,7 +372,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.qa,}),name: 'Sandbox',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 0,}),environmentDeployment({@@ -328,7 +384,7 @@ const APP_ENVIRONMENT_DEPLOYMENTS: EnvironmentDeployment[] = [targetVersion: VERSIONS.sprint42,}),name: 'Preview',- status: DeploymentStatus.DEPLOYMENT_STATUS_FAILED,+ runtimeState: RuntimeState.RUNTIME_STATE_UNDEPLOYED,}),]@@ -367,7 +423,7 @@ const ACTION_MATRIX_CASES: Array<{currentVersion: VERSIONS.sprint42,id: 'latest',name: 'Latest',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 0,}),},@@ -383,7 +439,7 @@ const ACTION_MATRIX_CASES: Array<{currentVersion: VERSIONS.version02,id: 'behind',name: 'Behind',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 1,}),},@@ -393,11 +449,17 @@ const ACTION_MATRIX_CASES: Array<{{ disabled: true, kind: 'redeploy' },{ disabled: true, kind: 'undeploy' },],- name: 'deploying',+ name: 'upgrading while the current version keeps running',row: environmentDeployment({+ currentVersion: VERSIONS.beta,id: 'deploying',+ latestOperation: deploymentOperation({+ id: 'deploying',+ status: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,+ targetVersion: VERSIONS.sprint42,+ }),name: 'Deploying',- status: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,}),},{@@ -410,8 +472,13 @@ const ACTION_MATRIX_CASES: Array<{row: environmentDeployment({currentVersion: VERSIONS.qa,id: 'undeploying',+ latestOperation: deploymentOperation({+ id: 'undeploying',+ status: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS,+ type: DeploymentOperationType.DEPLOYMENT_OPERATION_TYPE_UNDEPLOY,+ }),name: 'Undeploying',- status: DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STOPPING,}),},{@@ -428,7 +495,7 @@ const ACTION_MATRIX_CASES: Array<{targetVersion: VERSIONS.sprint42,}),name: 'Failed',- status: DeploymentStatus.DEPLOYMENT_STATUS_FAILED,+ runtimeState: RuntimeState.RUNTIME_STATE_UNDEPLOYED,}),},{@@ -447,7 +514,7 @@ const ACTION_MATRIX_CASES: Array<{targetVersion: VERSIONS.sprint42,}),name: 'Running failed',- status: DeploymentStatus.DEPLOYMENT_STATUS_RUNNING,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,versionsBehind: 2,}),},@@ -461,7 +528,16 @@ const ACTION_MATRIX_CASES: Array<{currentVersion: VERSIONS.qa,id: 'invalid',name: 'Invalid',- status: DeploymentStatus.DEPLOYMENT_STATUS_INVALID,+ runtimeState: RuntimeState.RUNTIME_STATE_ERROR,+ }),+ },+ {+ actions: [{ disabled: false, kind: 'changeVersion' }],+ name: 'invalid without a current version',+ row: environmentDeployment({+ id: 'invalid-without-version',+ name: 'Invalid without version',+ runtimeState: RuntimeState.RUNTIME_STATE_ERROR,}),},{@@ -474,7 +550,7 @@ const ACTION_MATRIX_CASES: Array<{currentVersion: VERSIONS.qa,id: 'unknown',name: 'Unknown',- status: DeploymentStatus.DEPLOYMENT_STATUS_UNSPECIFIED,+ runtimeState: RuntimeState.RUNTIME_STATE_UNKNOWN,}),},]@@ -611,10 +687,14 @@ function render(appEnvironments = APP_ENVIRONMENTS,environmentDeployments = APP_ENVIRONMENT_DEPLOYMENTS,publishedWorkflowVersions = PUBLISHED_WORKFLOW_VERSIONS,+ seedAppEnvironments = true,+ seedLatestPublishedWorkflow = true,}: {appEnvironments?: AppEnvironment[]environmentDeployments?: EnvironmentDeployment[]publishedWorkflowVersions?: WorkflowResponse[]+ seedAppEnvironments?: boolean+ seedLatestPublishedWorkflow?: boolean} = {},) {const queryClient = createConsoleQueryClient()@@ -624,16 +704,20 @@ function render(queryClient.setQueryDefaults(appEnvironmentDeploymentsQueryOptions.queryKey, {staleTime: Infinity,})- queryClient.setQueryData(appEnvironmentsQueryOptions.queryKey, {- data: appEnvironments,- })+ if (seedAppEnvironments) {+ queryClient.setQueryData(appEnvironmentsQueryOptions.queryKey, {+ data: appEnvironments,+ })+ }queryClient.setQueryData(appEnvironmentDeploymentsQueryOptions.queryKey, {environment_deployments: environmentDeployments,})- queryClient.setQueryData(- latestPublishedWorkflowQuery.queryKey,- mockBuiltInEnvironment.publishedWorkflow,- )+ if (seedLatestPublishedWorkflow) {+ queryClient.setQueryData(+ latestPublishedWorkflowQuery.queryKey,+ mockBuiltInEnvironment.publishedWorkflow,+ )+ }queryClient.setQueryData(appWorkflowVersionsQuery.queryKey, {pageParams: [1],pages: [@@ -650,12 +734,32 @@ function render(return renderWithConsoleQuery(ui, { queryClient })}+function environmentTableProps(+ overrides: Partial<ComponentProps<typeof EnvironmentTable>> = {},+): ComponentProps<typeof EnvironmentTable> {+ return {+ appId: APP_ID,+ canViewAccessPoint: true,+ onChangeVersion: vi.fn(),+ onDeployLatest: vi.fn(),+ onDeployToEnvironment: vi.fn(),+ onRedeploy: vi.fn(),+ onUndeploy: vi.fn(),+ ...overrides,+ }+}+let appPermissionKeys: string[] = [AppACLPermission.AccessPointView, AppACLPermission.Deploy]let appDetailAvailable = trueconst mockConsoleState = vi.hoisted(() => ({workspacePermissionKeys: [] as string[],}))-const mockDocLink = vi.hoisted(() => vi.fn((path: string) => `https://docs.example.com${path}`))+const mockGetEnterpriseDocUrl = vi.hoisted(() =>+ vi.fn(+ (path: string, docLanguage: string) =>+ `https://enterprise-docs.example.com/${docLanguage}${path}`,+ ),+)vi.mock('react-i18next', async () => {const { createReactI18nextMock } = await import('@/test/i18n-mock')@@ -666,14 +770,23 @@ vi.mock('react-i18next', async () => {'deployments.studio.undeployConfirmDesc':'The app will stop running in this environment, and all of its access points will become unavailable.','deployments.studio.undeployConfirmTitle': 'Undeploy {{versionName}} from {{envName}}',+ 'deployments.status.RUNTIME_INSTANCE_STATUS_DEPLOYING': 'Deploying',+ 'deployments.status.RUNTIME_INSTANCE_STATUS_FAILED': 'Deploy failed',+ 'deployments.status.RUNTIME_INSTANCE_STATUS_INVALID': 'Invalid','deployments.status.RUNTIME_INSTANCE_STATUS_READY': 'Running',+ 'deployments.status.RUNTIME_INSTANCE_STATUS_UNDEPLOYED': 'Not deployed',+ 'deployments.status.RUNTIME_INSTANCE_STATUS_UNDEPLOYING': 'Undeploying',+ 'deployments.status.RUNTIME_INSTANCE_STATUS_UNSPECIFIED': 'Unknown','deployments.studio.activity.deploySucceeded': 'Deploy {{target}} succeeded','deployments.studio.activity.meta': '{{name}} · {{time}}','deployments.studio.versionValue': 'Version value','deployments.studio.environmentsInUse': '{{used}} of {{total}} environments in use','deployments.studio.environmentVariablesDescription':"Use the value from the version you're deploying, keep the last deployed value, or enter a custom one.",+ 'deployments.studio.precheck.from': 'From',+ 'deployments.studio.precheck.nodeCount_other': '{{count}} nodes','deployments.studio.updatedAtBy': 'Updated at {{time}} by {{name}}',+ 'workflow.common.workflowAsTool': 'Workflow as Tool','workflow.common.publishedBy': 'Published {{time}} by {{author}}',})})@@ -732,7 +845,8 @@ vi.mock('@/context/permission-state', async () => {})vi.mock('@/context/i18n', () => ({- useDocLink: () => mockDocLink,+ getEnterpriseDocUrl: mockGetEnterpriseDocUrl,+ useLocale: () => 'en-US',}))vi.mock('@langgenius/dify-ui/toast', () => ({@@ -784,7 +898,7 @@ describe('AppDeploy', () => {expect(screen.getByRole('link', { name: 'common.operation.learnMore' })).toHaveAttribute('href',- 'https://docs.example.com/use/deploy/overview',+ 'https://enterprise-docs.example.com/en/use/deploy/overview',)})@@ -795,6 +909,86 @@ describe('AppDeploy', () => {},)+ it.each([+ [RuntimeState.RUNTIME_STATE_UNSPECIFIED, 'Unknown'],+ [RuntimeState.RUNTIME_STATE_UNDEPLOYED, 'Not deployed'],+ [RuntimeState.RUNTIME_STATE_RUNNING, 'Running'],+ [RuntimeState.RUNTIME_STATE_STARTING, 'Deploying'],+ [RuntimeState.RUNTIME_STATE_STOPPING, 'Undeploying'],+ [RuntimeState.RUNTIME_STATE_ERROR, 'Invalid'],+ [RuntimeState.RUNTIME_STATE_UNKNOWN, 'Unknown'],+ ] as const)('renders runtime state %s as %s', (runtimeState, label) => {+ render(<RuntimeStateIndicator runtimeState={runtimeState} />)++ expect(screen.getByText(label)).toBeInTheDocument()+ })++ it.each([RuntimeState.RUNTIME_STATE_STARTING, RuntimeState.RUNTIME_STATE_STOPPING])(+ 'continues polling transitional state %s without a latest operation',+ (runtimeState) => {+ expect(+ shouldPollEnvironmentDeployment(+ environmentDeployment({+ id: 'transitioning',+ name: 'Transitioning',+ runtimeState,+ }),+ ),+ ).toBe(true)+ },+ )++ it('disables Deploy latest and retries after the latest workflow request fails', async () => {+ const user = userEvent.setup()+ let requestCount = 0+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init)+ if (!new URL(request.url).pathname.endsWith('/apps/app-1/workflows/publish'))+ throw new Error(`Unexpected request: ${request.method} ${request.url}`)++ requestCount += 1+ if (requestCount === 1) {+ return new Response(JSON.stringify({ message: 'Failed to load the latest workflow' }), {+ headers: { 'Content-Type': 'application/json' },+ status: 500,+ })+ }++ return new Response(JSON.stringify(mockBuiltInEnvironment.publishedWorkflow), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ })+ })++ render(<AppDeploy />, { seedLatestPublishedWorkflow: false })++ const alert = await screen.findByRole('alert')+ expect(alert).toHaveTextContent('deployments.studio.latestVersionLoadFailed')++ const deployLatestButtons = screen.getAllByRole('button', {+ name: 'deployments.studio.deployLatest',+ })+ expect(deployLatestButtons.length).toBeGreaterThan(0)+ for (const button of deployLatestButtons) expect(button).toBeDisabled()++ await user.click(within(alert).getByRole('button', { name: 'common.operation.retry' }))++ await waitFor(() => {+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ })+ const stagingRow = within(screen.getByRole('row', { name: /Staging/ }))+ const preReleaseRow = within(screen.getByRole('row', { name: /Pre-release/ }))+ await waitFor(() => {+ expect(+ preReleaseRow.getByRole('button', { name: 'deployments.studio.deployLatest' }),+ ).toBeEnabled()+ })+ expect(+ stagingRow.getByRole('button', { name: 'deployments.studio.deployLatest' }),+ ).toBeDisabled()+ expect(requestCount).toBe(2)+ })+it('renders version, status, activity, and access from the deployment contract', () => {render(<AppDeploy />)@@ -963,6 +1157,42 @@ describe('AppDeploy', () => {expect(screen.queryByRole('menuitem')).not.toBeInTheDocument()})+ it('shows a retry entry when the environment list fails to load', async () => {+ const user = userEvent.setup()+ let requestCount = 0+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init)+ if (!new URL(request.url).pathname.endsWith('/enterprise/app-deploy/apps/app-1/environments'))+ throw new Error(`Unexpected request: ${request.method} ${request.url}`)++ requestCount += 1+ if (requestCount === 1) {+ return new Response(JSON.stringify({ message: 'Failed to load environments' }), {+ headers: { 'Content-Type': 'application/json' },+ status: 500,+ })+ }++ return new Response(JSON.stringify({ data: APP_ENVIRONMENTS }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ })+ })++ render(<AppDeploy />, { seedAppEnvironments: false })+ await waitFor(() => expect(requestCount).toBe(1))++ expect(screen.queryByText(/environments in use/)).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.appMenus.deploy' }))++ const menu = await screen.findByRole('menu')+ expect(within(menu).getByRole('alert')).toHaveTextContent('deployments.common.loadFailed')+ await user.click(within(menu).getByRole('button', { name: 'common.operation.retry' }))++ expect(await screen.findByText('8 of 12 environments in use')).toBeInTheDocument()+ expect(requestCount).toBe(2)+ })+it('opens the selected environment version picker from the deploy menu', async () => {const user = userEvent.setup()render(<AppDeploy />)@@ -970,9 +1200,14 @@ describe('AppDeploy', () => {await user.click(screen.getByRole('button', { name: 'common.appMenus.deploy' }))await user.click(await screen.findByRole('menuitem', { name: /Dev/ }))- const dialog = await screen.findByRole('dialog', {- name: 'deployments.versions.deployTo:{"name":"Dev"}',- })+ const dialog = await screen.findByRole(+ 'dialog',+ {+ name: 'deployments.versions.deployTo:{"name":"Dev"}',+ },+ { timeout: 3000 },+ )+ expect(dialog).toHaveClass('h-[min(44rem,calc(100dvh-32px))]')expect(within(dialog).getByText('deployments.studio.chooseVersionToDeploy')).toBeInTheDocument()expect(within(dialog).getByRole('button', { name: /Release 7/ })).toBeEnabled()expect(within(dialog).getByRole('button', { name: /Sprint-42/ })).toBeEnabled()@@ -1015,11 +1250,21 @@ describe('AppDeploy', () => {const configurationDialog = await screen.findByRole('dialog', {name: 'deployments.studio.deployConfiguration',})+ expect(configurationDialog).not.toHaveClass('h-[min(44rem,calc(100dvh-32px))]')expect(within(configurationDialog).getByText('Release 6')).toBeInTheDocument()expect(within(configurationDialog).getByText('Dev')).toBeInTheDocument()expect(within(configurationDialog).getByRole('combobox', { name: 'Moonshot' }),).toHaveTextContent('Enterprise deployment key')+ expect(+ within(configurationDialog).queryByRole('button', { name: /Moonshot: From/ }),+ ).not.toBeInTheDocument()+ expect(+ within(configurationDialog).getByRole('button', {+ name: 'Github: From Workflow as Tool',+ }),+ ).toBeInTheDocument()+ expect(within(configurationDialog).getByText('From Workflow as Tool')).toBeInTheDocument()expect(within(configurationDialog).getByRole('button', { name: 'common.appMenus.deploy' }),).toBeEnabled()@@ -1029,19 +1274,35 @@ describe('AppDeploy', () => {),).toBeInTheDocument()- const portSource = within(configurationDialog).getByRole('combobox', { name: /PORT/ })+ const rootVariables = within(+ within(configurationDialog).getByRole('group', { name: 'Finance APP' }),+ )+ const subworkflowVariables = within(+ within(configurationDialog).getByRole('group', { name: 'Workflow as Tool' }),+ )+ const portSource = rootVariables.getByRole('combobox', { name: /PORT/ })expect(portSource).toHaveTextContent('Version value')- const portInput = within(configurationDialog).getByRole('textbox', { name: 'PORT' })+ const portInput = rootVariables.getByRole('textbox', { name: 'PORT' })expect(portInput).toBeDisabled()expect(portInput).toHaveAttribute('placeholder', '2')- expect(within(configurationDialog).getByRole('textbox', { name: 'API_KEY' })).toHaveAttribute(+ expect(rootVariables.getByRole('textbox', { name: 'API_KEY' })).toHaveAttribute('placeholder','sk-123************bc',)- expect(within(configurationDialog).getByRole('textbox', { name: 'name' })).toHaveAttribute(+ expect(rootVariables.getByRole('textbox', { name: 'name' })).toHaveAttribute('placeholder','environment variable 01',)+ expect(subworkflowVariables.getByRole('textbox', { name: 'PORT' })).toHaveAttribute(+ 'placeholder',+ '8080',+ )++ await user.hover(subworkflowVariables.getByRole('button', { name: 'Workflow as Tool' }))+ const sourcePreview = await screen.findByRole('dialog', { name: 'Workflow as Tool' })+ expect(+ within(sourcePreview).getByRole('link', { name: /Finance APP.*Workflow as Tool/ }),+ ).toHaveAttribute('href', '/app/app-workflow-tool/workflow')await user.click(portSource)expect(@@ -1077,6 +1338,150 @@ describe('AppDeploy', () => {).toBeInTheDocument()})+ it('requires a value after refreshed deployment options reconcile the source to custom', async () => {+ const user = userEvent.setup()+ const deploymentRequests: Request[] = []+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init)+ if (!request.url.includes('/deployment:deploy'))+ throw new Error(`Unexpected request: ${request.method} ${request.url}`)++ deploymentRequests.push(request.clone())+ return new Response(JSON.stringify({ message: 'Stop after capturing the request' }), {+ headers: { 'Content-Type': 'application/json' },+ status: 502,+ })+ })+ const view = render(<AppDeploy />)++ await user.click(screen.getByRole('button', { name: 'common.appMenus.deploy' }))+ await user.click(screen.getByRole('menuitem', { name: /Dev/ }))+ const versionDialog = await screen.findByRole('dialog', {+ name: 'deployments.versions.deployTo:{"name":"Dev"}',+ })+ await user.click(within(versionDialog).getByRole('button', { name: /Release 6/ }))++ const configurationDialog = await screen.findByRole('dialog', {+ name: 'deployments.studio.deployConfiguration',+ })+ const rootVariables = within(+ within(configurationDialog).getByRole('group', { name: 'Finance APP' }),+ )+ await user.click(rootVariables.getByRole('combobox', { name: /PORT/ }))+ await user.click(+ await screen.findByRole('option', {+ name: 'deployments.deployDrawer.envVarSource.lastDeployment',+ }),+ )++ const deploymentOptionsQuery = workflowDeploymentOptionsQueryOptions(+ 'workflow-version-6',+ 'dev',+ )+ act(() => {+ view.queryClient.setQueryData(deploymentOptionsQuery.queryKey, {+ ...WORKFLOW_DEPLOYMENT_OPTIONS,+ environment_variable_groups: WORKFLOW_DEPLOYMENT_OPTIONS.environment_variable_groups.map(+ (group) => ({+ ...group,+ environment_variable_slots: group.from_app+ ? group.environment_variable_slots.map((slot) =>+ slot.key === 'PORT'+ ? {+ ...slot,+ has_configured_value: false,+ has_last_deployed_value: false,+ }+ : slot,+ )+ : group.environment_variable_slots,+ }),+ ),+ })+ })++ await waitFor(() => {+ expect(rootVariables.getByRole('combobox', { name: /PORT/ })).toHaveTextContent(+ 'deployments.deployDrawer.envVarSource.literal',+ )+ })+ const customPortInput = rootVariables.getByRole('spinbutton', { name: 'PORT' })+ expect(customPortInput).toBeEnabled()++ await user.click(+ within(configurationDialog).getByRole('button', { name: 'common.appMenus.deploy' }),+ )+ expect(deploymentRequests).toHaveLength(0)+ expect(toast.error).toHaveBeenCalledWith('Finance APP · PORT: workflow.env.modal.valueRequired')++ await user.type(customPortInput, '3000')+ await user.click(+ within(configurationDialog).getByRole('button', { name: 'common.appMenus.deploy' }),+ )+ await waitFor(() => expect(deploymentRequests).toHaveLength(1))++ const body = await deploymentRequests[0]!.json()+ expect(body.environment_variable_groups[0].environment_variables).toContainEqual({+ key: 'PORT',+ value: 3000,+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ })+ })++ it('shows a toast instead of submitting when a credential is missing', async () => {+ const user = userEvent.setup()+ const deploymentRequests: Request[] = []+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init)+ if (!request.url.includes('/deployment:deploy'))+ throw new Error(`Unexpected request: ${request.method} ${request.url}`)++ deploymentRequests.push(request.clone())+ return new Response(JSON.stringify({ message: 'Stop after capturing the request' }), {+ headers: { 'Content-Type': 'application/json' },+ status: 502,+ })+ })+ const view = render(<AppDeploy />)+ const deploymentOptionsQuery = workflowDeploymentOptionsQueryOptions(+ 'workflow-version-6',+ 'dev',+ )+ act(() => {+ view.queryClient.setQueryData(deploymentOptionsQuery.queryKey, {+ ...WORKFLOW_DEPLOYMENT_OPTIONS,+ credential_slots: WORKFLOW_DEPLOYMENT_OPTIONS.credential_slots.map((slot) =>+ slot.provider_id === 'moonshot'+ ? { ...slot, last_deployed_credential_id: undefined }+ : slot,+ ),+ })+ })++ await user.click(screen.getByRole('button', { name: 'common.appMenus.deploy' }))+ await user.click(screen.getByRole('menuitem', { name: /Dev/ }))+ const versionDialog = await screen.findByRole('dialog', {+ name: 'deployments.versions.deployTo:{"name":"Dev"}',+ })+ await user.click(within(versionDialog).getByRole('button', { name: /Release 6/ }))++ const configurationDialog = await screen.findByRole('dialog', {+ name: 'deployments.studio.deployConfiguration',+ })+ const deployButton = within(configurationDialog).getByRole('button', {+ name: 'common.appMenus.deploy',+ })+ expect(+ within(configurationDialog).getByRole('combobox', { name: 'Moonshot' }),+ ).toHaveTextContent('deployments.deployDrawer.selectCredential')+ expect(deployButton).toBeEnabled()++ await user.click(deployButton)++ expect(deploymentRequests).toHaveLength(0)+ expect(toast.error).toHaveBeenCalledWith('Moonshot: deployments.deployDrawer.selectCredential')+ })+it('deploys the selected workflow configuration and refreshes the deployment list', async () => {const user = userEvent.setup()const requests: Request[] = []@@ -1113,7 +1518,7 @@ describe('AppDeploy', () => {targetVersion: workflowVersion('Release 6', 'workflow-version-6'),}),name: 'Dev',- status: DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STARTING,}),],}),@@ -1154,15 +1559,18 @@ describe('AppDeploy', () => {const configurationDialog = await screen.findByRole('dialog', {name: 'deployments.studio.deployConfiguration',})+ const rootVariables = within(+ within(configurationDialog).getByRole('group', { name: 'Finance APP' }),+ )await user.click(within(configurationDialog).getByRole('combobox', { name: 'Moonshot' }))await user.click(await screen.findByRole('option', { name: 'Development key' }))- await user.click(within(configurationDialog).getByRole('combobox', { name: /PORT/ }))+ await user.click(rootVariables.getByRole('combobox', { name: /PORT/ }))await user.click(await screen.findByRole('option', {name: 'deployments.deployDrawer.envVarSource.literal',}),)- await user.type(within(configurationDialog).getByRole('spinbutton', { name: 'PORT' }), '3000')+ await user.type(rootVariables.getByRole('spinbutton', { name: 'PORT' }), '3000')await user.click(within(configurationDialog).getByRole('button', { name: 'common.appMenus.deploy' }),)@@ -1199,19 +1607,37 @@ describe('AppDeploy', () => {provider_id: 'github',},],- environment_variables: [- {- key: 'PORT',- value: '3000',- value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,- },+ environment_variable_groups: [{- key: 'API_KEY',- value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CONFIGURED,+ environment_variables: [+ {+ key: 'PORT',+ value: 3000,+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ {+ key: 'API_KEY',+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CONFIGURED,+ },+ {+ key: 'name',+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED,+ },+ ],+ workflow_id: 'workflow-version-6',},{- key: 'name',- value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED,+ environment_variables: [+ {+ key: 'PORT',+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CONFIGURED,+ },+ {+ key: 'API_KEY',+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CONFIGURED,+ },+ ],+ workflow_id: 'workflow-tool',},],})@@ -1262,7 +1688,7 @@ describe('AppDeploy', () => {type: DeploymentOperationType.DEPLOYMENT_OPERATION_TYPE_UNDEPLOY,}),name: 'Canary',- status: DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STOPPING,}): deployment,),@@ -1402,7 +1828,7 @@ describe('AppDeploy', () => {type: DeploymentOperationType.DEPLOYMENT_OPERATION_TYPE_UNDEPLOY,}),name: 'Canary',- status: DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYING,+ runtimeState: RuntimeState.RUNTIME_STATE_STOPPING,}),],})@@ -1510,6 +1936,45 @@ describe('AppDeploy', () => {).toBeInTheDocument()})+ it('keeps deployment configuration and entered values open after an outside press', async () => {+ const user = userEvent.setup()+ render(<AppDeploy />)++ const preReleaseRow = within(screen.getByRole('row', { name: /Pre-release/ }))+ await user.click(+ preReleaseRow.getByRole('button', {+ name: 'deployments.studio.deployLatest',+ }),+ )++ const configurationDialog = await screen.findByRole('dialog', {+ name: 'deployments.studio.deployConfiguration',+ })+ const rootVariables = within(+ within(configurationDialog).getByRole('group', { name: 'Finance APP' }),+ )+ await user.click(rootVariables.getByRole('combobox', { name: /PORT/ }))+ await user.click(+ await screen.findByRole('option', {+ name: 'deployments.deployDrawer.envVarSource.literal',+ }),+ )+ const customPortInput = rootVariables.getByRole('spinbutton', { name: 'PORT' })+ await user.type(customPortInput, '3000')++ await user.click(document.body)++ expect(configurationDialog).toBeInTheDocument()+ expect(customPortInput).toHaveValue(3000)++ await user.click(within(configurationDialog).getByRole('button', { name: 'Cancel' }))+ expect(+ screen.queryByRole('dialog', {+ name: 'deployments.studio.deployConfiguration',+ }),+ ).not.toBeInTheDocument()+ })+it('opens the failed version configuration for retry without a version-selection step', async () => {const user = userEvent.setup()render(<AppDeploy />)@@ -1571,7 +2036,10 @@ describe('AppDeploy', () => {const dialog = await screen.findByRole('dialog', {name: 'deployments.studio.changeVersion · Canary',})- expect(within(dialog).getByRole('button', { name: /Sprint-42/ })).toBeDisabled()+ const versionList = within(dialog).getByRole('region', {+ name: 'deployments.studio.changeVersion · Canary',+ })+ expect(within(versionList).getByRole('button', { name: /Sprint-42/ })).toBeDisabled()expect(within(dialog).getByText('deployments.studio.current')).toBeInTheDocument()})@@ -1579,7 +2047,7 @@ describe('AppDeploy', () => {const user = userEvent.setup()render(<AppDeployStateBoundary appId={APP_ID}>- <EnvironmentTable appId={APP_ID} canViewAccessPoint />+ <EnvironmentTable {...environmentTableProps()} /></AppDeployStateBoundary>,{appEnvironments: APP_ENVIRONMENTS.map((environment) => ({@@ -1640,10 +2108,14 @@ describe('AppDeploy', () => {queryClient.setQueryData(appEnvironmentsQueryOptions.queryKey, {data: APP_ENVIRONMENTS,})+ queryClient.setQueryData(+ latestPublishedWorkflowQuery.queryKey,+ mockBuiltInEnvironment.publishedWorkflow,+ )renderWithConsoleQuery(<AppDeployStateBoundary appId={APP_ID}>- <EnvironmentTable appId={APP_ID} canViewAccessPoint />+ <EnvironmentTable {...environmentTableProps()} /></AppDeployStateBoundary>,{ queryClient },)@@ -1745,7 +2217,7 @@ describe('AppDeploy', () => {const stagingRow = within(screen.getByRole('row', { name: /Staging/ }))expect(stagingRow.getByRole('button', {- name: 'deployments.studio.changeVersion',+ name: 'deployments.studio.deployLatest',}),).toBeDisabled()@@ -1756,7 +2228,7 @@ describe('AppDeploy', () => {)const menuItems = within(await screen.findByRole('menu')).getAllByRole('menuitem')- expect(menuItems).toHaveLength(2)+ expect(menuItems).toHaveLength(1)for (const item of menuItems) expect(item).toHaveAttribute('aria-disabled', 'true')})@@ -1765,7 +2237,7 @@ describe('AppDeploy', () => {const onUndeploy = vi.fn()render(<AppDeployStateBoundary appId={APP_ID}>- <EnvironmentTable appId={APP_ID} canViewAccessPoint onUndeploy={onUndeploy} />+ <EnvironmentTable {...environmentTableProps({ onUndeploy })} /></AppDeployStateBoundary>,)@@ -1802,7 +2274,7 @@ describe('AppDeploy', () => {const onUndeploy = vi.fn()render(<AppDeployStateBoundary appId={APP_ID}>- <EnvironmentTable appId={APP_ID} canViewAccessPoint onUndeploy={onUndeploy} />+ <EnvironmentTable {...environmentTableProps({ onUndeploy })} /></AppDeployStateBoundary>,)diff --git a/web/app/components/app/deploy/__tests__/version.spec.ts b/web/app/components/app/deploy/__tests__/version.spec.tsindex f942df6d088..deb4928e79e 100644--- a/web/app/components/app/deploy/__tests__/version.spec.ts+++ b/web/app/components/app/deploy/__tests__/version.spec.ts@@ -1,4 +1,4 @@-import { toDeploymentVersion } from '../version'+import { toDeploymentVersion } from '../utils/version'describe('toDeploymentVersion', () => {it('maps workflow metadata into the shared deployment version shape', () => {diff --git a/web/app/components/app/deploy/assets/github.png b/web/app/components/app/deploy/assets/github.pngdeleted file mode 100644index c00ac6ad25f..00000000000Binary files a/web/app/components/app/deploy/assets/github.png and /dev/null differdiff --git a/web/app/components/app/deploy/assets/moonshot.png b/web/app/components/app/deploy/assets/moonshot.pngdeleted file mode 100644index eb28f25f1dc..00000000000Binary files a/web/app/components/app/deploy/assets/moonshot.png and /dev/null differdiff --git a/web/app/components/app/deploy/assets/slack.png b/web/app/components/app/deploy/assets/slack.pngdeleted file mode 100644index cf4aa776d2b..00000000000Binary files a/web/app/components/app/deploy/assets/slack.png and /dev/null differdiff --git a/web/app/components/app/deploy/built-in-environment-card/index.tsx b/web/app/components/app/deploy/built-in-environment-card/index.tsxindex f6eb294b6ac..c288ef06622 100644--- a/web/app/components/app/deploy/built-in-environment-card/index.tsx+++ b/web/app/components/app/deploy/built-in-environment-card/index.tsx@@ -2,117 +2,122 @@import type { WorkflowVersion } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { Node } from '@/app/components/workflow/types'-import { DeploymentStatus as DeploymentStatusEnum } from '@dify/contracts/enterprise-app-deploy/types.gen'+import { RuntimeState } from '@dify/contracts/enterprise-app-deploy/types.gen'import { useQuery } from '@tanstack/react-query'+import { memo } from 'react'import { useTranslation } from 'react-i18next'import { useStore as useAppStore } from '@/app/components/app/store'import { BlockEnum, isTriggerNode } from '@/app/components/workflow/types'import useTimestamp from '@/hooks/use-timestamp'import { useMCPServerDetail } from '@/service/use-tools'import { appWorkflowQueryOptions } from '@/service/workflow-queries'-import { ACCESS_POINT_ORDER, getAccessPointHref } from '../access-point'import { AccessPointIcon } from '../shared/access-point-icon'-import { DeploymentStatus } from '../shared/deployment-status'+import { RuntimeStateIndicator } from '../shared/runtime-state'import { VersionLabel } from '../shared/version-label'+import { ACCESS_POINT_ORDER, getAccessPointHref } from '../utils/access-point'function Divider() {return <div className="i-custom-vender-deploy-line-5 h-10 w-3" />}-export function BuiltInEnvironmentCard({ canViewAccessPoint }: { canViewAccessPoint: boolean }) {- const { t } = useTranslation('deployments')- const { formatTime } = useTimestamp()- const appDetail = useAppStore((state) => state.appDetail)- const appId = appDetail?.id ?? ''- const { data: publishedWorkflow } = useQuery(appWorkflowQueryOptions(appId || null))- const { data: mcpServerDetail } = useMCPServerDetail(appId, Boolean(appId))- const publishedNodes = Array.isArray(publishedWorkflow?.graph.nodes)- ? (publishedWorkflow.graph.nodes as Node[])- : []- const hasStartNode = publishedNodes.some((node) => node.data.type === BlockEnum.Start)- const hasTriggerNode = publishedNodes.some((node) => isTriggerNode(node.data.type))- const serviceModeAvailable = Boolean(publishedWorkflow && hasStartNode && !hasTriggerNode)- const activeAccessPoints = {- mcp: serviceModeAvailable && mcpServerDetail?.status === 'active',- serviceApi: serviceModeAvailable && Boolean(appDetail?.enable_api),- trigger: Boolean(publishedWorkflow && hasTriggerNode),- webApp: serviceModeAvailable && Boolean(appDetail?.enable_site),- }- const publishedBy = publishedWorkflow?.created_by?.name ?? appDetail?.author_name ?? '--'- const updatedBy = publishedWorkflow?.updated_by?.name ?? publishedBy- const publishedVersion: WorkflowVersion | undefined = publishedWorkflow- ? {- created_at: publishedWorkflow.created_at,- created_by: publishedWorkflow.created_by ?? undefined,- id: publishedWorkflow.id,- marked_comment: publishedWorkflow.marked_comment,- marked_name: publishedWorkflow.marked_name,- version: publishedWorkflow.version,- version_number: publishedWorkflow.version_number ?? undefined,- }- : undefined+export const BuiltInEnvironmentCard = memo(+ ({ canViewAccessPoint }: { canViewAccessPoint: boolean }) => {+ const { t } = useTranslation('deployments')+ const { formatTime } = useTimestamp()+ const appDetail = useAppStore((state) => state.appDetail)+ const appId = appDetail?.id ?? ''+ const { data: publishedWorkflow } = useQuery(appWorkflowQueryOptions(appId || null))+ const { data: mcpServerDetail } = useMCPServerDetail(appId, Boolean(appId))+ const publishedNodes = Array.isArray(publishedWorkflow?.graph.nodes)+ ? (publishedWorkflow.graph.nodes as Node[])+ : []+ const hasStartNode = publishedNodes.some((node) => node.data.type === BlockEnum.Start)+ const hasTriggerNode = publishedNodes.some((node) => isTriggerNode(node.data.type))+ const serviceModeAvailable = Boolean(publishedWorkflow && hasStartNode && !hasTriggerNode)+ const activeAccessPoints = {+ mcp: serviceModeAvailable && mcpServerDetail?.status === 'active',+ serviceApi: serviceModeAvailable && Boolean(appDetail?.enable_api),+ trigger: Boolean(publishedWorkflow && hasTriggerNode),+ webApp: serviceModeAvailable && Boolean(appDetail?.enable_site),+ }+ const publishedBy = publishedWorkflow?.created_by?.name ?? appDetail?.author_name ?? '--'+ const updatedBy = publishedWorkflow?.updated_by?.name ?? publishedBy+ const publishedVersion: WorkflowVersion | undefined = publishedWorkflow+ ? {+ created_at: publishedWorkflow.created_at,+ created_by: publishedWorkflow.created_by ?? undefined,+ id: publishedWorkflow.id,+ marked_comment: publishedWorkflow.marked_comment,+ marked_name: publishedWorkflow.marked_name,+ version: publishedWorkflow.version,+ version_number: publishedWorkflow.version_number ?? undefined,+ }+ : undefined- return (- <section- aria-labelledby="built-in-environment-title"- className="shrink-0 rounded-[14px] bg-background-section p-1"- >- <div className="flex flex-col gap-2.5 rounded-[10px] border-[0.5px] border-divider-subtle bg-components-panel-bg p-4">- {/* Icon */}- <div className="flex size-9 items-center justify-center rounded-lg border-[0.5px] border-divider-regular">- <span aria-hidden className="i-ri-instance-line size-5 text-text-secondary" />- </div>- {/* Info */}- <div className="flex items-center gap-10">- <div className="flex flex-col gap-1">- <h2 id="built-in-environment-title" className="system-md-semibold text-text-primary">- {t(($) => $['studio.builtInTitle'])}- </h2>- <p className="truncate system-xs-regular text-text-tertiary">- {t(($) => $['studio.builtInDescription'])}- </p>+ return (+ <section+ aria-labelledby="built-in-environment-title"+ className="shrink-0 rounded-[14px] bg-background-section p-1"+ >+ <div className="flex flex-col gap-2.5 rounded-[10px] border-[0.5px] border-divider-subtle bg-components-panel-bg p-4">+ {/* Icon */}+ <div className="flex size-9 items-center justify-center rounded-lg border-[0.5px] border-divider-regular">+ <span aria-hidden className="i-ri-instance-line size-5 text-text-secondary" /></div>- <Divider />- <div className="flex flex-col gap-1">- <div className="system-2xs-medium-uppercase text-text-tertiary">- {t(($) => $['studio.liveVersion'])}+ {/* Info */}+ <div className="flex items-center gap-10">+ <div className="flex flex-col gap-1">+ <h2 id="built-in-environment-title" className="system-md-semibold text-text-primary">+ {t(($) => $['studio.builtInTitle'])}+ </h2>+ <p className="truncate system-xs-regular text-text-tertiary">+ {t(($) => $['studio.builtInDescription'])}+ </p></div>- <VersionLabel version={publishedVersion} isLatest />- </div>- <Divider />- <div className="flex flex-col gap-1">- <div className="system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['studio.accessPoints'])}+ <Divider />+ <div className="flex flex-col gap-1">+ <div className="system-2xs-medium-uppercase text-text-tertiary">+ {t(($) => $['studio.liveVersion'])}+ </div>+ <VersionLabel version={publishedVersion} isLatest /></div>- <div className="flex items-center gap-1">- {ACCESS_POINT_ORDER.map((accessPoint) => (- <AccessPointIcon- key={accessPoint}- accessPoint={accessPoint}- active={activeAccessPoints[accessPoint]}- href={- canViewAccessPoint- ? getAccessPointHref(appId, 'built-in', accessPoint)- : undefined- }- />- ))}+ <Divider />+ <div className="flex flex-col gap-1">+ <div className="system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['studio.accessPoints'])}+ </div>+ <div className="flex items-center gap-1">+ {ACCESS_POINT_ORDER.map((accessPoint) => (+ <AccessPointIcon+ key={accessPoint}+ accessPoint={accessPoint}+ active={activeAccessPoints[accessPoint]}+ href={+ canViewAccessPoint+ ? getAccessPointHref(appId, 'built-in', accessPoint)+ : undefined+ }+ />+ ))}+ </div></div></div></div>- </div>- {/* Status and updated time */}- <div className="flex items-center justify-between gap-4 px-4 py-2.5">- <DeploymentStatus status={DeploymentStatusEnum.DEPLOYMENT_STATUS_RUNNING} />- <p className="truncate system-xs-regular text-text-tertiary">- {publishedWorkflow- ? t(($) => $['studio.updatedAtBy'], {- name: updatedBy,- time: formatTime(publishedWorkflow.updated_at, 'MM-DD HH:mm'),- })- : '--'}- </p>- </div>- </section>- )-}+ {/* Status and updated time */}+ <div className="flex items-center justify-between gap-4 px-4 py-2.5">+ <RuntimeStateIndicator runtimeState={RuntimeState.RUNTIME_STATE_RUNNING} />+ <p className="truncate system-xs-regular text-text-tertiary">+ {publishedWorkflow+ ? t(($) => $['studio.updatedAtBy'], {+ name: updatedBy,+ time: formatTime(publishedWorkflow.updated_at, 'MM-DD HH:mm'),+ })+ : '--'}+ </p>+ </div>+ </section>+ )+ },+)++BuiltInEnvironmentCard.displayName = 'BuiltInEnvironmentCard'diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/content.tsx b/web/app/components/app/deploy/deployment-dialog/deployment-configuration/content.tsxdeleted file mode 100644index 8228026c57a..00000000000--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/content.tsx+++ /dev/null@@ -1,262 +0,0 @@-'use client'--import type { Dispatch, SetStateAction } from 'react'-import type { DeploymentVersion } from '../../version'-import type { DeploymentDialogRequest } from '../types'-import type { DeploymentConfigurationQueryState } from './use-deployment-configuration-queries'-import type { DeploymentConfigurationValues } from './use-deployment-configuration-values'-import { cn } from '@langgenius/dify-ui/cn'-import { useTranslation } from 'react-i18next'-import { CredentialField } from './credential-field'-import { DeploymentPrecheckAlert } from './deployment-precheck-alert'-import { EnvironmentVariableField } from './environment-variable-field'-import {- credentialSlotKey,- defaultCredentialId,- defaultEnvironmentVariableSelection,-} from './workflow-deployment-input'--function SectionHeading({ title, description }: { title: string; description: string }) {- return (- <div className="flex min-w-0 flex-col">- <h3 className="system-md-semibold text-text-primary">{title}</h3>- <p className="system-xs-regular text-text-tertiary">{description}</p>- </div>- )-}--function errorMessage(error: unknown, fallback: string) {- if (- typeof error === 'object' &&- error !== null &&- 'message' in error &&- typeof error.message === 'string' &&- error.message.trim()- ) {- return error.message.trim()- }-- return fallback-}--function ConfigurationError({ messages }: { messages: string[] }) {- const { t } = useTranslation('common')-- return (- <div role="alert" className="flex gap-2 text-text-destructive">- <span aria-hidden className="mt-0.5 i-ri-error-warning-fill size-4 shrink-0" />- <div className="min-w-0">- <p className="system-sm-semibold">{t(($) => $.error)}</p>- <ul className="mt-1 list-disc space-y-1 pl-4 system-xs-regular">- {messages.map((message) => (- <li key={message} className="wrap-break-word">- {message}- </li>- ))}- </ul>- </div>- </div>- )-}--function ConfigurationLoading({ label }: { label: string }) {- return (- <div role="status" className="flex items-center justify-center gap-2 py-8 text-text-tertiary">- <span- aria-hidden- className="i-ri-loader-2-line size-4 animate-spin motion-reduce:animate-none"- />- <span className="system-xs-regular">{label}</span>- </div>- )-}--export function DeploymentConfigurationContent({- compact = false,- onValuesChange,- queryState,- request,- values,- version,-}: {- compact?: boolean- onValuesChange: Dispatch<SetStateAction<DeploymentConfigurationValues>>- queryState: DeploymentConfigurationQueryState- request: DeploymentDialogRequest- values: DeploymentConfigurationValues- version: DeploymentVersion-}) {- const { t } = useTranslation('deployments')- const { t: tCommon } = useTranslation('common')- const horizontalPaddingClassName = compact ? 'px-4' : 'px-6'- const {- deploymentOptions,- deploymentOptionsError,- isLoadingDeploymentOptions,- isPrecheckBlocked,- isPrechecking,- precheck,- precheckError,- } = queryState- const unsupportedNodes = precheck?.unsupported_nodes ?? []- const showPrecheckAlert = !isPrechecking && !precheckError && isPrecheckBlocked- const showConfiguration = Boolean(deploymentOptions)- const credentialSlots = deploymentOptions?.credential_slots ?? []- const hasCredentialSlots = credentialSlots.length > 0- const environmentVariableSlots = deploymentOptions?.environment_variable_slots ?? []-- return (- <>- <div- className={cn(- 'shrink-0 pt-2',- showPrecheckAlert ? 'pb-0' : 'border-b border-divider-regular pb-4',- horizontalPaddingClassName,- )}- >- <div className="flex items-center justify-between gap-3 rounded-xl bg-background-section p-3">- <div className="flex min-w-0 flex-1 items-center gap-2">- <span aria-hidden className="i-ri-stack-line size-3.5 shrink-0 text-text-tertiary" />- <span className="truncate system-sm-medium text-text-secondary">{version.name}</span>- </div>- <span- aria-hidden- className="i-ri-arrow-right-line size-3.5 shrink-0 text-text-tertiary"- />- <div className="flex min-w-0 flex-1 items-center justify-end gap-2">- <span aria-hidden className="i-ri-instance-line size-3.5 shrink-0 text-text-tertiary" />- <span className="truncate system-sm-medium text-text-secondary">- {request.environment}- </span>- </div>- </div>- </div>-- <div- aria-busy={isPrechecking || isLoadingDeploymentOptions}- className="min-h-0 flex-1 overflow-y-auto"- >- {isPrechecking && (- <ConfigurationLoading label={t(($) => $['versions.checkingReleaseContent'])} />- )}- {!isPrechecking && precheckError && (- <div className={cn('py-4', horizontalPaddingClassName)}>- <ConfigurationError- messages={[- errorMessage(- precheckError,- tCommon(($) => $.error),- ),- ]}- />- </div>- )}- {showPrecheckAlert && (- <div- className={cn('border-b border-divider-regular pt-2 pb-4', horizontalPaddingClassName)}- >- <DeploymentPrecheckAlert nodes={unsupportedNodes} />- </div>- )}- {isLoadingDeploymentOptions && <ConfigurationLoading label={tCommon(($) => $.loading)} />}- {!isLoadingDeploymentOptions && deploymentOptionsError && (- <div className={cn('py-4', horizontalPaddingClassName)}>- <ConfigurationError- messages={[- errorMessage(- deploymentOptionsError,- t(($) => $['deployDrawer.bindingOptionsFailed']),- ),- ]}- />- </div>- )}- {showConfiguration && (- <>- {hasCredentialSlots && (- <section className={cn('flex flex-col gap-4 py-4', horizontalPaddingClassName)}>- <SectionHeading- title={t(($) => $['deployDrawer.runtimeCredentials'])}- description={t(($) => $['deployDrawer.bindingSelectionHint'])}- />- {credentialSlots.map((slot) => {- const slotKey = credentialSlotKey(slot)-- return (- <CredentialField- key={slotKey}- slot={slot}- value={values.credentials[slotKey] ?? defaultCredentialId(slot)}- onChange={(value) =>- onValuesChange((current) => ({- ...current,- credentials: {- ...current.credentials,- [slotKey]: value,- },- }))- }- />- )- })}- </section>- )}-- {environmentVariableSlots.length > 0 ? (- <section- className={cn(- 'flex flex-col gap-4 py-4',- hasCredentialSlots && 'border-t border-divider-regular',- horizontalPaddingClassName,- )}- >- <SectionHeading- title={t(($) => $['deployDrawer.envVars'])}- description={t(($) => $['studio.environmentVariablesDescription'])}- />- {environmentVariableSlots.map((slot) => {- const selection =- values.environmentVariables[slot.key] ??- defaultEnvironmentVariableSelection(slot)-- return (- <EnvironmentVariableField- key={slot.key}- slot={slot}- source={selection.source}- customValue={selection.customValue}- onSourceChange={(source) =>- onValuesChange((current) => ({- ...current,- environmentVariables: {- ...current.environmentVariables,- [slot.key]: {- ...selection,- source,- },- },- }))- }- onCustomValueChange={(customValue) =>- onValuesChange((current) => ({- ...current,- environmentVariables: {- ...current.environmentVariables,- [slot.key]: {- ...selection,- customValue,- },- },- }))- }- />- )- })}- </section>- ) : null}- </>- )}- </div>- </>- )-}diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/deployment-precheck-alert.tsx b/web/app/components/app/deploy/deployment-dialog/deployment-configuration/deployment-precheck-alert.tsxdeleted file mode 100644index 632cc32c420..00000000000--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/deployment-precheck-alert.tsx+++ /dev/null@@ -1,63 +0,0 @@-'use client'--import type { UnsupportedNode } from '@dify/contracts/enterprise-app-deploy/types.gen'-import type { Emoji } from '@/app/components/tools/types'-import { useTranslation } from 'react-i18next'-import BlockIcon from '@/app/components/workflow/block-icon'-import { BlockEnum } from '@/app/components/workflow/types'-import { useGetProviderIcon } from './use-provider-icon'--const WORKFLOW_BLOCK_TYPES = new Set<string>(Object.values(BlockEnum))--function isWorkflowBlockType(type: string): type is BlockEnum {- return WORKFLOW_BLOCK_TYPES.has(type)-}--function UnsupportedNodeIcon({ node, icon }: { node: UnsupportedNode; icon?: string | Emoji }) {- if (!isWorkflowBlockType(node.type)) {- return (- <span className="flex size-4 shrink-0 items-center justify-center rounded-[5px] bg-components-icon-bg-midnight-solid text-white shadow-xs">- <span aria-hidden className="i-ri-node-tree size-3" />- </span>- )- }-- return <BlockIcon type={node.type} size="xs" toolIcon={icon} />-}--export function DeploymentPrecheckAlert({ nodes }: { nodes: UnsupportedNode[] }) {- const { t } = useTranslation('deployments')- const getProviderIcon = useGetProviderIcon(nodes)-- return (- <div- role="alert"- className="relative flex flex-col gap-2 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-3 shadow-xs backdrop-blur-[5px]"- >- <div className="pointer-events-none absolute inset-0 bg-linear-to-r from-components-badge-status-light-warning-halo to-background-gradient-mask-transparent opacity-40" />- <span- aria-hidden- className="relative i-ri-alert-fill size-4 shrink-0 text-text-warning-secondary"- />- <div className="relative flex min-w-0 flex-col gap-1">- <p className="system-sm-medium text-text-primary">{t(($) => $['studio.precheck.title'])}</p>- <p className="system-xs-regular text-text-secondary">- {t(($) => $['studio.precheck.description'])}- </p>- <ul className="flex flex-col gap-2 py-1">- {nodes.map((node) => (- <li key={node.id} className="flex min-w-0 items-center gap-2">- <UnsupportedNodeIcon node={node} icon={getProviderIcon(node)} />- <span className="min-w-0 truncate system-xs-medium text-text-secondary">- {node.title}- </span>- </li>- ))}- </ul>- <p className="system-xs-regular text-text-secondary">- {t(($) => $['studio.precheck.supportMessage'])}- </p>- </div>- </div>- )-}diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/environment-variable-field.tsx b/web/app/components/app/deploy/deployment-dialog/deployment-configuration/environment-variable-field.tsxdeleted file mode 100644index 0bb746540fb..00000000000--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/environment-variable-field.tsx+++ /dev/null@@ -1,129 +0,0 @@-'use client'--import type {- EnvironmentVariableSlot,- EnvVarValueSource,-} from '@dify/contracts/enterprise-app-deploy/types.gen'-import {- EnvVarValueSource as EnvVarValueSourceEnum,- EnvVarValueType,-} from '@dify/contracts/enterprise-app-deploy/types.gen'-import { Input } from '@langgenius/dify-ui/input'-import {- Select,- SelectContent,- SelectItem,- SelectItemIndicator,- SelectItemText,- SelectTrigger,-} from '@langgenius/dify-ui/select'-import { useTranslation } from 'react-i18next'--export function EnvironmentVariableField({- slot,- source,- customValue,- onSourceChange,- onCustomValueChange,-}: {- slot: EnvironmentVariableSlot- source: EnvVarValueSource- customValue: string- onSourceChange: (source: EnvVarValueSource) => void- onCustomValueChange: (value: string) => void-}) {- const { t } = useTranslation('deployments')- const sourceLabels: Partial<Record<EnvVarValueSource, string>> = {- [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED]: t(($) => $['studio.versionValue']),- [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM]: t(- ($) => $['deployDrawer.envVarSource.literal'],- ),- [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED]: t(- ($) => $['deployDrawer.envVarSource.lastDeployment'],- ),- }- const availableSources = [- ...(slot.has_last_deployed_value- ? [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED]- : []),- ...(slot.has_configured_value ? [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED] : []),- EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM,- ]- const valueTypeLabel =- slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER- ? t(($) => $['deployDrawer.envVarType.number'])- : slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET- ? t(($) => $['deployDrawer.envVarType.secret'])- : t(($) => $['deployDrawer.envVarType.string'])- const inputId = `deployment-env-${slot.key}`- const editable = source === EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM- const inputType =- editable && slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET- ? 'password'- : editable && slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER- ? 'number'- : 'text'- const sourceLabel = sourceLabels[source] ?? t(($) => $['deployDrawer.envVarSource.literal'])- // Secret values arrive masked, so these are safe to show as-is.- const sourceValues: Partial<Record<EnvVarValueSource, string>> = {- [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED]: slot.configured_value,- [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED]: slot.last_deployed_value,- }- const placeholder = editable ? undefined : (sourceValues[source] ?? sourceLabel)-- return (- <div className="flex flex-col gap-1">- <div className="flex min-w-0 items-center gap-2">- <div className="flex min-w-0 grow items-center gap-1">- <span- aria-hidden- className="i-custom-vender-line-others-env size-4 shrink-0 text-util-colors-violet-violet-600"- />- <label htmlFor={inputId} className="truncate system-sm-medium text-text-primary">- {slot.key}- </label>- <span className="shrink-0 system-xs-regular text-text-tertiary">{valueTypeLabel}</span>- {slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET && (- <span aria-hidden className="i-ri-lock-2-line size-3 shrink-0 text-text-tertiary" />- )}- </div>- <Select- value={source}- onValueChange={(nextSource) => {- if (nextSource) onSourceChange(nextSource)- }}- >- <SelectTrigger- aria-label={t(($) => $['deployDrawer.envVarSource.ariaLabel'], {- key: slot.key,- })}- size="small"- className="h-7 w-auto max-w-48 shrink-0 border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-2 shadow-xs backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover focus-visible:bg-components-button-secondary-bg"- >- {sourceLabel}- </SelectTrigger>- <SelectContent placement="bottom-end" className="w-52">- {availableSources.map((option) => (- <SelectItem key={option} value={option}>- <SelectItemText>{sourceLabels[option]}</SelectItemText>- <SelectItemIndicator />- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- <Input- id={inputId}- type={inputType}- value={editable ? customValue : ''}- placeholder={placeholder}- disabled={!editable}- autoComplete="off"- onChange={(event) => onCustomValueChange(event.target.value)}- />- {slot.description && (- <p className="system-xs-regular text-text-tertiary">{slot.description}</p>- )}- </div>- )-}diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-deployment-configuration-values.ts b/web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-deployment-configuration-values.tsdeleted file mode 100644index 0157e1f5907..00000000000--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-deployment-configuration-values.ts+++ /dev/null@@ -1,23 +0,0 @@-'use client'--import type { EnvVarValueSource } from '@dify/contracts/enterprise-app-deploy/types.gen'-import { useState } from 'react'--type EnvironmentVariableSelection = {- customValue: string- source: EnvVarValueSource-}--export type DeploymentConfigurationValues = {- credentials: Record<string, string>- environmentVariables: Record<string, EnvironmentVariableSelection>-}--export function useDeploymentConfigurationValues() {- const [values, setValues] = useState<DeploymentConfigurationValues>({- credentials: {},- environmentVariables: {},- })-- return [values, setValues] as const-}diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/workflow-deployment-input.ts b/web/app/components/app/deploy/deployment-dialog/deployment-configuration/workflow-deployment-input.tsdeleted file mode 100644index e46ccc8981a..00000000000--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/workflow-deployment-input.ts+++ /dev/null@@ -1,82 +0,0 @@-import type {- CredentialSlot,- EnvironmentVariableSlot,- GetWorkflowDeploymentOptionsResponse,- WorkflowDeploymentInput,-} from '@dify/contracts/enterprise-app-deploy/types.gen'-import type { DeploymentConfigurationValues } from './use-deployment-configuration-values'-import { EnvVarValueSource as EnvVarValueSourceEnum } from '@dify/contracts/enterprise-app-deploy/types.gen'--export function credentialSlotKey(slot: CredentialSlot) {- return `${slot.provider_id}:${slot.category}`-}--export function defaultCredentialId(slot: CredentialSlot) {- if (- slot.last_deployed_credential_id &&- slot.candidates.some(- (candidate) => candidate.credential_id === slot.last_deployed_credential_id,- )- ) {- return slot.last_deployed_credential_id- }-- return slot.candidates.length === 1 ? slot.candidates[0]?.credential_id : undefined-}--export function defaultEnvironmentVariableSelection(- slot: EnvironmentVariableSlot,-): DeploymentConfigurationValues['environmentVariables'][string] {- if (slot.has_configured_value) {- return {- customValue: '',- source: EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED,- }- }-- if (slot.has_last_deployed_value) {- return {- customValue: '',- source: EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED,- }- }-- return {- customValue: '',- source: EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM,- }-}--export function workflowDeploymentInput(- deploymentOptions: GetWorkflowDeploymentOptionsResponse,- values: DeploymentConfigurationValues,-): WorkflowDeploymentInput | undefined {- const credentials: NonNullable<WorkflowDeploymentInput['credentials']> = []-- for (const slot of deploymentOptions.credential_slots) {- const credentialId = values.credentials[credentialSlotKey(slot)] ?? defaultCredentialId(slot)- if (!credentialId) return-- credentials.push({- category: slot.category,- credential_id: credentialId,- provider_id: slot.provider_id,- })- }-- return {- credentials,- environment_variables: deploymentOptions.environment_variable_slots.map((slot) => {- const selection =- values.environmentVariables[slot.key] ?? defaultEnvironmentVariableSelection(slot)-- return {- key: slot.key,- value_source: selection.source,- ...(selection.source === EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM- ? { value: selection.customValue }- : {}),- }- }),- }-}diff --git a/web/app/components/app/deploy/deployment-dialog/index.tsx b/web/app/components/app/deploy/deployment-dialog/index.tsxindex 850d02ea176..3b19289a8a7 100644--- a/web/app/components/app/deploy/deployment-dialog/index.tsx+++ b/web/app/components/app/deploy/deployment-dialog/index.tsx@@ -1,11 +1,12 @@'use client'-import type { DeploymentVersion } from '../version'-import type { DeploymentDialogRequest } from './types'+import type { DeploymentDialogRequest } from '../types'+import type { DeploymentVersion } from '../utils/version'+import { cn } from '@langgenius/dify-ui/cn'import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { useState } from 'react'-import { DeploymentConfiguration } from './deployment-configuration'-import { VersionSelection } from './version-selection'+import { DeploymentConfiguration } from '../shared/deployment-configuration'+import { VersionSelection } from '../shared/version-selection'type DeploymentDialogProps = {appId: string@@ -27,7 +28,12 @@ function DeploymentDialogSession({)return (- <DialogContent className="flex max-h-[min(44rem,calc(100dvh-32px))] min-h-0 w-120 max-w-[calc(100vw-32px)] flex-col overflow-hidden p-0">+ <DialogContent+ className={cn(+ 'flex max-h-[min(44rem,calc(100dvh-32px))] min-h-0 w-120 max-w-[calc(100vw-32px)] flex-col overflow-hidden p-0',+ !selectedVersion && 'h-[min(44rem,calc(100dvh-32px))]',+ )}+ >{selectedVersion ? (<DeploymentConfigurationappId={appId}@@ -46,7 +52,11 @@ function DeploymentDialogSession({export function DeploymentDialog({ appId, request, onClose }: DeploymentDialogProps) {return (- <Dialog open={Boolean(request)} onOpenChange={(open) => !open && onClose()}>+ <Dialog+ open={Boolean(request)}+ disablePointerDismissal+ onOpenChange={(open) => !open && onClose()}+ >{request && (<DeploymentDialogSessionappId={appId}diff --git a/web/app/components/app/deploy/deployment-dialog/version-selection/index.tsx b/web/app/components/app/deploy/deployment-dialog/version-selection/index.tsxdeleted file mode 100644index 0680e3b94d0..00000000000--- a/web/app/components/app/deploy/deployment-dialog/version-selection/index.tsx+++ /dev/null@@ -1,285 +0,0 @@-'use client'-import type { ReactNode } from 'react'-import type { DeploymentVersion } from '../../version'-import type { DeploymentDialogRequest } from '../types'-import { Button, buttonVariants } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'-import { DialogClose, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'-import { IconButton } from '@langgenius/dify-ui/icon-button'-import { useAtomValue } from 'jotai'-import { useTranslation } from 'react-i18next'-import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'-import Link from '@/next/link'-import { useInfiniteScroll } from '../../hooks/use-infinite-scroll'-import {- appWorkflowVersionsAtom,- appWorkflowVersionsErrorAtom,- appWorkflowVersionsFetchNextPageAtom,- appWorkflowVersionsHasNextPageAtom,- appWorkflowVersionsIsFetchingAtom,- appWorkflowVersionsIsFetchingNextPageAtom,- appWorkflowVersionsIsLoadingAtom,-} from '../../state'--function VersionBadge({ children }: { children: ReactNode }) {- return (- <span className="inline-flex min-w-4 shrink-0 items-center justify-center rounded-[5px] border border-text-accent bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-accent">- {children}- </span>- )-}--function VersionTag({ children }: { children: ReactNode }) {- return (- <span className="inline-flex h-4.5 min-w-4.5 items-center justify-center rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1.25 system-2xs-medium text-text-tertiary">- {children}- </span>- )-}--function VersionChoice({- version,- current,- disabled = false,- onSelect,-}: {- version: DeploymentVersion- current: boolean- disabled?: boolean- onSelect: (version: DeploymentVersion) => void-}) {- const { t } = useTranslation('deployments')- const { t: tWorkflow } = useTranslation('workflow')- const { formatTimeFromNow } = useFormatTimeFromNow()-- return (- <button- type="button"- disabled={current || disabled}- onClick={() => onSelect(version)}- className="flex w-full cursor-pointer flex-col items-start gap-0.5 rounded-lg p-2 text-start outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid disabled:cursor-not-allowed disabled:hover:bg-transparent"- >- <span className="flex min-w-0 items-center gap-1">- <span- className={cn('truncate system-md-medium text-text-secondary', current && 'opacity-50')}- >- {version.name}- </span>- {version.latest && <VersionBadge>{t(($) => $['overview.chip.latest'])}</VersionBadge>}- {current && <VersionBadge>{t(($) => $['studio.current'])}</VersionBadge>}- </span>- {version.description && (- <span className="line-clamp-3 system-xs-regular text-text-tertiary">- {version.description}- </span>- )}- {version.publishedAt !== undefined && version.publishedBy && (- <span className={cn('system-xs-regular text-text-tertiary', current && 'opacity-50')}>- {tWorkflow(($) => $['common.publishedBy'], {- time: formatTimeFromNow(version.publishedAt),- author: version.publishedBy,- })}- </span>- )}- {version.tags && version.tags.length > 0 && (- <span className="flex flex-wrap items-center gap-1 pt-1">- {version.tags.map((tag) => (- <VersionTag key={tag}>{tag}</VersionTag>- ))}- </span>- )}- </button>- )-}--function VersionList({- className,- currentVersionId,- disabled = false,- publishHref,- onSelect,-}: {- className?: string- currentVersionId?: string- disabled?: boolean- publishHref?: string- onSelect: (version: DeploymentVersion) => void-}) {- const { t: tCommon } = useTranslation('common')- const { t } = useTranslation('deployments')- const versions = useAtomValue(appWorkflowVersionsAtom)- const versionsError = useAtomValue(appWorkflowVersionsErrorAtom)- const fetchNextPage = useAtomValue(appWorkflowVersionsFetchNextPageAtom)- const hasNextPage = useAtomValue(appWorkflowVersionsHasNextPageAtom)- const isFetching = useAtomValue(appWorkflowVersionsIsFetchingAtom)- const isFetchingNextPage = useAtomValue(appWorkflowVersionsIsFetchingNextPageAtom)- const isLoading = useAtomValue(appWorkflowVersionsIsLoadingAtom)- const { rootRef, sentinelRef } = useInfiniteScroll<HTMLDivElement>({- error: versionsError,- fetchNextPage,- hasNextPage,- isFetching,- isFetchingNextPage,- isLoading,- })-- return (- <div ref={rootRef} className={cn('min-h-0 flex-1 overflow-y-auto', className)}>- <div className="flex flex-col gap-px">- {versions.map((version) => (- <VersionChoice- key={version.id}- version={version}- current={version.id === currentVersionId}- disabled={disabled}- onSelect={onSelect}- />- ))}- </div>- {isLoading && (- <div- role="status"- aria-label={tCommon(($) => $.loading)}- className="flex h-20 items-center justify-center"- >- <span- aria-hidden- className="i-ri-loader-2-line size-4 animate-spin text-text-tertiary motion-reduce:animate-none"- />- </div>- )}- {!isLoading && versionsError && versions.length === 0 && (- <p role="alert" className="px-2 py-6 text-center system-xs-regular text-text-tertiary">- {tCommon(($) => $.error)}- </p>- )}- {!isLoading && !versionsError && versions.length === 0 && (- <div className="flex flex-col items-center gap-2 px-2 py-6">- <p className="text-center system-sm-regular text-text-tertiary">- {t(($) => $['studio.accessPoint.noPublishedTitle'])}- </p>- {publishHref && (- <Link- href={publishHref}- className={cn(buttonVariants({ size: 'medium' }), 'flex items-center gap-1')}- >- {t(($) => $['studio.accessPoint.goToPublish'])}- <span aria-hidden className="i-ri-arrow-right-line size-4" />- </Link>- )}- </div>- )}- {isFetchingNextPage && versions.length > 0 && (- <div- role="status"- aria-label={tCommon(($) => $.loading)}- className="flex h-8 items-center justify-center"- >- <span- aria-hidden- className="i-ri-loader-2-line size-4 animate-spin text-text-tertiary motion-reduce:animate-none"- />- </div>- )}- <div ref={sentinelRef} aria-hidden className="h-px" />- </div>- )-}--function versionSelectionTitle(request: DeploymentDialogRequest, deployTo: string, change: string) {- return request.kind === 'deploy' ? deployTo : `${change} · ${request.environment}`-}--export function VersionSelection({- appId,- request,- onSelect,-}: {- appId: string- request: DeploymentDialogRequest- onSelect: (version: DeploymentVersion) => void-}) {- const { t } = useTranslation('deployments')- const { t: tCommon } = useTranslation('common')- const title = versionSelectionTitle(- request,- t(($) => $['versions.deployTo'], { name: request.environment }),- t(($) => $['studio.changeVersion']),- )-- return (- <>- <DialogClose- render={- <IconButton- aria-label={tCommon(($) => $['operation.close'])}- size="lg"- className="absolute top-5 right-5"- type="button"- >- <span aria-hidden className="i-ri-close-line size-4" />- </IconButton>- }- />- <header className="shrink-0 px-6 pt-6 pr-14 pb-3">- <DialogTitle className="title-2xl-semi-bold text-text-primary">{title}</DialogTitle>- <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">- {t(($) => $['studio.chooseVersionToDeploy'])}- </DialogDescription>- </header>- <VersionList- className="px-4 pt-2 pb-4"- currentVersionId={request.currentVersionId}- publishHref={`/app/${appId}/workflow`}- onSelect={onSelect}- />- </>- )-}--export function EmbeddedVersionSelection({- disabled,- request,- onBack,- onSelect,-}: {- disabled: boolean- request: DeploymentDialogRequest- onBack: () => void- onSelect: (version: DeploymentVersion) => void-}) {- const { t } = useTranslation('deployments')- const { t: tCommon } = useTranslation('common')- const title = versionSelectionTitle(- request,- t(($) => $['versions.deployTo'], { name: request.environment }),- t(($) => $['studio.changeVersion']),- )-- return (- <div className="flex h-133 max-h-[calc(100dvh-32px)] min-h-0 flex-none flex-col">- <header className="shrink-0 px-3 pt-3.5 pb-1">- <Button- type="button"- size="small"- variant="ghost-accent"- className="-ml-1 h-6 gap-1 px-1 system-xs-semibold-uppercase"- onClick={onBack}- >- <span aria-hidden className="i-ri-arrow-left-line size-4" />- {tCommon(($) => $['operation.back'])}- </Button>- <h2 className="mt-0.5 px-1 system-xl-semibold text-text-primary">{title}</h2>- <p className="mt-0.5 px-1 system-xs-regular text-text-tertiary">- {t(($) => $['studio.chooseVersionToDeploy'])}- </p>- </header>- <VersionList- className="p-2"- currentVersionId={request.currentVersionId}- disabled={disabled}- onSelect={onSelect}- />- </div>- )-}diff --git a/web/app/components/app/deploy/environment-table/activity-cell.tsx b/web/app/components/app/deploy/environment-table/activity-cell.tsxindex 2469b8fe280..8fda519c2cf 100644--- a/web/app/components/app/deploy/environment-table/activity-cell.tsx+++ b/web/app/components/app/deploy/environment-table/activity-cell.tsx@@ -31,6 +31,8 @@ export function ActivityCell({ activity }: { activity?: EnvironmentDeploymentOpeif (!activity) return <span className="text-text-quaternary">--</span>const failed = activity.status === DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_FAILED+ const inProgress =+ activity.status === DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESSreturn (<div className="flex min-w-0 flex-col gap-0.5">@@ -40,6 +42,12 @@ export function ActivityCell({ activity }: { activity?: EnvironmentDeploymentOpefailed ? 'text-text-warning' : 'text-text-secondary',)}>+ {inProgress && (+ <span+ aria-hidden+ className="i-ri-loader-2-line size-3 shrink-0 animate-spin motion-reduce:animate-none"+ />+ )}{failed && (<span aria-hidden className="i-ri-error-warning-fill size-3 shrink-0 text-text-warning" />)}diff --git a/web/app/components/app/deploy/environment-table/deploy-menu/index.tsx b/web/app/components/app/deploy/environment-table/deploy-menu/index.tsxindex fff3d63b53f..7e1b8d9c92d 100644--- a/web/app/components/app/deploy/environment-table/deploy-menu/index.tsx+++ b/web/app/components/app/deploy/environment-table/deploy-menu/index.tsx@@ -12,11 +12,18 @@ import {} from '@langgenius/dify-ui/dropdown-menu'import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'-import { undeployedAppEnvironmentsAtom } from '../../state'+import Loading from '@/app/components/base/loading'+import {+ appEnvironmentsIsErrorAtom,+ appEnvironmentsIsLoadingAtom,+ appEnvironmentsIsRetryingAtom,+ appEnvironmentsRefetchAtom,+ undeployedAppEnvironmentsAtom,+} from '../../state'type EnvironmentDeployMenuProps = {appearance?: 'empty' | 'header'- onSelectEnvironment?: (environment: AppEnvironment) => void+ onSelectEnvironment: (environment: AppEnvironment) => void}export function EnvironmentDeployMenu({@@ -25,7 +32,11 @@ export function EnvironmentDeployMenu({}: EnvironmentDeployMenuProps) {const { t } = useTranslation('deployments')const { t: tCommon } = useTranslation('common')- const undeployedEnvironments = useAtomValue(undeployedAppEnvironmentsAtom)+ const undeployedEnvironments = useAtomValue(undeployedAppEnvironmentsAtom) ?? []+ const isLoading = useAtomValue(appEnvironmentsIsLoadingAtom)+ const isError = useAtomValue(appEnvironmentsIsErrorAtom)+ const isRetrying = useAtomValue(appEnvironmentsIsRetryingAtom)+ const refetchEnvironments = useAtomValue(appEnvironmentsRefetchAtom)const isEmptyState = appearance === 'empty'const label = tCommon(($) => $['appMenus.deploy'])@@ -40,28 +51,58 @@ export function EnvironmentDeployMenu({</Button>}/>- <DropdownMenuContent placement="bottom-end" sideOffset={4} className="w-42 rounded-xl p-1">+ <DropdownMenuContent+ aria-busy={isLoading || isRetrying}+ placement="bottom-end"+ sideOffset={4}+ className="w-42 rounded-xl p-1"+ ><DropdownMenuGroup><DropdownMenuLabel className="px-2 py-1 system-xs-medium-uppercase text-text-tertiary">{t(($) => $['card.notDeployed'])}</DropdownMenuLabel>- {undeployedEnvironments.length === 0 && (+ {isLoading ? (+ <Loading className="h-7" />+ ) : isError ? (+ <div className="flex flex-col items-center">+ <p role="alert" className="px-2 py-1.5 system-xs-regular text-text-destructive">+ {t(($) => $['common.loadFailed'])}+ </p>+ <Button+ type="button"+ size="small"+ variant="ghost"+ loading={isRetrying}+ disabled={isRetrying}+ className="gap-1 px-2"+ onClick={() => void refetchEnvironments()}+ >+ <span aria-hidden className="i-ri-reset-left-line size-3" />+ <span>{tCommon(($) => $['operation.retry'])}</span>+ </Button>+ </div>+ ) : undeployedEnvironments.length === 0 ? (<p role="status" className="px-2 py-1.5 system-xs-regular text-text-tertiary">{t(($) => $['deployDrawer.noNewEnvironmentAvailable'])}</p>- )}- {undeployedEnvironments.map((environment) => (- <DropdownMenuItem- key={environment.id}- className="mx-0 flex gap-2 px-2 py-1.5"- onClick={() => onSelectEnvironment?.(environment)}- >- <span aria-hidden className="i-ri-instance-line size-4 shrink-0 text-text-tertiary" />- <span className="grow truncate system-md-regular text-text-secondary">- {environment.display_name}- </span>- </DropdownMenuItem>- ))}+ ) : null}+ {!isLoading &&+ !isError &&+ undeployedEnvironments.map((environment) => (+ <DropdownMenuItem+ key={environment.id}+ className="mx-0 flex gap-2 px-2 py-1.5"+ onClick={() => onSelectEnvironment(environment)}+ >+ <span+ aria-hidden+ className="i-ri-instance-line size-4 shrink-0 text-text-tertiary"+ />+ <span className="grow truncate system-md-regular text-text-secondary">+ {environment.display_name}+ </span>+ </DropdownMenuItem>+ ))}</DropdownMenuGroup></DropdownMenuContent></DropdownMenu>diff --git a/web/app/components/app/deploy/environment-table/empty-state/index.tsx b/web/app/components/app/deploy/environment-table/empty-state/index.tsxindex 40fac6b5cb5..82d47cc7cf0 100644--- a/web/app/components/app/deploy/environment-table/empty-state/index.tsx+++ b/web/app/components/app/deploy/environment-table/empty-state/index.tsx@@ -9,7 +9,7 @@ import { EmptyTableSkeleton } from './skeleton'type EnvironmentTableEmptyProps =| {state: 'empty'- onSelectEnvironment?: (environment: AppEnvironment) => void+ onSelectEnvironment: (environment: AppEnvironment) => void}| {state: 'error'diff --git a/web/app/components/app/deploy/environment-table/index.tsx b/web/app/components/app/deploy/environment-table/index.tsxindex 1103233aa34..3711f311c64 100644--- a/web/app/components/app/deploy/environment-table/index.tsx+++ b/web/app/components/app/deploy/environment-table/index.tsx@@ -4,18 +4,25 @@ import type {AppEnvironment,EnvironmentDeployment,} from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { DeploymentVersion } from '../utils/version'import type { UndeployHandler } from './types'+import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { useAtomValue } from 'jotai'+import { memo } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'import {appEnvironmentDeploymentsAtom,appEnvironmentDeploymentsIsErrorAtom,- appEnvironmentDeploymentsIsFetchingAtom,appEnvironmentDeploymentsIsLoadingAtom,+ appEnvironmentDeploymentsIsRetryingAtom,appEnvironmentDeploymentsRefetchAtom,appEnvironmentUsageAtom,+ latestAppWorkflowVersionAtom,+ latestAppWorkflowVersionIsErrorAtom,+ latestAppWorkflowVersionIsRetryingAtom,+ latestAppWorkflowVersionRefetchAtom,} from '../state'import { EnvironmentDeployMenu } from './deploy-menu'import { EnvironmentTableEmpty } from './empty-state'@@ -24,128 +31,175 @@ import { EnvironmentRow } from './row'type EnvironmentTableProps = {appId: stringcanViewAccessPoint: boolean- onChangeVersion?: (deployment: EnvironmentDeployment) => void- onDeployLatest?: (deployment: EnvironmentDeployment) => void- onDeployToEnvironment?: (environment: AppEnvironment) => void- onRedeploy?: (deployment: EnvironmentDeployment) => void- onUndeploy?: UndeployHandler+ onChangeVersion: (deployment: EnvironmentDeployment) => void+ onDeployLatest: (deployment: EnvironmentDeployment, version: DeploymentVersion) => void+ onDeployToEnvironment: (environment: AppEnvironment) => void+ onRedeploy: (deployment: EnvironmentDeployment) => void+ onUndeploy: UndeployHandler}-export function EnvironmentTable({- appId,- canViewAccessPoint,- onChangeVersion,- onDeployLatest,- onDeployToEnvironment,- onRedeploy,- onUndeploy,-}: EnvironmentTableProps) {+function EnvironmentTableColumns() {+ return (+ <colgroup>+ <col className="w-43" />+ <col className="w-46" />+ <col className="w-44" />+ <col />+ <col className="w-36" />+ <col className="w-44" />+ </colgroup>+ )+}++function EnvironmentTableHeader() {const { t } = useTranslation('deployments')- const deployments = useAtomValue(appEnvironmentDeploymentsAtom) ?? []- const isLoading = useAtomValue(appEnvironmentDeploymentsIsLoadingAtom)- const isError = useAtomValue(appEnvironmentDeploymentsIsErrorAtom)- const isFetching = useAtomValue(appEnvironmentDeploymentsIsFetchingAtom)- const refetchDeployments = useAtomValue(appEnvironmentDeploymentsRefetchAtom)- const usage = useAtomValue(appEnvironmentUsageAtom)- const used = usage?.used ?? deployments.length- const total = usage?.total ?? deployments.length- const showLoadingState = isLoading && deployments.length === 0- const showErrorState = isError && deployments.length === 0- const isRetrying = showErrorState && isFetching- const showEmptyState = !isLoading && !isError && deployments.length === 0return (- <section- aria-labelledby="deploy-environments-title"- aria-busy={showLoadingState || isRetrying}- className="flex min-h-0 grow flex-col gap-3"- >- <div className="flex shrink-0 items-center justify-between">- <div className="flex min-w-0 items-center gap-2">- <h2- id="deploy-environments-title"- className="truncate system-md-semibold text-text-primary"- >- {t(($) => $['studio.environments'])}- </h2>- <span aria-hidden className="system-xs-regular text-text-quaternary">- ·- </span>- <span className="truncate system-xs-regular text-text-tertiary">- {t(($) => $['studio.environmentsInUse'], {- total,- used,- })}- </span>- </div>- <EnvironmentDeployMenu onSelectEnvironment={onDeployToEnvironment} />- </div>+ <thead>+ <tr className="sticky top-0 z-10 h-7 bg-background-section-burn">+ <th className="rounded-l-lg pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['deployTab.col.environment'])}+ </th>+ <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['studio.liveVersion'])}+ </th>+ <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['deployTab.col.status'])}+ </th>+ <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['studio.lastActivity'])}+ </th>+ <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['studio.accessPoints'])}+ </th>+ <th className="rounded-r-lg pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['deployTab.col.actions'])}+ </th>+ </tr>+ </thead>+ )+}- <div- className={cn(- 'min-h-0 w-full grow overflow-y-auto',- deployments.length > 0 ? 'overflow-x-auto' : 'overflow-x-hidden',- )}+export const EnvironmentTable = memo(+ ({+ appId,+ canViewAccessPoint,+ onChangeVersion,+ onDeployLatest,+ onDeployToEnvironment,+ onRedeploy,+ onUndeploy,+ }: EnvironmentTableProps) => {+ const { t } = useTranslation('deployments')+ const { t: tCommon } = useTranslation('common')+ const deployments = useAtomValue(appEnvironmentDeploymentsAtom) ?? []+ const isLoading = useAtomValue(appEnvironmentDeploymentsIsLoadingAtom)+ const isError = useAtomValue(appEnvironmentDeploymentsIsErrorAtom)+ const isRetrying = useAtomValue(appEnvironmentDeploymentsIsRetryingAtom)+ const refetchDeployments = useAtomValue(appEnvironmentDeploymentsRefetchAtom)+ const usage = useAtomValue(appEnvironmentUsageAtom)+ const latestVersion = useAtomValue(latestAppWorkflowVersionAtom)+ const latestVersionIsError = useAtomValue(latestAppWorkflowVersionIsErrorAtom)+ const latestVersionIsRetrying = useAtomValue(latestAppWorkflowVersionIsRetryingAtom)+ const refetchLatestVersion = useAtomValue(latestAppWorkflowVersionRefetchAtom)+ const deployableLatestVersion = latestVersionIsError ? undefined : latestVersion+ const showLoadingState = isLoading && deployments.length === 0+ const showErrorState = isError && deployments.length === 0+ const showEmptyState = !isLoading && !isError && deployments.length === 0++ return (+ <section+ aria-labelledby="deploy-environments-title"+ aria-busy={showLoadingState || isRetrying || latestVersionIsRetrying}+ className="flex min-h-0 grow flex-col gap-3">- {showLoadingState ? (- <Loading className="h-full" />- ) : showErrorState ? (- <EnvironmentTableEmpty- state="error"- isRetrying={isRetrying}- onRetry={() => void refetchDeployments()}- />- ) : showEmptyState ? (- <EnvironmentTableEmpty state="empty" onSelectEnvironment={onDeployToEnvironment} />- ) : (- <table className="w-full min-w-260 table-fixed border-separate border-spacing-0">- <colgroup>- <col className="w-43" />- <col className="w-46" />- <col className="w-44" />- <col />- <col className="w-36" />- <col className="w-44" />- </colgroup>- <thead>- <tr className="sticky top-0 z-10 h-7 bg-background-section-burn">- <th className="rounded-l-lg pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['deployTab.col.environment'])}- </th>- <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['studio.liveVersion'])}- </th>- <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['deployTab.col.status'])}- </th>- <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['studio.lastActivity'])}- </th>- <th className="pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['studio.accessPoints'])}- </th>- <th className="rounded-r-lg pr-2 pl-3 text-left system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['deployTab.col.actions'])}- </th>- </tr>- </thead>- <tbody>- {deployments.map((row) => (- <EnvironmentRow- key={row.environment.id}- appId={appId}- canViewAccessPoint={canViewAccessPoint}- row={row}- onChangeVersion={onChangeVersion}- onDeployLatest={onDeployLatest}- onRedeploy={onRedeploy}- onUndeploy={onUndeploy}- />- ))}- </tbody>- </table>+ <div className="flex shrink-0 items-center justify-between">+ <div className="flex min-w-0 items-center gap-2">+ <h2+ id="deploy-environments-title"+ className="truncate system-md-semibold text-text-primary"+ >+ {t(($) => $['studio.environments'])}+ </h2>+ {usage && (+ <>+ <span aria-hidden className="system-xs-regular text-text-quaternary">+ ·+ </span>+ <span className="truncate system-xs-regular text-text-tertiary">+ {t(($) => $['studio.environmentsInUse'], usage)}+ </span>+ </>+ )}+ </div>+ <EnvironmentDeployMenu onSelectEnvironment={onDeployToEnvironment} />+ </div>++ {latestVersionIsError && (+ <div+ role="alert"+ className="flex shrink-0 items-center gap-2 rounded-xl border border-state-destructive-border bg-state-destructive-hover-alt p-3"+ >+ <span+ aria-hidden+ className="i-ri-error-warning-fill size-4 shrink-0 text-text-destructive"+ />+ <p className="grow system-sm-medium text-text-destructive">+ {t(($) => $['studio.latestVersionLoadFailed'])}+ </p>+ <Button+ size="small"+ variant="secondary"+ loading={latestVersionIsRetrying}+ disabled={latestVersionIsRetrying}+ onClick={() => void refetchLatestVersion()}+ className="gap-1 px-2"+ >+ <span aria-hidden className="i-ri-reset-left-line size-3" />+ <span>{tCommon(($) => $['operation.retry'])}</span>+ </Button>+ </div>)}- </div>- </section>- )-}++ <div+ className={cn(+ 'min-h-0 w-full grow overflow-y-auto',+ deployments.length > 0 ? 'overflow-x-auto' : 'overflow-x-hidden',+ )}+ >+ {showLoadingState ? (+ <Loading className="h-full" />+ ) : showErrorState ? (+ <EnvironmentTableEmpty+ state="error"+ isRetrying={isRetrying}+ onRetry={() => void refetchDeployments()}+ />+ ) : showEmptyState ? (+ <EnvironmentTableEmpty state="empty" onSelectEnvironment={onDeployToEnvironment} />+ ) : (+ <table className="w-full min-w-260 table-fixed border-separate border-spacing-0">+ <EnvironmentTableColumns />+ <EnvironmentTableHeader />+ <tbody>+ {deployments.map((row) => (+ <EnvironmentRow+ key={row.environment.id}+ appId={appId}+ canViewAccessPoint={canViewAccessPoint}+ latestVersion={deployableLatestVersion}+ row={row}+ onChangeVersion={onChangeVersion}+ onDeployLatest={onDeployLatest}+ onRedeploy={onRedeploy}+ onUndeploy={onUndeploy}+ />+ ))}+ </tbody>+ </table>+ )}+ </div>+ </section>+ )+ },+)diff --git a/web/app/components/app/deploy/environment-table/row-actions.tsx b/web/app/components/app/deploy/environment-table/row-actions.tsxindex dca7b0f9d6b..976807ceab1 100644--- a/web/app/components/app/deploy/environment-table/row-actions.tsx+++ b/web/app/components/app/deploy/environment-table/row-actions.tsx@@ -1,5 +1,6 @@import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'-import type { EnvironmentDeploymentAction } from '../state'+import type { EnvironmentDeploymentAction } from '../utils/environment-deployment'+import type { DeploymentVersion } from '../utils/version'import type { UndeployHandler } from './types'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'@@ -11,10 +12,11 @@ import {DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { toast } from '@langgenius/dify-ui/toast'import { Fragment, useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { getWorkflowVersionName } from '@/app/components/workflow/utils/version'-import { getEnvironmentDeploymentActions } from '../state'+import { getEnvironmentDeploymentActions } from '../utils/environment-deployment'import { UndeployConfirmDialog } from './undeploy-confirm-dialog'function rowActionLabel(@@ -52,17 +54,19 @@ const ROW_ACTION_ICON_CLASS_NAMES: Record<EnvironmentDeploymentAction['kind'], s}export function EnvironmentRowActions({+ latestVersion,row,onChangeVersion,onDeployLatest,onRedeploy,onUndeploy,}: {+ latestVersion?: DeploymentVersionrow: EnvironmentDeployment- onChangeVersion?: (deployment: EnvironmentDeployment) => void- onDeployLatest?: (deployment: EnvironmentDeployment) => void- onRedeploy?: (deployment: EnvironmentDeployment) => void- onUndeploy?: UndeployHandler+ onChangeVersion: (deployment: EnvironmentDeployment) => void+ onDeployLatest: (deployment: EnvironmentDeployment, version: DeploymentVersion) => void+ onRedeploy: (deployment: EnvironmentDeployment) => void+ onUndeploy: UndeployHandler}) {const { t } = useTranslation('deployments')const { t: tWorkflow } = useTranslation('workflow')@@ -73,7 +77,9 @@ export function EnvironmentRowActions({)const [showUndeployConfirm, setShowUndeployConfirm] = useState(false)const [isUndeploying, setIsUndeploying] = useState(false)- const actions = getEnvironmentDeploymentActions(row)+ const actions = getEnvironmentDeploymentActions(row, {+ deployLatestDisabled: !latestVersion,+ })const primaryAction = actions[0]const moreActions = actions.slice(1)@@ -83,21 +89,27 @@ export function EnvironmentRowActions({switch (action.kind) {case 'changeVersion':- onChangeVersion?.(row)+ onChangeVersion(row)break- case 'deployLatest':- onDeployLatest?.(row)+ case 'deployLatest': {+ if (!latestVersion) {+ toast.error(t(($) => $['studio.latestVersionLoadFailed']))+ return+ }++ onDeployLatest(row, latestVersion)break+ }case 'redeploy':case 'retry':- onRedeploy?.(row)+ onRedeploy(row)breakcase 'undeploy':setShowUndeployConfirm(true)break}},- [onChangeVersion, onDeployLatest, onRedeploy, row],+ [latestVersion, onChangeVersion, onDeployLatest, onRedeploy, row, t],)const handleUndeploy = useCallback(async () => {@@ -105,7 +117,7 @@ export function EnvironmentRowActions({setIsUndeploying(true)try {- await onUndeploy?.(row)+ await onUndeploy(row)setShowUndeployConfirm(false)} catch {// The request layer reports the error; keep the dialog open so the user can retry.diff --git a/web/app/components/app/deploy/environment-table/row.tsx b/web/app/components/app/deploy/environment-table/row.tsxindex b1d4ce7cd6d..f0bf850a87e 100644--- a/web/app/components/app/deploy/environment-table/row.tsx+++ b/web/app/components/app/deploy/environment-table/row.tsx@@ -1,85 +1,98 @@import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'-import type { AccessPoint } from '../access-point'+import type { AccessPoint } from '../utils/access-point'+import type { DeploymentVersion } from '../utils/version'import type { UndeployHandler } from './types'-import { ACCESS_POINT_ORDER, getAccessPointHref } from '../access-point'+import { RuntimeState } from '@dify/contracts/enterprise-app-deploy/types.gen'+import { memo } from 'react'import { AccessPointIcon } from '../shared/access-point-icon'-import { DeploymentStatus } from '../shared/deployment-status'+import { RuntimeStateIndicator } from '../shared/runtime-state'import { VersionLabel } from '../shared/version-label'+import { ACCESS_POINT_ORDER, getAccessPointHref } from '../utils/access-point'import { ActivityCell } from './activity-cell'import { EnvironmentRowActions } from './row-actions'-export function EnvironmentRow({- appId,- canViewAccessPoint,- row,- onChangeVersion,- onDeployLatest,- onRedeploy,- onUndeploy,-}: {- appId: string- canViewAccessPoint: boolean- row: EnvironmentDeployment- onChangeVersion?: (deployment: EnvironmentDeployment) => void- onDeployLatest?: (deployment: EnvironmentDeployment) => void- onRedeploy?: (deployment: EnvironmentDeployment) => void- onUndeploy?: UndeployHandler-}) {- const isAccessPointActive = (accessPoint: AccessPoint) => {- if (accessPoint === 'webApp') return row.access.enable_site- if (accessPoint === 'serviceApi') return row.access.enable_api- return false- }+export const EnvironmentRow = memo(+ ({+ appId,+ canViewAccessPoint,+ latestVersion,+ row,+ onChangeVersion,+ onDeployLatest,+ onRedeploy,+ onUndeploy,+ }: {+ appId: string+ canViewAccessPoint: boolean+ latestVersion?: DeploymentVersion+ row: EnvironmentDeployment+ onChangeVersion: (deployment: EnvironmentDeployment) => void+ onDeployLatest: (deployment: EnvironmentDeployment, version: DeploymentVersion) => void+ onRedeploy: (deployment: EnvironmentDeployment) => void+ onUndeploy: UndeployHandler+ }) => {+ const runtimeState = row.deployment+ ? row.deployment.runtimeState+ : RuntimeState.RUNTIME_STATE_UNDEPLOYED- return (- <tr className="h-14 border-b border-divider-subtle hover:bg-state-base-hover">- <td className="border-b border-divider-subtle pr-2 pl-3">- <div className="flex min-w-0 items-center gap-2.5">- <span className="flex size-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-regular bg-components-panel-bg text-text-secondary">- <span aria-hidden className="i-ri-instance-line size-3.5" />- </span>- <span className="truncate system-md-medium text-text-secondary">- {row.environment.display_name}- </span>- </div>- </td>- <td className="border-b border-divider-subtle pr-2 pl-3">- <VersionLabel- version={row.deployment?.current_version}- versionsBehind={row.deployment?.versions_behind}- />- </td>- <td className="border-b border-divider-subtle px-2">- <DeploymentStatus status={row.deployment?.status} />- </td>- <td className="border-b border-divider-subtle pr-2 pl-3">- <ActivityCell activity={row.deployment?.latest_operation} />- </td>- <td className="border-b border-divider-subtle pr-2 pl-3">- <div className="flex items-center gap-1">- {ACCESS_POINT_ORDER.map((accessPoint) => (- <AccessPointIcon- key={accessPoint}- accessPoint={accessPoint}- active={isAccessPointActive(accessPoint)}- href={- canViewAccessPoint- ? getAccessPointHref(appId, row.environment.id, accessPoint)- : undefined- }- />- ))}- </div>- </td>- <td className="border-b border-divider-subtle pr-2 pl-3">- <EnvironmentRowActions- row={row}- onChangeVersion={onChangeVersion}- onDeployLatest={onDeployLatest}- onRedeploy={onRedeploy}- onUndeploy={onUndeploy}- />- </td>- </tr>- )-}+ const isAccessPointActive = (accessPoint: AccessPoint) => {+ if (accessPoint === 'webApp') return row.access.enable_site+ if (accessPoint === 'serviceApi') return row.access.enable_api+ return false+ }++ return (+ <tr className="h-14 border-b border-divider-subtle hover:bg-state-base-hover">+ <td className="border-b border-divider-subtle pr-2 pl-3">+ <div className="flex min-w-0 items-center gap-2.5">+ <span className="flex size-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-regular bg-components-panel-bg text-text-secondary">+ <span aria-hidden className="i-ri-instance-line size-3.5" />+ </span>+ <span className="truncate system-md-medium text-text-secondary">+ {row.environment.display_name}+ </span>+ </div>+ </td>+ <td className="border-b border-divider-subtle pr-2 pl-3">+ <VersionLabel+ version={row.deployment?.current_version}+ versionsBehind={row.deployment?.versions_behind}+ />+ </td>+ <td className="border-b border-divider-subtle px-2">+ <RuntimeStateIndicator runtimeState={runtimeState} />+ </td>+ <td className="border-b border-divider-subtle pr-2 pl-3">+ <ActivityCell activity={row.deployment?.latest_operation} />+ </td>+ <td className="border-b border-divider-subtle pr-2 pl-3">+ <div className="flex items-center gap-1">+ {ACCESS_POINT_ORDER.map((accessPoint) => (+ <AccessPointIcon+ key={accessPoint}+ accessPoint={accessPoint}+ active={isAccessPointActive(accessPoint)}+ href={+ canViewAccessPoint+ ? getAccessPointHref(appId, row.environment.id, accessPoint)+ : undefined+ }+ />+ ))}+ </div>+ </td>+ <td className="border-b border-divider-subtle pr-2 pl-3">+ <EnvironmentRowActions+ latestVersion={latestVersion}+ row={row}+ onChangeVersion={onChangeVersion}+ onDeployLatest={onDeployLatest}+ onRedeploy={onRedeploy}+ onUndeploy={onUndeploy}+ />+ </td>+ </tr>+ )+ },+)+EnvironmentRow.displayName = 'EnvironmentRow'diff --git a/web/app/components/app/deploy/use-deploy-workflow.ts b/web/app/components/app/deploy/hooks/use-deploy-workflow.tssimilarity index 100%rename from web/app/components/app/deploy/use-deploy-workflow.tsrename to web/app/components/app/deploy/hooks/use-deploy-workflow.tsdiff --git a/web/app/components/app/deploy/use-refresh-app-environments-after-deployment-polling.ts b/web/app/components/app/deploy/hooks/use-refresh-app-environments-after-deployment-polling.tssimilarity index 91%rename from web/app/components/app/deploy/use-refresh-app-environments-after-deployment-polling.tsrename to web/app/components/app/deploy/hooks/use-refresh-app-environments-after-deployment-polling.tsindex 1a58435ee18..b3b02c37f3e 100644--- a/web/app/components/app/deploy/use-refresh-app-environments-after-deployment-polling.ts+++ b/web/app/components/app/deploy/hooks/use-refresh-app-environments-after-deployment-polling.ts@@ -4,7 +4,7 @@ import type { ListEnvironmentDeploymentsResponse } from '@dify/contracts/enterprimport { hashKey, useQueryClient } from '@tanstack/react-query'import { useEffect } from 'react'import { consoleQuery } from '@/service/client'-import { hasInProgressEnvironmentDeployments } from './state'+import { hasDeploymentsRequiringPolling } from '../utils/environment-deployment'export function useRefreshAppEnvironmentsAfterDeploymentPolling(appId: string) {const queryClient = useQueryClient()@@ -32,7 +32,7 @@ export function useRefreshAppEnvironmentsAfterDeploymentPolling(appId: string) {environmentDeploymentsQuery.queryKey,)- return hasInProgressEnvironmentDeployments(data?.environment_deployments ?? [])+ return hasDeploymentsRequiringPolling(data?.environment_deployments ?? [])}let wasPolling = isPolling()diff --git a/web/app/components/app/deploy/use-undeploy-workflow.ts b/web/app/components/app/deploy/hooks/use-undeploy-workflow.tssimilarity index 73%rename from web/app/components/app/deploy/use-undeploy-workflow.tsrename to web/app/components/app/deploy/hooks/use-undeploy-workflow.tsindex 2622202ddb2..1dbf3a7705b 100644--- a/web/app/components/app/deploy/use-undeploy-workflow.ts+++ b/web/app/components/app/deploy/hooks/use-undeploy-workflow.ts@@ -1,11 +1,14 @@'use client'import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'+import { toast } from '@langgenius/dify-ui/toast'import { useMutation } from '@tanstack/react-query'import { useCallback } from 'react'+import { useTranslation } from 'react-i18next'import { consoleQuery } from '@/service/client'export function useUndeployWorkflow(appId: string) {+ const { t } = useTranslation('deployments')const { mutateAsync } = useMutation(consoleQuery.enterprise.appDeploy.deploymentService.undeployWorkflow.mutationOptions(),)@@ -13,7 +16,10 @@ export function useUndeployWorkflow(appId: string) {return useCallback((deployment: EnvironmentDeployment) => {const workflowId = deployment.deployment?.current_version?.id- if (!workflowId) return+ if (!workflowId) {+ toast.error(t(($) => $['deployTab.undeployUnavailable']))+ return+ }return mutateAsync({params: {@@ -23,6 +29,6 @@ export function useUndeployWorkflow(appId: string) {},}).then(() => undefined)},- [appId, mutateAsync],+ [appId, mutateAsync, t],)}diff --git a/web/app/components/app/deploy/index.tsx b/web/app/components/app/deploy/index.tsxindex 11a2d8d458f..8ef0fa7f57e 100644--- a/web/app/components/app/deploy/index.tsx+++ b/web/app/components/app/deploy/index.tsx@@ -1,26 +1,34 @@'use client'-import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'-import type { DeploymentDialogRequest } from './deployment-dialog/types'-import type { DocPathWithoutLang } from '@/types/doc-paths'+import type {+ AppEnvironment,+ EnvironmentDeployment,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { DeploymentDialogRequest } from './types'+import type { DeploymentVersion } from './utils/version'import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'-import { useState } from 'react'+import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { useStore as useAppStore } from '@/app/components/app/store'import Loading from '@/app/components/base/loading'-import { useDocLink } from '@/context/i18n'+import { getEnterpriseDocUrl, useLocale } from '@/context/i18n'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'+import { getDocLanguage } from '@/i18n-config/language'+import dynamic from '@/next/dynamic'import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'import { BuiltInEnvironmentCard } from './built-in-environment-card'-import { DeploymentDialog } from './deployment-dialog'import { EnvironmentTable } from './environment-table'-import { AppDeployStateBoundary, latestAppWorkflowVersionAtom } from './state'-import { useRefreshAppEnvironmentsAfterDeploymentPolling } from './use-refresh-app-environments-after-deployment-polling'-import { useUndeployWorkflow } from './use-undeploy-workflow'-import { toDeploymentVersion } from './version'+import { useRefreshAppEnvironmentsAfterDeploymentPolling } from './hooks/use-refresh-app-environments-after-deployment-polling'+import { useUndeployWorkflow } from './hooks/use-undeploy-workflow'+import { AppDeployStateBoundary } from './state'+import { toDeploymentVersion } from './utils/version'++const DeploymentDialog = dynamic(() =>+ import('./deployment-dialog').then((module) => module.DeploymentDialog),+)function AppDeployContent({appId,@@ -32,42 +40,71 @@ function AppDeployContent({const { t } = useTranslation('deployments')const { t: tCommon } = useTranslation('common')const { t: tWorkflow } = useTranslation('workflow')- const docLink = useDocLink()- // TODO: Replace useDocLink with the EE-specific generator for the versioned- // `en/3.13.x/use/deploy/overview.mdx` URL once it is available.- const deployOverviewDocUrl = docLink('/use/deploy/overview' as DocPathWithoutLang)+ const locale = useLocale()+ const docLanguage = getDocLanguage(locale)+ const deployOverviewDocUrl = getEnterpriseDocUrl('/use/deploy/overview', docLanguage)const [deploymentRequest, setDeploymentRequest] = useState<DeploymentDialogRequest>()- const latestVersion = useAtomValue(latestAppWorkflowVersionAtom)useRefreshAppEnvironmentsAfterDeploymentPolling(appId)const undeployWorkflow = useUndeployWorkflow(appId)- const handleRedeploy = (deployment: EnvironmentDeployment) => {- const deploymentState = deployment.deployment- const version =- deploymentState?.latest_operation?.target_version ?? deploymentState?.current_version- const environment = deployment.environment.display_name- const environmentId = deployment.environment.id+ const handleDeployToEnvironment = useCallback((environment: AppEnvironment) => {+ setDeploymentRequest({+ environment: environment.display_name,+ environmentId: environment.id,+ kind: 'deploy',+ })+ }, [])+ const handleChangeVersion = useCallback((deployment: EnvironmentDeployment) => {+ setDeploymentRequest({+ currentVersionId: deployment.deployment?.current_version?.id,+ environment: deployment.environment.display_name,+ environmentId: deployment.environment.id,+ kind: 'changeVersion',+ })+ }, [])+ const handleDeployLatest = useCallback(+ (deployment: EnvironmentDeployment, latestVersion: DeploymentVersion) => {+ setDeploymentRequest({+ currentVersionId: deployment.deployment?.current_version?.id,+ environment: deployment.environment.display_name,+ environmentId: deployment.environment.id,+ initialVersion: latestVersion,+ kind: 'deployLatest',+ })+ },+ [],+ )+ const handleRedeploy = useCallback(+ (deployment: EnvironmentDeployment) => {+ const deploymentState = deployment.deployment+ const version =+ deploymentState?.latest_operation?.target_version ?? deploymentState?.current_version+ const environment = deployment.environment.display_name+ const environmentId = deployment.environment.id++ if (!version) {+ setDeploymentRequest({+ environment,+ environmentId,+ kind: 'changeVersion',+ })+ return+ }- if (!version) {setDeploymentRequest({+ currentVersionId: deploymentState?.current_version?.id,environment,environmentId,- kind: 'changeVersion',+ initialVersion: toDeploymentVersion(+ version,+ tWorkflow(($) => $['versionHistory.defaultName']),+ ),+ kind: 'redeploy',})- return- }-- setDeploymentRequest({- currentVersionId: deploymentState?.current_version?.id,- environment,- environmentId,- initialVersion: toDeploymentVersion(- version,- tWorkflow(($) => $['versionHistory.defaultName']),- ),- kind: 'redeploy',- })- }+ },+ [tWorkflow],+ )+ const handleCloseDeploymentDialog = useCallback(() => setDeploymentRequest(undefined), [])return (<>@@ -96,42 +133,21 @@ function AppDeployContent({<EnvironmentTableappId={appId}canViewAccessPoint={canViewAccessPoint}- onDeployToEnvironment={(environment) =>- setDeploymentRequest({- environment: environment.display_name,- environmentId: environment.id,- kind: 'deploy',- })- }- onChangeVersion={(deployment) =>- setDeploymentRequest({- currentVersionId: deployment.deployment?.current_version?.id,- environment: deployment.environment.display_name,- environmentId: deployment.environment.id,- kind: 'changeVersion',- })- }- onDeployLatest={(deployment) => {- if (!latestVersion) return-- setDeploymentRequest({- currentVersionId: deployment.deployment?.current_version?.id,- environment: deployment.environment.display_name,- environmentId: deployment.environment.id,- initialVersion: latestVersion,- kind: 'deployLatest',- })- }}+ onDeployToEnvironment={handleDeployToEnvironment}+ onChangeVersion={handleChangeVersion}+ onDeployLatest={handleDeployLatest}onRedeploy={handleRedeploy}onUndeploy={undeployWorkflow}/></div></main>- <DeploymentDialog- appId={appId}- request={deploymentRequest}- onClose={() => setDeploymentRequest(undefined)}- />+ {deploymentRequest && (+ <DeploymentDialog+ appId={appId}+ request={deploymentRequest}+ onClose={handleCloseDeploymentDialog}+ />+ )}</>)}@@ -152,7 +168,11 @@ export default function AppDeploy() {workspacePermissionKeys,})- if (appDetail.mode !== AppModeEnum.WORKFLOW || !canDeploy) return null+ if (+ (appDetail.mode !== AppModeEnum.WORKFLOW && appDetail.mode !== AppModeEnum.ADVANCED_CHAT) ||+ !canDeploy+ )+ return nullreturn (<AppDeployStateBoundary appId={appDetail.id}>diff --git a/web/app/components/app/deploy/shared/access-point-icon.tsx b/web/app/components/app/deploy/shared/access-point-icon.tsxindex 052a5efee37..a8d4b1daf2b 100644--- a/web/app/components/app/deploy/shared/access-point-icon.tsx+++ b/web/app/components/app/deploy/shared/access-point-icon.tsx@@ -1,6 +1,6 @@'use client'-import type { AccessPoint } from '../access-point'+import type { AccessPoint } from '../utils/access-point'import { cn } from '@langgenius/dify-ui/cn'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useTranslation } from 'react-i18next'diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/__tests__/credential-field.spec.tsx b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/credential-field.spec.tsxsimilarity index 52%rename from web/app/components/app/deploy/deployment-dialog/deployment-configuration/__tests__/credential-field.spec.tsxrename to web/app/components/app/deploy/shared/deployment-configuration/__tests__/credential-field.spec.tsxindex c10c9f02e38..14491ac40e4 100644--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/__tests__/credential-field.spec.tsx+++ b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/credential-field.spec.tsx@@ -1,4 +1,8 @@-import type { CredentialSlot } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type {+ CredentialSlot,+ WorkflowPath,+ WorkflowReference,+} from '@dify/contracts/enterprise-app-deploy/types.gen'import { PluginCategory } from '@dify/contracts/enterprise-app-deploy/types.gen'import { screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -6,6 +10,14 @@ import { API_PREFIX } from '@/config'import { renderWithConsoleQuery } from '@/test/console/query-data'import { CredentialField } from '../credential-field'+vi.mock('react-i18next', async () => {+ const { createReactI18nextMock } = await import('@/test/i18n-mock')+ return createReactI18nextMock({+ 'deployments.studio.precheck.from': 'From',+ 'deployments.studio.precheck.nodeCount_other': '{{count}} nodes',+ })+})+const themeState = vi.hoisted(() => ({theme: 'light',}))@@ -30,6 +42,21 @@ const credentialSlot: CredentialSlot = {provider_id: 'langgenius/deepseek',}+function workflowReference(name: string, suffix: string): WorkflowReference {+ return {+ app_id: `app-${suffix}`,+ icon: '🤖',+ icon_background: '#FFEAD5',+ icon_type: 'emoji',+ name,+ workflow_id: `workflow-${suffix}`,+ }+}++function workflowPath(...workflows: WorkflowReference[]): WorkflowPath {+ return { workflows }+}+function renderCredentialField() {return renderWithConsoleQuery(<CredentialField slot={credentialSlot} value="credential-1" onChange={vi.fn()} />,@@ -89,4 +116,56 @@ describe('CredentialField', () => {).toBeInTheDocument()expect(within(listbox).queryByRole('option')).not.toBeInTheDocument()})++ it('shows the only source app name and opens its source preview', async () => {+ const user = userEvent.setup()+ const root = workflowReference('Deployed app', 'root')+ const source = workflowReference('Order fulfillment', 'order')+ renderWithConsoleQuery(+ <CredentialField+ slot={credentialSlot}+ paths={[workflowPath(root, source)]}+ value="credential-1"+ onChange={vi.fn()}+ />,+ )++ const sourceButton = screen.getByRole('button', {+ name: 'Deepseek: From Order fulfillment',+ })+ await user.hover(sourceButton)++ const preview = await screen.findByRole('dialog', { name: 'Deepseek' })+ expect(+ within(preview).getByRole('link', { name: /Deployed app.*Order fulfillment/ }),+ ).toHaveAttribute('href', '/app/app-order/workflow')+ })++ it('shows only a count when several source apps use the credential', async () => {+ const user = userEvent.setup()+ renderWithConsoleQuery(+ <CredentialField+ slot={credentialSlot}+ paths={[+ workflowPath(+ workflowReference('Deployed app', 'root'),+ workflowReference('Order fulfillment', 'order'),+ ),+ workflowPath(+ workflowReference('Deployed app', 'root'),+ workflowReference('Audit workflow', 'audit'),+ ),+ ]}+ value="credential-1"+ onChange={vi.fn()}+ />,+ )++ const sourceButton = screen.getByRole('button', { name: 'Deepseek: From 2 nodes' })+ expect(sourceButton).not.toHaveTextContent('Order fulfillment')+ await user.click(sourceButton)++ const preview = await screen.findByRole('dialog', { name: 'Deepseek' })+ expect(within(preview).getAllByRole('link')).toHaveLength(2)+ })})diff --git a/web/app/components/app/deploy/shared/deployment-configuration/__tests__/deployment-configuration-cache.spec.tsx b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/deployment-configuration-cache.spec.tsxnew file mode 100644index 00000000000..b0c45aab3d3--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/deployment-configuration-cache.spec.tsx@@ -0,0 +1,171 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen, waitFor, within } from '@testing-library/react'+import { DeploymentConfiguration } from '../index'++const APP_ID = 'app-1'+const ENVIRONMENT_ID = 'staging'+const WORKFLOW_ID = 'workflow-1'++function createQueryClient() {+ return new QueryClient({+ defaultOptions: {+ mutations: { retry: false },+ queries: {+ retry: false,+ staleTime: 5 * 60 * 1000,+ },+ },+ })+}++function renderConfiguration(queryClient: QueryClient) {+ return render(+ <QueryClientProvider client={queryClient}>+ <DeploymentConfiguration+ appId={APP_ID}+ embedded+ request={{+ environment: 'Staging',+ environmentId: ENVIRONMENT_ID,+ initialVersion: { id: WORKFLOW_ID, name: 'Release 1' },+ kind: 'deployLatest',+ }}+ version={{ id: WORKFLOW_ID, name: 'Release 1' }}+ onClose={vi.fn()}+ />+ </QueryClientProvider>,+ )+}++describe('DeploymentConfiguration query freshness', () => {+ it('fetches precheck and deployment options again whenever the form is reopened', async () => {+ const requestCounts = {+ deploymentOptions: 0,+ precheck: 0,+ }+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init)+ const pathname = new URL(request.url).pathname++ if (+ pathname.endsWith(`/enterprise/app-deploy/apps/${APP_ID}/workflows/${WORKFLOW_ID}:precheck`)+ ) {+ requestCounts.precheck += 1+ return new Response(JSON.stringify({ unsupported_nodes: [] }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ })+ }++ if (+ pathname.endsWith(+ `/enterprise/app-deploy/apps/${APP_ID}/workflows/${WORKFLOW_ID}/environments/${ENVIRONMENT_ID}/deployment-options`,+ )+ ) {+ requestCounts.deploymentOptions += 1+ return new Response(+ JSON.stringify({ credential_slots: [], environment_variable_groups: [] }),+ {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ },+ )+ }++ throw new Error(`Unexpected request: ${request.method} ${request.url}`)+ })++ const queryClient = createQueryClient()+ const firstRender = renderConfiguration(queryClient)++ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'common.appMenus.deploy' })).toBeEnabled()+ })+ expect(requestCounts).toEqual({ deploymentOptions: 1, precheck: 1 })++ firstRender.unmount()+ await waitFor(() => {+ expect(queryClient.getQueryCache().getAll()).toHaveLength(0)+ })++ renderConfiguration(queryClient)++ await waitFor(() => {+ expect(requestCounts).toEqual({ deploymentOptions: 2, precheck: 2 })+ expect(screen.getByRole('button', { name: 'common.appMenus.deploy' })).toBeEnabled()+ })+ })++ it('shows the backend message when precheck fails', async () => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init)+ const pathname = new URL(request.url).pathname++ if (+ pathname.endsWith(`/enterprise/app-deploy/apps/${APP_ID}/workflows/${WORKFLOW_ID}:precheck`)+ ) {+ return new Response(+ JSON.stringify({+ code: 422,+ message: 'workflow tool dependencies form a cycle',+ metadata: {},+ reason: 'APPDEPLOY_WORKFLOW_NOT_DEPLOYABLE',+ }),+ {+ headers: { 'Content-Type': 'application/json' },+ status: 422,+ },+ )+ }++ throw new Error(`Unexpected request: ${request.method} ${request.url}`)+ })++ const view = renderConfiguration(createQueryClient())++ const alert = await within(view.container).findByRole('alert')+ expect(alert).toHaveTextContent('workflow tool dependencies form a cycle')+ })++ it('shows the backend message when deployment options fail', async () => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const request = input instanceof Request ? input : new Request(input, init)+ const pathname = new URL(request.url).pathname++ if (+ pathname.endsWith(`/enterprise/app-deploy/apps/${APP_ID}/workflows/${WORKFLOW_ID}:precheck`)+ ) {+ return new Response(JSON.stringify({ unsupported_nodes: [] }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ })+ }++ if (+ pathname.endsWith(+ `/enterprise/app-deploy/apps/${APP_ID}/workflows/${WORKFLOW_ID}/environments/${ENVIRONMENT_ID}/deployment-options`,+ )+ ) {+ return new Response(+ JSON.stringify({+ code: 422,+ message: 'workflow deployment options are invalid',+ metadata: {},+ reason: 'APPDEPLOY_WORKFLOW_NOT_DEPLOYABLE',+ }),+ {+ headers: { 'Content-Type': 'application/json' },+ status: 422,+ },+ )+ }++ throw new Error(`Unexpected request: ${request.method} ${request.url}`)+ })++ const view = renderConfiguration(createQueryClient())++ const alert = await within(view.container).findByRole('alert')+ expect(alert).toHaveTextContent('workflow deployment options are invalid')+ })+})diff --git a/web/app/components/app/deploy/shared/deployment-configuration/__tests__/deployment-precheck-alert.spec.tsx b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/deployment-precheck-alert.spec.tsxnew file mode 100644index 00000000000..623c8fef38b--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/deployment-precheck-alert.spec.tsx@@ -0,0 +1,131 @@+import type {+ UnsupportedNode,+ WorkflowAsToolDependency,+ WorkflowReference,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { DeploymentPrecheckAlert } from '../deployment-precheck-alert'++vi.mock('react-i18next', async () => {+ const { createReactI18nextMock } = await import('@/test/i18n-mock')+ return createReactI18nextMock({+ 'deployments.studio.precheck.description': 'It contains node types that are not yet supported:',+ 'deployments.studio.precheck.from': 'From',+ 'deployments.studio.precheck.nodeCount_other': '{{count}} nodes',+ 'deployments.studio.precheck.supportMessage':+ 'Support for these node types is coming in a future release.',+ 'deployments.studio.precheck.title': "This version can't be deployed to this environment",+ })+})++vi.mock('../use-provider-icon', () => ({+ useGetProviderIcon: () => () => undefined,+}))++function workflowReference(name: string, suffix: string): WorkflowReference {+ return {+ app_id: `app-${suffix}`,+ icon: '🤖',+ icon_background: '#FFEAD5',+ icon_type: 'emoji',+ name,+ workflow_id: `workflow-${suffix}`,+ }+}++function workflowAsToolDependency(...paths: WorkflowReference[][]): WorkflowAsToolDependency {+ return {+ paths: paths.map((workflows) => ({ workflows })),+ }+}++function unsupportedNode(id: string, owner: Partial<UnsupportedNode> = {}): UnsupportedNode {+ return {+ id,+ title: 'Slack',+ type: 'human-input',+ ...owner,+ }+}++describe('DeploymentPrecheckAlert', () => {+ it('does not show a source for an unsupported node from the deployed app', () => {+ render(<DeploymentPrecheckAlert nodes={[unsupportedNode('root-node')]} />)++ expect(screen.getByText('Slack')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /From/ })).not.toBeInTheDocument()+ })++ it('shows the leaf subworkflow name and its complete dependency path', async () => {+ const user = userEvent.setup()+ const root = workflowReference('Deployed app', 'root')+ const translation = workflowReference('Translation', 'translation')+ const source = workflowReference('Order fulfillment', 'order')+ render(+ <DeploymentPrecheckAlert+ nodes={[+ unsupportedNode('child-node', {+ workflow_as_tool_dependency: workflowAsToolDependency([root, translation, source]),+ }),+ ]}+ />,+ )++ await user.hover(screen.getByRole('button', { name: 'Slack: From Order fulfillment' }))++ const preview = await screen.findByRole('dialog', { name: 'Slack' })+ const sourceLink = within(preview).getByRole('link', {+ name: /Deployed app.*Translation.*Order fulfillment/,+ })+ expect(sourceLink).toHaveAttribute('href', '/app/app-order/workflow')+ expect(sourceLink).toHaveAttribute('target', '_blank')+ })++ it('includes the deployed app when matching nodes also come from workflow-as-tool paths', async () => {+ const user = userEvent.setup()+ const root = workflowReference('Deployed app', 'root')+ const orderSource = workflowReference('Order fulfillment', 'order')+ const auditSource = workflowReference('Audit workflow', 'audit')+ const sharedSource = workflowReference('Shared workflow', 'shared')+ const orderPath = [root, orderSource, sharedSource]+ const auditPath = [root, auditSource, sharedSource]+ render(+ <DeploymentPrecheckAlert+ nodes={[+ unsupportedNode('root-node'),+ unsupportedNode('order-node-1', {+ workflow_as_tool_dependency: workflowAsToolDependency(orderPath),+ }),+ unsupportedNode('order-node-2', {+ workflow_as_tool_dependency: workflowAsToolDependency(orderPath),+ }),+ unsupportedNode('audit-node', {+ workflow_as_tool_dependency: workflowAsToolDependency(auditPath),+ }),+ ]}+ />,+ )++ expect(screen.getAllByText('Slack')).toHaveLength(1)++ await user.click(screen.getByRole('button', { name: 'Slack: From 3 nodes' }))++ const preview = await screen.findByRole('dialog', { name: 'Slack' })+ expect(within(preview).getAllByRole('link')).toHaveLength(3)+ expect(within(preview).getByRole('link', { name: 'Deployed app' })).toHaveAttribute(+ 'href',+ '/app/app-root/workflow',+ )+ expect(+ within(preview).getByRole('link', {+ name: /Deployed app.*Order fulfillment.*Shared workflow/,+ }),+ ).toBeInTheDocument()+ expect(+ within(preview).getByRole('link', {+ name: /Deployed app.*Audit workflow.*Shared workflow/,+ }),+ ).toBeInTheDocument()+ })+})diff --git a/web/app/components/app/deploy/shared/deployment-configuration/__tests__/environment-variable-field.spec.tsx b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/environment-variable-field.spec.tsxnew file mode 100644index 00000000000..b8dc243de6f--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/environment-variable-field.spec.tsx@@ -0,0 +1,188 @@+import type { EnvironmentVariableSlot } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { ModelParameterModalProps } from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'+import { EnvVarValueSource, EnvVarValueType } from '@dify/contracts/enterprise-app-deploy/types.gen'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { EnvironmentVariableField } from '../environment-variable-field'++const activeModelList = vi.hoisted(() => [+ {+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [+ {+ deprecated: false,+ has_invalid_load_balancing_configs: false,+ label: { en_US: 'Chat model', zh_Hans: 'Chat model' },+ load_balancing_enabled: false,+ model: 'chat-model',+ model_properties: { mode: 'chat' },+ model_type: 'llm',+ status: 'active',+ },+ {+ deprecated: false,+ has_invalid_load_balancing_configs: false,+ label: { en_US: 'Chat model v2', zh_Hans: 'Chat model v2' },+ load_balancing_enabled: false,+ model: 'chat-model-v2',+ model_properties: { mode: 'chat' },+ model_type: 'llm',+ status: 'active',+ },+ {+ deprecated: false,+ has_invalid_load_balancing_configs: false,+ label: { en_US: 'Completion model', zh_Hans: 'Completion model' },+ load_balancing_enabled: false,+ model: 'completion-model',+ model_properties: { mode: 'completion' },+ model_type: 'llm',+ status: 'active',+ },+ ],+ provider: 'langgenius/openai/openai',+ },+])++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useTextGenerationCurrentProviderAndModelAndModelList: () => ({+ activeTextGenerationModelList: activeModelList,+ }),+}))++vi.mock(+ '@/app/components/header/account-setting/model-provider-page/model-parameter-modal',+ () => ({+ default: ({+ completionParams,+ modelId,+ modelList = [],+ modelSelectorReadonly,+ provider,+ readonly,+ onCompletionParamsChange,+ setModel,+ }: ModelParameterModalProps) => {+ const selectableModels = modelList.flatMap((providerItem) =>+ providerItem.models.map((model) => ({ model, provider: providerItem.provider })),+ )+ const nextModel = selectableModels.find(({ model }) => model.model === 'chat-model-v2')++ return (+ <div>+ <button+ type="button"+ aria-label="Select deployment model"+ disabled={readonly || modelSelectorReadonly}+ onClick={() => {+ if (!nextModel) return++ setModel({+ modelId: nextModel.model.model,+ mode: nextModel.model.model_properties.mode as string,+ provider: nextModel.provider,+ })+ }}+ >+ {provider && modelId ? `${provider}/${modelId}` : 'No model selected'}+ </button>+ <button+ type="button"+ onClick={() => onCompletionParamsChange({ ...completionParams, temperature: 0.4 })}+ >+ Set temperature+ </button>+ {selectableModels.map(({ model }) => (+ <span key={model.model}>{model.model}</span>+ ))}+ </div>+ )+ },+ }),+)++const llmSlot: EnvironmentVariableSlot = {+ configured_value: {+ completion_params: { temperature: 0.2 },+ mode: 'chat',+ name: 'chat-model',+ provider: 'langgenius/openai/openai',+ },+ description: 'Chat model used by the workflow',+ has_configured_value: true,+ has_last_deployed_value: false,+ key: 'MODEL',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_LLM,+}++describe('EnvironmentVariableField', () => {+ it('selects a compatible custom LLM and keeps its parameters structured', async () => {+ const user = userEvent.setup()+ const onChange = vi.fn()+ render(+ <EnvironmentVariableField+ slot={llmSlot}+ workflowId="workflow-1"+ getInitialSelection={() => undefined}+ onChange={onChange}+ />,+ )++ const modelSelector = await screen.findByRole('button', { name: 'Select deployment model' })+ expect(modelSelector).toBeDisabled()+ expect(modelSelector).toHaveTextContent('langgenius/openai/openai/chat-model')+ expect(screen.getByText('workflow.blocks.llm')).toBeInTheDocument()+ expect(screen.getByText('chat-model-v2')).toBeInTheDocument()+ expect(screen.queryByText('completion-model')).not.toBeInTheDocument()++ await user.click(screen.getByRole('combobox', { name: /MODEL/ }))+ await user.click(+ await screen.findByRole('option', {+ name: 'deployments.deployDrawer.envVarSource.literal',+ }),+ )++ expect(modelSelector).toBeEnabled()+ await user.click(modelSelector)+ await user.click(screen.getByRole('button', { name: 'Set temperature' }))++ expect(onChange).toHaveBeenLastCalledWith('workflow-1', 'MODEL', {+ customValue: {+ completion_params: { temperature: 0.4 },+ mode: 'chat',+ name: 'chat-model-v2',+ provider: 'langgenius/openai/openai',+ },+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ })+ })++ it('shows the last deployed LLM as a read-only source', async () => {+ render(+ <EnvironmentVariableField+ slot={{+ ...llmSlot,+ configured_value: undefined,+ has_configured_value: false,+ has_last_deployed_value: true,+ last_deployed_value: {+ completion_params: {},+ mode: 'chat',+ name: 'chat-model-v2',+ provider: 'langgenius/openai/openai',+ },+ }}+ workflowId="workflow-1"+ getInitialSelection={() => undefined}+ onChange={vi.fn()}+ />,+ )++ const modelSelector = await screen.findByRole('button', { name: 'Select deployment model' })+ expect(modelSelector).toBeDisabled()+ expect(modelSelector).toHaveTextContent('langgenius/openai/openai/chat-model-v2')+ expect(screen.getByRole('combobox', { name: /MODEL/ })).toHaveTextContent(+ 'deployments.deployDrawer.envVarSource.lastDeployment',+ )+ })+})diff --git a/web/app/components/app/deploy/shared/deployment-configuration/__tests__/workflow-deployment-input.spec.ts b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/workflow-deployment-input.spec.tsnew file mode 100644index 00000000000..e7873c56f4e--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/workflow-deployment-input.spec.ts@@ -0,0 +1,306 @@+import type { GetWorkflowDeploymentOptionsResponse } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { DeploymentConfigurationValues } from '../use-deployment-configuration-values'+import {+ EnvVarValueSource,+ EnvVarValueType,+ PluginCategory,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import { environmentVariableSelectionKey } from '../use-deployment-configuration-values'+import {+ credentialSlotKey,+ hasValidDeploymentEnvironmentVariables,+ workflowDeploymentInput,+} from '../utils/workflow-deployment-input'++const deploymentOptions: GetWorkflowDeploymentOptionsResponse = {+ credential_slots: [],+ environment_variable_groups: [+ {+ environment_variable_slots: [+ {+ description: 'Chat model used by the workflow',+ has_configured_value: false,+ has_last_deployed_value: false,+ key: 'MODEL',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_LLM,+ },+ ],+ from_app: {+ app_id: 'app-1',+ icon: '🤖',+ icon_background: '#FFFFFF',+ icon_type: 'emoji',+ name: 'Primary workflow',+ workflow_id: 'workflow-1',+ },+ },+ ],+}++describe('workflowDeploymentInput', () => {+ it('keeps a custom LLM value structured inside its workflow group', () => {+ const llmValue = {+ completion_params: { temperature: 0.2 },+ mode: 'chat',+ name: 'chat-model',+ provider: 'langgenius/openai/openai',+ }+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {+ [environmentVariableSelectionKey('workflow-1', 'MODEL')]: {+ customValue: llmValue,+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ },+ }++ expect(hasValidDeploymentEnvironmentVariables(deploymentOptions, values)).toBe(true)+ expect(workflowDeploymentInput(deploymentOptions, values)).toEqual({+ credentials: [],+ environment_variable_groups: [+ {+ environment_variables: [+ {+ key: 'MODEL',+ value: llmValue,+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ ],+ workflow_id: 'workflow-1',+ },+ ],+ })+ })++ it('rejects a custom LLM source without a selected model', () => {+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {+ [environmentVariableSelectionKey('workflow-1', 'MODEL')]: {+ customValue: '',+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ },+ }++ expect(hasValidDeploymentEnvironmentVariables(deploymentOptions, values)).toBe(false)+ expect(workflowDeploymentInput(deploymentOptions, values)).toBeUndefined()+ })++ it.each([+ ['String', EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING],+ ['Number', EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER],+ ['Secret', EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET],+ ])('rejects an empty custom %s value', (_, valueType) => {+ const options: GetWorkflowDeploymentOptionsResponse = {+ ...deploymentOptions,+ environment_variable_groups: deploymentOptions.environment_variable_groups.map((group) => ({+ ...group,+ environment_variable_slots: group.environment_variable_slots.map((slot) => ({+ ...slot,+ key: 'VALUE',+ value_type: valueType,+ })),+ })),+ }+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {+ [environmentVariableSelectionKey('workflow-1', 'VALUE')]: {+ customValue: '',+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ },+ }++ expect(hasValidDeploymentEnvironmentVariables(options, values)).toBe(false)+ expect(workflowDeploymentInput(options, values)).toBeUndefined()+ })++ it.each([' ', 'not-a-number', 'Infinity'])(+ 'rejects an invalid custom Number value: %j',+ (customValue) => {+ const options: GetWorkflowDeploymentOptionsResponse = {+ ...deploymentOptions,+ environment_variable_groups: deploymentOptions.environment_variable_groups.map((group) => ({+ ...group,+ environment_variable_slots: group.environment_variable_slots.map((slot) => ({+ ...slot,+ key: 'PORT',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER,+ })),+ })),+ }+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {+ [environmentVariableSelectionKey('workflow-1', 'PORT')]: {+ customValue,+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ },+ }++ expect(hasValidDeploymentEnvironmentVariables(options, values)).toBe(false)+ expect(workflowDeploymentInput(options, values)).toBeUndefined()+ },+ )++ it('normalizes a valid custom Number value before building the deployment payload', () => {+ const options: GetWorkflowDeploymentOptionsResponse = {+ ...deploymentOptions,+ environment_variable_groups: deploymentOptions.environment_variable_groups.map((group) => ({+ ...group,+ environment_variable_slots: group.environment_variable_slots.map((slot) => ({+ ...slot,+ key: 'PORT',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER,+ })),+ })),+ }+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {+ [environmentVariableSelectionKey('workflow-1', 'PORT')]: {+ customValue: '3000.5',+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ },+ }++ expect(workflowDeploymentInput(options, values)).toEqual({+ credentials: [],+ environment_variable_groups: [+ {+ environment_variables: [+ {+ key: 'PORT',+ value: 3000.5,+ value_source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ ],+ workflow_id: 'workflow-1',+ },+ ],+ })+ })++ it.each([+ ['configured', true, false, { configured_value: '' }],+ ['last deployed', false, true, { last_deployed_value: '' }],+ ])(+ 'rejects an empty %s environment variable value',+ (_, hasConfiguredValue, hasLastDeployedValue, sourceValue) => {+ const options: GetWorkflowDeploymentOptionsResponse = {+ ...deploymentOptions,+ environment_variable_groups: deploymentOptions.environment_variable_groups.map((group) => ({+ ...group,+ environment_variable_slots: group.environment_variable_slots.map((slot) => ({+ ...slot,+ ...sourceValue,+ has_configured_value: hasConfiguredValue,+ has_last_deployed_value: hasLastDeployedValue,+ key: 'VALUE',+ value_type: EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING,+ })),+ })),+ }+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {},+ }++ expect(hasValidDeploymentEnvironmentVariables(options, values)).toBe(false)+ expect(workflowDeploymentInput(options, values)).toBeUndefined()+ },+ )++ it.each([+ { mode: '', name: '', provider: '' },+ { mode: 'embedding', name: 'embedding-model', provider: 'provider' },+ ])('rejects an invalid custom LLM value', (customValue) => {+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {+ [environmentVariableSelectionKey('workflow-1', 'MODEL')]: {+ customValue,+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ },+ }++ expect(hasValidDeploymentEnvironmentVariables(deploymentOptions, values)).toBe(false)+ expect(workflowDeploymentInput(deploymentOptions, values)).toBeUndefined()+ })++ it('rejects a custom LLM value with a different mode from the configured value', () => {+ const options: GetWorkflowDeploymentOptionsResponse = {+ ...deploymentOptions,+ environment_variable_groups: deploymentOptions.environment_variable_groups.map((group) => ({+ ...group,+ environment_variable_slots: group.environment_variable_slots.map((slot) => ({+ ...slot,+ configured_value: {+ mode: 'chat',+ name: 'chat-model',+ provider: 'provider',+ },+ has_configured_value: true,+ })),+ })),+ }+ const values: DeploymentConfigurationValues = {+ credentials: {},+ environmentVariables: {+ [environmentVariableSelectionKey('workflow-1', 'MODEL')]: {+ customValue: {+ mode: 'completion',+ name: 'completion-model',+ provider: 'provider',+ },+ source: EnvVarValueSource.ENV_VAR_VALUE_SOURCE_CUSTOM,+ },+ },+ }++ expect(hasValidDeploymentEnvironmentVariables(options, values)).toBe(false)+ expect(workflowDeploymentInput(options, values)).toBeUndefined()+ })++ it.each(['', 'removed-credential'])(+ 'rejects an empty or unavailable credential selection: %j',+ (credentialId) => {+ const credentialSlot = {+ candidates: [+ {+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ credential_id: 'credential-1',+ display_name: 'Credential 1',+ from_enterprise: false,+ provider_id: 'provider',+ },+ {+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ credential_id: 'credential-2',+ display_name: 'Credential 2',+ from_enterprise: false,+ provider_id: 'provider',+ },+ ],+ category: PluginCategory.PLUGIN_CATEGORY_MODEL,+ provider_id: 'provider',+ }+ const options: GetWorkflowDeploymentOptionsResponse = {+ credential_slots: [credentialSlot],+ environment_variable_groups: [],+ }+ const values: DeploymentConfigurationValues = {+ credentials: { [credentialSlotKey(credentialSlot)]: credentialId },+ environmentVariables: {},+ }++ expect(workflowDeploymentInput(options, values)).toBeUndefined()+ },+ )+})diff --git a/web/app/components/app/deploy/shared/deployment-configuration/content.tsx b/web/app/components/app/deploy/shared/deployment-configuration/content.tsxnew file mode 100644index 00000000000..1a725c9ce15--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/content.tsx@@ -0,0 +1,148 @@+'use client'++import type { DeploymentDialogRequest } from '../../types'+import type { DeploymentVersion } from '../../utils/version'+import type { DeploymentConfigurationQueryState } from './use-deployment-configuration-queries'+import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import { CredentialsSection } from './credentials-section'+import { DeploymentPrecheckAlert } from './deployment-precheck-alert'+import { EnvironmentVariablesSection } from './environment-variables-section'+import { getDeploymentErrorMessage } from './utils/deployment-error'++function ConfigurationError({ messages }: { messages: string[] }) {+ const { t } = useTranslation('common')++ return (+ <div role="alert" className="flex gap-2 text-text-destructive">+ <span aria-hidden className="mt-0.5 i-ri-error-warning-fill size-4 shrink-0" />+ <div className="min-w-0">+ <p className="system-sm-semibold">{t(($) => $.error)}</p>+ <ul className="mt-1 list-disc space-y-1 pl-4 system-xs-regular">+ {messages.map((message) => (+ <li key={message} className="wrap-break-word">+ {message}+ </li>+ ))}+ </ul>+ </div>+ </div>+ )+}++export function DeploymentConfigurationContent({+ compact = false,+ configurationValues,+ queryState,+ request,+ version,+}: {+ compact?: boolean+ configurationValues: DeploymentConfigurationValuesController+ queryState: DeploymentConfigurationQueryState+ request: DeploymentDialogRequest+ version: DeploymentVersion+}) {+ const { t } = useTranslation('deployments')+ const { t: tCommon } = useTranslation('common')+ const horizontalPaddingClassName = compact ? 'px-4' : 'px-6'+ const {+ deploymentOptions,+ deploymentOptionsError,+ isLoadingDeploymentOptions,+ isPrecheckBlocked,+ isPrechecking,+ precheck,+ precheckError,+ } = queryState+ const {+ credentials,+ getEnvironmentVariableSelection,+ setCredential,+ setEnvironmentVariableSelection,+ } = configurationValues+ const unsupportedNodes = precheck?.unsupported_nodes ?? []+ const showPrecheckAlert = !isPrechecking && !precheckError && isPrecheckBlocked+ const showConfiguration = Boolean(deploymentOptions)+ const hasCredentialSlots = Boolean(deploymentOptions?.credential_slots.length)++ return (+ <>+ <div+ className={cn(+ 'shrink-0 pt-2',+ showPrecheckAlert ? 'pb-0' : 'border-b border-divider-regular pb-4',+ horizontalPaddingClassName,+ )}+ >+ <div className="flex items-center justify-between gap-3 rounded-xl bg-background-section p-3">+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <span aria-hidden className="i-ri-stack-line size-3.5 shrink-0 text-text-tertiary" />+ <span className="truncate system-sm-medium text-text-secondary">{version.name}</span>+ </div>+ <span+ aria-hidden+ className="i-ri-arrow-right-line size-3.5 shrink-0 text-text-tertiary"+ />+ <div className="flex min-w-0 flex-1 items-center justify-end gap-2">+ <span aria-hidden className="i-ri-instance-line size-3.5 shrink-0 text-text-tertiary" />+ <span className="truncate system-sm-medium text-text-secondary">+ {request.environment}+ </span>+ </div>+ </div>+ </div>++ <div+ aria-busy={isPrechecking || isLoadingDeploymentOptions}+ className="min-h-0 flex-1 overflow-y-auto"+ >+ {isPrechecking && <Loading className="py-8" />}+ {!isPrechecking && precheckError && (+ <div className={cn('py-4', horizontalPaddingClassName)}>+ <ConfigurationError+ messages={[getDeploymentErrorMessage(precheckError) ?? tCommon(($) => $.error)]}+ />+ </div>+ )}+ {showPrecheckAlert && (+ <div+ className={cn('border-b border-divider-regular pt-2 pb-4', horizontalPaddingClassName)}+ >+ <DeploymentPrecheckAlert nodes={unsupportedNodes} />+ </div>+ )}+ {isLoadingDeploymentOptions && <Loading className="py-8" />}+ {!isLoadingDeploymentOptions && deploymentOptionsError && (+ <div className={cn('py-4', horizontalPaddingClassName)}>+ <ConfigurationError+ messages={[+ getDeploymentErrorMessage(deploymentOptionsError) ??+ t(($) => $['deployDrawer.bindingOptionsFailed']),+ ]}+ />+ </div>+ )}+ {showConfiguration && (+ <>+ <CredentialsSection+ credentialSlots={deploymentOptions?.credential_slots ?? []}+ credentials={credentials}+ horizontalPaddingClassName={horizontalPaddingClassName}+ onChange={setCredential}+ />+ <EnvironmentVariablesSection+ environmentVariableGroups={deploymentOptions?.environment_variable_groups ?? []}+ getEnvironmentVariableSelection={getEnvironmentVariableSelection}+ hasCredentialSlots={hasCredentialSlots}+ horizontalPaddingClassName={horizontalPaddingClassName}+ setEnvironmentVariableSelection={setEnvironmentVariableSelection}+ />+ </>+ )}+ </div>+ </>+ )+}diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/credential-field.tsx b/web/app/components/app/deploy/shared/deployment-configuration/credential-field.tsxsimilarity index 76%rename from web/app/components/app/deploy/deployment-dialog/deployment-configuration/credential-field.tsxrename to web/app/components/app/deploy/shared/deployment-configuration/credential-field.tsxindex 3ea848db8c6..c5bb3d37915 100644--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/credential-field.tsx+++ b/web/app/components/app/deploy/shared/deployment-configuration/credential-field.tsx@@ -1,4 +1,4 @@-import type { CredentialSlot } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { CredentialSlot, WorkflowPath } from '@dify/contracts/enterprise-app-deploy/types.gen'import { PluginCategory } from '@dify/contracts/enterprise-app-deploy/types.gen'import {Select,@@ -14,23 +14,17 @@ import { useTranslation } from 'react-i18next'import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'import useTheme from '@/hooks/use-theme'import { Theme } from '@/types/app'--function providerName(providerId: string) {- const name = providerId.split('/').filter(Boolean).at(-1) ?? providerId-- return name- .split(/[-_]/)- .filter(Boolean)- .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)- .join(' ')-}+import { credentialProviderName } from './utils/workflow-deployment-input'+import { WorkflowDependencyPreview } from './workflow-source-popover'export function CredentialField({slot,+ paths = [],value,onChange,}: {slot: CredentialSlot+ paths?: WorkflowPath[]value?: stringonChange: (value: string) => void}) {@@ -39,7 +33,7 @@ export function CredentialField({const { getIconUrl } = useGetIcon()const { theme } = useTheme()const selectedOption = slot.candidates.find((candidate) => candidate.credential_id === value)- const name = providerName(slot.provider_id)+ const name = credentialProviderName(slot.provider_id)const iconFileName =theme === Theme.dark ? slot.icon_dark || slot.icon : slot.icon || slot.icon_darkconst iconSrc = iconFileName ? getIconUrl(iconFileName) : undefined@@ -52,19 +46,24 @@ export function CredentialField({return (<div className="flex flex-col gap-1">- <div className="flex items-center gap-1">- <span className="size-5 shrink-0 overflow-hidden rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge">- {iconSrc ? (- <img alt="" src={iconSrc} className="size-full object-contain" />- ) : (- <span- aria-hidden- className="i-ri-plug-2-line flex size-full items-center justify-center text-text-tertiary"- />+ <div className="flex min-w-0 items-center justify-between gap-2 py-0.5">+ <div className="flex min-w-0 flex-1 items-center gap-1">+ <span className="size-5 shrink-0 overflow-hidden rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge">+ {iconSrc ? (+ <img alt="" src={iconSrc} className="size-full object-contain" />+ ) : (+ <span+ aria-hidden+ className="i-ri-plug-2-line flex size-full items-center justify-center text-text-tertiary"+ />+ )}+ </span>+ <span className="truncate system-sm-medium text-text-primary">{name}</span>+ {category && (+ <span className="shrink-0 system-xs-regular text-text-tertiary">{category}</span>)}- </span>- <span className="system-sm-medium text-text-primary">{name}</span>- {category && <span className="system-xs-regular text-text-tertiary">{category}</span>}+ </div>+ <WorkflowDependencyPreview subjectName={name} paths={paths} /></div><Selectvalue={value ?? null}diff --git a/web/app/components/app/deploy/shared/deployment-configuration/credentials-section.tsx b/web/app/components/app/deploy/shared/deployment-configuration/credentials-section.tsxnew file mode 100644index 00000000000..210d46649a7--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/credentials-section.tsx@@ -0,0 +1,106 @@+import type { CredentialSlot } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'+import { cn } from '@langgenius/dify-ui/cn'+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import { CredentialField } from './credential-field'+import { SectionHeading } from './section-heading'+import { credentialSlotKey, defaultCredentialId } from './utils/workflow-deployment-input'++const CredentialConfigurationField = memo(+ ({+ onChange,+ paths,+ slot,+ slotKey,+ value,+ }: {+ onChange: DeploymentConfigurationValuesController['setCredential']+ paths?: NonNullable<CredentialSlot['workflow_as_tool_dependency']>['paths']+ slot: CredentialSlot+ slotKey: string+ value?: string+ }) => {+ return (+ <CredentialField+ paths={paths}+ slot={slot}+ value={value}+ onChange={(value) => onChange(slotKey, value)}+ />+ )+ },+)+CredentialConfigurationField.displayName = 'CredentialConfigurationField'++export const CredentialsSection = memo(+ ({+ credentialSlots,+ credentials,+ horizontalPaddingClassName,+ onChange,+ }: {+ credentialSlots: CredentialSlot[]+ credentials: DeploymentConfigurationValuesController['credentials']+ horizontalPaddingClassName: string+ onChange: DeploymentConfigurationValuesController['setCredential']+ }) => {+ const { t } = useTranslation('deployments')+ const { t: tWorkflow } = useTranslation('workflow')+ const appCredentialSlots = credentialSlots.filter((slot) => !slot.workflow_as_tool_dependency)+ const subworkflowCredentialSlots = credentialSlots.filter(+ (slot) => slot.workflow_as_tool_dependency,+ )++ if (credentialSlots.length === 0) return null++ return (+ <section className={cn('flex flex-col gap-4 py-4', horizontalPaddingClassName)}>+ <SectionHeading+ title={t(($) => $['deployDrawer.runtimeCredentials'])}+ description={t(($) => $['deployDrawer.bindingSelectionHint'])}+ />+ {appCredentialSlots.map((slot) => {+ const slotKey = credentialSlotKey(slot)++ return (+ <CredentialConfigurationField+ key={slotKey}+ slot={slot}+ slotKey={slotKey}+ value={credentials[slotKey] ?? defaultCredentialId(slot)}+ onChange={onChange}+ />+ )+ })}+ {subworkflowCredentialSlots.length > 0 && (+ <>+ <div className="flex min-w-0 items-center gap-2 pt-2">+ <span className="shrink-0 system-xs-medium-uppercase text-text-tertiary">+ {t(($) => $['studio.precheck.from'])} {tWorkflow(($) => $['common.workflowAsTool'])}+ </span>+ <span+ aria-hidden+ className="h-px min-w-0 flex-1 bg-linear-to-r from-divider-regular to-background-gradient-mask-transparent"+ />+ </div>+ {subworkflowCredentialSlots.map((slot) => {+ const slotKey = credentialSlotKey(slot)++ return (+ <CredentialConfigurationField+ key={slotKey}+ paths={slot.workflow_as_tool_dependency?.paths}+ slot={slot}+ slotKey={slotKey}+ value={credentials[slotKey] ?? defaultCredentialId(slot)}+ onChange={onChange}+ />+ )+ })}+ </>+ )}+ </section>+ )+ },+)diff --git a/web/app/components/app/deploy/shared/deployment-configuration/deployment-precheck-alert.tsx b/web/app/components/app/deploy/shared/deployment-configuration/deployment-precheck-alert.tsxnew file mode 100644index 00000000000..b2821e6239d--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/deployment-precheck-alert.tsx@@ -0,0 +1,153 @@+'use client'++import type { UnsupportedNode, WorkflowPath } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { Emoji } from '@/app/components/tools/types'+import { useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import BlockIcon from '@/app/components/workflow/block-icon'+import { BlockEnum } from '@/app/components/workflow/types'+import { useGetProviderIcon } from './use-provider-icon'+import { workflowPathKey } from './utils/workflow-path'+import { WorkflowDependencyPreview } from './workflow-source-popover'++const WORKFLOW_BLOCK_TYPES = new Set<string>(Object.values(BlockEnum))++function isWorkflowBlockType(type: string): type is BlockEnum {+ return WORKFLOW_BLOCK_TYPES.has(type)+}++function UnsupportedNodeIcon({ node, icon }: { node: UnsupportedNode; icon?: string | Emoji }) {+ if (!isWorkflowBlockType(node.type)) {+ return (+ <span className="flex size-5 shrink-0 items-center justify-center rounded-md bg-components-icon-bg-midnight-solid text-white shadow-xs">+ <span aria-hidden className="i-ri-node-tree size-3.5" />+ </span>+ )+ }++ return <BlockIcon type={node.type} size="sm" toolIcon={icon} />+}++type UnsupportedNodeGroup = {+ key: string+ node: UnsupportedNode+ paths: WorkflowPath[]+}++type MutableUnsupportedNodeGroup = UnsupportedNodeGroup & {+ hasDeployedAppNode: boolean+ pathKeys: Set<string>+}++function unsupportedNodeGroupKey(node: UnsupportedNode) {+ return JSON.stringify([+ node.type,+ node.title,+ node.provider?.plugin_id,+ node.provider?.provider_id,+ node.provider?.provider_type,+ node.provider?.provider_name,+ ])+}++function groupUnsupportedNodes(nodes: UnsupportedNode[]): UnsupportedNodeGroup[] {+ const groups = new Map<string, MutableUnsupportedNodeGroup>()++ for (const node of nodes) {+ const key = unsupportedNodeGroupKey(node)+ let group = groups.get(key)++ if (!group) {+ group = {+ hasDeployedAppNode: false,+ key,+ node,+ pathKeys: new Set<string>(),+ paths: [],+ }+ groups.set(key, group)+ }++ const dependency = node.workflow_as_tool_dependency+ if (!dependency) {+ group.hasDeployedAppNode = true+ continue+ }++ for (const path of dependency.paths) {+ if (path.workflows.length === 0) continue++ const pathKey = workflowPathKey(path)+ if (group.pathKeys.has(pathKey)) continue++ group.pathKeys.add(pathKey)+ group.paths.push(path)+ }+ }++ return [...groups.values()].map(+ ({ hasDeployedAppNode, key, node, pathKeys, paths }): UnsupportedNodeGroup => {+ if (!hasDeployedAppNode) return { key, node, paths }++ // Root occurrences have no dependency payload. When a matching node also appears in a+ // subworkflow, its paths provide the deployed app reference for the root-only source row.+ const deployedAppPaths: WorkflowPath[] = []+ for (const path of paths) {+ const deployedApp = path.workflows[0]+ if (!deployedApp) continue++ const deployedAppPath = { workflows: [deployedApp] }+ const deployedAppPathKey = workflowPathKey(deployedAppPath)+ if (pathKeys.has(deployedAppPathKey)) continue++ pathKeys.add(deployedAppPathKey)+ deployedAppPaths.push(deployedAppPath)+ }++ return {+ key,+ node,+ paths: [...deployedAppPaths, ...paths],+ }+ },+ )+}++export function DeploymentPrecheckAlert({ nodes }: { nodes: UnsupportedNode[] }) {+ const { t } = useTranslation('deployments')+ const getProviderIcon = useGetProviderIcon(nodes)+ const nodeGroups = useMemo(() => groupUnsupportedNodes(nodes), [nodes])++ return (+ <div+ role="alert"+ className="relative flex flex-col gap-2 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-4 shadow-xs backdrop-blur-[5px]"+ >+ <div className="pointer-events-none absolute inset-0 bg-linear-to-r from-components-badge-status-light-warning-halo to-background-gradient-mask-transparent opacity-40" />+ <span+ aria-hidden+ className="relative i-ri-alert-fill size-5 shrink-0 text-text-warning-secondary"+ />+ <div className="relative flex min-w-0 flex-col gap-1">+ <p className="system-sm-medium text-text-primary">{t(($) => $['studio.precheck.title'])}</p>+ <p className="system-xs-regular text-text-secondary">+ {t(($) => $['studio.precheck.description'])}+ </p>+ </div>+ <ul className="relative flex flex-col gap-1.5 border-y border-divider-regular py-3">+ {nodeGroups.map(({ key, node, paths }) => (+ <li key={key} className="flex items-center gap-2 pr-1">+ <UnsupportedNodeIcon node={node} icon={getProviderIcon(node)} />+ <span className="min-w-0 flex-1 truncate system-xs-medium text-text-secondary">+ {node.title}+ </span>+ <WorkflowDependencyPreview subjectName={node.title} paths={paths} />+ </li>+ ))}+ </ul>+ <p className="relative system-xs-regular text-text-secondary">+ {t(($) => $['studio.precheck.supportMessage'])}+ </p>+ </div>+ )+}diff --git a/web/app/components/app/deploy/shared/deployment-configuration/environment-variable-field.tsx b/web/app/components/app/deploy/shared/deployment-configuration/environment-variable-field.tsxnew file mode 100644index 00000000000..4cdf9d6f2f8--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/environment-variable-field.tsx@@ -0,0 +1,228 @@+'use client'++import type {+ EnvironmentVariableSlot,+ EnvVarValueSource,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { EnvironmentVariableSelection } from './use-deployment-configuration-values'+import type { LLMEnvironmentVariableValue } from '@/app/components/workflow/types'+import {+ EnvVarValueSource as EnvVarValueSourceEnum,+ EnvVarValueType,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import { Input } from '@langgenius/dify-ui/input'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectTrigger,+} from '@langgenius/dify-ui/select'+import { memo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'+import dynamic from '@/next/dynamic'+import { resolveEnvironmentVariableSelection } from './utils/workflow-deployment-input'++const LLMEnvironmentVariableValueField = dynamic(+ () =>+ import('@/app/components/workflow/llm-environment-variable-value-field').then(+ (module) => module.LLMEnvironmentVariableValueField,+ ),+ {+ loading: () => (+ <div+ aria-hidden+ className="h-8 w-full animate-pulse rounded-lg bg-components-input-bg-normal"+ />+ ),+ },+)++function displayEnvironmentVariableValue(value: unknown) {+ if (value === undefined) return undefined+ if (typeof value === 'string') return value+ if (typeof value === 'number' || typeof value === 'boolean') return String(value)++ return JSON.stringify(value)+}++export const EnvironmentVariableField = memo(+ ({+ slot,+ workflowId,+ getInitialSelection,+ onChange,+ }: {+ slot: EnvironmentVariableSlot+ workflowId: string+ getInitialSelection: (+ workflowId: string,+ key: string,+ ) => EnvironmentVariableSelection | undefined+ onChange: (workflowId: string, key: string, value: EnvironmentVariableSelection) => void+ }) => {+ const { t } = useTranslation('deployments')+ const { t: tWorkflow } = useTranslation('workflow')+ const [selection, setSelection] = useState(() =>+ resolveEnvironmentVariableSelection(slot, getInitialSelection(workflowId, slot.key)),+ )+ const { customValue, source } = selection+ const isLLM = slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_LLM+ const sourceLabels: Partial<Record<EnvVarValueSource, string>> = {+ [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED]: t(($) => $['studio.versionValue']),+ [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM]: t(+ ($) => $['deployDrawer.envVarSource.literal'],+ ),+ [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED]: t(+ ($) => $['deployDrawer.envVarSource.lastDeployment'],+ ),+ }+ const availableSources = [+ ...(slot.has_last_deployed_value+ ? [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED]+ : []),+ ...(slot.has_configured_value ? [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED] : []),+ EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM,+ ]+ const valueTypeLabel = isLLM+ ? tWorkflow(($) => $['blocks.llm'])+ : slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER+ ? t(($) => $['deployDrawer.envVarType.number'])+ : slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET+ ? t(($) => $['deployDrawer.envVarType.secret'])+ : t(($) => $['deployDrawer.envVarType.string'])+ const inputId = `deployment-env-${encodeURIComponent(workflowId)}-${encodeURIComponent(slot.key)}`+ const labelId = `${inputId}-label`+ const editable = source === EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM+ const inputType =+ editable && slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET+ ? 'password'+ : editable && slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER+ ? 'number'+ : 'text'+ const sourceLabel = sourceLabels[source] ?? t(($) => $['deployDrawer.envVarSource.literal'])+ // Secret values arrive masked, so these are safe to show as-is.+ const sourceValues: Partial<Record<EnvVarValueSource, string>> = {+ [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED]: displayEnvironmentVariableValue(+ slot.configured_value,+ ),+ [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED]: displayEnvironmentVariableValue(+ slot.last_deployed_value,+ ),+ }+ const placeholder = editable ? undefined : (sourceValues[source] ?? sourceLabel)+ const configuredLLMValue = isLLMEnvironmentVariableValue(slot.configured_value)+ ? slot.configured_value+ : undefined+ const lastDeployedLLMValue = isLLMEnvironmentVariableValue(slot.last_deployed_value)+ ? slot.last_deployed_value+ : undefined+ const llmSourceValues: Partial<Record<EnvVarValueSource, LLMEnvironmentVariableValue>> = {+ [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED]: configuredLLMValue,+ [EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED]: lastDeployedLLMValue,+ }+ const displayedLLMValue = editable+ ? isLLMEnvironmentVariableValue(customValue)+ ? customValue+ : undefined+ : llmSourceValues[source]+ const requiredLLMMode = configuredLLMValue?.mode ?? lastDeployedLLMValue?.mode++ const updateSelection = (nextSelection: EnvironmentVariableSelection) => {+ setSelection(nextSelection)+ onChange(workflowId, slot.key, nextSelection)+ }++ return (+ <div className="flex flex-col gap-1">+ <div className="flex min-w-0 items-center gap-2">+ <div className="flex min-w-0 grow items-center gap-1">+ <span+ aria-hidden+ className="i-custom-vender-line-others-env size-4 shrink-0 text-util-colors-violet-violet-600"+ />+ {isLLM ? (+ <span id={labelId} className="truncate system-sm-medium text-text-primary">+ {slot.key}+ </span>+ ) : (+ <label htmlFor={inputId} className="truncate system-sm-medium text-text-primary">+ {slot.key}+ </label>+ )}+ <span className="shrink-0 system-xs-regular text-text-tertiary">{valueTypeLabel}</span>+ {slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET && (+ <span aria-hidden className="i-ri-lock-2-line size-3 shrink-0 text-text-tertiary" />+ )}+ </div>+ <Select+ value={source}+ onValueChange={(nextSource) => {+ if (!nextSource) return++ const nextSelection = {+ ...selection,+ source: nextSource,+ }+ updateSelection(nextSelection)+ }}+ >+ <SelectTrigger+ aria-label={t(($) => $['deployDrawer.envVarSource.ariaLabel'], {+ key: slot.key,+ })}+ size="small"+ className="h-7 w-auto max-w-48 shrink-0 border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-2 shadow-xs backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover focus-visible:bg-components-button-secondary-bg"+ >+ {sourceLabel}+ </SelectTrigger>+ <SelectContent placement="bottom-end" className="w-52">+ {availableSources.map((option) => (+ <SelectItem key={option} value={option}>+ <SelectItemText>{sourceLabels[option]}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {isLLM ? (+ <div role="group" aria-labelledby={labelId} className="flex w-full min-w-0">+ <LLMEnvironmentVariableValueField+ disabled={!editable}+ requiredMode={requiredLLMMode}+ value={displayedLLMValue}+ onChange={(nextCustomValue) =>+ updateSelection({+ ...selection,+ customValue: nextCustomValue,+ })+ }+ />+ </div>+ ) : (+ <Input+ id={inputId}+ type={inputType}+ value={editable && typeof customValue === 'string' ? customValue : ''}+ placeholder={placeholder}+ disabled={!editable}+ autoComplete="off"+ onChange={(event) =>+ updateSelection({+ ...selection,+ customValue: event.target.value,+ })+ }+ />+ )}+ {slot.description && (+ <p className="system-xs-regular text-text-tertiary">{slot.description}</p>+ )}+ </div>+ )+ },+)+EnvironmentVariableField.displayName = 'EnvironmentVariableField'diff --git a/web/app/components/app/deploy/shared/deployment-configuration/environment-variables-section.tsx b/web/app/components/app/deploy/shared/deployment-configuration/environment-variables-section.tsxnew file mode 100644index 00000000000..eae0486fda1--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/environment-variables-section.tsx@@ -0,0 +1,103 @@+import type { EnvironmentVariableGroup } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'+import { cn } from '@langgenius/dify-ui/cn'+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import { EnvironmentVariableField } from './environment-variable-field'+import { SectionHeading } from './section-heading'+import { SubworkflowSourceTitle, WorkflowReferenceIcon } from './workflow-source-popover'++function EnvironmentVariableGroupFields({+ group,+ getEnvironmentVariableSelection,+ setEnvironmentVariableSelection,+}: {+ group: EnvironmentVariableGroup+ getEnvironmentVariableSelection: DeploymentConfigurationValuesController['getEnvironmentVariableSelection']+ setEnvironmentVariableSelection: DeploymentConfigurationValuesController['setEnvironmentVariableSelection']+}) {+ const owner = group.from_app ?? group.from_workflow_as_tool?.workflow+ if (!owner) return null++ return (+ <fieldset aria-label={owner.name} className="min-w-0 pb-2">+ <div className="flex min-w-0 items-center gap-2 pt-1 pb-3">+ <WorkflowReferenceIcon reference={owner} />+ {group.from_workflow_as_tool ? (+ <SubworkflowSourceTitle source={group.from_workflow_as_tool} />+ ) : (+ <span className="min-w-0 flex-1 truncate system-sm-semibold text-text-primary">+ {owner.name}+ </span>+ )}+ </div>+ <div className="flex min-w-0 items-stretch gap-2">+ <span aria-hidden className="flex w-5 shrink-0 justify-center pt-1">+ <span className="h-full w-0.5 rounded-full bg-divider-subtle" />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-4">+ {group.environment_variable_slots.map((slot) => (+ <EnvironmentVariableField+ key={`${owner.workflow_id}:${slot.key}:${slot.has_configured_value}:${slot.has_last_deployed_value}`}+ slot={slot}+ workflowId={owner.workflow_id}+ getInitialSelection={getEnvironmentVariableSelection}+ onChange={setEnvironmentVariableSelection}+ />+ ))}+ </div>+ </div>+ </fieldset>+ )+}++export const EnvironmentVariablesSection = memo(+ ({+ environmentVariableGroups,+ getEnvironmentVariableSelection,+ hasCredentialSlots,+ horizontalPaddingClassName,+ setEnvironmentVariableSelection,+ }: {+ environmentVariableGroups: EnvironmentVariableGroup[]+ getEnvironmentVariableSelection: DeploymentConfigurationValuesController['getEnvironmentVariableSelection']+ hasCredentialSlots: boolean+ horizontalPaddingClassName: string+ setEnvironmentVariableSelection: DeploymentConfigurationValuesController['setEnvironmentVariableSelection']+ }) => {+ const { t } = useTranslation('deployments')+ const visibleGroups = environmentVariableGroups.filter(+ (group) => group.environment_variable_slots.length > 0,+ )++ if (visibleGroups.length === 0) return null++ return (+ <section+ className={cn(+ 'flex flex-col gap-4 py-4',+ hasCredentialSlots && 'border-t border-divider-regular',+ horizontalPaddingClassName,+ )}+ >+ <SectionHeading+ title={t(($) => $['deployDrawer.envVars'])}+ description={t(($) => $['studio.environmentVariablesDescription'])}+ />+ {visibleGroups.map((group) => {+ const owner = group.from_app ?? group.from_workflow_as_tool?.workflow+ if (!owner) return null++ return (+ <EnvironmentVariableGroupFields+ key={owner.workflow_id}+ group={group}+ getEnvironmentVariableSelection={getEnvironmentVariableSelection}+ setEnvironmentVariableSelection={setEnvironmentVariableSelection}+ />+ )+ })}+ </section>+ )+ },+)diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/index.tsx b/web/app/components/app/deploy/shared/deployment-configuration/index.tsxsimilarity index 68%rename from web/app/components/app/deploy/deployment-dialog/deployment-configuration/index.tsxrename to web/app/components/app/deploy/shared/deployment-configuration/index.tsxindex ca40aacbae2..aa9afd8cae9 100644--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/index.tsx+++ b/web/app/components/app/deploy/shared/deployment-configuration/index.tsx@@ -1,16 +1,15 @@'use client'-import type { DeploymentVersion } from '../../version'-import type { DeploymentDialogRequest } from '../types'+import type { DeploymentDialogRequest } from '../../types'+import type { DeploymentVersion } from '../../utils/version'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { DialogClose, DialogTitle } from '@langgenius/dify-ui/dialog'import { IconButton } from '@langgenius/dify-ui/icon-button'import { useTranslation } from 'react-i18next'-import { useDeployWorkflow } from '../../use-deploy-workflow'import { DeploymentConfigurationContent } from './content'+import { useDeploymentConfigurationForm } from './use-deployment-configuration-form'import { useDeploymentConfigurationQueries } from './use-deployment-configuration-queries'import { useDeploymentConfigurationValues } from './use-deployment-configuration-values'-import { workflowDeploymentInput } from './workflow-deployment-input'export function DeploymentConfiguration({appId,@@ -35,47 +34,26 @@ export function DeploymentConfiguration({}) {const { t } = useTranslation('deployments')const { t: tCommon } = useTranslation('common')- const [configurationValues, setConfigurationValues] = useDeploymentConfigurationValues()+ const configurationValues = useDeploymentConfigurationValues()const queryState = useDeploymentConfigurationQueries({appId,environmentId: request.environmentId,workflowId: version.id,})- const deploymentInput = queryState.deploymentOptions- ? workflowDeploymentInput(queryState.deploymentOptions, configurationValues)- : undefined- const deployMutation = useDeployWorkflow({+ const { canDeploy, handleSubmit, isDeploying } = useDeploymentConfigurationForm({appId,+ configurationValues,+ disabled,+ environmentId: request.environmentId,invalidateAppEnvironmentsOnSuccess,- onSuccess: (response) => {- onDeploymentStarted?.(response.operation.id)- onClose()- },+ queryState,+ workflowId: version.id,+ onClose,+ onDeploymentStarted,})- const canDeploy =- Boolean(appId) &&- !disabled &&- queryState.canDeploy &&- Boolean(deploymentInput) &&- !deployMutation.isPendingreturn (- <form- className="flex min-h-0 flex-1 flex-col"- onSubmit={(event) => {- event.preventDefault()- if (!appId || !canDeploy || !deploymentInput) return-- deployMutation.mutate({- body: deploymentInput,- params: {- app_id: appId,- environment_id: request.environmentId,- workflow_id: version.id,- },- })- }}- >+ <form className="flex min-h-0 flex-1 flex-col" onSubmit={handleSubmit}>{!embedded && (<DialogCloserender={@@ -116,10 +94,9 @@ export function DeploymentConfiguration({<DeploymentConfigurationContentcompact={embedded}- onValuesChange={setConfigurationValues}+ configurationValues={configurationValues}queryState={queryState}request={request}- values={configurationValues}version={version}/>@@ -132,12 +109,7 @@ export function DeploymentConfiguration({<Button type="button" variant="secondary" onClick={onClose}>{tCommon(($) => $['operation.cancel'])}</Button>- <Button- type="submit"- variant="primary"- disabled={!canDeploy}- loading={deployMutation.isPending}- >+ <Button type="submit" variant="primary" disabled={!canDeploy} loading={isDeploying}>{tCommon(($) => $['appMenus.deploy'])}</Button></footer>diff --git a/web/app/components/app/deploy/shared/deployment-configuration/section-heading.tsx b/web/app/components/app/deploy/shared/deployment-configuration/section-heading.tsxnew file mode 100644index 00000000000..80873dc3ebc--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/section-heading.tsx@@ -0,0 +1,8 @@+export function SectionHeading({ title, description }: { title: string; description: string }) {+ return (+ <div className="flex min-w-0 flex-col">+ <h3 className="system-md-semibold text-text-primary">{title}</h3>+ <p className="system-xs-regular text-text-tertiary">{description}</p>+ </div>+ )+}diff --git a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-form.ts b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-form.tsnew file mode 100644index 00000000000..baa4388d5f1--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-form.ts@@ -0,0 +1,110 @@+'use client'++import type { FormEventHandler } from 'react'+import type { DeploymentConfigurationQueryState } from './use-deployment-configuration-queries'+import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'+import { toast } from '@langgenius/dify-ui/toast'+import { useTranslation } from 'react-i18next'+import { useDeployWorkflow } from '../../hooks/use-deploy-workflow'+import {+ credentialProviderName,+ findInvalidDeploymentCredential,+ findInvalidDeploymentEnvironmentVariable,+ hasValidDeploymentEnvironmentVariables,+ workflowDeploymentInput,+} from './utils/workflow-deployment-input'++export function useDeploymentConfigurationForm({+ appId,+ configurationValues,+ disabled,+ environmentId,+ invalidateAppEnvironmentsOnSuccess,+ queryState,+ workflowId,+ onClose,+ onDeploymentStarted,+}: {+ appId?: string+ configurationValues: DeploymentConfigurationValuesController+ disabled: boolean+ environmentId: string+ invalidateAppEnvironmentsOnSuccess: boolean+ queryState: DeploymentConfigurationQueryState+ workflowId: string+ onClose: () => void+ onDeploymentStarted?: (operationId: string) => void+}) {+ const { t: tCommon } = useTranslation('common')+ const { t: tDeployments } = useTranslation('deployments')+ const { t: tWorkflow } = useTranslation('workflow')+ const deployMutation = useDeployWorkflow({+ appId,+ invalidateAppEnvironmentsOnSuccess,+ onSuccess: (response) => {+ onDeploymentStarted?.(response.operation.id)+ onClose()+ },+ })+ const canDeploy = Boolean(appId) && !disabled && queryState.canDeploy && !deployMutation.isPending++ const handleSubmit: FormEventHandler<HTMLFormElement> = (event) => {+ event.preventDefault()+ if (!appId || !canDeploy || !queryState.deploymentOptions) return++ const values = configurationValues.getValues()+ const invalidCredential = findInvalidDeploymentCredential(+ queryState.deploymentOptions,+ values.credentials,+ )+ if (invalidCredential) {+ toast.error(+ `${credentialProviderName(invalidCredential.provider_id)}: ${+ invalidCredential.candidates.length === 0+ ? tDeployments(($) => $['deployDrawer.noCredentialCandidates'])+ : tDeployments(($) => $['deployDrawer.selectCredential'])+ }`,+ )+ return+ }++ const invalidEnvironmentVariable = findInvalidDeploymentEnvironmentVariable(+ queryState.deploymentOptions,+ values,+ )+ if (invalidEnvironmentVariable) {+ toast.error(+ `${invalidEnvironmentVariable.owner.name} · ${invalidEnvironmentVariable.slot.key}: ${tWorkflow(+ ($) => $['env.modal.valueRequired'],+ )}`,+ )+ return+ }++ if (!hasValidDeploymentEnvironmentVariables(queryState.deploymentOptions, values)) {+ toast.error(tCommon(($) => $.error))+ return+ }++ const deploymentInput = workflowDeploymentInput(queryState.deploymentOptions, values)+ if (!deploymentInput) {+ toast.error(tCommon(($) => $.error))+ return+ }++ deployMutation.mutate({+ body: deploymentInput,+ params: {+ app_id: appId,+ environment_id: environmentId,+ workflow_id: workflowId,+ },+ })+ }++ return {+ canDeploy,+ handleSubmit,+ isDeploying: deployMutation.isPending,+ }+}diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-deployment-configuration-queries.ts b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.tssimilarity index 71%rename from web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-deployment-configuration-queries.tsrename to web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.tsindex 7bb52bc8f03..2a95046cbda 100644--- a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-deployment-configuration-queries.ts+++ b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.ts@@ -1,7 +1,19 @@'use client'+import type { QueryFunction } from '@tanstack/react-query'import { skipToken, useQuery } from '@tanstack/react-query'import { consoleQuery } from '@/service/client'+import { normalizeDeploymentError } from './utils/deployment-error'++function withNormalizedDeploymentError<TData>(queryFn: QueryFunction<TData>): QueryFunction<TData> {+ return async (context) => {+ try {+ return await queryFn(context)+ } catch (error) {+ throw await normalizeDeploymentError(error)+ }+ }+}export function useDeploymentConfigurationQueries({appId,@@ -12,8 +24,9 @@ export function useDeploymentConfigurationQueries({environmentId: stringworkflowId: string}) {- const precheckQuery = useQuery(+ const precheckQueryOptions =consoleQuery.enterprise.appDeploy.deploymentService.precheckWorkflowDeployment.queryOptions({+ gcTime: 0,input: appId? {params: {@@ -23,14 +36,18 @@ export function useDeploymentConfigurationQueries({}: skipToken,retry: false,- }),- )+ })+ const precheckQuery = useQuery({+ ...precheckQueryOptions,+ queryFn: withNormalizedDeploymentError(precheckQueryOptions.queryFn),+ })const precheck = precheckQuery.dataconst precheckPassed =precheckQuery.isSuccess && !precheckQuery.isFetching && precheck?.unsupported_nodes.length === 0- const deploymentOptionsQuery = useQuery(+ const deploymentOptionsQueryOptions =consoleQuery.enterprise.appDeploy.deploymentService.getWorkflowDeploymentOptions.queryOptions({+ gcTime: 0,input: appId? {params: {@@ -42,8 +59,11 @@ export function useDeploymentConfigurationQueries({: skipToken,enabled: precheckPassed,retry: false,- }),- )+ })+ const deploymentOptionsQuery = useQuery({+ ...deploymentOptionsQueryOptions,+ queryFn: withNormalizedDeploymentError(deploymentOptionsQueryOptions.queryFn),+ })const isPrechecking = Boolean(appId) && (precheckQuery.isLoading || precheckQuery.isFetching)const isLoadingDeploymentOptions =diff --git a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-values.ts b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-values.tsnew file mode 100644index 00000000000..3122ad586a1--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-values.ts@@ -0,0 +1,84 @@+'use client'++import type { EnvVarValueSource } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { LLMEnvironmentVariableValue } from '@/app/components/workflow/types'+import { useCallback, useRef, useState } from 'react'++export type EnvironmentVariableSelection = {+ customValue: string | LLMEnvironmentVariableValue+ source: EnvVarValueSource+}++export type DeploymentConfigurationValues = {+ credentials: Record<string, string>+ environmentVariables: Record<string, EnvironmentVariableSelection>+}++export type DeploymentConfigurationValuesController = {+ credentials: DeploymentConfigurationValues['credentials']+ getEnvironmentVariableSelection: (+ workflowId: string,+ key: string,+ ) => EnvironmentVariableSelection | undefined+ getValues: () => DeploymentConfigurationValues+ setCredential: (key: string, value: string) => void+ setEnvironmentVariableSelection: (+ workflowId: string,+ key: string,+ value: EnvironmentVariableSelection,+ ) => void+}++export function environmentVariableSelectionKey(workflowId: string, key: string) {+ return JSON.stringify([workflowId, key])+}++export function useDeploymentConfigurationValues() {+ const valuesRef = useRef<DeploymentConfigurationValues>({+ credentials: {},+ environmentVariables: {},+ })+ const [credentials, setCredentials] = useState<DeploymentConfigurationValues['credentials']>({})++ const getEnvironmentVariableSelection = useCallback(+ (workflowId: string, key: string) =>+ valuesRef.current.environmentVariables[environmentVariableSelectionKey(workflowId, key)],+ [],+ )+ const getValues = useCallback(() => valuesRef.current, [])+ const setCredential = useCallback((key: string, value: string) => {+ const current = valuesRef.current+ if (current.credentials[key] === value) return++ const nextCredentials = {+ ...current.credentials,+ [key]: value,+ }+ valuesRef.current = {+ ...current,+ credentials: nextCredentials,+ }+ setCredentials(nextCredentials)+ }, [])+ const setEnvironmentVariableSelection = useCallback(+ (workflowId: string, key: string, value: EnvironmentVariableSelection) => {+ const current = valuesRef.current+ valuesRef.current = {+ ...current,+ environmentVariables: {+ ...current.environmentVariables,+ [environmentVariableSelectionKey(workflowId, key)]: value,+ },+ }+ },+ [],+ )++ return {+ credentials,+ getEnvironmentVariableSelection,+ getValues,+ setCredential,+ setEnvironmentVariableSelection,+ } satisfies DeploymentConfigurationValuesController+}diff --git a/web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-provider-icon.ts b/web/app/components/app/deploy/shared/deployment-configuration/use-provider-icon.tssimilarity index 100%rename from web/app/components/app/deploy/deployment-dialog/deployment-configuration/use-provider-icon.tsrename to web/app/components/app/deploy/shared/deployment-configuration/use-provider-icon.tsdiff --git a/web/app/components/app/deploy/shared/deployment-configuration/utils/deployment-error.ts b/web/app/components/app/deploy/shared/deployment-configuration/utils/deployment-error.tsnew file mode 100644index 00000000000..90554b305a2--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/utils/deployment-error.ts@@ -0,0 +1,36 @@+function messageFrom(value: unknown) {+ if (typeof value !== 'object' || value === null) return undefined++ if ('message' in value && typeof value.message === 'string')+ return value.message.trim() || undefined+ if ('error' in value && typeof value.error === 'string') return value.error.trim() || undefined++ return undefined+}++export function getDeploymentErrorMessage(error: unknown) {+ if (typeof error === 'object' && error !== null && 'data' in error) {+ const data = error.data+ if (typeof data === 'object' && data !== null && 'body' in data) {+ const bodyMessage = messageFrom(data.body)+ if (bodyMessage) return bodyMessage+ }++ const dataMessage = messageFrom(data)+ if (dataMessage) return dataMessage+ }++ return messageFrom(error)+}++export async function normalizeDeploymentError(error: unknown) {+ if (error instanceof Response && !error.bodyUsed) {+ try {+ const response: unknown = await error.clone().json()+ const message = getDeploymentErrorMessage(response)+ if (message) return new Error(message)+ } catch {}+ }++ return error+}diff --git a/web/app/components/app/deploy/shared/deployment-configuration/utils/workflow-deployment-input.ts b/web/app/components/app/deploy/shared/deployment-configuration/utils/workflow-deployment-input.tsnew file mode 100644index 00000000000..c73266482f1--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/utils/workflow-deployment-input.ts@@ -0,0 +1,251 @@+import type {+ CredentialSlot,+ EnvironmentVariableSlot,+ GetWorkflowDeploymentOptionsResponse,+ WorkflowDeploymentInput,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { DeploymentConfigurationValues } from '../use-deployment-configuration-values'+import {+ EnvVarValueSource as EnvVarValueSourceEnum,+ EnvVarValueType,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'+import { environmentVariableSelectionKey } from '../use-deployment-configuration-values'++export function credentialSlotKey(slot: CredentialSlot) {+ return `${slot.provider_id}:${slot.category}`+}++export function credentialProviderName(providerId: string) {+ const name = providerId.split('/').filter(Boolean).at(-1) ?? providerId++ return name+ .split(/[-_]/)+ .filter(Boolean)+ .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)+ .join(' ')+}++export function defaultCredentialId(slot: CredentialSlot) {+ if (+ slot.last_deployed_credential_id &&+ slot.candidates.some(+ (candidate) => candidate.credential_id === slot.last_deployed_credential_id,+ )+ ) {+ return slot.last_deployed_credential_id+ }++ return slot.candidates.length === 1 ? slot.candidates[0]?.credential_id : undefined+}++function selectedCredentialId(+ slot: CredentialSlot,+ credentials: DeploymentConfigurationValues['credentials'],+) {+ const credentialId = credentials[credentialSlotKey(slot)] ?? defaultCredentialId(slot)+ if (!credentialId) return undefined++ return slot.candidates.some((candidate) => candidate.credential_id === credentialId)+ ? credentialId+ : undefined+}++function defaultEnvironmentVariableSelection(+ slot: EnvironmentVariableSlot,+): DeploymentConfigurationValues['environmentVariables'][string] {+ if (slot.has_configured_value) {+ return {+ customValue: '',+ source: EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED,+ }+ }++ if (slot.has_last_deployed_value) {+ return {+ customValue: '',+ source: EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED,+ }+ }++ return {+ customValue: '',+ source: EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM,+ }+}++function isEnvironmentVariableSelectionAvailable(+ slot: EnvironmentVariableSlot,+ selection: DeploymentConfigurationValues['environmentVariables'][string],+) {+ switch (selection.source) {+ case EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED:+ return slot.has_configured_value+ case EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED:+ return slot.has_last_deployed_value+ case EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM:+ return true+ default:+ return false+ }+}++export function resolveEnvironmentVariableSelection(+ slot: EnvironmentVariableSlot,+ selection?: DeploymentConfigurationValues['environmentVariables'][string],+) {+ if (selection && isEnvironmentVariableSelectionAvailable(slot, selection)) return selection++ return {+ ...defaultEnvironmentVariableSelection(slot),+ customValue: selection?.customValue ?? '',+ }+}++export function findInvalidDeploymentCredential(+ deploymentOptions: GetWorkflowDeploymentOptionsResponse,+ credentials: DeploymentConfigurationValues['credentials'],+) {+ return deploymentOptions.credential_slots.find((slot) => !selectedCredentialId(slot, credentials))+}++function selectedEnvironmentVariableValue(+ slot: EnvironmentVariableSlot,+ selection: DeploymentConfigurationValues['environmentVariables'][string],+) {+ let value: unknown++ switch (selection.source) {+ case EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CONFIGURED:+ value = slot.configured_value+ break+ case EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_LAST_DEPLOYED:+ value = slot.last_deployed_value+ break+ case EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM:+ value = selection.customValue+ break+ default:+ return undefined+ }++ if (slot.value_type !== EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER) return value+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined+ if (typeof value !== 'string' || value.trim() === '') return undefined++ const numberValue = Number(value)+ return Number.isFinite(numberValue) ? numberValue : undefined+}++function hasValidEnvironmentVariableValue(slot: EnvironmentVariableSlot, value: unknown) {+ switch (slot.value_type) {+ case EnvVarValueType.ENV_VAR_VALUE_TYPE_LLM:+ return isLLMEnvironmentVariableValue(value)+ case EnvVarValueType.ENV_VAR_VALUE_TYPE_NUMBER:+ return typeof value === 'number' && Number.isFinite(value)+ case EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET:+ case EnvVarValueType.ENV_VAR_VALUE_TYPE_STRING:+ return typeof value === 'string' && value !== ''+ default:+ return false+ }+}++export function hasValidDeploymentEnvironmentVariables(+ deploymentOptions: GetWorkflowDeploymentOptionsResponse,+ values: DeploymentConfigurationValues,+) {+ if (+ deploymentOptions.environment_variable_groups.some(+ (group) => !group.from_app && !group.from_workflow_as_tool,+ )+ )+ return false++ return !findInvalidDeploymentEnvironmentVariable(deploymentOptions, values)+}++export function findInvalidDeploymentEnvironmentVariable(+ deploymentOptions: GetWorkflowDeploymentOptionsResponse,+ values: DeploymentConfigurationValues,+) {+ for (const group of deploymentOptions.environment_variable_groups) {+ const owner = group.from_app ?? group.from_workflow_as_tool?.workflow+ if (!owner) continue++ for (const slot of group.environment_variable_slots) {+ const selection = resolveEnvironmentVariableSelection(+ slot,+ values.environmentVariables[environmentVariableSelectionKey(owner.workflow_id, slot.key)],+ )+ const selectedValue = selectedEnvironmentVariableValue(slot, selection)+ if (!hasValidEnvironmentVariableValue(slot, selectedValue)) return { owner, slot }++ if (+ selection.source === EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM &&+ slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_LLM &&+ isLLMEnvironmentVariableValue(selectedValue)+ ) {+ const requiredMode = isLLMEnvironmentVariableValue(slot.configured_value)+ ? slot.configured_value.mode+ : isLLMEnvironmentVariableValue(slot.last_deployed_value)+ ? slot.last_deployed_value.mode+ : undefined+ if (requiredMode && selectedValue.mode !== requiredMode) return { owner, slot }+ }+ }+ }++ return undefined+}++export function workflowDeploymentInput(+ deploymentOptions: GetWorkflowDeploymentOptionsResponse,+ values: DeploymentConfigurationValues,+): WorkflowDeploymentInput | undefined {+ if (!hasValidDeploymentEnvironmentVariables(deploymentOptions, values)) return++ const credentials: NonNullable<WorkflowDeploymentInput['credentials']> = []++ for (const slot of deploymentOptions.credential_slots) {+ const credentialId = selectedCredentialId(slot, values.credentials)+ if (!credentialId) return++ credentials.push({+ category: slot.category,+ credential_id: credentialId,+ provider_id: slot.provider_id,+ })+ }++ const environmentVariableGroups: WorkflowDeploymentInput['environment_variable_groups'] = []++ for (const group of deploymentOptions.environment_variable_groups) {+ const owner = group.from_app ?? group.from_workflow_as_tool?.workflow+ if (!owner) return++ environmentVariableGroups.push({+ workflow_id: owner.workflow_id,+ environment_variables: group.environment_variable_slots.map((slot) => {+ const selection = resolveEnvironmentVariableSelection(+ slot,+ values.environmentVariables[environmentVariableSelectionKey(owner.workflow_id, slot.key)],+ )+ const value = selectedEnvironmentVariableValue(slot, selection)++ return {+ key: slot.key,+ value_source: selection.source,+ ...(selection.source === EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM+ ? { value }+ : {}),+ }+ }),+ })+ }++ return {+ credentials,+ environment_variable_groups: environmentVariableGroups,+ }+}diff --git a/web/app/components/app/deploy/shared/deployment-configuration/utils/workflow-path.ts b/web/app/components/app/deploy/shared/deployment-configuration/utils/workflow-path.tsnew file mode 100644index 00000000000..53b29a15db5--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/utils/workflow-path.ts@@ -0,0 +1,15 @@+import type { WorkflowPath } from '@dify/contracts/enterprise-app-deploy/types.gen'++export function workflowPathKey(path: WorkflowPath) {+ return JSON.stringify(path.workflows.map((workflow) => [workflow.app_id, workflow.workflow_id]))+}++export function uniqueWorkflowPaths(paths: WorkflowPath[]) {+ return [+ ...new Map(+ paths+ .filter((path) => path.workflows.length > 0)+ .map((path) => [workflowPathKey(path), path] as const),+ ).values(),+ ]+}diff --git a/web/app/components/app/deploy/shared/deployment-configuration/workflow-source-popover.tsx b/web/app/components/app/deploy/shared/deployment-configuration/workflow-source-popover.tsxnew file mode 100644index 00000000000..c1ff3566a8c--- /dev/null+++ b/web/app/components/app/deploy/shared/deployment-configuration/workflow-source-popover.tsx@@ -0,0 +1,172 @@+'use client'++import type {+ WorkflowAsToolSource,+ WorkflowPath,+ WorkflowReference,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { AppIconType } from '@/types/app'+import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'+import { Fragment } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import Link from '@/next/link'+import { uniqueWorkflowPaths, workflowPathKey } from './utils/workflow-path'++function workflowReferenceIconType(reference: WorkflowReference): AppIconType | undefined {+ if (reference.icon_type === 'emoji') return 'emoji'+ if (reference.icon_type === 'image' || reference.icon_type === 'link') return 'image'++ return undefined+}++function workflowReferenceImageUrl(reference: WorkflowReference) {+ if (reference.icon_type !== 'image' && reference.icon_type !== 'link') return undefined++ return reference.icon_url ?? reference.icon+}++export function WorkflowReferenceIcon({ reference }: { reference: WorkflowReference }) {+ return (+ <span aria-hidden className="shrink-0">+ <AppIcon+ size="xs"+ iconType={workflowReferenceIconType(reference)}+ icon={reference.icon}+ background={reference.icon_background}+ imageUrl={workflowReferenceImageUrl(reference)}+ className="size-5 rounded-md text-sm"+ />+ </span>+ )+}++function WorkflowPathLink({ path }: { path: WorkflowPath }) {+ const leafWorkflow = path.workflows.at(-1)+ if (!leafWorkflow) return null++ return (+ <Link+ href={`/app/${leafWorkflow.app_id}/workflow`}+ target="_blank"+ rel="noopener noreferrer"+ className="group flex min-h-7 min-w-0 items-center gap-1 rounded-md py-1 pr-2 pl-1 system-sm-regular text-text-secondary outline-hidden hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-state-accent-solid"+ >+ <span className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden">+ {path.workflows.map((workflow, index) => (+ <Fragment key={`${workflow.app_id}:${workflow.workflow_id}`}>+ {index > 0 && (+ <span+ aria-hidden+ className="i-ri-arrow-right-s-line size-3.5 shrink-0 text-text-tertiary"+ />+ )}+ <span className="flex min-w-0 shrink items-center gap-2">+ <WorkflowReferenceIcon reference={workflow} />+ <span className="min-w-0 truncate">{workflow.name}</span>+ </span>+ </Fragment>+ ))}+ </span>+ <span+ aria-hidden+ className="i-ri-external-link-line size-3 shrink-0 text-text-tertiary group-hover:text-text-secondary"+ />+ </Link>+ )+}++function WorkflowSourceContent({ paths, title }: { paths: WorkflowPath[]; title: string }) {+ return (+ <PopoverContent+ placement="top-end"+ sideOffset={4}+ className="w-max max-w-[min(30rem,calc(100vw-32px))] bg-components-panel-bg-blur p-1 shadow-lg backdrop-blur-[5px]"+ >+ <PopoverTitle className="sr-only">{title}</PopoverTitle>+ <ul className="flex flex-col gap-px">+ {paths.map((path) => (+ <li key={workflowPathKey(path)}>+ <WorkflowPathLink path={path} />+ </li>+ ))}+ </ul>+ </PopoverContent>+ )+}++export function WorkflowDependencyPreview({+ paths,+ subjectName,+}: {+ paths: WorkflowPath[]+ subjectName: string+}) {+ const { t } = useTranslation('deployments')+ const validPaths = uniqueWorkflowPaths(paths)+ const firstLeafWorkflow = validPaths[0]?.workflows.at(-1)++ if (!firstLeafWorkflow) return null++ const sourceLabel =+ validPaths.length === 1+ ? firstLeafWorkflow.name+ : t(($) => $['studio.precheck.nodeCount_other'], { count: validPaths.length })++ return (+ <Popover>+ <PopoverTrigger+ openOnHover+ delay={300}+ closeDelay={200}+ render={+ <button+ type="button"+ className="group/source flex min-w-0 shrink-0 cursor-help items-center gap-1 rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-state-accent-solid"+ >+ <span className="sr-only">{subjectName}: </span>+ <span className="shrink-0 system-xs-regular text-text-tertiary">+ {t(($) => $['studio.precheck.from'])}+ </span>+ <span className="max-w-30 truncate border-b border-dotted border-text-quaternary system-xs-regular text-text-tertiary group-hover/source:text-text-secondary group-data-popup-open/source:text-text-secondary">+ {sourceLabel}+ </span>+ </button>+ }+ />+ <WorkflowSourceContent paths={validPaths} title={subjectName} />+ </Popover>+ )+}++export function SubworkflowSourceTitle({ source }: { source: WorkflowAsToolSource }) {+ const { workflow } = source+ const paths = uniqueWorkflowPaths(source.paths)++ if (paths.length === 0) {+ return (+ <span className="min-w-0 flex-1 truncate system-sm-semibold text-text-primary">+ {workflow.name}+ </span>+ )+ }++ return (+ <Popover>+ <PopoverTrigger+ openOnHover+ delay={300}+ closeDelay={200}+ render={+ <button+ type="button"+ className="group/source max-w-full min-w-0 cursor-help truncate rounded-sm border-b border-dotted border-text-quaternary text-start system-sm-semibold text-text-primary outline-hidden hover:text-text-secondary focus-visible:ring-1 focus-visible:ring-state-accent-solid data-popup-open:text-text-secondary"+ >+ {workflow.name}+ </button>+ }+ />+ <WorkflowSourceContent paths={paths} title={workflow.name} />+ </Popover>+ )+}diff --git a/web/app/components/app/deploy/shared/deployment-status.tsx b/web/app/components/app/deploy/shared/deployment-status.tsxdeleted file mode 100644index 4f4aabd2076..00000000000--- a/web/app/components/app/deploy/shared/deployment-status.tsx+++ /dev/null@@ -1,76 +0,0 @@-'use client'--import type { DeploymentStatus as DeploymentStatusValue } from '@dify/contracts/enterprise-app-deploy/types.gen'-import type { StatusDotStatus } from '@langgenius/dify-ui/status-dot'-import { DeploymentStatus as DeploymentStatusEnum } from '@dify/contracts/enterprise-app-deploy/types.gen'-import { cn } from '@langgenius/dify-ui/cn'-import { StatusDot } from '@langgenius/dify-ui/status-dot'-import { useTranslation } from 'react-i18next'--const STATUS_TEXT_CLASS_NAMES: Record<DeploymentStatusValue, string> = {- [DeploymentStatusEnum.DEPLOYMENT_STATUS_UNSPECIFIED]: 'text-text-tertiary',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_UNDEPLOYED]: 'text-text-tertiary',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_DEPLOYING]: 'text-util-colors-blue-light-blue-light-600',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_RUNNING]: 'text-util-colors-green-green-600',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_UNDEPLOYING]:- 'text-util-colors-blue-light-blue-light-600',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_INVALID]: 'text-util-colors-red-red-600',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_FAILED]: 'text-util-colors-red-red-600',-}--const STATUS_DOT: Partial<Record<DeploymentStatusValue, StatusDotStatus>> = {- [DeploymentStatusEnum.DEPLOYMENT_STATUS_UNSPECIFIED]: 'disabled',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_UNDEPLOYED]: 'disabled',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_RUNNING]: 'success',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_INVALID]: 'error',- [DeploymentStatusEnum.DEPLOYMENT_STATUS_FAILED]: 'error',-}--function getStatusLabel(- status: DeploymentStatusValue,- t: ReturnType<typeof useTranslation<'deployments'>>['t'],-) {- switch (status) {- case DeploymentStatusEnum.DEPLOYMENT_STATUS_DEPLOYING:- return t(($) => $['status.RUNTIME_INSTANCE_STATUS_DEPLOYING'])- case DeploymentStatusEnum.DEPLOYMENT_STATUS_RUNNING:- return t(($) => $['status.RUNTIME_INSTANCE_STATUS_READY'])- case DeploymentStatusEnum.DEPLOYMENT_STATUS_UNDEPLOYING:- return t(($) => $['status.RUNTIME_INSTANCE_STATUS_UNDEPLOYING'])- case DeploymentStatusEnum.DEPLOYMENT_STATUS_FAILED:- return t(($) => $['status.RUNTIME_INSTANCE_STATUS_FAILED'])- case DeploymentStatusEnum.DEPLOYMENT_STATUS_INVALID:- return t(($) => $['status.RUNTIME_INSTANCE_STATUS_INVALID'])- case DeploymentStatusEnum.DEPLOYMENT_STATUS_UNSPECIFIED:- return t(($) => $['status.RUNTIME_INSTANCE_STATUS_UNSPECIFIED'])- default:- return t(($) => $['status.RUNTIME_INSTANCE_STATUS_UNDEPLOYED'])- }-}--export function DeploymentStatus({ status }: { status?: DeploymentStatusValue }) {- const { t } = useTranslation('deployments')- const resolvedStatus = status ?? DeploymentStatusEnum.DEPLOYMENT_STATUS_UNDEPLOYED- const label = getStatusLabel(resolvedStatus, t)- const isInProgress =- resolvedStatus === DeploymentStatusEnum.DEPLOYMENT_STATUS_DEPLOYING ||- resolvedStatus === DeploymentStatusEnum.DEPLOYMENT_STATUS_UNDEPLOYING-- return (- <span- className={cn(- 'inline-flex min-w-0 items-center gap-1 system-xs-semibold-uppercase',- STATUS_TEXT_CLASS_NAMES[resolvedStatus],- )}- >- {isInProgress ? (- <span aria-hidden className="i-ri-loader-2-line size-4 shrink-0 animate-spin" />- ) : (- <StatusDot size="small" status={STATUS_DOT[resolvedStatus]} />- )}- <span className="truncate" title={label}>- {label}- </span>- </span>- )-}diff --git a/web/app/components/app/deploy/environment-deployment-flow/index.tsx b/web/app/components/app/deploy/shared/environment-deployment-flow/index.tsxsimilarity index 71%rename from web/app/components/app/deploy/environment-deployment-flow/index.tsxrename to web/app/components/app/deploy/shared/environment-deployment-flow/index.tsxindex f8181e81b28..19cf49a3195 100644--- a/web/app/components/app/deploy/environment-deployment-flow/index.tsx+++ b/web/app/components/app/deploy/shared/environment-deployment-flow/index.tsx@@ -2,11 +2,12 @@import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { ReactNode } from 'react'-import type { DeploymentVersion } from '../version'-import { useState } from 'react'-import { DeploymentConfiguration } from '../deployment-dialog/deployment-configuration'-import { EmbeddedVersionSelection } from '../deployment-dialog/version-selection'-import { AppDeployStateBoundary, isEnvironmentDeploymentInProgress } from '../state'+import type { DeploymentVersion } from '../../utils/version'+import { useEffect, useState } from 'react'+import { AppDeployStateBoundary } from '../../state'+import { shouldPollEnvironmentDeployment } from '../../utils/environment-deployment'+import { DeploymentConfiguration } from '../deployment-configuration'+import { EmbeddedVersionSelection } from '../version-selection'type EnvironmentDeploymentFlowView = 'configuration' | 'overview' | 'versions'@@ -23,6 +24,7 @@ type EnvironmentDeploymentFlowProps = {disabled?: booleanenvironmentId: stringenvironmentName: string+ onConfigurationOpenChange?: (open: boolean) => voidonDeploymentStarted: (operationId: string) => void}@@ -33,12 +35,13 @@ function EnvironmentDeploymentFlowContent({disabled = false,environmentId,environmentName,+ onConfigurationOpenChange,onDeploymentStarted,}: EnvironmentDeploymentFlowProps) {const [view, setView] = useState<EnvironmentDeploymentFlowView>('overview')const [selectedVersion, setSelectedVersion] = useState<DeploymentVersion>()const currentVersionId = deployment?.deployment?.current_version?.id- const deploymentActionsDisabled = disabled || isEnvironmentDeploymentInProgress(deployment)+ const deploymentActionsDisabled = disabled || shouldPollEnvironmentDeployment(deployment)const request = {currentVersionId,environment: environmentName,@@ -46,15 +49,27 @@ function EnvironmentDeploymentFlowContent({kind: 'deploy' as const,}+ useEffect(+ () => () => {+ onConfigurationOpenChange?.(false)+ },+ [onConfigurationOpenChange],+ )++ const changeView = (nextView: EnvironmentDeploymentFlowView) => {+ setView(nextView)+ onConfigurationOpenChange?.(nextView === 'configuration')+ }+const showVersionSelection = () => {if (deploymentActionsDisabled) return- setView('versions')+ changeView('versions')}const deployVersion = (version: DeploymentVersion) => {if (deploymentActionsDisabled) returnsetSelectedVersion(version)- setView('configuration')+ changeView('configuration')}if (view === 'configuration' && selectedVersion) {@@ -67,7 +82,7 @@ function EnvironmentDeploymentFlowContent({request={request}version={selectedVersion}onBack={showVersionSelection}- onClose={() => setView('overview')}+ onClose={() => changeView('overview')}onDeploymentStarted={onDeploymentStarted}/>)@@ -78,7 +93,7 @@ function EnvironmentDeploymentFlowContent({<EmbeddedVersionSelectiondisabled={deploymentActionsDisabled}request={request}- onBack={() => setView('overview')}+ onBack={() => changeView('overview')}onSelect={deployVersion}/>)diff --git a/web/app/components/app/deploy/shared/runtime-state.tsx b/web/app/components/app/deploy/shared/runtime-state.tsxnew file mode 100644index 00000000000..7c8918745b3--- /dev/null+++ b/web/app/components/app/deploy/shared/runtime-state.tsx@@ -0,0 +1,84 @@+'use client'++import type { RuntimeState as RuntimeStateValue } from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { StatusDotStatus } from '@langgenius/dify-ui/status-dot'+import { RuntimeState } from '@dify/contracts/enterprise-app-deploy/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { StatusDot } from '@langgenius/dify-ui/status-dot'+import { useTranslation } from 'react-i18next'++type RuntimeStateIndicatorProps = {+ runtimeState: RuntimeStateValue+}++const RUNTIME_STATE_TEXT_CLASS_NAMES: Record<RuntimeStateValue, string> = {+ [RuntimeState.RUNTIME_STATE_UNSPECIFIED]: 'text-text-tertiary',+ [RuntimeState.RUNTIME_STATE_UNDEPLOYED]: 'text-text-tertiary',+ [RuntimeState.RUNTIME_STATE_RUNNING]: 'text-util-colors-green-green-600',+ [RuntimeState.RUNTIME_STATE_STARTING]: 'text-util-colors-blue-light-blue-light-600',+ [RuntimeState.RUNTIME_STATE_STOPPING]: 'text-util-colors-blue-light-blue-light-600',+ [RuntimeState.RUNTIME_STATE_ERROR]: 'text-util-colors-red-red-600',+ [RuntimeState.RUNTIME_STATE_UNKNOWN]: 'text-text-warning',+}++const RUNTIME_STATE_DOT: Partial<Record<RuntimeStateValue, StatusDotStatus>> = {+ [RuntimeState.RUNTIME_STATE_UNSPECIFIED]: 'disabled',+ [RuntimeState.RUNTIME_STATE_UNDEPLOYED]: 'disabled',+ [RuntimeState.RUNTIME_STATE_RUNNING]: 'success',+ [RuntimeState.RUNTIME_STATE_ERROR]: 'error',+ [RuntimeState.RUNTIME_STATE_UNKNOWN]: 'warning',+}++function getRuntimeStateLabel(+ runtimeState: RuntimeStateValue,+ t: ReturnType<typeof useTranslation<'deployments'>>['t'],+) {+ switch (runtimeState) {+ case RuntimeState.RUNTIME_STATE_STARTING:+ return t(($) => $['status.RUNTIME_INSTANCE_STATUS_DEPLOYING'])+ case RuntimeState.RUNTIME_STATE_RUNNING:+ return t(($) => $['status.RUNTIME_INSTANCE_STATUS_READY'])+ case RuntimeState.RUNTIME_STATE_STOPPING:+ return t(($) => $['status.RUNTIME_INSTANCE_STATUS_UNDEPLOYING'])+ case RuntimeState.RUNTIME_STATE_ERROR:+ return t(($) => $['status.RUNTIME_INSTANCE_STATUS_INVALID'])+ case RuntimeState.RUNTIME_STATE_UNKNOWN:+ case RuntimeState.RUNTIME_STATE_UNSPECIFIED:+ return t(($) => $['status.RUNTIME_INSTANCE_STATUS_UNSPECIFIED'])+ case RuntimeState.RUNTIME_STATE_UNDEPLOYED:+ return t(($) => $['status.RUNTIME_INSTANCE_STATUS_UNDEPLOYED'])+ default: {+ const exhaustiveState: never = runtimeState+ return exhaustiveState+ }+ }+}++export function RuntimeStateIndicator({ runtimeState }: RuntimeStateIndicatorProps) {+ const { t } = useTranslation('deployments')+ const label = getRuntimeStateLabel(runtimeState, t)+ const isInProgress =+ runtimeState === RuntimeState.RUNTIME_STATE_STARTING ||+ runtimeState === RuntimeState.RUNTIME_STATE_STOPPING++ return (+ <span+ className={cn(+ 'inline-flex min-w-0 items-center gap-1 system-xs-semibold-uppercase',+ RUNTIME_STATE_TEXT_CLASS_NAMES[runtimeState],+ )}+ >+ {isInProgress ? (+ <span+ aria-hidden+ className="i-ri-loader-2-line size-4 shrink-0 animate-spin motion-reduce:animate-none"+ />+ ) : (+ <StatusDot size="small" status={RUNTIME_STATE_DOT[runtimeState]} />+ )}+ <span className="truncate" title={label}>+ {label}+ </span>+ </span>+ )+}diff --git a/web/app/components/app/deploy/hooks/__tests__/use-infinite-scroll.spec.ts b/web/app/components/app/deploy/shared/version-selection/__tests__/use-infinite-scroll.spec.tssimilarity index 82%rename from web/app/components/app/deploy/hooks/__tests__/use-infinite-scroll.spec.tsrename to web/app/components/app/deploy/shared/version-selection/__tests__/use-infinite-scroll.spec.tsindex c0a06a34d25..fd61bacd0e3 100644--- a/web/app/components/app/deploy/hooks/__tests__/use-infinite-scroll.spec.ts+++ b/web/app/components/app/deploy/shared/version-selection/__tests__/use-infinite-scroll.spec.ts@@ -1,6 +1,6 @@import type { InfiniteScrollQuery } from '../use-infinite-scroll'import { act, render } from '@testing-library/react'-import { createElement } from 'react'+import { createElement, useCallback } from 'react'import { afterAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { useInfiniteScroll } from '../use-infinite-scroll'@@ -10,6 +10,7 @@ let scrollRoot: HTMLDivElement | null = nulllet scrollSentinel: HTMLDivElement | null = nullconst observe = vi.fn()const disconnect = vi.fn()+const observerConstructed = vi.fn()const originalIntersectionObserver = globalThis.IntersectionObserverclass MockIntersectionObserver implements IntersectionObserver {@@ -19,6 +20,7 @@ class MockIntersectionObserver implements IntersectionObserver {readonly thresholds: ReadonlyArray<number>constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {+ observerConstructed()intersectionCallback = callbackintersectionOptions = optionsthis.root = options?.root ?? null@@ -36,20 +38,28 @@ class MockIntersectionObserver implements IntersectionObserver {function TestInfiniteScroll({ query }: { query: InfiniteScrollQuery }) {const { rootRef, sentinelRef } = useInfiniteScroll(query)+ const setRootRef = useCallback(+ (node: HTMLDivElement | null) => {+ scrollRoot = node+ rootRef(node)+ },+ [rootRef],+ )+ const setSentinelRef = useCallback(+ (node: HTMLDivElement | null) => {+ scrollSentinel = node+ sentinelRef(node)+ },+ [sentinelRef],+ )return createElement('div',{- ref: (node: HTMLDivElement | null) => {- scrollRoot = node- rootRef(node)- },+ ref: setRootRef,},createElement('div', {- ref: (node: HTMLDivElement | null) => {- scrollSentinel = node- sentinelRef(node)- },+ ref: setSentinelRef,}),)}@@ -114,6 +124,20 @@ describe('deploy useInfiniteScroll', () => {expect(query.fetchNextPage).toHaveBeenCalledWith({ cancelRefetch: false })})+ it('should keep the observer when only the query snapshot changes', () => {+ const initialQuery = createQuery()+ const nextQuery = createQuery()+ const view = render(createElement(TestInfiniteScroll, { query: initialQuery }))++ expect(observerConstructed).toHaveBeenCalledOnce()++ view.rerender(createElement(TestInfiniteScroll, { query: nextQuery }))+ triggerIntersection(true)++ expect(observerConstructed).toHaveBeenCalledOnce()+ expect(nextQuery.fetchNextPage).toHaveBeenCalledOnce()+ })+it.each([['there is no next page', { hasNextPage: false }],['the first page is loading', { isLoading: true }],diff --git a/web/app/components/app/deploy/shared/version-selection/index.tsx b/web/app/components/app/deploy/shared/version-selection/index.tsxnew file mode 100644index 00000000000..1a1bb208368--- /dev/null+++ b/web/app/components/app/deploy/shared/version-selection/index.tsx@@ -0,0 +1,108 @@+'use client'+import type { DeploymentDialogRequest } from '../../types'+import type { DeploymentVersion } from '../../utils/version'+import { Button } from '@langgenius/dify-ui/button'+import { DialogClose, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useTranslation } from 'react-i18next'+import { VersionList } from './version-list'++function versionSelectionTitle(request: DeploymentDialogRequest, deployTo: string, change: string) {+ return request.kind === 'deploy' ? deployTo : `${change} · ${request.environment}`+}++export function VersionSelection({+ appId,+ request,+ onSelect,+}: {+ appId: string+ request: DeploymentDialogRequest+ onSelect: (version: DeploymentVersion) => void+}) {+ const { t } = useTranslation('deployments')+ const { t: tCommon } = useTranslation('common')+ const title = versionSelectionTitle(+ request,+ t(($) => $['versions.deployTo'], { name: request.environment }),+ t(($) => $['studio.changeVersion']),+ )++ return (+ <>+ <DialogClose+ render={+ <IconButton+ aria-label={tCommon(($) => $['operation.close'])}+ size="lg"+ className="absolute top-5 right-5"+ type="button"+ >+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton>+ }+ />+ <header className="shrink-0 px-6 pt-6 pr-14 pb-3">+ <DialogTitle className="title-2xl-semi-bold text-text-primary">{title}</DialogTitle>+ <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">+ {t(($) => $['studio.chooseVersionToDeploy'])}+ </DialogDescription>+ </header>+ <VersionList+ className="px-4 pt-2 pb-4"+ currentVersionId={request.currentVersionId}+ label={title}+ publishHref={`/app/${appId}/workflow`}+ onSelect={onSelect}+ />+ </>+ )+}++export function EmbeddedVersionSelection({+ disabled,+ request,+ onBack,+ onSelect,+}: {+ disabled: boolean+ request: DeploymentDialogRequest+ onBack: () => void+ onSelect: (version: DeploymentVersion) => void+}) {+ const { t } = useTranslation('deployments')+ const { t: tCommon } = useTranslation('common')+ const title = versionSelectionTitle(+ request,+ t(($) => $['versions.deployTo'], { name: request.environment }),+ t(($) => $['studio.changeVersion']),+ )++ return (+ <div className="flex h-133 max-h-[calc(100dvh-32px)] min-h-0 flex-none flex-col">+ <header className="shrink-0 px-3 pt-3.5 pb-1">+ <Button+ type="button"+ size="small"+ variant="ghost-accent"+ className="-ml-1 h-6 gap-1 px-1 system-xs-semibold-uppercase"+ onClick={onBack}+ >+ <span aria-hidden className="i-ri-arrow-left-line size-4" />+ {tCommon(($) => $['operation.back'])}+ </Button>+ <h2 className="mt-0.5 px-1 system-xl-semibold text-text-primary">{title}</h2>+ <p className="mt-0.5 px-1 system-xs-regular text-text-tertiary">+ {t(($) => $['studio.chooseVersionToDeploy'])}+ </p>+ </header>+ <VersionList+ className="p-2"+ currentVersionId={request.currentVersionId}+ disabled={disabled}+ label={title}+ onSelect={onSelect}+ />+ </div>+ )+}diff --git a/web/app/components/app/deploy/hooks/use-infinite-scroll.ts b/web/app/components/app/deploy/shared/version-selection/use-infinite-scroll.tssimilarity index 93%rename from web/app/components/app/deploy/hooks/use-infinite-scroll.tsrename to web/app/components/app/deploy/shared/version-selection/use-infinite-scroll.tsindex f66509a3bfe..bd2d9723c1c 100644--- a/web/app/components/app/deploy/hooks/use-infinite-scroll.ts+++ b/web/app/components/app/deploy/shared/version-selection/use-infinite-scroll.ts@@ -47,8 +47,6 @@ export function useInfiniteScroll<const loadingLockRef = useRef(false)const latestQueryRef = useRef(query)- latestQueryRef.current = query-const disconnectObserver = useCallback(() => {observerRef.current?.disconnect()observerRef.current = null@@ -58,9 +56,10 @@ export function useInfiniteScroll<const connectObserver = useCallback(() => {const root = rootRef.currentconst sentinel = sentinelRef.current+ const latestQuery = latestQueryRef.currentif (- !canFetchNextPage(query) ||+ !canFetchNextPage(latestQuery) ||!root ||!sentinel ||typeof IntersectionObserver === 'undefined'@@ -111,7 +110,7 @@ export function useInfiniteScroll<observer.observe(sentinel)observerRef.current = observerobservedTargetRef.current = { root, sentinel }- }, [disconnectObserver, query])+ }, [disconnectObserver])const setRootRef = useCallback((node: TRoot | null) => {@@ -130,10 +129,13 @@ export function useInfiniteScroll<)useEffect(() => {+ latestQueryRef.current = queryconnectObserver()+ }, [connectObserver, query])+ useEffect(() => {return disconnectObserver- }, [connectObserver, disconnectObserver])+ }, [disconnectObserver])return {rootRef: setRootRef,diff --git a/web/app/components/app/deploy/shared/version-selection/version-list.tsx b/web/app/components/app/deploy/shared/version-selection/version-list.tsxnew file mode 100644index 00000000000..3d2f12c1006--- /dev/null+++ b/web/app/components/app/deploy/shared/version-selection/version-list.tsx@@ -0,0 +1,215 @@+import type { ReactNode } from 'react'+import type { DeploymentVersion } from '../../utils/version'+import { buttonVariants } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import {+ ScrollArea,+ ScrollAreaContent,+ ScrollAreaScrollbar,+ ScrollAreaThumb,+ ScrollAreaViewport,+} from '@langgenius/dify-ui/scroll-area'+import { useAtomValue } from 'jotai'+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import Link from '@/next/link'+import {+ appWorkflowVersionsAtom,+ appWorkflowVersionsErrorAtom,+ appWorkflowVersionsFetchNextPageAtom,+ appWorkflowVersionsHasNextPageAtom,+ appWorkflowVersionsIsFetchingAtom,+ appWorkflowVersionsIsFetchingNextPageAtom,+ appWorkflowVersionsIsLoadingAtom,+} from '../../state'+import { useInfiniteScroll } from './use-infinite-scroll'++function VersionBadge({ children }: { children: ReactNode }) {+ return (+ <span className="inline-flex min-w-4 shrink-0 items-center justify-center rounded-[5px] border border-text-accent bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-accent">+ {children}+ </span>+ )+}++function VersionTag({ children }: { children: ReactNode }) {+ return (+ <span className="inline-flex h-4.5 min-w-4.5 items-center justify-center rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1.25 system-2xs-medium text-text-tertiary">+ {children}+ </span>+ )+}++const VersionChoice = memo(+ ({+ version,+ current,+ disabled = false,+ onSelect,+ }: {+ version: DeploymentVersion+ current: boolean+ disabled?: boolean+ onSelect: (version: DeploymentVersion) => void+ }) => {+ const { t } = useTranslation('deployments')+ const { t: tWorkflow } = useTranslation('workflow')+ const { formatTimeFromNow } = useFormatTimeFromNow()++ return (+ <button+ type="button"+ disabled={current || disabled}+ onClick={() => onSelect(version)}+ className="flex w-full cursor-pointer flex-col items-start gap-0.5 rounded-lg p-2 text-start outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid disabled:cursor-not-allowed disabled:hover:bg-transparent"+ >+ <span className="flex min-w-0 items-center gap-1">+ <span+ className={cn('truncate system-md-medium text-text-secondary', current && 'opacity-50')}+ >+ {version.name}+ </span>+ {version.latest && <VersionBadge>{t(($) => $['overview.chip.latest'])}</VersionBadge>}+ {current && <VersionBadge>{t(($) => $['studio.current'])}</VersionBadge>}+ </span>+ {version.description && (+ <span className="line-clamp-3 system-xs-regular text-text-tertiary">+ {version.description}+ </span>+ )}+ {version.publishedAt !== undefined && version.publishedBy && (+ <span className={cn('system-xs-regular text-text-tertiary', current && 'opacity-50')}>+ {tWorkflow(($) => $['common.publishedBy'], {+ time: formatTimeFromNow(version.publishedAt),+ author: version.publishedBy,+ })}+ </span>+ )}+ {version.tags && version.tags.length > 0 && (+ <span className="flex flex-wrap items-center gap-1 pt-1">+ {version.tags.map((tag) => (+ <VersionTag key={tag}>{tag}</VersionTag>+ ))}+ </span>+ )}+ </button>+ )+ },+)+VersionChoice.displayName = 'VersionChoice'++const VersionChoices = memo(+ ({+ currentVersionId,+ disabled,+ onSelect,+ versions,+ }: {+ currentVersionId?: string+ disabled: boolean+ onSelect: (version: DeploymentVersion) => void+ versions: DeploymentVersion[]+ }) => {+ return versions.map((version) => (+ <VersionChoice+ key={version.id}+ version={version}+ current={version.id === currentVersionId}+ disabled={disabled}+ onSelect={onSelect}+ />+ ))+ },+)+VersionChoices.displayName = 'VersionChoices'++export function VersionList({+ className,+ currentVersionId,+ disabled = false,+ label,+ publishHref,+ onSelect,+}: {+ className?: string+ currentVersionId?: string+ disabled?: boolean+ label: string+ publishHref?: string+ onSelect: (version: DeploymentVersion) => void+}) {+ const { t: tCommon } = useTranslation('common')+ const { t } = useTranslation('deployments')+ const versions = useAtomValue(appWorkflowVersionsAtom)+ const versionsError = useAtomValue(appWorkflowVersionsErrorAtom)+ const fetchNextPage = useAtomValue(appWorkflowVersionsFetchNextPageAtom)+ const hasNextPage = useAtomValue(appWorkflowVersionsHasNextPageAtom)+ const isFetching = useAtomValue(appWorkflowVersionsIsFetchingAtom)+ const isFetchingNextPage = useAtomValue(appWorkflowVersionsIsFetchingNextPageAtom)+ const isLoading = useAtomValue(appWorkflowVersionsIsLoadingAtom)+ const { rootRef, sentinelRef } = useInfiniteScroll<HTMLDivElement>({+ error: versionsError,+ fetchNextPage,+ hasNextPage,+ isFetching,+ isFetchingNextPage,+ isLoading,+ })++ return (+ <ScrollArea className="relative min-h-0 flex-1 overflow-hidden">+ <ScrollAreaViewport+ ref={rootRef}+ aria-label={label}+ className="max-h-full max-w-full overscroll-contain"+ role="region"+ style={{ overflowX: 'hidden' }}+ >+ <ScrollAreaContent+ className={cn('h-full w-full max-w-full', className)}+ style={{ minWidth: 0 }}+ >+ <div className="flex flex-col gap-px">+ <VersionChoices+ currentVersionId={currentVersionId}+ disabled={disabled}+ onSelect={onSelect}+ versions={versions}+ />+ </div>+ {isLoading && <Loading type="app" />}+ {!isLoading && versionsError && versions.length === 0 && (+ <div className="flex h-full flex-col items-center justify-center px-2 py-6">+ <p role="alert" className="text-center system-xs-regular text-text-tertiary">+ {tCommon(($) => $.error)}+ </p>+ </div>+ )}+ {!isLoading && !versionsError && versions.length === 0 && (+ <div className="flex h-full flex-col items-center justify-center gap-2 px-2 py-6">+ <p className="text-center system-sm-regular text-text-tertiary">+ {t(($) => $['studio.accessPoint.noPublishedTitle'])}+ </p>+ {publishHref && (+ <Link+ href={publishHref}+ className={cn(buttonVariants({ size: 'medium' }), 'flex items-center gap-1')}+ >+ {t(($) => $['studio.accessPoint.goToPublish'])}+ <span aria-hidden className="i-ri-arrow-right-line size-4" />+ </Link>+ )}+ </div>+ )}+ {isFetchingNextPage && versions.length > 0 && <Loading className="h-8" />}+ <div ref={sentinelRef} aria-hidden className="h-px" />+ </ScrollAreaContent>+ </ScrollAreaViewport>+ <ScrollAreaScrollbar>+ <ScrollAreaThumb />+ </ScrollAreaScrollbar>+ </ScrollArea>+ )+}diff --git a/web/app/components/app/deploy/state.ts b/web/app/components/app/deploy/state.tsindex 114b73e8a31..e634cba9839 100644--- a/web/app/components/app/deploy/state.ts+++ b/web/app/components/app/deploy/state.ts@@ -1,12 +1,6 @@'use client'-import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { ReactNode } from 'react'-import {- DeploymentOperationStatus,- DeploymentOperationType,- DeploymentStatus,-} from '@dify/contracts/enterprise-app-deploy/types.gen'import { skipToken } from '@tanstack/react-query'import { atom } from 'jotai'import { atomWithInfiniteQuery, atomWithQuery } from 'jotai-tanstack-query'@@ -17,24 +11,41 @@ import {appWorkflowQueryOptions,appWorkflowVersionsInfiniteQueryOptions,} from '@/service/workflow-queries'-import { toDeploymentVersion } from './version'+import { hasDeploymentsRequiringPolling } from './utils/environment-deployment'+import { toDeploymentVersion } from './utils/version'-const DEPLOYMENT_STATUS_POLLING_INTERVAL = 3000+const ENVIRONMENT_DEPLOYMENT_POLLING_INTERVAL = 3000-type EnvironmentDeploymentActionKind =- | 'changeVersion'- | 'deployLatest'- | 'redeploy'- | 'retry'- | 'undeploy'+const appDeployAppIdAtom = atom<string | null>(null)+const defaultWorkflowVersionNameAtom = atom('')-export type EnvironmentDeploymentAction = {- disabled: boolean- kind: EnvironmentDeploymentActionKind+type DeploymentVersionSource = Parameters<typeof toDeploymentVersion>[0]+type DeploymentVersionCacheEntry = {+ defaultName: string+ latestWorkflowId?: string+ version: ReturnType<typeof toDeploymentVersion>}-const appDeployAppIdAtom = atom<string | null>(null)-const defaultWorkflowVersionNameAtom = atom('')+const deploymentVersionCache = new WeakMap<DeploymentVersionSource, DeploymentVersionCacheEntry>()++function toStableDeploymentVersion(+ source: DeploymentVersionSource,+ defaultName: string,+ latestWorkflowId?: string,+) {+ const cached = deploymentVersionCache.get(source)+ if (cached?.defaultName === defaultName && cached.latestWorkflowId === latestWorkflowId)+ return cached.version++ const version = toDeploymentVersion(source, defaultName, latestWorkflowId)+ deploymentVersionCache.set(source, {+ defaultName,+ latestWorkflowId,+ version,+ })++ return version+}export function AppDeployStateBoundary({appId,@@ -71,9 +82,24 @@ export const latestAppWorkflowVersionAtom = atom((get) => {const workflow = get(latestPublishedWorkflowAtom)if (!workflow) return- return toDeploymentVersion(workflow, get(defaultWorkflowVersionNameAtom), workflow.id)+ return toStableDeploymentVersion(workflow, get(defaultWorkflowVersionNameAtom), workflow.id)})+export const latestAppWorkflowVersionIsErrorAtom = selectAtom(+ latestPublishedWorkflowQueryAtom,+ (query) => query.isError,+)++export const latestAppWorkflowVersionIsRetryingAtom = selectAtom(+ latestPublishedWorkflowQueryAtom,+ (query) => query.isError && query.isFetching,+)++export const latestAppWorkflowVersionRefetchAtom = selectAtom(+ latestPublishedWorkflowQueryAtom,+ (query) => query.refetch,+)+const appWorkflowVersionsQueryAtom = atomWithInfiniteQuery((get) => {return appWorkflowVersionsInfiniteQueryOptions(get(appDeployAppIdAtom))})@@ -88,7 +114,7 @@ export const appWorkflowVersionsAtom = atom((get) => {return pages.flatMap((page) =>page.items.filter((workflow) => workflow.version !== 'draft')- .map((workflow) => toDeploymentVersion(workflow, defaultName, latestWorkflowId)),+ .map((workflow) => toStableDeploymentVersion(workflow, defaultName, latestWorkflowId)),)})@@ -138,6 +164,26 @@ const appEnvironmentsQueryAtom = atomWithQuery((get) => {const appEnvironmentsAtom = selectAtom(appEnvironmentsQueryAtom, (query) => query.data?.data)+export const appEnvironmentsIsErrorAtom = selectAtom(+ appEnvironmentsQueryAtom,+ (query) => query.isError,+)++export const appEnvironmentsIsLoadingAtom = selectAtom(+ appEnvironmentsQueryAtom,+ (query) => query.isLoading,+)++export const appEnvironmentsIsRetryingAtom = selectAtom(+ appEnvironmentsQueryAtom,+ (query) => query.isError && query.isFetching,+)++export const appEnvironmentsRefetchAtom = selectAtom(+ appEnvironmentsQueryAtom,+ (query) => query.refetch,+)+export const appEnvironmentUsageAtom = atom((get) => {const environments = get(appEnvironmentsAtom)if (!environments) return@@ -148,23 +194,10 @@ export const appEnvironmentUsageAtom = atom((get) => {}})-export const undeployedAppEnvironmentsAtom = atom(- (get) => get(appEnvironmentsAtom)?.filter((environment) => environment.in_use === false) ?? [],+export const undeployedAppEnvironmentsAtom = atom((get) =>+ get(appEnvironmentsAtom)?.filter((environment) => environment.in_use === false),)-export function isEnvironmentDeploymentInProgress(deployment?: EnvironmentDeployment) {- const status = deployment?.deployment?.status-- return (- status === DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING ||- status === DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYING- )-}--export function hasInProgressEnvironmentDeployments(deployments: EnvironmentDeployment[]) {- return deployments.some(isEnvironmentDeploymentInProgress)-}-const appEnvironmentDeploymentsQueryAtom = atomWithQuery((get) => {const appId = get(appDeployAppIdAtom)@@ -179,8 +212,8 @@ const appEnvironmentDeploymentsQueryAtom = atomWithQuery((get) => {: skipToken,refetchInterval: (query) => {const deployments = query.state.data?.environment_deployments ?? []- return hasInProgressEnvironmentDeployments(deployments)- ? DEPLOYMENT_STATUS_POLLING_INTERVAL+ return hasDeploymentsRequiringPolling(deployments)+ ? ENVIRONMENT_DEPLOYMENT_POLLING_INTERVAL: false},},@@ -202,67 +235,13 @@ export const appEnvironmentDeploymentsIsErrorAtom = selectAtom((query) => query.isError,)-export const appEnvironmentDeploymentsIsFetchingAtom = selectAtom(+export const appEnvironmentDeploymentsIsRetryingAtom = selectAtom(appEnvironmentDeploymentsQueryAtom,- (query) => query.isFetching,+ (query) =>+ query.isError && (query.data?.environment_deployments.length ?? 0) === 0 && query.isFetching,)export const appEnvironmentDeploymentsRefetchAtom = selectAtom(appEnvironmentDeploymentsQueryAtom,(query) => query.refetch,)--function deploymentActions(- kinds: EnvironmentDeploymentActionKind[],- disabled = false,-): EnvironmentDeploymentAction[] {- return kinds.map((kind) => ({ disabled, kind }))-}--function isLatestDeployOperationFailed(row: EnvironmentDeployment) {- const operation = row.deployment?.latest_operation-- return (- operation?.type === DeploymentOperationType.DEPLOYMENT_OPERATION_TYPE_DEPLOY &&- operation.status === DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_FAILED- )-}--export function getEnvironmentDeploymentActions(- row: EnvironmentDeployment,-): EnvironmentDeploymentAction[] {- const deployment = row.deployment- // Currently, this case may not be possible, but we still handle it to avoid potential errors in the future.- if (!deployment || deployment.status === DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYED) {- return deploymentActions(['deployLatest', 'changeVersion'])- }-- const hasCurrentVersion = Boolean(deployment.current_version)- const hasFailedDeploy =- deployment.status === DeploymentStatus.DEPLOYMENT_STATUS_FAILED ||- (deployment.status === DeploymentStatus.DEPLOYMENT_STATUS_RUNNING &&- isLatestDeployOperationFailed(row))-- if (hasFailedDeploy) {- return deploymentActions(- hasCurrentVersion ? ['retry', 'changeVersion', 'undeploy'] : ['retry', 'changeVersion'],- )- }-- if (- deployment.status === DeploymentStatus.DEPLOYMENT_STATUS_DEPLOYING ||- deployment.status === DeploymentStatus.DEPLOYMENT_STATUS_UNDEPLOYING- ) {- return deploymentActions(['changeVersion', 'redeploy', 'undeploy'], true)- }-- if (deployment.status === DeploymentStatus.DEPLOYMENT_STATUS_RUNNING) {- if ((deployment.versions_behind ?? 0) > 0) {- return deploymentActions(['deployLatest', 'changeVersion', 'redeploy', 'undeploy'])- }-- return deploymentActions(['changeVersion', 'redeploy', 'undeploy'])- }-- return deploymentActions(['redeploy', 'undeploy'])-}diff --git a/web/app/components/app/deploy/deployment-dialog/types.ts b/web/app/components/app/deploy/types.tssimilarity index 87%rename from web/app/components/app/deploy/deployment-dialog/types.tsrename to web/app/components/app/deploy/types.tsindex 87c36a34908..e60ec089656 100644--- a/web/app/components/app/deploy/deployment-dialog/types.ts+++ b/web/app/components/app/deploy/types.ts@@ -1,4 +1,4 @@-import type { DeploymentVersion } from '../version'+import type { DeploymentVersion } from './utils/version'type VersionSelectionRequest = {currentVersionId?: stringdiff --git a/web/app/components/app/deploy/access-point.ts b/web/app/components/app/deploy/utils/access-point.tssimilarity index 100%rename from web/app/components/app/deploy/access-point.tsrename to web/app/components/app/deploy/utils/access-point.tsdiff --git a/web/app/components/app/deploy/utils/environment-deployment.ts b/web/app/components/app/deploy/utils/environment-deployment.tsnew file mode 100644index 00000000000..f0a424c4885--- /dev/null+++ b/web/app/components/app/deploy/utils/environment-deployment.ts@@ -0,0 +1,119 @@+import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'+import {+ DeploymentOperationStatus,+ DeploymentOperationType,+ RuntimeState,+} from '@dify/contracts/enterprise-app-deploy/types.gen'++type EnvironmentDeploymentActionKind =+ | 'changeVersion'+ | 'deployLatest'+ | 'redeploy'+ | 'retry'+ | 'undeploy'++export type EnvironmentDeploymentAction = {+ disabled: boolean+ kind: EnvironmentDeploymentActionKind+}++function isDeploymentOperationInProgress(deployment?: EnvironmentDeployment) {+ return (+ deployment?.deployment?.latest_operation?.status ===+ DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_IN_PROGRESS+ )+}++export function shouldPollEnvironmentDeployment(deployment?: EnvironmentDeployment) {+ if (isDeploymentOperationInProgress(deployment)) return true++ const runtimeState = deployment?.deployment?.runtimeState+ return (+ runtimeState === RuntimeState.RUNTIME_STATE_STARTING ||+ runtimeState === RuntimeState.RUNTIME_STATE_STOPPING+ )+}++export function hasDeploymentsRequiringPolling(deployments: EnvironmentDeployment[]) {+ return deployments.some(shouldPollEnvironmentDeployment)+}++function deploymentActions(+ kinds: EnvironmentDeploymentActionKind[],+ disabled = false,+ deployLatestDisabled = false,+): EnvironmentDeploymentAction[] {+ return kinds.map((kind) => ({+ disabled: disabled || (kind === 'deployLatest' && deployLatestDisabled),+ kind,+ }))+}++function isLatestDeployOperationFailed(row: EnvironmentDeployment) {+ const operation = row.deployment?.latest_operation++ return (+ operation?.type === DeploymentOperationType.DEPLOYMENT_OPERATION_TYPE_DEPLOY &&+ operation.status === DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_FAILED+ )+}++export function getEnvironmentDeploymentActions(+ row: EnvironmentDeployment,+ { deployLatestDisabled = false }: { deployLatestDisabled?: boolean } = {},+): EnvironmentDeploymentAction[] {+ const deployment = row.deployment+ const actions = (kinds: EnvironmentDeploymentActionKind[], disabled = false) =>+ deploymentActions(kinds, disabled, deployLatestDisabled)++ if (!deployment) {+ return actions(['deployLatest', 'changeVersion'])+ }++ const hasCurrentVersion = Boolean(deployment.current_version)+ if (isDeploymentOperationInProgress(row)) {+ return actions(+ hasCurrentVersion+ ? ['changeVersion', 'redeploy', 'undeploy']+ : ['deployLatest', 'changeVersion'],+ true,+ )+ }++ if (isLatestDeployOperationFailed(row)) {+ const hasRetryVersion = Boolean(+ deployment.latest_operation?.target_version ?? deployment.current_version,+ )+ if (!hasRetryVersion) return actions(['changeVersion'])++ return actions(+ hasCurrentVersion ? ['retry', 'changeVersion', 'undeploy'] : ['retry', 'changeVersion'],+ )+ }++ if (deployment.runtimeState === RuntimeState.RUNTIME_STATE_UNDEPLOYED) {+ return actions(['deployLatest', 'changeVersion'])+ }++ if (deployment.runtimeState === RuntimeState.RUNTIME_STATE_RUNNING) {+ if ((deployment.versions_behind ?? 0) > 0) {+ return actions(['deployLatest', 'changeVersion', 'redeploy', 'undeploy'])+ }++ return actions(['changeVersion', 'redeploy', 'undeploy'])+ }++ if (+ deployment.runtimeState === RuntimeState.RUNTIME_STATE_STARTING ||+ deployment.runtimeState === RuntimeState.RUNTIME_STATE_STOPPING+ ) {+ return actions(+ hasCurrentVersion+ ? ['changeVersion', 'redeploy', 'undeploy']+ : ['deployLatest', 'changeVersion'],+ true,+ )+ }++ return hasCurrentVersion ? actions(['redeploy', 'undeploy']) : actions(['changeVersion'])+}diff --git a/web/app/components/app/deploy/version.ts b/web/app/components/app/deploy/utils/version.tssimilarity index 100%rename from web/app/components/app/deploy/version.tsrename to web/app/components/app/deploy/utils/version.tsdiff --git a/web/app/components/app/access-point/shared/access-point-card.tsx b/web/app/components/base/access-point/card.tsxsimilarity index 78%rename from web/app/components/app/access-point/shared/access-point-card.tsxrename to web/app/components/base/access-point/card.tsxindex be0450c6dde..fcc9e2f65a1 100644--- a/web/app/components/app/access-point/shared/access-point-card.tsx+++ b/web/app/components/base/access-point/card.tsx@@ -1,12 +1,12 @@'use client'import type { ReactNode } from 'react'-import type { AccessPointStatus } from './access-point-status'+import type { AccessPointStatus } from './status'import { cn } from '@langgenius/dify-ui/cn'import { StatusDot, StatusDotSkeleton } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useId } from 'react'-import { useTranslation } from 'react-i18next'type AccessPointCardProps = {actions?: ReactNode@@ -14,12 +14,15 @@ type AccessPointCardProps = {description: stringicon: ReactNode | stringstatus: AccessPointStatus+ statusLabel: stringtitle: stringclassName?: string+ headingLevel?: 2 | 3highlighted?: booleanonEnabledChange?: (enabled: boolean) => voidshowStatus?: booleanswitchDisabled?: boolean+ switchDisabledReason?: stringswitchLabel?: stringswitchLoading?: boolean}@@ -29,28 +32,39 @@ export function AccessPointCard({children,className,description,+ headingLevel = 2,highlighted = false,icon,onEnabledChange,showStatus = true,status,+ statusLabel,switchDisabled = false,+ switchDisabledReason,switchLabel,switchLoading = false,title,}: AccessPointCardProps) {- const { t } = useTranslation()const titleId = useId()const isEnabled = status === 'inService'const isLoading = status === 'loading'const showSwitch = (status === 'disabled' || status === 'inService') && Boolean(onEnabledChange)- const statusLabel: Record<AccessPointStatus, string> = {- disabled: t(($) => $['overview.status.disable'], { ns: 'appOverview' }),- inService: t(($) => $['agentDetail.access.status.inService'], { ns: 'agentV2' }),- loading: t(($) => $.loading, { ns: 'common' }),- unavailable: t(($) => $['health.ENVIRONMENT_STATUS_FAILED'], { ns: 'deployments' }),- unsupported: t(($) => $['studio.accessPoint.notSupported'], { ns: 'deployments' }),- }+ const hasSwitchDisabledReason = switchDisabled && Boolean(switchDisabledReason)+ const Heading = headingLevel === 3 ? 'h3' : 'h2'+ const switchControl = (+ <Switch+ checked={isEnabled}+ disabled={switchDisabled && !hasSwitchDisabledReason}+ loading={switchLoading}+ {...(hasSwitchDisabledReason+ ? { readOnly: true, 'aria-disabled': true, 'data-disabled': '' }+ : {})}+ aria-label={switchLabel || title}+ onCheckedChange={(enabled) => {+ if (!switchDisabled) onEnabledChange?.(enabled)+ }}+ />+ )return (<section@@ -72,9 +86,13 @@ export function AccessPointCard({icon)}<span className="min-w-0 flex-1">- <h2 id={titleId} className="truncate system-md-semibold text-text-primary" title={title}>+ <Heading+ id={titleId}+ className="truncate system-md-semibold text-text-primary"+ title={title}+ >{title}- </h2>+ </Heading><span className="block truncate system-xs-regular text-text-tertiary" title={description}>{description}</span>@@ -93,17 +111,17 @@ export function AccessPointCard({) : (<StatusDot status={status === 'inService' ? 'success' : 'disabled'} />)}- {statusLabel[status]}+ {statusLabel}</span>- {showSwitch && (- <Switch- checked={isEnabled}- disabled={switchDisabled}- loading={switchLoading}- aria-label={switchLabel || title}- onCheckedChange={onEnabledChange}- />- )}+ {showSwitch &&+ (hasSwitchDisabledReason ? (+ <Tooltip>+ <TooltipTrigger render={switchControl} />+ <TooltipContent role="tooltip">{switchDisabledReason}</TooltipContent>+ </Tooltip>+ ) : (+ switchControl+ ))}</>)}</header>diff --git a/web/app/components/app/access-point/shared/access-point-status.ts b/web/app/components/base/access-point/status.tssimilarity index 100%rename from web/app/components/app/access-point/shared/access-point-status.tsrename to web/app/components/base/access-point/status.tsdiff --git a/web/app/components/app/access-point/shared/access-point-url.tsx b/web/app/components/base/access-point/url.tsxsimilarity index 75%rename from web/app/components/app/access-point/shared/access-point-url.tsxrename to web/app/components/base/access-point/url.tsxindex cd90c57c111..678946d64bc 100644--- a/web/app/components/app/access-point/shared/access-point-url.tsx+++ b/web/app/components/base/access-point/url.tsx@@ -3,38 +3,53 @@import { Button, buttonVariants } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useTranslation } from 'react-i18next'import { CopyFeedback } from '@/app/components/base/copy-feedback'import ShareQRCode from '@/app/components/base/qrcode'-import { AccessPointEndpoint } from './access-point-card'+import { AccessPointEndpoint } from './card'type AccessPointUrlProps = {enabled: booleanlabel: stringunavailableLabel: stringvalue: string+ copiedLabel?: stringcopyDisabled?: boolean+ copyLabel?: stringloading?: booleanunavailable?: booleanshowOpen?: booleanshowQrCode?: booleanshowRegenerate?: booleanopenUrl?: string+ onCopyError?: () => voidonRegenerate?: () => void+ openDisabledReason?: stringopenLabel?: string+ qrCodeDownloadLabel?: string+ qrCodeLabel?: string+ qrCodeScanLabel?: stringregenerateLabel?: stringregenerateDisabled?: booleanregenerating?: boolean}export function AccessPointUrl({+ copiedLabel,+ copyDisabled = false,+ copyLabel,enabled,label,loading = false,- copyDisabled = false,+ onCopyError,onRegenerate,+ openDisabledReason,openLabel,openUrl,+ qrCodeDownloadLabel,+ qrCodeLabel,+ qrCodeScanLabel,regenerateDisabled = false,regenerateLabel,regenerating = false,@@ -47,6 +62,26 @@ export function AccessPointUrl({}: AccessPointUrlProps) {const { t } = useTranslation()const detailsAvailable = !loading && !unavailable+ const disabledOpenButton = (+ <Button+ variant="secondary"+ size="small"+ className="h-6 gap-1 px-1.5"+ disabled+ focusableWhenDisabled={Boolean(openDisabledReason)}+ >+ <span aria-hidden className="i-ri-external-link-line size-3.5" />+ {openLabel}+ </Button>+ )+ const disabledOpenAction = openDisabledReason ? (+ <Tooltip>+ <TooltipTrigger render={disabledOpenButton} />+ <TooltipContent role="tooltip">{openDisabledReason}</TooltipContent>+ </Tooltip>+ ) : (+ disabledOpenButton+ )const disabledActions = (<div className="flex items-center gap-0.5">@@ -82,7 +117,13 @@ export function AccessPointUrl({<span aria-hidden className="i-ri-file-copy-line size-4 text-text-disabled" /></div>) : (- <CopyFeedback content={value} className="size-6" />+ <CopyFeedback+ content={value}+ className="size-6"+ copyLabel={copyLabel}+ copiedLabel={copiedLabel}+ onCopyError={onCopyError}+ />)}{showQrCode &&(copyDisabled ? (@@ -90,7 +131,12 @@ export function AccessPointUrl({<span aria-hidden className="i-ri-qr-code-line size-4 text-text-disabled" /></div>) : (- <ShareQRCode content={value} />+ <ShareQRCode+ content={value}+ triggerLabel={qrCodeLabel}+ scanLabel={qrCodeScanLabel}+ downloadLabel={qrCodeDownloadLabel}+ />))}{showRegenerate && (<IconButton@@ -121,10 +167,7 @@ export function AccessPointUrl({{openLabel}</a>) : (- <Button variant="secondary" size="small" className="h-6 gap-1 px-1.5" disabled>- <span aria-hidden className="i-ri-external-link-line size-3.5" />- {openLabel}- </Button>+ disabledOpenAction)}</>)}diff --git a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsxindex 56d7a58ded6..12004cb7c28 100644--- a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx+++ b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx@@ -90,6 +90,7 @@ const createQueryClient = () =>defaultOptions: {queries: {retry: false,+ retryDelay: 0,},},})@@ -150,11 +151,13 @@ const setConversationIdInfo = (appId: string, conversationId: string) => {describe('useChatWithHistory', () => {beforeEach(() => {vi.clearAllMocks()+ window.history.replaceState({}, '', '/')localStorage.removeItem(CONVERSATION_ID_INFO)sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)localStorage.removeItem('webappSidebarCollapse')mockStoreState.appInfo = {app_id: 'app-1',+ end_user_id: 'user-1',custom_config: null,site: {title: 'Test App',@@ -297,6 +300,46 @@ describe('useChatWithHistory', () => {})expect(mockFetchChatList).toHaveBeenCalledTimes(1)})++ it('should clear a stale Environment selection when the server returns not found', async () => {+ window.history.replaceState({}, '', '/environment/workflow/environment-code')+ setConversationIdInfo('environment:environment-code', 'conversation-1')+ mockFetchConversations.mockResolvedValue(createConversationData())+ mockFetchChatList.mockRejectedValue(+ new Response(JSON.stringify({ reason: 'APPDEPLOY_CONVERSATION_NOT_FOUND' }), {+ status: 404,+ }),+ )++ const { result } = await renderWithClient(() => useChatWithHistory())++ await waitFor(() => {+ expect(mockFetchChatList).toHaveBeenCalledTimes(1)+ })+ await waitFor(() => {+ expect(result!.current.currentConversationId).toBe('')+ })+ expect(result!.current.clearChatList).toBe(true)+ const storedSelections = JSON.parse(localStorage.getItem(CONVERSATION_ID_INFO)!)+ expect(storedSelections['environment:environment-code']['user-1']).toBe('')+ })++ it('should keep the selected Environment conversation for other errors', async () => {+ window.history.replaceState({}, '', '/environment/workflow/environment-code')+ setConversationIdInfo('environment:environment-code', 'conversation-1')+ mockFetchConversations.mockResolvedValue(createConversationData())+ const response = new Response(JSON.stringify({ reason: 'OTHER_ERROR' }), { status: 404 })+ mockFetchChatList.mockRejectedValue(response)++ const { result } = await renderWithClient(() => useChatWithHistory())++ await waitFor(() => {+ expect(mockFetchChatList).toHaveBeenCalledTimes(1)+ })+ expect(result!.current.currentConversationId).toBe('conversation-1')+ expect(result!.current.clearChatList).toBe(false)+ expect(localStorage.getItem(CONVERSATION_ID_INFO)).toContain('conversation-1')+ })})// Scenario: the active conversation is tab-scoped while the last selection is cross-tab.@@ -349,6 +392,76 @@ describe('useChatWithHistory', () => {expect(mockFetchChatList).not.toHaveBeenCalled()})+ it('should isolate built-in and Environment conversations in the same browser', async () => {+ window.history.replaceState({}, '', '/environment/chat/environment-code')+ localStorage.setItem(+ CONVERSATION_ID_INFO,+ JSON.stringify({+ 'app-1': { 'user-1': 'built-in-conversation' },+ 'environment:environment-code': { 'user-1': 'environment-conversation' },+ }),+ )+ mockFetchConversations.mockResolvedValue(createConversationData())+ mockFetchChatList.mockResolvedValue({ data: [] })++ const { result } = await renderWithClient(() => useChatWithHistory())++ expect(result!.current.currentConversationId).toBe('environment-conversation')+ expect(mockFetchChatList).toHaveBeenCalledWith(+ 'environment-conversation',+ AppSourceType.webApp,+ 'app-1',+ )+ expect(mockFetchChatList).not.toHaveBeenCalledWith(+ 'built-in-conversation',+ AppSourceType.webApp,+ 'app-1',+ )+ })++ it('should select by the current EndUser after access mode changes', async () => {+ window.history.replaceState({}, '', '/environment/chat/environment-code')+ mockStoreState.appInfo = {+ ...mockStoreState.appInfo!,+ end_user_id: 'authenticated-end-user',+ }+ localStorage.setItem(+ CONVERSATION_ID_INFO,+ JSON.stringify({+ 'environment:environment-code': {+ 'anonymous-end-user': 'anonymous-conversation',+ 'authenticated-end-user': 'authenticated-conversation',+ },+ }),+ )+ mockFetchConversations.mockResolvedValue(createConversationData())+ mockFetchChatList.mockResolvedValue({ data: [] })++ const { result } = await renderWithClient(() => useChatWithHistory())++ expect(result!.current.currentConversationId).toBe('authenticated-conversation')+ expect(mockFetchChatList).not.toHaveBeenCalledWith(+ 'anonymous-conversation',+ AppSourceType.webApp,+ 'app-1',+ )+ })++ it('should not initialize WebApp selection before EndUser is known', async () => {+ mockStoreState.appInfo = { ...mockStoreState.appInfo!, end_user_id: undefined }+ localStorage.setItem(+ CONVERSATION_ID_INFO,+ JSON.stringify({ 'app-1': { DEFAULT: 'stale-conversation' } }),+ )+ mockFetchConversations.mockResolvedValue(createConversationData())+ mockFetchChatList.mockResolvedValue({ data: [] })++ const { result } = await renderWithClient(() => useChatWithHistory())++ expect(result!.current.currentConversationId).toBe('')+ expect(mockFetchChatList).not.toHaveBeenCalled()+ })+it('should ignore last conversation updates from another tab', async () => {// ArrangemockFetchConversations.mockResolvedValue(createConversationData())@@ -403,14 +516,8 @@ describe('useChatWithHistory', () => {const tabStoredValue = sessionStorage.getItem(TAB_CONVERSATION_ID_INFO)const tabConversationIdInfo = tabStoredValue ? JSON.parse(tabStoredValue) : {}- expect([- lastConversationIdInfo['app-1']?.['user-1'],- lastConversationIdInfo['app-1']?.DEFAULT,- ]).toContain('conversation-new')- expect([- tabConversationIdInfo['app-1']?.['user-1'],- tabConversationIdInfo['app-1']?.DEFAULT,- ]).toContain('conversation-new')+ expect(lastConversationIdInfo['app-1']?.['user-1']).toBe('conversation-new')+ expect(tabConversationIdInfo['app-1']?.['user-1']).toBe('conversation-new')})})})@@ -2131,7 +2238,7 @@ describe('useChatWithHistory', () => {expect(localStorage.getItem(CONVERSATION_ID_INFO)).toBe(original)})- it('should write conversation id under DEFAULT key when user id is missing', async () => {+ it('should use the site EndUser when the URL user id is missing', async () => {// Arrangeconst { getProcessedSystemVariablesFromUrlParams } = await import('../../utils')vi.mocked(getProcessedSystemVariablesFromUrlParams).mockResolvedValueOnce({@@ -2151,7 +2258,7 @@ describe('useChatWithHistory', () => {await waitFor(() => {const stored = localStorage.getItem(CONVERSATION_ID_INFO)const parsed = stored ? JSON.parse(stored) : {}- expect(parsed['app-1']?.DEFAULT).toBe('conversation-default-user')+ expect(parsed['app-1']?.['user-1']).toBe('conversation-default-user')})})})diff --git a/web/app/components/base/chat/chat-with-history/hooks.tsx b/web/app/components/base/chat/chat-with-history/hooks.tsxindex e3bdb0374b2..cea9d1b77aa 100644--- a/web/app/components/base/chat/chat-with-history/hooks.tsx+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx@@ -26,11 +26,13 @@ import {updateFeedback,} from '@/service/share'import {+ EnvironmentConversationNotFoundError,useInvalidateShareConversations,useShareChatList,useShareConversationName,useShareConversations,} from '@/service/use-share'+import { getWebAppConversationScopeId, resolveWebAppAddress } from '@/service/webapp-address'import { TransferMethod } from '@/types/app'import { addFileInfos, sortAgentSorts } from '../../../tools/utils'import { enrichSubmittedHumanInputFormData } from '../chat/answer/human-input-content/submitted-utils'@@ -164,6 +166,7 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {return appInfo}, [isInstalledApp, installedAppInfo, appInfo])const appId = useMemo(() => appData?.app_id, [appData])+ const conversationScopeId = getWebAppConversationScopeId(resolveWebAppAddress(), appId)const [userId, setUserId] = useState<string>()useEffect(() => {getProcessedSystemVariablesFromUrlParams().then(({ user_id }) => {@@ -186,8 +189,8 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {[appId, setStoredSidebarCollapseState],)const { currentConversationId, handleConversationIdInfoChange } = useConversationSelection({- appId,- userId,+ scopeId: isInstalledApp || appData?.end_user_id ? conversationScopeId : '',+ userId: isInstalledApp ? userId : appData?.end_user_id,})const [newConversationId, setNewConversationId] = useState('')const chatShouldReloadKey = useMemo(() => {@@ -221,7 +224,11 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {refetchOnReconnect: false,},)- const { data: appChatListData, isLoading: appChatListDataLoading } = useShareChatList(+ const {+ data: appChatListData,+ error: appChatListError,+ isLoading: appChatListDataLoading,+ } = useShareChatList({conversationId: chatShouldReloadKey,appSourceType,@@ -236,6 +243,15 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {const invalidateShareConversations = useInvalidateShareConversations()const [clearChatList, setClearChatList] = useState(false)const [isResponding, setIsResponding] = useState(false)+ useEffect(() => {+ if (!(appChatListError instanceof EnvironmentConversationNotFoundError)) return++ // oxlint-disable-next-line eslint-react/set-state-in-effect -- A missing Environment conversation resets the active conversation.+ setNewConversationId('')+ handleConversationIdInfoChange('')+ // oxlint-disable-next-line eslint-react/set-state-in-effect -- A missing Environment conversation must clear the rendered chat.+ setClearChatList(true)+ }, [appChatListError, handleConversationIdInfoChange])const appPrevChatTree = useMemo(() =>currentConversationId && appChatListData?.data.lengthdiff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsxindex 0f022253500..7bed22ea171 100644--- a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx@@ -165,6 +165,7 @@ describe('useEmbeddedChatbot', () => {sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)mockStoreState.appInfo = {app_id: 'app-1',+ end_user_id: 'user-1',custom_config: null,site: {title: 'Test App',@@ -396,14 +397,8 @@ describe('useEmbeddedChatbot', () => {const tabStoredValue = sessionStorage.getItem(TAB_CONVERSATION_ID_INFO)const tabConversationIdInfo = tabStoredValue ? JSON.parse(tabStoredValue) : {}- expect([- lastConversationIdInfo['app-1']?.['embedded-user-1'],- lastConversationIdInfo['app-1']?.DEFAULT,- ]).toContain('conversation-new')- expect([- tabConversationIdInfo['app-1']?.['embedded-user-1'],- tabConversationIdInfo['app-1']?.DEFAULT,- ]).toContain('conversation-new')+ expect(lastConversationIdInfo['app-1']?.['user-1']).toBe('conversation-new')+ expect(tabConversationIdInfo['app-1']?.['user-1']).toBe('conversation-new')})})})@@ -452,7 +447,7 @@ describe('useEmbeddedChatbot', () => {const { result } = await renderWithClient(() => useEmbeddedChatbot(AppSourceType.webApp))act(() => {- result.current.removeConversationIdInfo('app-1')+ result.current.removeConversationIdInfo()})await waitFor(() => {@@ -656,7 +651,7 @@ describe('useEmbeddedChatbot', () => {localStorage.setItem(CONVERSATION_ID_INFO,JSON.stringify({- 'app-1': { DEFAULT: 'stored-conv-id' },+ 'app-1': { 'user-1': 'stored-conv-id' },}),)mockStoreState.embeddedConversationId = null@@ -697,17 +692,13 @@ describe('useEmbeddedChatbot', () => {describe('Language settings', () => {it('should set language from URL parameters', async () => {- const originalSearch = window.location.search- Object.defineProperty(window, 'location', {- writable: true,- value: { search: '?locale=zh-Hans' },- })+ window.history.replaceState({}, '', '/?locale=zh-Hans')const { changeLanguage } = await import('@/i18n-config/client')await renderWithClient(() => useEmbeddedChatbot(AppSourceType.webApp))expect(changeLanguage).toHaveBeenCalledWith('zh-Hans')- Object.defineProperty(window, 'location', { value: { search: originalSearch } })+ window.history.replaceState({}, '', '/')})it('should set language from system variables when URL param is missing', async () => {@@ -780,14 +771,11 @@ describe('useEmbeddedChatbot', () => {await waitFor(() => {const stored = JSON.parse(localStorage.getItem(CONVERSATION_ID_INFO) || '{}')const appEntry = stored['app-1']- // userId may be 'embedded-user-1' or 'DEFAULT' depending on timing; either is valid- const storedId = appEntry?.['embedded-user-1'] ?? appEntry?.DEFAULT- expect(storedId).toBe('new-conv-id')+ expect(appEntry?.['user-1']).toBe('new-conv-id')})})- it('should use DEFAULT when userId is null', async () => {- // Override userId to be null/empty to exercise the "|| 'DEFAULT'" fallback path+ it('should use the site EndUser when embeddedUserId is null', async () => {mockStoreState.embeddedUserId = nullconst { result } = await renderWithClient(() => useEmbeddedChatbot(AppSourceType.webApp))@@ -798,8 +786,7 @@ describe('useEmbeddedChatbot', () => {await waitFor(() => {const stored = JSON.parse(localStorage.getItem(CONVERSATION_ID_INFO) || '{}')const appEntry = stored['app-1']- // Should use DEFAULT key since userId is null- expect(appEntry?.DEFAULT).toBe('default-conv-id')+ expect(appEntry?.['user-1']).toBe('default-conv-id')})})})@@ -939,7 +926,7 @@ describe('useEmbeddedChatbot', () => {// Ensure a currentConversationId is set so appChatListData is fetchedlocalStorage.setItem(CONVERSATION_ID_INFO,- JSON.stringify({ 'app-1': { DEFAULT: 'conversation-1' } }),+ JSON.stringify({ 'app-1': { 'user-1': 'conversation-1' } }),)mockFetchConversations.mockResolvedValue(createConversationData({ data: [createConversationItem({ id: 'conversation-1' })] }),@@ -981,7 +968,7 @@ describe('useEmbeddedChatbot', () => {mockFetchChatList.mockResolvedValue({ data: [] })localStorage.setItem(CONVERSATION_ID_INFO,- JSON.stringify({ 'app-1': { DEFAULT: 'pinned-conv' } }),+ JSON.stringify({ 'app-1': { 'user-1': 'pinned-conv' } }),)const { result } = await renderWithClient(() => useEmbeddedChatbot(AppSourceType.webApp))@@ -1029,7 +1016,7 @@ describe('useEmbeddedChatbot', () => {describe('currentConversationLatestInputs', () => {it('should return inputs from latest chat message when conversation has data', async () => {const convId = 'conversation-with-inputs'- localStorage.setItem(CONVERSATION_ID_INFO, JSON.stringify({ 'app-1': { DEFAULT: convId } }))+ localStorage.setItem(CONVERSATION_ID_INFO, JSON.stringify({ 'app-1': { 'user-1': convId } }))mockFetchConversations.mockResolvedValue(createConversationData({ data: [createConversationItem({ id: convId })] }),)diff --git a/web/app/components/base/chat/embedded-chatbot/hooks.tsx b/web/app/components/base/chat/embedded-chatbot/hooks.tsxindex 0c7950f562c..6f5a3a32fda 100644--- a/web/app/components/base/chat/embedded-chatbot/hooks.tsx+++ b/web/app/components/base/chat/embedded-chatbot/hooks.tsx@@ -21,6 +21,7 @@ import {useShareConversations,} from '@/service/use-share'import { useGetTryAppInfo, useGetTryAppParams } from '@/service/use-try-app'+import { getWebAppConversationScopeId, resolveWebAppAddress } from '@/service/webapp-address'import { TransferMethod } from '@/types/app'import { getProcessedFilesFromResponse } from '../../file-uploader/utils'import {@@ -119,8 +120,14 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: strisetLanguageFromParams()}, [appInfo])const allowResetChat = !conversationId+ const conversationScopeId = getWebAppConversationScopeId(resolveWebAppAddress(), appId)+ const endUserId = (appInfo as AppData | undefined)?.end_user_idconst { currentConversationId, handleConversationIdInfoChange, removeConversationIdInfo } =- useConversationSelection({ appId, userId, conversationId })+ useConversationSelection({+ scopeId: isTryApp || endUserId ? conversationScopeId : '',+ userId: isTryApp ? userId : endUserId,+ conversationId,+ })const [newConversationId, setNewConversationId] = useState('')const chatShouldReloadKey = useMemo(() => {if (currentConversationId === newConversationId) return ''diff --git a/web/app/components/base/chat/storage.ts b/web/app/components/base/chat/storage.tsindex ea7e65733da..de29c80c413 100644--- a/web/app/components/base/chat/storage.ts+++ b/web/app/components/base/chat/storage.ts@@ -17,117 +17,120 @@ const [_useSetWebAppSidebarCollapseState,] = createLocalStorageState<string>('webappSidebarCollapse', undefined, { raw: true })-const getAppConversationIds = (conversationIdInfo: ConversationIdInfo | null, appId: string) => {- const appConversationIds = conversationIdInfo?.[appId]- return typeof appConversationIds === 'object' && appConversationIds !== null- ? appConversationIds+const getScopeConversationIds = (+ conversationIdInfo: ConversationIdInfo | null,+ scopeId: string,+) => {+ const scopeConversationIds = conversationIdInfo?.[scopeId]+ return typeof scopeConversationIds === 'object' && scopeConversationIds !== null+ ? scopeConversationIds: undefined}const hasConversationId = (conversationIdInfo: ConversationIdInfo | null,- appId: string,+ scopeId: string,userId: string,-) => Object.hasOwn(getAppConversationIds(conversationIdInfo, appId) ?? {}, userId)+) => Object.hasOwn(getScopeConversationIds(conversationIdInfo, scopeId) ?? {}, userId)const getConversationId = (conversationIdInfo: ConversationIdInfo | null,- appId: string,+ scopeId: string,userId: string,-) => getAppConversationIds(conversationIdInfo, appId)?.[userId] ?? ''+) => getScopeConversationIds(conversationIdInfo, scopeId)?.[userId] ?? ''const setConversationId = (conversationIdInfo: ConversationIdInfo | null,- appId: string,+ scopeId: string,userId: string,conversationId: string,): ConversationIdInfo => ({...(conversationIdInfo ?? {}),- [appId]: {- ...getAppConversationIds(conversationIdInfo, appId),+ [scopeId]: {+ ...getScopeConversationIds(conversationIdInfo, scopeId),[userId]: conversationId,},})-const removeAppConversationIds = (+const removeScopeConversationIds = (conversationIdInfo: ConversationIdInfo | null,- appId: string,+ scopeId: string,): ConversationIdInfo => {const nextConversationIdInfo = { ...(conversationIdInfo ?? {}) }- delete nextConversationIdInfo[appId]+ delete nextConversationIdInfo[scopeId]return nextConversationIdInfo}type UseConversationSelectionOptions = {- appId?: string+ scopeId?: stringuserId?: stringconversationId?: string}const useConversationSelection = ({- appId,+ scopeId,userId,conversationId,}: UseConversationSelectionOptions) => {const [lastConversationIdInfo, setLastConversationIdInfo] = useLastConversationIdInfo()const [tabConversationIdInfo, setTabConversationIdInfo] = useTabConversationIdInfo()- const storageAppId = appId ?? ''+ const storageScopeId = scopeId ?? ''const storageUserId = userId || 'DEFAULT'const hasTabConversationId =- !!appId && hasConversationId(tabConversationIdInfo, storageAppId, storageUserId)- const lastConversationId = appId- ? getConversationId(lastConversationIdInfo, storageAppId, storageUserId)+ !!scopeId && hasConversationId(tabConversationIdInfo, storageScopeId, storageUserId)+ const lastConversationId = scopeId+ ? getConversationId(lastConversationIdInfo, storageScopeId, storageUserId): ''- const tabConversationId = appId- ? getConversationId(tabConversationIdInfo, storageAppId, storageUserId)+ const tabConversationId = scopeId+ ? getConversationId(tabConversationIdInfo, storageScopeId, storageUserId): ''// Seed this tab once from the cross-tab last selection. Later localStorage updates can change// the fallback without changing the active conversation already owned by this tab.useEffect(() => {- if (!appId || hasTabConversationId) return+ if (!scopeId || hasTabConversationId) returnsetTabConversationIdInfo((currentConversationIdInfo) => {- if (hasConversationId(currentConversationIdInfo, appId, storageUserId))+ if (hasConversationId(currentConversationIdInfo, scopeId, storageUserId))return currentConversationIdInfo- return setConversationId(currentConversationIdInfo, appId, storageUserId, lastConversationId)+ return setConversationId(+ currentConversationIdInfo,+ scopeId,+ storageUserId,+ lastConversationId,+ )})- }, [appId, hasTabConversationId, lastConversationId, setTabConversationIdInfo, storageUserId])+ }, [scopeId, hasTabConversationId, lastConversationId, setTabConversationIdInfo, storageUserId])const handleConversationIdInfoChange = useCallback((nextConversationId: string) => {- if (!appId) return+ if (!scopeId) returnsetTabConversationIdInfo((currentConversationIdInfo) =>- setConversationId(currentConversationIdInfo, appId, storageUserId, nextConversationId),+ setConversationId(currentConversationIdInfo, scopeId, storageUserId, nextConversationId),)setLastConversationIdInfo((currentConversationIdInfo) =>- setConversationId(currentConversationIdInfo, appId, storageUserId, nextConversationId),+ setConversationId(currentConversationIdInfo, scopeId, storageUserId, nextConversationId),)},- [appId, setLastConversationIdInfo, setTabConversationIdInfo, storageUserId],+ [scopeId, setLastConversationIdInfo, setTabConversationIdInfo, storageUserId],)- const removeConversationIdInfo = useCallback(- (targetAppId: string) => {- setTabConversationIdInfo((currentConversationIdInfo) => {- const nextConversationIdInfo = removeAppConversationIds(- currentConversationIdInfo,- targetAppId,- )- if (targetAppId !== appId) return nextConversationIdInfo-- // An explicit empty entry keeps this tab on New Chat instead of falling back to a last- // conversation that another tab may write after the reset.- return setConversationId(nextConversationIdInfo, targetAppId, storageUserId, '')- })- setLastConversationIdInfo((currentConversationIdInfo) =>- removeAppConversationIds(currentConversationIdInfo, targetAppId),- )- },- [appId, setLastConversationIdInfo, setTabConversationIdInfo, storageUserId],- )+ const removeConversationIdInfo = useCallback(() => {+ if (!scopeId) return++ setTabConversationIdInfo((currentConversationIdInfo) => {+ const nextConversationIdInfo = removeScopeConversationIds(currentConversationIdInfo, scopeId)++ // An explicit empty entry keeps this tab on New Chat instead of falling back to a last+ // conversation that another tab may write after the reset.+ return setConversationId(nextConversationIdInfo, scopeId, storageUserId, '')+ })+ setLastConversationIdInfo((currentConversationIdInfo) =>+ removeScopeConversationIds(currentConversationIdInfo, scopeId),+ )+ }, [scopeId, setLastConversationIdInfo, setTabConversationIdInfo, storageUserId])return {currentConversationId:diff --git a/web/app/components/base/copy-feedback/index.tsx b/web/app/components/base/copy-feedback/index.tsxindex 8cbda5df6a4..66b7062f456 100644--- a/web/app/components/base/copy-feedback/index.tsx+++ b/web/app/components/base/copy-feedback/index.tsx@@ -9,20 +9,29 @@ import { useTranslation } from 'react-i18next'type CopyFeedbackProps = Readonly<{content: stringclassName?: string+ copiedLabel?: string+ copyLabel?: string+ onCopyError?: () => void}>const prefixEmbedded = 'overview.appInfo.embedded'-export function CopyFeedback({ content, className }: CopyFeedbackProps) {+export function CopyFeedback({+ content,+ className,+ copiedLabel,+ copyLabel,+ onCopyError,+}: CopyFeedbackProps) {const { t } = useTranslation()// Rely on useClipboard's own timer to flip `copied` back to false so the// "Copied" tooltip stays visible long enough to be read, matching the// KeyValueItem pattern. Do NOT reset on mouse leave.- const { copied, copy } = useClipboard({ timeout: 2000 })+ const { copied, copy } = useClipboard({ timeout: 2000, onCopyError })const tooltipText = copied- ? t(($) => $[`${prefixEmbedded}.copied`], { ns: 'appOverview' })- : t(($) => $[`${prefixEmbedded}.copy`], { ns: 'appOverview' })+ ? (copiedLabel ?? t(($) => $[`${prefixEmbedded}.copied`], { ns: 'appOverview' }))+ : (copyLabel ?? t(($) => $[`${prefixEmbedded}.copy`], { ns: 'appOverview' }))/* v8 ignore next -- i18n test mock always returns a non-empty string; runtime fallback is defensive. -- @preserve */const safeText = tooltipText || ''diff --git a/web/app/components/base/qrcode/__tests__/index.spec.tsx b/web/app/components/base/qrcode/__tests__/index.spec.tsxindex ca20ec627b7..7c3441f5033 100644--- a/web/app/components/base/qrcode/__tests__/index.spec.tsx+++ b/web/app/components/base/qrcode/__tests__/index.spec.tsx@@ -14,6 +14,23 @@ describe('ShareQRCode', () => {vi.clearAllMocks()})+ it('uses caller-provided labels instead of App-specific defaults', async () => {+ const user = userEvent.setup()+ render(+ <ShareQRCode+ content={content}+ triggerLabel="Show QR code"+ scanLabel="Scan to share"+ downloadLabel="Download QR code"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Show QR code' }))++ expect(screen.getByText('Scan to share')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Download QR code' })).toBeInTheDocument()+ })+describe('Rendering', () => {it('renders correctly', () => {render(<ShareQRCode content={content} />)diff --git a/web/app/components/base/qrcode/index.tsx b/web/app/components/base/qrcode/index.tsxindex 0772420a335..ad5227a6c9f 100644--- a/web/app/components/base/qrcode/index.tsx+++ b/web/app/components/base/qrcode/index.tsx@@ -9,11 +9,14 @@ import { downloadUrl } from '@/utils/download'type Props = Readonly<{content: string+ downloadLabel?: string+ scanLabel?: string+ triggerLabel?: string}>const prefixEmbedded = 'overview.appInfo.qrcode.title'-const ShareQRCode = ({ content }: Props) => {+const ShareQRCode = ({ content, downloadLabel, scanLabel, triggerLabel }: Props) => {const { t } = useTranslation()const [isShow, setIsShow] = useState<boolean>(false)const qrCodeRef = useRef<HTMLDivElement>(null)@@ -42,10 +45,11 @@ const ShareQRCode = ({ content }: Props) => {downloadUrl({ url: canvas.toDataURL(), fileName: 'qrcode.png' })}- const tooltipText = t(($) => $[`${prefixEmbedded}`], { ns: 'appOverview' })+ const tooltipText = triggerLabel ?? t(($) => $[`${prefixEmbedded}`], { ns: 'appOverview' })/* v8 ignore next -- react-i18next returns a non-empty key/string in configured runtime; empty fallback protects against missing i18n payloads. @preserve */const safeTooltipText = tooltipText || ''- const downloadText = t(($) => $['overview.appInfo.qrcode.download'], { ns: 'appOverview' })+ const downloadText =+ downloadLabel ?? t(($) => $['overview.appInfo.qrcode.download'], { ns: 'appOverview' })return (<Tooltip>@@ -64,6 +68,12 @@ const ShareQRCode = ({ content }: Props) => {><QRCode size={160} value={content} className="mb-2" /><div className="flex items-center system-xs-regular">+ {scanLabel ? (+ <>+ <div className="text-text-tertiary">{scanLabel}</div>+ <div className="text-text-tertiary">·</div>+ </>+ ) : null}<buttontype="button"className="cursor-pointer border-none bg-transparent p-0 text-left text-text-accent-secondary focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"diff --git a/web/app/components/explore/try-app/app/__tests__/chat.spec.tsx b/web/app/components/explore/try-app/app/__tests__/chat.spec.tsxindex d8a6ad7511b..9c7935885a4 100644--- a/web/app/components/explore/try-app/app/__tests__/chat.spec.tsx+++ b/web/app/components/explore/try-app/app/__tests__/chat.spec.tsx@@ -154,7 +154,7 @@ describe('TryApp (chat.tsx)', () => {fireEvent.click(screen.getByRole('button', { name: 'share.chat.resetChat' }))- expect(mockRemoveConversationIdInfo).toHaveBeenCalledWith('test-app-id')+ expect(mockRemoveConversationIdInfo).toHaveBeenCalledWith()expect(mockHandleNewConversation).toHaveBeenCalled()})})@@ -238,7 +238,7 @@ describe('TryApp (chat.tsx)', () => {render(<TryApp appId="my-app-id" appDetail={appDetail} className="test-class" />)- expect(mockRemoveConversationIdInfo).toHaveBeenCalledWith('my-app-id')+ expect(mockRemoveConversationIdInfo).toHaveBeenCalledWith()})})})diff --git a/web/app/components/explore/try-app/app/chat.tsx b/web/app/components/explore/try-app/app/chat.tsxindex ca1dafc50bc..b5e84b0946d 100644--- a/web/app/components/explore/try-app/app/chat.tsx+++ b/web/app/components/explore/try-app/app/chat.tsx@@ -38,12 +38,12 @@ const TryApp: FC<Props> = ({ appId, appDetail, className }) => {const currentConversationId = chatData.currentConversationIdconst inputsForms = chatData.inputsFormsuseEffect(() => {- if (appId) removeConversationIdInfo(appId)- }, [appId])+ if (appId) removeConversationIdInfo()+ }, [appId, removeConversationIdInfo])const [isHideTryNotice, { setTrue: hideTryNotice }] = useBoolean(false)const handleNewConversation = () => {- removeConversationIdInfo(appId)+ removeConversationIdInfo()chatData.handleNewConversation()}return (diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsxindex a79bd03ba1d..560c5e5c255 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx@@ -27,6 +27,7 @@ import { getSupportedPresetConfig } from './presets-parameter-utils'export type ModelParameterModalProps = Pick<PopoverContentProps, 'placement'> & {trigger?: ReactElement<ComponentPropsWithRef<'button'>>+ triggerContainerClassName?: stringpopupClassName?: stringmodelSelectorPopupClassName?: stringisAdvancedMode: boolean@@ -58,6 +59,7 @@ export type ModelParameterModalProps = Pick<PopoverContentProps, 'placement'> &const ModelParameterModal: FC<ModelParameterModalProps> = ({trigger,+ triggerContainerClassName,popupClassName,modelSelectorPopupClassName,placement,@@ -156,7 +158,12 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({{trigger ? (<PopoverTrigger render={trigger} />) : (- <div className="isolate flex h-8 min-w-74 items-center gap-px rounded-lg">+ <div+ className={cn(+ 'isolate flex h-8 min-w-74 items-center gap-px rounded-lg',+ triggerContainerClassName,+ )}+ ><SplitModelSelectorvalue={hasSelectedModel ? { provider, model: modelId } : undefined}models={selectableModelList}diff --git a/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsx b/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsxindex 99e90b25c81..6f6ce929618 100644--- a/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsx+++ b/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsx@@ -6,9 +6,6 @@ import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import MCPServerModal from '../mcp-server-modal'-const mockGetSocket = vi.hoisted(() => vi.fn())-const mockSocketEmit = vi.hoisted(() => vi.fn())-// Mock the servicesvi.mock('@/service/use-tools', () => ({useCreateMCPServer: () => ({@@ -22,12 +19,6 @@ vi.mock('@/service/use-tools', () => ({useInvalidateMCPServerDetail: () => vi.fn(),}))-vi.mock('@/app/components/workflow/collaboration/core/websocket-manager', () => ({- webSocketClient: {- getSocket: mockGetSocket,- },-}))-describe('MCPServerModal', () => {const createWrapper = () => {const queryClient = new QueryClient({@@ -49,7 +40,6 @@ describe('MCPServerModal', () => {beforeEach(() => {vi.clearAllMocks()- mockGetSocket.mockReturnValue(null)})describe('Rendering', () => {@@ -378,31 +368,6 @@ describe('MCPServerModal', () => {})})- it('should emit a created update when socket exists', async () => {- const onHide = vi.fn()- mockGetSocket.mockReturnValue({ emit: mockSocketEmit })-- render(<MCPServerModal {...defaultProps} onHide={onHide} />, { wrapper: createWrapper() })-- fireEvent.change(- screen.getByPlaceholderText('tools.mcp.server.modal.descriptionPlaceholder'),- {- target: { value: 'Test description' },- },- )- fireEvent.click(screen.getByText('tools.mcp.server.modal.confirm'))-- await waitFor(() => {- expect(mockSocketEmit).toHaveBeenCalledWith(- 'collaboration_event',- expect.objectContaining({- type: 'mcp_server_update',- data: expect.objectContaining({ action: 'created' }),- }),- )- })- })-it('should handle empty description submission', async () => {const onHide = vi.fn()render(<MCPServerModal {...defaultProps} onHide={onHide} />, { wrapper: createWrapper() })diff --git a/web/app/components/tools/mcp/mcp-server-modal.tsx b/web/app/components/tools/mcp/mcp-server-modal.tsxindex cc9b71e6fc3..617df8aff77 100644--- a/web/app/components/tools/mcp/mcp-server-modal.tsx+++ b/web/app/components/tools/mcp/mcp-server-modal.tsx@@ -8,7 +8,6 @@ import * as React from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import MCPServerParamItem from '@/app/components/tools/mcp/mcp-server-param-item'-import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'import {useCreateMCPServer,useInvalidateMCPServerDetail,@@ -60,21 +59,6 @@ const MCPServerModal = ({ appID, latestParams = [], data, show, onHide, appInforeturn res}- const emitMcpServerUpdate = (action: 'created' | 'updated') => {- const socket = webSocketClient.getSocket(appID)- if (!socket) return-- const timestamp = Date.now()- socket.emit('collaboration_event', {- type: 'mcp_server_update',- data: {- action,- timestamp,- },- timestamp,- })- }-const submit = async () => {if (!data) {const payload: {@@ -90,7 +74,6 @@ const MCPServerModal = ({ appID, latestParams = [], data, show, onHide, appInfoawait createMCPServer(payload)invalidateMCPServerDetail(appID)- emitMcpServerUpdate('created')onHide()} else {const payload: {@@ -107,7 +90,6 @@ const MCPServerModal = ({ appID, latestParams = [], data, show, onHide, appInfoawait updateMCPServer(payload)invalidateMCPServerDetail(appID)- emitMcpServerUpdate('updated')onHide()}}diff --git a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsxindex 61d1712e409..c6253bf8706 100644--- a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx+++ b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx@@ -2,11 +2,13 @@ import type { ReactNode } from 'react'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'+import { AppModeEnum } from '@/types/app'import WorkflowPanel from '../workflow-panel'type AppStoreState = {appDetail?: {id?: string+ mode?: AppModeEnumworkflow?: {id?: string}@@ -55,6 +57,7 @@ vi.mock('@/app/components/workflow/panel', () => ({restoreVersionUrl: (versionId: string) => stringupdateVersionUrl: (versionId: string) => stringlatestVersionId?: string+ appMode?: AppModeEnum}}) => (<div@@ -64,6 +67,7 @@ vi.mock('@/app/components/workflow/panel', () => ({data-restore-version-url={versionHistoryPanelProps?.restoreVersionUrl('version-1') ?? ''}data-update-version-url={versionHistoryPanelProps?.updateVersionUrl('version-1') ?? ''}data-latest-version-id={versionHistoryPanelProps?.latestVersionId ?? ''}+ data-app-mode={versionHistoryPanelProps?.appMode ?? ''}><div data-testid="panel-left">{components?.left}</div><div data-testid="panel-right">{components?.right}</div>@@ -140,6 +144,7 @@ describe('WorkflowPanel', () => {appStoreState = {appDetail: {id: 'app-123',+ mode: AppModeEnum.WORKFLOW,workflow: {id: 'workflow-version-id',},@@ -171,6 +176,7 @@ describe('WorkflowPanel', () => {)expect(panel).toHaveAttribute('data-update-version-url', '/apps/app-123/workflows/version-1')expect(panel).toHaveAttribute('data-latest-version-id', 'workflow-version-id')+ expect(panel).toHaveAttribute('data-app-mode', AppModeEnum.WORKFLOW)})it('should render and close the message log modal from the left panel slot', async () => {diff --git a/web/app/components/workflow-app/components/workflow-panel.tsx b/web/app/components/workflow-app/components/workflow-panel.tsxindex 2636a24a87b..6bc8daf0783 100644--- a/web/app/components/workflow-app/components/workflow-panel.tsx+++ b/web/app/components/workflow-app/components/workflow-panel.tsx@@ -94,13 +94,14 @@ const WorkflowPanel = () => {const versionHistoryPanelProps = useMemo(() => {const appId = appDetail?.idreturn {+ appMode: appDetail?.mode,getVersionListUrl: `/apps/${appId}/workflows`,deleteVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}`,restoreVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}/restore`,updateVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}`,latestVersionId: appDetail?.workflow?.id,}- }, [appDetail?.id, appDetail?.workflow?.id])+ }, [appDetail?.id, appDetail?.mode, appDetail?.workflow?.id])const panelProps: PanelProps = useMemo(() => {return {diff --git a/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.socket-and-subscriptions.spec.ts b/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.socket-and-subscriptions.spec.tsindex 7ae9f4fa7d5..078d8646e0f 100644--- a/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.socket-and-subscriptions.spec.ts+++ b/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.socket-and-subscriptions.spec.ts@@ -501,10 +501,8 @@ describe('CollaborationManager socket and subscription behavior', () => {internals.setupSocketEventListeners(socket as unknown as Socket)const varsFeatureHandler = vi.fn()- const appStateHandler = vi.fn()const appMetaHandler = vi.fn()const appPublishHandler = vi.fn()- const mcpHandler = vi.fn()const workflowUpdateHandler = vi.fn()const commentsHandler = vi.fn()const restoreIntentHandler = vi.fn()@@ -515,10 +513,8 @@ describe('CollaborationManager socket and subscription behavior', () => {let latestCursors: Record<string, unknown> | null = nullmanager.onVarsAndFeaturesUpdate(varsFeatureHandler)- manager.onAppStateUpdate(appStateHandler)manager.onAppMetaUpdate(appMetaHandler)manager.onAppPublishUpdate(appPublishHandler)- manager.onMcpServerUpdate(mcpHandler)manager.onWorkflowUpdate(workflowUpdateHandler)manager.onCommentsUpdate(commentsHandler)manager.onRestoreIntent(restoreIntentHandler)@@ -547,11 +543,6 @@ describe('CollaborationManager socket and subscription behavior', () => {type: 'vars_and_features_update',data: { value: 1 },} satisfies CollaborationUpdate)- socket.trigger('collaboration_update', {- ...baseUpdate,- type: 'app_state_update',- data: { value: 2 },- } satisfies CollaborationUpdate)socket.trigger('collaboration_update', {...baseUpdate,type: 'app_meta_update',@@ -562,11 +553,6 @@ describe('CollaborationManager socket and subscription behavior', () => {type: 'app_publish_update',data: { value: 4 },} satisfies CollaborationUpdate)- socket.trigger('collaboration_update', {- ...baseUpdate,- type: 'mcp_server_update',- data: { value: 5 },- } satisfies CollaborationUpdate)socket.trigger('collaboration_update', {...baseUpdate,type: 'workflow_update',@@ -627,10 +613,8 @@ describe('CollaborationManager socket and subscription behavior', () => {'u-1': { x: 1, y: 2, userId: 'u-1' },})expect(varsFeatureHandler).toHaveBeenCalledTimes(1)- expect(appStateHandler).toHaveBeenCalledTimes(1)expect(appMetaHandler).toHaveBeenCalledTimes(1)expect(appPublishHandler).toHaveBeenCalledTimes(1)- expect(mcpHandler).toHaveBeenCalledTimes(1)expect(workflowUpdateHandler).toHaveBeenCalledWith({ appId: 'wf', timestamp: 9 })expect(commentsHandler).toHaveBeenCalledWith({ appId: 'wf', timestamp: 10 })expect(latestPresence).toMatchObject({ 'n-1': { 'socket-events': { userId: 'u-1' } } })diff --git a/web/app/components/workflow/collaboration/core/collaboration-manager.ts b/web/app/components/workflow/collaboration/core/collaboration-manager.tsindex 6323fc4e559..016741b4962 100644--- a/web/app/components/workflow/collaboration/core/collaboration-manager.ts+++ b/web/app/components/workflow/collaboration/core/collaboration-manager.ts@@ -1081,10 +1081,6 @@ export class CollaborationManager {return this.eventEmitter.on('varsAndFeaturesUpdate', callback)}- onAppStateUpdate(callback: (update: CollaborationUpdate) => void): () => void {- return this.eventEmitter.on('appStateUpdate', callback)- }-onAppPublishUpdate(callback: (update: CollaborationUpdate) => void): () => void {return this.eventEmitter.on('appPublishUpdate', callback)}@@ -1093,10 +1089,6 @@ export class CollaborationManager {return this.eventEmitter.on('appMetaUpdate', callback)}- onMcpServerUpdate(callback: (update: CollaborationUpdate) => void): () => void {- return this.eventEmitter.on('mcpServerUpdate', callback)- }-onNodePanelPresenceUpdate(callback: (presence: NodePanelPresenceMap) => void): () => void {const off = this.eventEmitter.on('nodePanelPresence', callback)callback(this.getNodePanelPresenceSnapshot())@@ -1782,14 +1774,10 @@ export class CollaborationManager {this.eventEmitter.emit('cursors', { ...this.cursors })} else if (update.type === 'vars_and_features_update') {this.eventEmitter.emit('varsAndFeaturesUpdate', update)- } else if (update.type === 'app_state_update') {- this.eventEmitter.emit('appStateUpdate', update)} else if (update.type === 'app_meta_update') {this.eventEmitter.emit('appMetaUpdate', update)} else if (update.type === 'app_publish_update') {this.eventEmitter.emit('appPublishUpdate', update)- } else if (update.type === 'mcp_server_update') {- this.eventEmitter.emit('mcpServerUpdate', update)} else if (update.type === 'workflow_update') {this.eventEmitter.emit('workflowUpdate', update.data)} else if (update.type === 'comments_update') {diff --git a/web/app/components/workflow/collaboration/types/collaboration.ts b/web/app/components/workflow/collaboration/types/collaboration.tsindex 9a1ec0538f3..c8f788b4c15 100644--- a/web/app/components/workflow/collaboration/types/collaboration.ts+++ b/web/app/components/workflow/collaboration/types/collaboration.ts@@ -39,9 +39,7 @@ type CollaborationEventType =| 'mouse_move'| 'vars_and_features_update'| 'sync_request'- | 'app_state_update'| 'app_meta_update'- | 'mcp_server_update'| 'workflow_update'| 'comments_update'| 'node_panel_presence'diff --git a/web/app/components/workflow/llm-environment-variable-value-field.tsx b/web/app/components/workflow/llm-environment-variable-value-field.tsxnew file mode 100644index 00000000000..a3fcecdefd3--- /dev/null+++ b/web/app/components/workflow/llm-environment-variable-value-field.tsx@@ -0,0 +1,82 @@+'use client'++import type { ModelParameterModalProps } from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'+import type {+ LLMCompletionParams,+ LLMEnvironmentVariableValue,+} from '@/app/components/workflow/types'+import { toast } from '@langgenius/dify-ui/toast'+import { useTranslation } from 'react-i18next'+import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'+import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'++export function LLMEnvironmentVariableValueField({+ disabled = false,+ popupClassName,+ requiredMode,+ value,+ onChange,+}: {+ disabled?: boolean+ popupClassName?: string+ requiredMode?: string+ value?: LLMEnvironmentVariableValue+ onChange: (value: LLMEnvironmentVariableValue) => void+}) {+ const { t } = useTranslation()+ const { activeTextGenerationModelList } = useTextGenerationCurrentProviderAndModelAndModelList()+ const selectableModelList = requiredMode+ ? activeTextGenerationModelList+ .map((provider) => ({+ ...provider,+ models: provider.models.filter((model) => model.model_properties.mode === requiredMode),+ }))+ .filter((provider) => provider.models.length > 0)+ : activeTextGenerationModelList++ const handleModelSelect: ModelParameterModalProps['setModel'] = ({ provider, modelId }) => {+ const targetProvider = activeTextGenerationModelList.find(+ (providerItem) => providerItem.provider === provider,+ )+ const targetModel = targetProvider?.models.find((modelItem) => modelItem.model === modelId)+ const mode = targetModel?.model_properties.mode++ if (typeof mode !== 'string') return+ if (requiredMode && mode !== requiredMode) {+ toast.error(t(($) => $['modelProvider.selector.incompatibleTip'], { ns: 'common' }))+ return+ }++ const completionParams =+ value?.provider === provider && value.name === modelId ? (value.completion_params ?? {}) : {}+ onChange({+ completion_params: completionParams,+ mode,+ name: modelId,+ provider,+ })+ }++ const handleCompletionParamsChange = (completionParams: LLMCompletionParams) => {+ if (!value) return+ onChange({ ...value, completion_params: completionParams })+ }++ return (+ <ModelParameterModal+ triggerContainerClassName="w-full min-w-0"+ provider={value?.provider ?? ''}+ modelId={value?.name ?? ''}+ completionParams={value?.completion_params ?? {}}+ modelList={selectableModelList}+ popupClassName={popupClassName}+ isAdvancedMode={true}+ setModel={handleModelSelect}+ onCompletionParamsChange={handleCompletionParamsChange}+ readonly={disabled}+ modelSelectorReadonly={disabled}+ hideDebugWithMultipleModel+ debugWithMultipleModel={false}+ />+ )+}diff --git a/web/app/components/workflow/llm-environment-variable.ts b/web/app/components/workflow/llm-environment-variable.tsnew file mode 100644index 00000000000..213ad98d800--- /dev/null+++ b/web/app/components/workflow/llm-environment-variable.ts@@ -0,0 +1,23 @@+import type { LLMEnvironmentVariableValue } from '@/app/components/workflow/types'++const VALID_LLM_ENVIRONMENT_VARIABLE_MODES = new Set(['chat', 'completion'])++export function isLLMEnvironmentVariableValue(+ value: unknown,+): value is LLMEnvironmentVariableValue {+ if (typeof value !== 'object' || value === null) return false++ const candidate = value as Partial<LLMEnvironmentVariableValue>+ return (+ typeof candidate.provider === 'string' &&+ candidate.provider.trim().length > 0 &&+ typeof candidate.name === 'string' &&+ candidate.name.trim().length > 0 &&+ typeof candidate.mode === 'string' &&+ VALID_LLM_ENVIRONMENT_VARIABLE_MODES.has(candidate.mode) &&+ (candidate.completion_params === undefined ||+ (typeof candidate.completion_params === 'object' &&+ candidate.completion_params !== null &&+ !Array.isArray(candidate.completion_params)))+ )+}diff --git a/web/app/components/workflow/nodes/_base/components/form-input-item.sections.tsx b/web/app/components/workflow/nodes/_base/components/form-input-item.sections.tsxindex a0301facaf2..1bfdc204647 100644--- a/web/app/components/workflow/nodes/_base/components/form-input-item.sections.tsx+++ b/web/app/components/workflow/nodes/_base/components/form-input-item.sections.tsx@@ -61,7 +61,7 @@ export const MultiSelectField: FC<MultiSelectFieldProps> = ({return (<Select multiple value={value} onValueChange={onChange} disabled={disabled || isLoading}>- <div className="grow">+ <div className="min-w-0 grow"><SelectTrigger aria-label={placeholder || selectedLabel || 'Options'}><span className={cn('flex min-w-0 items-center', textClassName)}>{isLoading && <LoadingIndicator />}diff --git a/web/app/components/workflow/nodes/_base/components/form-input-item.tsx b/web/app/components/workflow/nodes/_base/components/form-input-item.tsxindex 457132a169d..56dff0cf320 100644--- a/web/app/components/workflow/nodes/_base/components/form-input-item.tsx+++ b/web/app/components/workflow/nodes/_base/components/form-input-item.tsx@@ -395,7 +395,7 @@ const FormInputItem: FC<Props> = ({disabled={readOnly}onValueChange={(value) => value && handleValueChange(value)}>- <SelectTrigger className="h-8 grow">+ <SelectTrigger className="h-8 min-w-0 grow">{selectedStaticOption?.name ?? placeholder?.[language] ?? placeholder?.en_US}</SelectTrigger><SelectContent>@@ -425,7 +425,7 @@ const FormInputItem: FC<Props> = ({disabled={readOnly || isLoadingOptions}onValueChange={(value) => value && handleValueChange(value)}>- <SelectTrigger className="h-8 grow">+ <SelectTrigger className="h-8 min-w-0 grow">{selectedDynamicOption?.name ??(isLoadingOptions ? 'Loading...' : (placeholder?.[language] ?? placeholder?.en_US))}</SelectTrigger>diff --git a/web/app/components/workflow/nodes/llm/utils.ts b/web/app/components/workflow/nodes/llm/utils.tsindex f4cbd69649a..d0fab3edff5 100644--- a/web/app/components/workflow/nodes/llm/utils.ts+++ b/web/app/components/workflow/nodes/llm/utils.ts@@ -7,6 +7,7 @@ import type {ValueSelector,} from '@/app/components/workflow/types'import * as z from 'zod'+import { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'import { draft07Validator, forbidBooleanProperties } from '@/utils/validators'import { extractPluginId } from '../../utils/plugin'import { ArrayType, Type } from './types'@@ -16,13 +17,6 @@ export enum LLMModelIssueCode {providerPluginUnavailable = 'provider-plugin-unavailable',}-const isLLMEnvironmentVariableValue = (value: unknown): value is LLMEnvironmentVariableValue => {- if (!value || typeof value !== 'object') return false-- const candidate = value as Partial<LLMEnvironmentVariableValue>- return !!candidate.provider && !!candidate.name && !!candidate.mode-}-export const isEnvironmentModelSource = (modelSelector: ValueSelector | undefined) =>modelSelector != null && (modelSelector.length === 0 || modelSelector[0] === 'env')diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsxindex 44863fc3af6..f0c704111b2 100644--- a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx+++ b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx@@ -90,8 +90,8 @@ const ToolFormItem: FC<Props> = ({return (<div className="space-y-0.5 py-1"><div>- <div className="flex h-6 items-center">- <div className="system-sm-medium text-text-secondary">+ <div className="flex min-h-6 min-w-0 items-center">+ <div className="min-w-0 system-sm-medium wrap-break-word text-text-secondary">{label[language] || label.en_US}</div>{required && (diff --git a/web/app/components/workflow/panel/env-panel/__tests__/variable-modal.spec.tsx b/web/app/components/workflow/panel/env-panel/__tests__/variable-modal.spec.tsxindex ffe3704b148..afa46bf2e93 100644--- a/web/app/components/workflow/panel/env-panel/__tests__/variable-modal.spec.tsx+++ b/web/app/components/workflow/panel/env-panel/__tests__/variable-modal.spec.tsx@@ -145,6 +145,16 @@ describe('VariableModal', () => {latestModelParameterModalProps = undefined})+ it('closes from an accessible icon button', async () => {+ const user = userEvent.setup()+ const onClose = vi.fn()+ renderWithProviders(<VariableModal onClose={onClose} onSave={vi.fn()} />)++ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))++ expect(onClose).toHaveBeenCalledTimes(1)+ })+it('creates a secret environment variable and normalizes spaces in its name', async () => {const user = userEvent.setup()const onSave = vi.fn()@@ -281,6 +291,26 @@ describe('VariableModal', () => {})})+ it('rejects an LLM environment variable with an empty model selection', async () => {+ const user = userEvent.setup()+ const onSave = vi.fn()+ const env = createEnv({+ value: { mode: '', name: '', provider: '' },+ value_type: 'llm',+ })++ renderWithProviders(<VariableModal env={env} onClose={vi.fn()} onSave={onSave} />, {+ storeState: {+ environmentVariables: [env],+ },+ })++ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))++ expect(mockToastError).toHaveBeenCalledWith('workflow.env.modal.valueRequired')+ expect(onSave).not.toHaveBeenCalled()+ })+it('keeps an edited LLM environment variable within its existing model mode', async () => {const user = userEvent.setup()const onSave = vi.fn()diff --git a/web/app/components/workflow/panel/env-panel/index.tsx b/web/app/components/workflow/panel/env-panel/index.tsxindex 89ed16c100b..11ea558c0a0 100644--- a/web/app/components/workflow/panel/env-panel/index.tsx+++ b/web/app/components/workflow/panel/env-panel/index.tsx@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'+import { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'import RemoveEffectVarConfirm from '@/app/components/workflow/nodes/_base/components/remove-effect-var-confirm'import {findUsedVarNodes,@@ -143,12 +144,10 @@ const environmentVariableGraphPatchMatches = (const getLLMEnvironmentValue = (variable: EnvironmentVariable,): LLMEnvironmentVariableValue | undefined => {- if (variable.value_type !== 'llm' || !variable.value || typeof variable.value !== 'object')+ if (variable.value_type !== 'llm' || !isLLMEnvironmentVariableValue(variable.value))return undefined- const value = variable.value as Partial<LLMEnvironmentVariableValue>- if (!value.provider || !value.name || !value.mode) return undefined- return value as LLMEnvironmentVariableValue+ return variable.value}const useEnvPanelActions = ({diff --git a/web/app/components/workflow/panel/env-panel/variable-modal.tsx b/web/app/components/workflow/panel/env-panel/variable-modal.tsxindex 931d017dc2b..3f0672806cb 100644--- a/web/app/components/workflow/panel/env-panel/variable-modal.tsx+++ b/web/app/components/workflow/panel/env-panel/variable-modal.tsx@@ -1,21 +1,16 @@-import type {- EnvironmentVariable,- EnvironmentVariableValue,- LLMCompletionParams,- LLMEnvironmentVariableValue,-} from '@/app/components/workflow/types'+import type { EnvironmentVariable, EnvironmentVariableValue } from '@/app/components/workflow/types'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'+import { IconButton } from '@langgenius/dify-ui/icon-button'import { toast } from '@langgenius/dify-ui/toast'-import { RiCloseLine } from '@remixicon/react'import * as React from 'react'-import { useEffect, useMemo } from 'react'+import { useEffect } from 'react'import { useTranslation } from 'react-i18next'import { v4 as uuid4 } from 'uuid'import { Infotip } from '@/app/components/base/infotip'import Input from '@/app/components/base/input'-import { useTextGenerationCurrentProviderAndModelAndModelList } 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 { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'+import { LLMEnvironmentVariableValueField } from '@/app/components/workflow/llm-environment-variable-value-field'import { useWorkflowStore } from '@/app/components/workflow/store'import { checkKeys, replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'@@ -25,19 +20,6 @@ type ModalPropsType = {onSave: (env: EnvironmentVariable) => void}-const isLLMEnvironmentVariableValue = (value: unknown): value is LLMEnvironmentVariableValue => {- if (typeof value !== 'object' || value === null) return false-- return (- 'provider' in value &&- typeof value.provider === 'string' &&- 'name' in value &&- typeof value.name === 'string' &&- 'mode' in value &&- typeof value.mode === 'string'- )-}-const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {const { t } = useTranslation()const workflowStore = useWorkflowStore()@@ -45,21 +27,10 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {const [name, setName] = React.useState('')const [value, setValue] = React.useState<EnvironmentVariableValue>()const [description, setDescription] = React.useState<string>('')- const { activeTextGenerationModelList } = useTextGenerationCurrentProviderAndModelAndModelList()const originalLLMMode =env?.value_type === 'llm' && isLLMEnvironmentVariableValue(env.value)? env.value.mode: undefined- const selectableModelList = useMemo(() => {- if (!originalLLMMode) return activeTextGenerationModelList-- return activeTextGenerationModelList- .map((provider) => ({- ...provider,- models: provider.models.filter((model) => model.model_properties.mode === originalLLMMode),- }))- .filter((provider) => provider.models.length > 0)- }, [activeTextGenerationModelList, originalLLMMode])const isTypeChangeDisabled = (nextType: EnvironmentVariable['value_type']) =>!!env && (env.value_type === 'llm') !== (nextType === 'llm')@@ -105,31 +76,6 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {if (typeof value === 'number') setValue(String(value))}- const handleModelSelect = ({ provider, modelId }: { provider: string; modelId: string }) => {- const targetProvider = activeTextGenerationModelList.find(- (providerItem) => providerItem.provider === provider,- )- const targetModel = targetProvider?.models.find((modelItem) => modelItem.model === modelId)- const mode = targetModel?.model_properties.mode-- if (typeof mode !== 'string') return- if (originalLLMMode && mode !== originalLLMMode) {- toast.error(t(($) => $['modelProvider.selector.incompatibleTip'], { ns: 'common' }))- return- }-- const completionParams =- isLLMEnvironmentVariableValue(value) && value.provider === provider && value.name === modelId- ? (value.completion_params ?? {})- : {}- setValue({ provider, name: modelId, mode, completion_params: completionParams })- }-- const handleCompletionParamsChange = (completionParams: LLMCompletionParams) => {- if (!isLLMEnvironmentVariableValue(value)) return- setValue({ ...value, completion_params: completionParams })- }-const handleSave = () => {if (!checkVariableName(name)) returnif (@@ -187,11 +133,9 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {{!env? t(($) => $['env.modal.title'], { ns: 'workflow' }): t(($) => $['env.modal.editTitle'], { ns: 'workflow' })}- <div className="flex items-center">- <div className="flex size-6 cursor-pointer items-center justify-center" onClick={onClose}>- <RiCloseLine className="size-4 text-text-tertiary" />- </div>- </div>+ <IconButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} onClick={onClose}>+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton></div><div className="px-4 py-2">{/* type */}@@ -289,21 +233,13 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {? t(($) => $['modelProvider.model'], { ns: 'common' }): t(($) => $['env.modal.value'], { ns: 'workflow' })}</div>- <div className="flex [&>div]:w-full">+ <div className="flex">{type === 'llm' ? (- <ModelParameterModal- provider={isLLMEnvironmentVariableValue(value) ? value.provider : ''}- modelId={isLLMEnvironmentVariableValue(value) ? value.name : ''}- completionParams={- isLLMEnvironmentVariableValue(value) ? (value.completion_params ?? {}) : {}- }- modelList={selectableModelList}+ <LLMEnvironmentVariableValueField+ value={isLLMEnvironmentVariableValue(value) ? value : undefined}+ requiredMode={originalLLMMode}popupClassName="w-[328px]! max-w-[328px]!"- isAdvancedMode={true}- setModel={handleModelSelect}- onCompletionParamsChange={handleCompletionParamsChange}- hideDebugWithMultipleModel- debugWithMultipleModel={false}+ onChange={setValue}/>) : type !== 'number' ? (<textareadiff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsxindex 607b8cdd7fa..1e84e2cdc75 100644--- a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx@@ -5,6 +5,7 @@ import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useEffect, useRef } from 'react'import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { AppModeEnum } from '@/types/app'import { VersionHistoryContextMenuOptions, WorkflowVersion } from '../../../types'const mockHandleRestoreFromPublishedWorkflow = vi.fn()@@ -508,6 +509,7 @@ describe('VersionHistoryPanel', () => {render(<VersionHistoryPanel+ appMode={AppModeEnum.WORKFLOW}latestVersionId="published-version-id"restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}updateVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}`}@@ -518,6 +520,16 @@ describe('VersionHistoryPanel', () => {fireEvent.click(screen.getByRole('button', { name: 'submit version info' }))await waitFor(() => {+ expect(mockUpdateWorkflow).toHaveBeenCalledWith(+ {+ appId: 'app-1',+ appMode: AppModeEnum.WORKFLOW,+ releaseNotes: 'Updated notes',+ title: 'Updated release',+ url: '/apps/app-1/workflows/published-version-id',+ },+ expect.any(Object),+ )expect(mockInvalidateAppWorkflow).toHaveBeenCalledWith('app-1')})})diff --git a/web/app/components/workflow/panel/version-history-panel/index.tsx b/web/app/components/workflow/panel/version-history-panel/index.tsxindex c8b4d7872f1..4a011c4964e 100644--- a/web/app/components/workflow/panel/version-history-panel/index.tsx+++ b/web/app/components/workflow/panel/version-history-panel/index.tsx@@ -1,5 +1,6 @@'use client'+import type { AppModeEnum } from '@/types/app'import type { VersionHistory } from '@/types/workflow'import { toast } from '@langgenius/dify-ui/toast'import { useSuspenseQuery } from '@tanstack/react-query'@@ -44,6 +45,7 @@ const HISTORY_PER_PAGE = 10const INITIAL_PAGE = 1export type VersionHistoryPanelProps = {+ appMode?: AppModeEnumgetVersionListUrl?: stringdeleteVersionUrl?: (versionId: string) => stringrestoreVersionUrl: (versionId: string) => string@@ -52,6 +54,7 @@ export type VersionHistoryPanelProps = {}export const VersionHistoryPanel = ({+ appMode,getVersionListUrl,deleteVersionUrl,restoreVersionUrl,@@ -323,6 +326,9 @@ export const VersionHistoryPanel = ({const { id, ...rest } = paramsawait updateWorkflow({+ ...(configsMap?.flowType === FlowType.appFlow && configsMap.flowId+ ? { appId: configsMap.flowId, appMode }+ : {}),url: updateVersionUrl?.(id || '') || '',...rest,},@@ -347,6 +353,7 @@ export const VersionHistoryPanel = ({)},[+ appMode,configsMap?.flowId,configsMap?.flowType,invalidateAppWorkflow,diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-card.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-card.spec.tsxdeleted file mode 100644index 3e909668afd..00000000000--- a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-card.spec.tsx+++ /dev/null@@ -1,88 +0,0 @@-import { render, screen } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { AccessSurfaceCard } from '../access-surface-card'--const mockCopy = vi.fn()-let mockCopied = false--vi.mock('foxact/use-clipboard', () => ({- useClipboard: () => ({- copied: mockCopied,- copy: mockCopy,- }),-}))--vi.mock('@langgenius/dify-ui/toast', () => ({- toast: {- error: vi.fn(),- },-}))--describe('AccessSurfaceCard', () => {- beforeEach(() => {- mockCopied = false- vi.clearAllMocks()- })-- describe('Copy feedback', () => {- it('should expose the surface card by its title', () => {- render(- <AccessSurfaceCard- title="Web app"- icon="i-ri-window-line"- iconClassName="bg-state-accent-solid"- endpointLabel="Access URL"- endpoint="https://chat.example.test/agent/token"- enabled- onEnabledChange={vi.fn()}- copyLabel="Copy access URL"- >- <button type="button">Action</button>- </AccessSurfaceCard>,- )-- expect(screen.getByRole('article', { name: 'Web app' })).toBeInTheDocument()- expect(screen.getByRole('heading', { name: 'Web app' })).toHaveAttribute('title', 'Web app')- })-- it('should copy the endpoint and render copied state from the clipboard hook', async () => {- const user = userEvent.setup()- const { rerender } = render(- <AccessSurfaceCard- title="Web app"- icon="i-ri-window-line"- iconClassName="bg-state-accent-solid"- endpointLabel="Access URL"- endpoint="https://chat.example.test/agent/token"- enabled- onEnabledChange={vi.fn()}- copyLabel="Copy access URL"- >- <button type="button">Action</button>- </AccessSurfaceCard>,- )-- await user.click(screen.getByRole('button', { name: 'Copy access URL' }))-- expect(mockCopy).toHaveBeenCalledWith('https://chat.example.test/agent/token')-- mockCopied = true- rerender(- <AccessSurfaceCard- title="Web app"- icon="i-ri-window-line"- iconClassName="bg-state-accent-solid"- endpointLabel="Access URL"- endpoint="https://chat.example.test/agent/token"- enabled- onEnabledChange={vi.fn()}- copyLabel="Copy access URL"- >- <button type="button">Action</button>- </AccessSurfaceCard>,- )-- expect(screen.getByRole('button', { name: 'common.operation.copied' })).toBeInTheDocument()- })- })-})diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsxindex 536d14b8e95..b0abc7600c6 100644--- a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({createApiKeyMutation: vi.fn(),deleteApiKeyMutation: vi.fn(),accessControlRender: vi.fn(),+ accessSubjectsQueryFn: vi.fn(),}))vi.mock('@/app/components/app/app-access-control', () => ({@@ -98,6 +99,16 @@ vi.mock('@/service/client', () => ({}),},},+ enterprise: {+ webAppAuth: {+ getWebAppWhitelistSubjects: {+ queryOptions: ({ input }: { input: { query: { appId?: string } } }) => ({+ queryKey: ['web-app-whitelist-subjects', input.query.appId],+ queryFn: () => mocks.accessSubjectsQueryFn(input),+ }),+ },+ },+ },apps: {byAppId: {siteEnable: {@@ -292,6 +303,7 @@ function createDeferredPromise<T>() {describe('Agent access surface cards', () => {beforeEach(() => {vi.clearAllMocks()+ mocks.accessSubjectsQueryFn.mockResolvedValue({ groups: [], members: [] })})describe('Web app access', () => {@@ -311,9 +323,27 @@ describe('Agent access surface cards', () => {expect(screen.getByText('https://chat.example.test/agent/site-token')).toBeInTheDocument()expect(- screen.getByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.launch' }),+ screen.getByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),).toHaveAttribute('href', 'https://chat.example.test/agent/site-token')- expect(screen.getByText('agentV2.agentDetail.access.webApp.ssoEnabled')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.access.webApp.description')).toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.copyAccessUrl' }),+ ).toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.showQrCode' }),+ ).toBeInTheDocument()+ const webAppCard = screen.getByRole('region', {+ name: 'agentV2.agentDetail.access.webApp.title',+ })+ expect(+ within(webAppCard).getByRole('heading', {+ name: 'agentV2.agentDetail.access.webApp.title',+ level: 3,+ }),+ ).toBeInTheDocument()+ expect(+ within(within(webAppCard).getByRole('contentinfo')).getAllByRole('button'),+ ).toHaveLength(3)const accessSwitch = screen.getByRole('switch', {name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.webApp.title"}',@@ -323,7 +353,7 @@ describe('Agent access surface cards', () => {expect(accessSwitch).toHaveAttribute('aria-checked', 'false')expect(accessSwitch).toBeEnabled()expect(- screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.launch' }),+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),).toBeDisabled()expect(mocks.siteEnableMutation.mock.calls[0]?.[0]).toEqual({params: {@@ -338,7 +368,7 @@ describe('Agent access surface cards', () => {expect(accessSwitch).toHaveAttribute('aria-checked', 'true')expect(- screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.launch' }),+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),).toBeDisabled()expect(mocks.siteEnableMutation).toHaveBeenCalledTimes(1)@@ -383,13 +413,13 @@ describe('Agent access surface cards', () => {})expect(await screen.findByRole('link', {- name: 'agentV2.agentDetail.access.webApp.actions.launch',+ name: 'agentV2.agentDetail.access.webApp.actions.open',}),).toHaveAttribute('href', 'https://chat.example.test/agent/site-token')expect(toast.success).not.toHaveBeenCalled()})- it('should keep launch disabled while enabling is pending and roll back after failure', async () => {+ it('should keep open disabled while enabling is pending and roll back after failure', async () => {const user = userEvent.setup()const toggle = createDeferredPromise<AppDetail>()mocks.siteEnableMutation.mockReturnValueOnce(toggle.promise)@@ -405,16 +435,16 @@ describe('Agent access surface cards', () => {const accessSwitch = screen.getByRole('switch', {name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.webApp.title"}',})- const launchButton = screen.getByRole('button', {- name: 'agentV2.agentDetail.access.webApp.actions.launch',+ const openButton = screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.open',})await user.click(accessSwitch)expect(accessSwitch).toHaveAttribute('aria-checked', 'true')expect(accessSwitch).toBeEnabled()- expect(launchButton).toBeDisabled()+ expect(openButton).toBeDisabled()expect(- screen.queryByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.launch' }),+ screen.queryByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),).not.toBeInTheDocument()toggle.reject(new Error('request failed'))@@ -422,7 +452,7 @@ describe('Agent access surface cards', () => {await waitFor(() => {expect(accessSwitch).toHaveAttribute('aria-checked', 'false')})- expect(launchButton).toBeDisabled()+ expect(openButton).toBeDisabled()expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')})@@ -434,7 +464,9 @@ describe('Agent access surface cards', () => {)await user.click(- screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.customize' }),+ screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.customFrontend',+ }),)const dialog = await screen.findByRole('dialog', {@@ -457,7 +489,9 @@ describe('Agent access surface cards', () => {)await user.click(- screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.embedded' }),+ screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.embedIntoSite',+ }),)const dialog = await screen.findByRole('dialog', {@@ -486,7 +520,9 @@ describe('Agent access surface cards', () => {)await user.click(- screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.embedded' }),+ screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.embedIntoSite',+ }),)const dialog = await screen.findByRole('dialog', {name: 'appOverview.overview.appInfo.embedded.title',@@ -680,7 +716,9 @@ describe('Agent access surface cards', () => {)expect(- screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.embedded' }),+ screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.embedIntoSite',+ }),).toBeDisabled()})@@ -723,11 +761,13 @@ describe('Agent access surface cards', () => {)expect(- screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.customize' }),+ screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.customFrontend',+ }),).toBeDisabled()})- it('should explain that publishing enables the Web App switch and launch action', async () => {+ it('should explain that publishing enables the Web App switch and open action', async () => {const user = userEvent.setup()renderWithQueryClient(<WebAppAccessCard@@ -755,7 +795,7 @@ describe('Agent access surface cards', () => {await user.hover(screen.getByRole('button', {- name: 'agentV2.agentDetail.access.webApp.actions.launch',+ name: 'agentV2.agentDetail.access.webApp.actions.open',}),)expect(await screen.findByRole('tooltip')).toHaveTextContent(@@ -774,6 +814,23 @@ describe('Agent access surface cards', () => {renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)expect(await screen.findByText('https://api.example.test/v1')).toBeInTheDocument()+ expect(+ screen.getByRole('heading', {+ name: 'agentV2.agentDetail.access.serviceApi.title',+ level: 3,+ }),+ ).toBeInTheDocument()+ expect(+ screen.getByText('agentV2.agentDetail.access.serviceApi.description'),+ ).toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: 'agentV2.agentDetail.access.copyServiceEndpoint' }),+ ).toBeInTheDocument()+ expect(+ screen.getByRole('link', {+ name: 'agentV2.agentDetail.access.serviceApi.actions.apiReference',+ }),+ ).toHaveAttribute('href', 'https://docs.example.test/api-reference/guides/agent')expect(screen.getByText('2')).toBeInTheDocument()const accessSwitch = screen.getByRole('switch', {@@ -923,82 +980,122 @@ describe('Agent access surface cards', () => {'agentV2.agentDetail.access.publishRequired',)})++ it('should show the unavailable status when the Service API query fails', async () => {+ mocks.apiAccessQueryFn.mockRejectedValueOnce(new Error('Service API unavailable'))++ renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)++ expect(+ await screen.findByText('agentV2.agentDetail.access.status.unavailable'),+ ).toBeInTheDocument()+ expect(screen.queryByText('common.loading')).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.operation.retry' })).toBeEnabled()+ })})- describe('Web app access control', () => {+ describe('App-style Web app access control', () => {const accessControlAgent = () =>createAgent({- access_mode: 'private',- maintainer: 'user-1',+ access_mode: 'private_all',+ maintainer: 'user-2',permission_keys: ['app.acl.release_and_version'],})- const accessControlButtonName = 'agentV2.agentDetail.access.webApp.actions.accessControl'+ const organizationAccessLabel = 'app.accessControlDialog.accessItems.organization'- it('should render the access control button when webapp auth is enabled and user can manage', () => {+ it('should render the access mode entry in the card content', () => {renderWithQueryClient(<WebAppAccessCard agent={accessControlAgent()} agentId="agent-1" isLoading={false} />,)- expect(screen.getByRole('button', { name: accessControlButtonName })).toBeInTheDocument()+ const entry = screen.getByRole('button', { name: organizationAccessLabel })+ const card = screen.getByRole('region', {+ name: 'agentV2.agentDetail.access.webApp.title',+ })+ expect(entry).toBeInTheDocument()+ expect(within(card).getByRole('contentinfo')).not.toContainElement(entry)+ })++ it('should render the access control skeleton while the card is loading', () => {+ renderWithQueryClient(<WebAppAccessCard agent={undefined} agentId="agent-1" isLoading />)++ const card = screen.getByRole('region', {+ name: 'agentV2.agentDetail.access.webApp.title',+ })+ expect(within(card).getByRole('status', { name: 'common.loading' })).toBeInTheDocument()+ })++ it('should keep access control interactive before the Agent is published', () => {+ renderWithQueryClient(+ <WebAppAccessCard+ agent={createAgent({+ ...accessControlAgent(),+ access_ready: false,+ })}+ agentId="agent-1"+ isLoading={false}+ />,+ )++ expect(screen.getByRole('button', { name: organizationAccessLabel })).toBeEnabled()+ expect(screen.queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()})- it('should hide the access control button when webapp auth is disabled', () => {+ it('should hide the access mode entry when Web app auth is disabled', () => {renderWithQueryClient(<WebAppAccessCard agent={accessControlAgent()} agentId="agent-1" isLoading={false} />,{ webAppAuthEnabled: false },)expect(- screen.queryByRole('button', { name: accessControlButtonName }),+ screen.queryByRole('button', { name: organizationAccessLabel }),).not.toBeInTheDocument()})- it('should hide the access control button when the user cannot manage access control', () => {+ it('should disable the access mode entry when the user cannot manage access control', () => {renderWithQueryClient(<WebAppAccessCard- agent={createAgent({ access_mode: 'private', permission_keys: [] })}+ agent={createAgent({+ access_mode: 'private_all',+ maintainer: 'user-2',+ permission_keys: [],+ })}agentId="agent-1"isLoading={false}/>,)- expect(- screen.queryByRole('button', { name: accessControlButtonName }),- ).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: organizationAccessLabel })).toBeDisabled()})it.each([null, 'future-access-mode'])(- 'should hide the access control button when the access mode is %s',+ 'should hide the access mode entry when the access mode is %s',(accessMode) => {renderWithQueryClient(<WebAppAccessCard- agent={createAgent({- access_mode: accessMode,- maintainer: 'user-1',- permission_keys: ['app.acl.release_and_version'],- })}+ agent={createAgent({ access_mode: accessMode })}agentId="agent-1"isLoading={false}/>,)expect(- screen.queryByRole('button', { name: accessControlButtonName }),+ screen.queryByRole('button', { name: organizationAccessLabel }),).not.toBeInTheDocument()},)- it('should open the access control dialog wired with the backing app id', async () => {+ it('should open the shared App access control dialog for the backing app', async () => {const user = userEvent.setup()renderWithQueryClient(<WebAppAccessCardagent={createAgent({- access_mode: 'private',+ access_mode: 'private_all',app_id: 'source-app-1',backing_app_id: 'backing-app-1',- maintainer: 'user-1',+ maintainer: 'user-2',permission_keys: ['app.acl.release_and_version'],})}agentId="agent-1"@@ -1006,12 +1103,12 @@ describe('Agent access surface cards', () => {/>,)- await user.click(screen.getByRole('button', { name: accessControlButtonName }))+ await user.click(screen.getByRole('button', { name: organizationAccessLabel }))- expect(screen.getByRole('dialog', { name: 'access-control' })).toBeInTheDocument()+ expect(await screen.findByRole('dialog', { name: 'access-control' })).toBeInTheDocument()expect(mocks.accessControlRender).toHaveBeenCalledWith({id: 'backing-app-1',- access_mode: 'private',+ access_mode: 'private_all',})})})diff --git a/web/features/agent-v2/agent-detail/access/components/access-surface-card.tsx b/web/features/agent-v2/agent-detail/access/components/access-surface-card.tsxdeleted file mode 100644index 5f266ea0156..00000000000--- a/web/features/agent-v2/agent-detail/access/components/access-surface-card.tsx+++ /dev/null@@ -1,163 +0,0 @@-'use client'--import type { ReactNode } from 'react'-import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'-import { StatusDot } from '@langgenius/dify-ui/status-dot'-import { Switch } from '@langgenius/dify-ui/switch'-import { toast } from '@langgenius/dify-ui/toast'-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { useClipboard } from 'foxact/use-clipboard'-import { useId } from 'react'-import { useTranslation } from 'react-i18next'--export type AccessSurfaceCardProps = {- title: string- icon: string- iconClassName: string- endpointLabel: string- endpoint: string- enabled: boolean- onEnabledChange: (enabled: boolean) => void- copyLabel: string- children: ReactNode- badge?: ReactNode- endpointActions?: ReactNode- disabled?: boolean- disabledReason?: string-}--export function AccessSurfaceCard({- title,- icon,- iconClassName,- endpointLabel,- endpoint,- enabled,- onEnabledChange,- copyLabel,- children,- badge,- endpointActions,- disabled = false,- disabledReason,-}: AccessSurfaceCardProps) {- const { t } = useTranslation('agentV2')- const { t: tCommon } = useTranslation('common')- const titleId = useId()- const { copied, copy } = useClipboard({- timeout: 2000,- onCopyError: () => {- toast.error(t(($) => $['agentDetail.access.copyFailed']))- },- })- const canCopyEndpoint = Boolean(endpoint)- const hasDisabledReason = disabled && Boolean(disabledReason)- const switchControl = (- <Switch- size="md"- checked={enabled}- disabled={disabled && !hasDisabledReason}- readOnly={hasDisabledReason}- aria-disabled={hasDisabledReason || undefined}- data-disabled={hasDisabledReason ? '' : undefined}- aria-label={t(($) => $['agentDetail.access.toggleSurface'], { name: title })}- onCheckedChange={(nextEnabled) => {- if (!disabled) onEnabledChange(nextEnabled)- }}- />- )-- const handleCopyEndpoint = () => {- if (!canCopyEndpoint) return-- void copy(endpoint)- }-- return (- <article- aria-labelledby={titleId}- className="rounded-xl border border-components-panel-border bg-components-panel-bg shadow-xs"- >- <div className="px-4 pt-4 pb-4">- <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2">- <div className="flex min-w-48 flex-1 items-center gap-2">- <span- className={cn(- 'flex size-6 shrink-0 items-center justify-center rounded-lg',- iconClassName,- )}- >- <span aria-hidden className={cn(icon, 'size-4')} />- </span>- <h3- id={titleId}- className="truncate system-md-semibold text-text-secondary"- title={title}- >- {title}- </h3>- {badge}- </div>-- <div className="flex shrink-0 items-center gap-3">- <span- className={cn(- 'inline-flex items-center gap-1 system-xs-semibold-uppercase',- enabled ? 'text-util-colors-green-green-700' : 'text-text-tertiary',- )}- >- <StatusDot status={enabled ? 'success' : 'disabled'} size="small" />- {t(- ($) =>- $[- enabled- ? 'agentDetail.access.status.inService'- : 'agentDetail.access.status.outOfService'- ],- )}- </span>- {disabled && disabledReason ? (- <Tooltip>- <TooltipTrigger render={switchControl} />- <TooltipContent role="tooltip">{disabledReason}</TooltipContent>- </Tooltip>- ) : (- switchControl- )}- </div>- </div>-- <div className="mt-3">- <div className="system-xs-medium text-text-tertiary">{endpointLabel}</div>- <div className="mt-1 flex h-8 min-w-0 items-center rounded-lg bg-components-input-bg-normal px-2">- <span- className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary"- translate="no"- >- {endpoint || t(($) => $['agentDetail.access.workflow.notAvailable'])}- </span>- <Button- variant="ghost"- size="small"- className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"- aria-label={copied ? tCommon(($) => $['operation.copied']) : copyLabel}- disabled={!canCopyEndpoint}- onClick={handleCopyEndpoint}- >- <span- aria-hidden- className={cn(copied ? 'i-ri-check-line' : 'i-ri-file-copy-line', 'size-4')}- />- </Button>- {endpointActions}- </div>- </div>- </div>-- <div className="flex min-h-16 flex-wrap items-center gap-2 border-t border-divider-subtle px-4 py-4">- {children}- </div>- </article>- )-}diff --git a/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsxindex a1496e41320..095cc0422b5 100644--- a/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx+++ b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx@@ -2,13 +2,15 @@import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'import { Button, buttonVariants } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'import { toast } from '@langgenius/dify-ui/toast'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { useState } from 'react'import { useTranslation } from 'react-i18next'+import { AccessPointCard } from '@/app/components/base/access-point/card'+import { AccessPointUrl } from '@/app/components/base/access-point/url'import { useDocLink } from '@/context/i18n'import { consoleQuery } from '@/service/client'-import { AccessSurfaceCard } from './access-surface-card'import { AgentApiKeyModal } from './agent-api-key-modal'export function ServiceApiAccessCard({ agentId }: { agentId: string }) {@@ -55,6 +57,28 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {toggleServiceApiMutation.isPending && pendingEnabled !== undefined? pendingEnabled: Boolean(apiAccess?.enabled)+ const endpoint = apiAccess?.service_api_base_url ?? ''+ const status = apiAccessQuery.isPending+ ? 'loading'+ : apiAccessQuery.isError+ ? 'unavailable'+ : optimisticEnabled+ ? 'inService'+ : 'disabled'+ const statusLabel = apiAccessQuery.isPending+ ? tCommon(($) => $.loading)+ : apiAccessQuery.isError+ ? t(($) => $['agentDetail.access.status.unavailable'])+ : t(+ ($) =>+ $[+ optimisticEnabled+ ? 'agentDetail.access.status.inService'+ : 'agentDetail.access.status.outOfService'+ ],+ )+ const notAvailableLabel = t(($) => $['agentDetail.access.workflow.notAvailable'])+ const apiKeyActionDisabled = apiAccessQuery.isPending || apiAccessQuery.isError || !accessReadyconst showPublishRequiredMessage =!apiAccessQuery.isPending && !apiAccessQuery.isError && !accessReady@@ -71,54 +95,85 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {return (<>- <AccessSurfaceCard+ <AccessPointCard+ className="min-h-[222px]"+ headingLevel={3}title={t(($) => $['agentDetail.access.serviceApi.title'])}- icon="i-ri-node-tree"- iconClassName="bg-state-accent-solid text-text-primary-on-surface"- endpointLabel={t(($) => $['agentDetail.access.serviceApi.endpoint'])}- endpoint={apiAccess?.service_api_base_url ?? ''}- enabled={optimisticEnabled}- onEnabledChange={handleEnabledChange}- copyLabel={t(($) => $['agentDetail.access.copyServiceEndpoint'])}- disabled={apiAccessQuery.isPending || apiAccessQuery.isError || !accessReady}- disabledReason={+ description={t(($) => $['agentDetail.access.serviceApi.description'])}+ icon="i-custom-vender-knowledge-api-aggregate"+ status={status}+ statusLabel={statusLabel}+ switchDisabled={apiAccessQuery.isPending || apiAccessQuery.isError || !accessReady}+ switchDisabledReason={showPublishRequiredMessage ? t(($) => $['agentDetail.access.publishRequired']) : undefined}+ switchLabel={t(($) => $['agentDetail.access.toggleSurface'], {+ name: t(($) => $['agentDetail.access.serviceApi.title']),+ })}+ onEnabledChange={handleEnabledChange}+ actions={+ <>+ <Button+ variant="secondary"+ disabled={apiKeyActionDisabled}+ onClick={() => setApiKeyModalOpen(true)}+ className="flex items-center gap-1 px-3"+ >+ <span aria-hidden className="i-ri-key-2-line size-4" />+ {t(($) => $['agentDetail.access.serviceApi.actions.apiKey'])}+ <span+ className={cn(+ 'flex min-w-4 items-center justify-center rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase tabular-nums',+ apiKeyActionDisabled ? 'text-text-disabled' : 'text-text-tertiary',+ )}+ >+ {apiAccess?.api_key_count ?? 0}+ </span>+ </Button>+ <a+ href={docLink('/api-reference/guides/agent')}+ target="_blank"+ rel="noopener noreferrer"+ className={buttonVariants({+ variant: 'secondary',+ size: 'medium',+ className: 'flex items-center gap-1 px-3',+ })}+ >+ <span aria-hidden className="i-ri-book-open-line size-4" />+ {t(($) => $['agentDetail.access.serviceApi.actions.apiReference'])}+ <span aria-hidden className="i-ri-arrow-right-up-line size-3.5" />+ </a>+ {apiAccessQuery.isError && (+ <Button+ variant="secondary"+ className="flex items-center gap-1 px-3"+ onClick={() => {+ void apiAccessQuery.refetch()+ }}+ >+ <span aria-hidden className="i-ri-refresh-line size-4" />+ {tCommon(($) => $['operation.retry'])}+ </Button>+ )}+ </>+ }>- <Button- variant="secondary"- size="medium"- disabled={apiAccessQuery.isPending || apiAccessQuery.isError || !accessReady}- onClick={() => setApiKeyModalOpen(true)}- >- <span aria-hidden className="i-ri-key-2-line size-4" />- {t(($) => $['agentDetail.access.serviceApi.actions.apiKey'])}- <span className="rounded-md bg-components-badge-bg-gray-soft px-1.5 code-xs-regular text-text-tertiary">- {apiAccess?.api_key_count ?? 0}- </span>- </Button>- <a- href={docLink('/api-reference/guides/agent')}- target="_blank"- rel="noreferrer"- className={buttonVariants({ variant: 'secondary', size: 'medium' })}- >- <span aria-hidden className="i-ri-book-open-line size-4" />- {t(($) => $['agentDetail.access.serviceApi.actions.apiReference'])}- </a>- {apiAccessQuery.isError && (- <Button- variant="secondary"- size="medium"- onClick={() => {- void apiAccessQuery.refetch()- }}- >- <span aria-hidden className="i-ri-refresh-line size-4" />- {tCommon(($) => $['operation.retry'])}- </Button>- )}- </AccessSurfaceCard>+ <AccessPointUrl+ label={t(($) => $['agentDetail.access.serviceApi.endpoint'])}+ value={endpoint || notAvailableLabel}+ enabled={optimisticEnabled}+ copyDisabled={!endpoint}+ loading={apiAccessQuery.isPending}+ unavailable={apiAccessQuery.isError}+ unavailableLabel={notAvailableLabel}+ copyLabel={t(($) => $['agentDetail.access.copyServiceEndpoint'])}+ copiedLabel={tCommon(($) => $['operation.copied'])}+ onCopyError={() => {+ toast.error(t(($) => $['agentDetail.access.copyFailed']))+ }}+ />+ </AccessPointCard><AgentApiKeyModalagentId={agentId}diff --git a/web/features/agent-v2/agent-detail/access/components/use-web-app-access-control.ts b/web/features/agent-v2/agent-detail/access/components/use-web-app-access-control.tsnew file mode 100644index 00000000000..76f4fa8603a--- /dev/null+++ b/web/features/agent-v2/agent-detail/access/components/use-web-app-access-control.ts@@ -0,0 +1,74 @@+'use client'++import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'+import type { SelectorParam } from 'i18next'+import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'+import { useTranslation } from 'react-i18next'+import { workspacePermissionKeysAtom } from '@/context/permission-state'+import { userProfileQueryOptions } from '@/features/account-profile/client'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'+import { AccessMode, isAccessMode } from '@/models/access-control'+import { useAppWhiteListSubjects } from '@/service/access-control/use-app-access-control'+import { getAppACLCapabilities } from '@/utils/permission'++const ACCESS_MODE_ICON_MAP: Record<AccessMode, string> = {+ [AccessMode.ORGANIZATION]: 'i-ri-building-line',+ [AccessMode.SPECIFIC_GROUPS_MEMBERS]: 'i-ri-lock-line',+ [AccessMode.PUBLIC]: 'i-ri-global-line',+ [AccessMode.EXTERNAL_MEMBERS]: 'i-ri-verified-badge-line',+}++const ACCESS_MODE_LABEL_MAP: Record<AccessMode, SelectorParam<'app'>> = {+ [AccessMode.ORGANIZATION]: ($) => $['accessControlDialog.accessItems.organization'],+ [AccessMode.SPECIFIC_GROUPS_MEMBERS]: ($) => $['accessControlDialog.accessItems.specific'],+ [AccessMode.PUBLIC]: ($) => $['accessControlDialog.accessItems.anyone'],+ [AccessMode.EXTERNAL_MEMBERS]: ($) => $['accessControlDialog.accessItems.external'],+}++export function useWebAppAccessControl(+ agent: AgentAppDetailWithSite | undefined,+ isLoading: boolean,+) {+ const { t } = useTranslation()+ const appId = agent?.backing_app_id ?? undefined+ const accessMode = isAccessMode(agent?.access_mode) ? agent.access_mode : undefined+ const { data: webAppAuthEnabled } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: (systemFeatures) => systemFeatures.webapp_auth.enabled,+ })+ const { data: currentUserId } = useSuspenseQuery({+ ...userProfileQueryOptions(),+ select: (data) => data.profile.id,+ })+ const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)+ const { canReleaseAndVersion: canManage } = getAppACLCapabilities(agent?.permission_keys, {+ currentUserId,+ resourceMaintainer: agent?.maintainer,+ workspacePermissionKeys,+ })+ const hasAccessControl = Boolean(webAppAuthEnabled && appId && accessMode)+ const { data: accessSubjects } = useAppWhiteListSubjects(+ appId,+ hasAccessControl && canManage && accessMode === AccessMode.SPECIFIC_GROUPS_MEMBERS,+ )+ const accessConfigured =+ !accessSubjects ||+ accessMode !== AccessMode.SPECIFIC_GROUPS_MEMBERS ||+ Boolean(accessSubjects.groups.length || accessSubjects.members.length)++ if (!webAppAuthEnabled) return { state: 'hidden' as const }+ if (isLoading) return { state: 'loading' as const }+ if (!appId || !accessMode) return { state: 'hidden' as const }++ return {+ state: 'ready' as const,+ app: { id: appId, access_mode: accessMode },+ entryProps: {+ accessConfigured,+ accessIcon: ACCESS_MODE_ICON_MAP[accessMode],+ accessLabel: t(ACCESS_MODE_LABEL_MAP[accessMode], { ns: 'app' }),+ disabled: !canManage,+ },+ }+}diff --git a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsxindex bc753046dd1..904f8f6f859 100644--- a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx+++ b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx@@ -4,72 +4,29 @@ import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/timport type { AppSiteUpdatePayload } from '@dify/contracts/api/console/apps/types.gen'import type { ConfigParams, SettingsAppInfo } from '@/app/components/app/overview/settings'import type { AppIconType } from '@/types/app'-import { Button, buttonVariants } from '@langgenius/dify-ui/button'+import { Button } from '@langgenius/dify-ui/button'import { toast } from '@langgenius/dify-ui/toast'-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useMutation, useQueryClient } from '@tanstack/react-query'import { useState } from 'react'import { useTranslation } from 'react-i18next'+import {+ WebAppAccessControlEntry,+ WebAppAccessControlEntrySkeleton,+} from '@/app/components/app/access-point/shared/web-app-access-control'import CustomizeModal from '@/app/components/app/overview/customize'import EmbeddedModal from '@/app/components/app/overview/embedded'import SettingsModal from '@/app/components/app/overview/settings'-import ShareQRCode from '@/app/components/base/qrcode'-import { AccessMode } from '@/models/access-control'+import { AccessPointCard } from '@/app/components/base/access-point/card'+import { AccessPointUrl } from '@/app/components/base/access-point/url'+import AppIcon from '@/app/components/base/app-icon'+import dynamic from '@/next/dynamic'import { consoleQuery } from '@/service/client'import { AppModeEnum } from '@/types/app'-import { AccessSurfaceCard } from './access-surface-card'-import { WebAppAccessControlButton } from './web-app-access-control-button'+import { useWebAppAccessControl } from './use-web-app-access-control'-function WebAppLaunchAction({- href,- label,- disabledReason,-}: {- href?: string- label: string- disabledReason?: string-}) {- const content = (- <>- <span aria-hidden className="i-ri-external-link-line size-4" />- {label}- </>- )-- if (href) {- return (- <a- href={href}- target="_blank"- rel="noreferrer"- aria-label={label}- className={buttonVariants({ variant: 'secondary', size: 'medium' })}- >- {content}- </a>- )- }-- const disabledButton = (- <Button- variant="secondary"- size="medium"- disabled- focusableWhenDisabled={Boolean(disabledReason)}- >- {content}- </Button>- )-- if (!disabledReason) return disabledButton-- return (- <Tooltip>- <TooltipTrigger render={disabledButton} />- <TooltipContent role="tooltip">{disabledReason}</TooltipContent>- </Tooltip>- )-}+const AccessControl = dynamic(() => import('@/app/components/app/app-access-control'), {+ ssr: false,+})export function WebAppAccessCard({agent,@@ -112,10 +69,11 @@ export function WebAppAccessCard({appId,}: null- const showSsoBadge = agent?.access_mode === AccessMode.EXTERNAL_MEMBERSconst [showCustomizeModal, setShowCustomizeModal] = useState(false)const [showEmbeddedModal, setShowEmbeddedModal] = useState(false)const [showSettingsModal, setShowSettingsModal] = useState(false)+ const [showAccessControl, setShowAccessControl] = useState(false)+ const accessControl = useWebAppAccessControl(agent, isLoading)const agentDetailQueryKey = consoleQuery.agent.byAgentId.get.queryKey({input: { params: { agent_id: agentId } },})@@ -173,7 +131,20 @@ export function WebAppAccessCard({toggleSiteMutation.isPending && pendingEnabled !== undefined? pendingEnabled: Boolean(agent?.enable_site)- const launchHref =+ const status = isLoading ? 'loading' : optimisticEnabled ? 'inService' : 'disabled'+ const statusLabel = isLoading+ ? tCommon(($) => $.loading)+ : t(+ ($) =>+ $[+ optimisticEnabled+ ? 'agentDetail.access.status.inService'+ : 'agentDetail.access.status.outOfService'+ ],+ )+ const icon = agent ? getSettingsIcon(agent) : null+ const notAvailableLabel = t(($) => $['agentDetail.access.workflow.notAvailable'])+ const openUrl =webAppUrl && agent?.enable_site && !toggleSiteMutation.isPending ? webAppUrl : undefinedconst publishRequiredMessage = t(($) => $['agentDetail.access.publishRequired'])const showPublishRequiredMessage = !isLoading && !accessReady@@ -249,70 +220,100 @@ export function WebAppAccessCard({}return (- <AccessSurfaceCard- title={t(($) => $['agentDetail.access.webApp.title'])}- icon="i-ri-window-line"- iconClassName="bg-state-accent-solid text-text-primary-on-surface"- endpointLabel={t(($) => $['agentDetail.access.webApp.accessUrl'])}- endpoint={webAppUrl}- enabled={optimisticEnabled}- onEnabledChange={handleEnabledChange}- copyLabel={t(($) => $['agentDetail.access.copyAccessUrl'])}- badge={showSsoBadge ? <SsoBadge /> : undefined}- endpointActions={- webAppUrl ? (+ <>+ <AccessPointCard+ className="min-h-55.5"+ headingLevel={3}+ title={t(($) => $['agentDetail.access.webApp.title'])}+ description={t(($) => $['agentDetail.access.webApp.description'])}+ icon={+ icon ? (+ <AppIcon+ size="large"+ iconType={icon.icon_type}+ icon={icon.icon}+ background={icon.icon_background}+ imageUrl={icon.icon_url}+ />+ ) : (+ 'i-ri-window-line'+ )+ }+ status={status}+ statusLabel={statusLabel}+ switchDisabled={isLoading || !canManageWebApp}+ switchDisabledReason={showPublishRequiredMessage ? publishRequiredMessage : undefined}+ switchLabel={t(($) => $['agentDetail.access.toggleSurface'], {+ name: t(($) => $['agentDetail.access.webApp.title']),+ })}+ onEnabledChange={handleEnabledChange}+ actions={<>- <span className="mx-1.5 h-3.5 w-px shrink-0 bg-divider-regular" />- <ShareQRCode content={webAppUrl} /><Button- variant="ghost"- size="small"- className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"- aria-label={t(($) => $['agentDetail.access.webApp.refreshUrl'])}- disabled={!canManageWebApp || resetAccessTokenMutation.isPending}- onClick={handleRefreshUrl}+ variant="secondary"+ disabled={!embeddedConfig}+ onClick={() => setShowEmbeddedModal(true)}+ className="flex items-center gap-1 px-3"+ >+ <span aria-hidden className="i-ri-window-line size-4" />+ {t(($) => $['agentDetail.access.webApp.actions.embedIntoSite'])}+ </Button>+ <Button+ variant="secondary"+ disabled={!customizeConfig}+ onClick={() => setShowCustomizeModal(true)}+ className="flex items-center gap-1 px-3"+ >+ <span aria-hidden className="i-custom-vender-deploy-code-block size-4" />+ {t(($) => $['agentDetail.access.webApp.actions.customFrontend'])}+ </Button>+ <Button+ variant="secondary"+ disabled={!settingsAppInfo || updateSiteMutation.isPending}+ onClick={() => setShowSettingsModal(true)}+ className="flex items-center gap-1 px-3">- <span aria-hidden className="i-ri-refresh-line size-4" />+ <span aria-hidden className="i-ri-equalizer-2-line size-4" />+ {t(($) => $['agentDetail.access.webApp.actions.settings'])}</Button></>- ) : undefined- }- disabled={isLoading || !canManageWebApp}- disabledReason={showPublishRequiredMessage ? publishRequiredMessage : undefined}- >- <WebAppLaunchAction- href={launchHref}- label={t(($) => $['agentDetail.access.webApp.actions.launch'])}- disabledReason={showPublishRequiredMessage ? publishRequiredMessage : undefined}- />- <Button- variant="secondary"- size="medium"- disabled={!embeddedConfig}- onClick={() => setShowEmbeddedModal(true)}- >- <span aria-hidden className="i-ri-window-line size-4" />- {t(($) => $['agentDetail.access.webApp.actions.embedded'])}- </Button>- <Button- variant="secondary"- size="medium"- disabled={!customizeConfig}- onClick={() => setShowCustomizeModal(true)}- >- <span aria-hidden className="i-ri-paint-brush-line size-4" />- {t(($) => $['agentDetail.access.webApp.actions.customize'])}- </Button>- <Button- variant="secondary"- size="medium"- disabled={!settingsAppInfo || updateSiteMutation.isPending}- onClick={() => setShowSettingsModal(true)}+ }>- <span aria-hidden className="i-ri-palette-line size-4" />- {t(($) => $['agentDetail.access.webApp.actions.settings'])}- </Button>- <WebAppAccessControlButton agent={agent} />+ <AccessPointUrl+ label={t(($) => $['agentDetail.access.webApp.accessUrl'])}+ value={webAppUrl || notAvailableLabel}+ enabled={optimisticEnabled}+ copyDisabled={!webAppUrl}+ loading={isLoading}+ unavailableLabel={notAvailableLabel}+ showOpen+ showQrCode+ showRegenerate+ openDisabledReason={showPublishRequiredMessage ? publishRequiredMessage : undefined}+ openLabel={t(($) => $['agentDetail.access.webApp.actions.open'])}+ openUrl={openUrl}+ qrCodeLabel={t(($) => $['agentDetail.access.webApp.showQrCode'])}+ qrCodeScanLabel={t(($) => $['agentDetail.access.webApp.qrCode.scanToShare'])}+ qrCodeDownloadLabel={t(($) => $['agentDetail.access.webApp.qrCode.download'])}+ regenerateLabel={t(($) => $['agentDetail.access.webApp.refreshUrl'])}+ regenerateDisabled={!canManageWebApp}+ regenerating={resetAccessTokenMutation.isPending}+ onRegenerate={handleRefreshUrl}+ copyLabel={t(($) => $['agentDetail.access.copyAccessUrl'])}+ copiedLabel={tCommon(($) => $['operation.copied'])}+ onCopyError={() => {+ toast.error(t(($) => $['agentDetail.access.copyFailed']))+ }}+ />+ {accessControl.state === 'loading' && <WebAppAccessControlEntrySkeleton loading />}+ {accessControl.state === 'ready' && (+ <WebAppAccessControlEntry+ {...accessControl.entryProps}+ onClick={() => setShowAccessControl(true)}+ />+ )}+ </AccessPointCard>+{settingsAppInfo && (<SettingsModalisChat@@ -341,7 +342,14 @@ export function WebAppAccessCard({webAppRoute="agent"/>)}- </AccessSurfaceCard>+ {showAccessControl && accessControl.state === 'ready' && (+ <AccessControl+ app={accessControl.app}+ onClose={() => setShowAccessControl(false)}+ onConfirm={() => setShowAccessControl(false)}+ />+ )}+ </>)}@@ -416,14 +424,3 @@ function getAgentWebAppUrl(agent?: AgentAppDetailWithSite) {site?.app_base_url || (typeof window === 'undefined' ? '' : window.location.origin)return `${baseUrl.replace(/\/$/, '')}/agent/${token}`}--function SsoBadge() {- const { t } = useTranslation('agentV2')-- return (- <span className="inline-flex h-4.5 shrink-0 items-center gap-1 rounded-sm border border-divider-deep px-1.5 system-2xs-semibold-uppercase text-text-tertiary">- <span aria-hidden className="i-ri-shield-check-line size-3" />- {t(($) => $['agentDetail.access.webApp.ssoEnabled'])}- </span>- )-}diff --git a/web/features/agent-v2/agent-detail/access/components/web-app-access-control-button.tsx b/web/features/agent-v2/agent-detail/access/components/web-app-access-control-button.tsxdeleted file mode 100644index 980476696d7..00000000000--- a/web/features/agent-v2/agent-detail/access/components/web-app-access-control-button.tsx+++ /dev/null@@ -1,61 +0,0 @@-'use client'--import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'-import { Button } from '@langgenius/dify-ui/button'-import { useSuspenseQuery } from '@tanstack/react-query'-import { useAtomValue } from 'jotai'-import { useState } from 'react'-import { useTranslation } from 'react-i18next'-import { workspacePermissionKeysAtom } from '@/context/permission-state'-import { userProfileQueryOptions } from '@/features/account-profile/client'-import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { isAccessMode } from '@/models/access-control'-import dynamic from '@/next/dynamic'-import { getAppACLCapabilities } from '@/utils/permission'--const AccessControl = dynamic(() => import('@/app/components/app/app-access-control'), {- ssr: false,-})--export function WebAppAccessControlButton({ agent }: { agent?: AgentAppDetailWithSite }) {- const { t } = useTranslation('agentV2')- const [showAccessControl, setShowAccessControl] = useState(false)- const appId = agent?.backing_app_id- const rawAccessMode = agent?.access_mode- const accessMode = isAccessMode(rawAccessMode) ? rawAccessMode : undefined- const { data: webAppAuthEnabled } = useSuspenseQuery({- ...systemFeaturesQueryOptions(),- select: (systemFeatures) => systemFeatures.webapp_auth.enabled,- })- const { data: currentUserId } = useSuspenseQuery({- ...userProfileQueryOptions(),- select: (data) => data.profile.id,- })- const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)- const { canReleaseAndVersion: canManageWebAppAccessControl } = getAppACLCapabilities(- agent?.permission_keys,- {- currentUserId,- resourceMaintainer: agent?.maintainer,- workspacePermissionKeys,- },- )-- if (!webAppAuthEnabled || !canManageWebAppAccessControl || !appId || !accessMode) return null-- return (- <>- <Button variant="secondary" size="medium" onClick={() => setShowAccessControl(true)}>- <span aria-hidden className="i-ri-lock-2-line size-4" />- {t(($) => $['agentDetail.access.webApp.actions.accessControl'])}- </Button>- {showAccessControl && (- <AccessControl- app={{ id: appId, access_mode: accessMode }}- onClose={() => setShowAccessControl(false)}- onConfirm={() => setShowAccessControl(false)}- />- )}- </>- )-}diff --git a/web/hooks/use-app-favicon.spec.ts b/web/hooks/use-app-favicon.spec.tsnew file mode 100644index 00000000000..dc83e02b4d6--- /dev/null+++ b/web/hooks/use-app-favicon.spec.ts@@ -0,0 +1,112 @@+import { renderHook, waitFor } from '@testing-library/react'+import { useAppFavicon } from './use-app-favicon'++vi.mock('@/utils/emoji', () => ({+ searchEmoji: vi.fn(async () => '🤖'),+}))++const firstAppIcon = 'https://example.com/app-one.png'+const secondAppIcon = 'https://example.com/app-two.png'++describe('useAppFavicon', () => {+ beforeEach(() => {+ document.head.querySelectorAll('link[rel*="icon"]').forEach((link) => link.remove())+ })++ afterEach(() => {+ document.head.querySelectorAll('link[rel*="icon"]').forEach((link) => link.remove())+ })++ it('leaves the framework favicon untouched and cleans up only its own icon', async () => {+ const frameworkFavicon = document.createElement('link')+ frameworkFavicon.rel = 'icon'+ frameworkFavicon.href = '/favicon.ico'+ document.head.appendChild(frameworkFavicon)++ const { unmount } = renderHook(() =>+ useAppFavicon({ icon_type: 'image', icon_url: firstAppIcon }),+ )++ await waitFor(() => {+ expect(document.head.querySelector('link[data-dify-app-favicon]')).toHaveAttribute(+ 'href',+ firstAppIcon,+ )+ })+ expect(frameworkFavicon.isConnected).toBe(true)+ expect(frameworkFavicon).toHaveAttribute('href', '/favicon.ico')++ unmount()++ expect(frameworkFavicon.isConnected).toBe(true)+ expect(document.head.querySelector('link[data-dify-app-favicon]')).not.toBeInTheDocument()+ })++ it('replaces its managed icon when the image URL changes and removes it when disabled', async () => {+ const { rerender } = renderHook(+ ({ enable, iconUrl }) => useAppFavicon({ enable, icon_type: 'image', icon_url: iconUrl }),+ {+ initialProps: { enable: true, iconUrl: firstAppIcon },+ },+ )++ await waitFor(() => {+ expect(document.head.querySelector('link[data-dify-app-favicon]')).toHaveAttribute(+ 'href',+ firstAppIcon,+ )+ })++ rerender({ enable: true, iconUrl: secondAppIcon })++ await waitFor(() => {+ expect(document.head.querySelector('link[data-dify-app-favicon]')).toHaveAttribute(+ 'href',+ secondAppIcon,+ )+ })+ expect(document.head.querySelectorAll('link[data-dify-app-favicon]')).toHaveLength(1)++ rerender({ enable: false, iconUrl: secondAppIcon })++ await waitFor(() => {+ expect(document.head.querySelector('link[data-dify-app-favicon]')).not.toBeInTheDocument()+ })+ })++ it('renders emoji icons as SVG favicons', async () => {+ renderHook(() =>+ useAppFavicon({ icon_type: 'emoji', icon: 'robot', icon_background: '#ffffff' }),+ )++ await waitFor(() => {+ const favicon = document.head.querySelector('link[data-dify-app-favicon]')+ expect(favicon).toHaveAttribute('rel', 'icon')+ expect(favicon).toHaveAttribute('type', 'image/svg+xml')+ expect(favicon?.getAttribute('href')).toContain('data:image/svg+xml')+ expect(favicon?.getAttribute('href')).toContain('%23ffffff')+ expect(favicon?.getAttribute('href')).toContain('🤖')+ })+ })++ it('uses linked icons as direct favicon URLs', async () => {+ renderHook(() => useAppFavicon({ icon_type: 'link', icon: firstAppIcon }))++ await waitFor(() => {+ expect(document.head.querySelector('link[data-dify-app-favicon]')).toHaveAttribute(+ 'href',+ firstAppIcon,+ )+ })+ })++ it('preserves the fallback icon for legacy null icon metadata', async () => {+ renderHook(() => useAppFavicon({ icon_type: null }))++ await waitFor(() => {+ expect(+ document.head.querySelector('link[data-dify-app-favicon]')?.getAttribute('href'),+ ).toContain('🤖')+ })+ })+})diff --git a/web/hooks/use-app-favicon.ts b/web/hooks/use-app-favicon.tsindex c6c493bef1f..1ef87c53a47 100644--- a/web/hooks/use-app-favicon.ts+++ b/web/hooks/use-app-favicon.ts@@ -1,5 +1,5 @@import type { AppIconType } from '@/types/app'-import { useAsyncEffect } from 'ahooks'+import { useEffect } from 'react'import { appDefaultIconBackground } from '@/config'import { searchEmoji } from '@/utils/emoji'@@ -14,25 +14,43 @@ type UseAppFaviconOptions = {export function useAppFavicon(options: UseAppFaviconOptions) {const { enable = true, icon_type = 'emoji', icon, icon_background, icon_url } = options- useAsyncEffect(async () => {- if (!enable || (icon_type === 'image' && !icon_url) || (icon_type === 'emoji' && !icon)) return+ useEffect(() => {+ let cancelled = false+ let favicon: HTMLLinkElement | null = null- const isValidImageIcon = icon_type === 'image' && icon_url+ const syncFavicon = async () => {+ let href: string | null | undefined+ let type: string | undefined- const link: HTMLLinkElement =- document.querySelector('link[rel*="icon"]') || document.createElement('link')+ if (icon_type === 'image') {+ href = icon_url+ } else if (icon_type === 'link') {+ href = icon+ } else if (icon_type !== 'emoji' || icon) {+ const emoji = icon ? await searchEmoji(icon) : '🤖'+ href =+ 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22>' ++ `<rect width=%22100%25%22 height=%22100%25%22 fill=%22${encodeURIComponent(icon_background || appDefaultIconBackground)}%22 rx=%2230%22 ry=%2230%22 />` ++ `<text x=%2212.5%22 y=%221em%22 font-size=%2275%22>${emoji}</text>` ++ '</svg>'+ type = 'image/svg+xml'+ }- link.href = isValidImageIcon- ? icon_url- : 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22>' +- `<rect width=%22100%25%22 height=%22100%25%22 fill=%22${encodeURIComponent(icon_background || appDefaultIconBackground)}%22 rx=%2230%22 ry=%2230%22 />` +- `<text x=%2212.5%22 y=%221em%22 font-size=%2275%22>${- icon ? await searchEmoji(icon) : '🤖'- }</text>` +- '</svg>'+ if (cancelled || !href) return- link.rel = 'shortcut icon'- link.type = 'image/svg'- document.getElementsByTagName('head')[0]!.appendChild(link)- }, [enable, icon, icon_background])+ favicon = document.createElement('link')+ favicon.dataset.difyAppFavicon = ''+ favicon.rel = 'icon'+ favicon.href = href+ if (type) favicon.type = type+ document.head.appendChild(favicon)+ }++ if (enable) void syncFavicon()++ return () => {+ cancelled = true+ favicon?.remove()+ }+ }, [enable, icon, icon_background, icon_type, icon_url])}diff --git a/web/hooks/use-document-title.spec.ts b/web/hooks/use-document-title.spec.tsindex 111de92e15b..0496cdaed8b 100644--- a/web/hooks/use-document-title.spec.ts+++ b/web/hooks/use-document-title.spec.ts@@ -2,6 +2,10 @@ import { renderHookWithConsoleQuery } from '@/test/console/query-data'import useDocumentTitle from './use-document-title'describe('useDocumentTitle', () => {+ afterEach(() => {+ document.head.querySelectorAll('link').forEach((link) => link.remove())+ })+it('keeps the title empty while system features are pending', () => {renderHookWithConsoleQuery(() => useDocumentTitle('Settings'), { systemFeatures: null })expect(document.title).toBe('')@@ -32,4 +36,25 @@ describe('useDocumentTitle', () => {expect(document.title).toBe('Route title - Dify')})++ it('does not mutate framework-owned favicon metadata', () => {+ const favicon = document.createElement('link')+ favicon.rel = 'icon'+ favicon.href = '/favicon.ico'+ document.head.appendChild(favicon)++ renderHookWithConsoleQuery(() => useDocumentTitle('Settings'), {+ systemFeatures: {+ branding: {+ application_title: 'Acme',+ enabled: true,+ favicon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>',+ },+ },+ })++ expect(favicon.isConnected).toBe(true)+ expect(favicon).toHaveAttribute('rel', 'icon')+ expect(favicon).toHaveAttribute('href', '/favicon.ico')+ })})diff --git a/web/i18n/ar-TN/agent-v-2.json b/web/i18n/ar-TN/agent-v-2.jsonindex 99f7e9d9853..c851c41328b 100644--- a/web/i18n/ar-TN/agent-v-2.json+++ b/web/i18n/ar-TN/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "انشر الوكيل لتفعيل هذا الخيار.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "نقطة نهاية API من جانب الخادم","agentDetail.access.serviceApi.endpoint": "نقطة نهاية API الخدمة","agentDetail.access.serviceApi.title": "API خدمة الواجهة الخلفية","agentDetail.access.status.inService": "في الخدمة","agentDetail.access.status.outOfService": "خارج الخدمة",+ "agentDetail.access.status.unavailable": "غير متاح","agentDetail.access.title": "نقطة الوصول","agentDetail.access.toggleSurface": "تبديل وصول {{name}}",- "agentDetail.access.webApp.accessUrl": "عنوان URL لتطبيق الويب",- "agentDetail.access.webApp.actions.accessControl": "التحكم في الوصول",- "agentDetail.access.webApp.actions.customize": "واجهة أمامية مخصصة",- "agentDetail.access.webApp.actions.embedded": "مضمّن",- "agentDetail.access.webApp.actions.launch": "تشغيل",- "agentDetail.access.webApp.actions.settings": "العلامة التجارية",+ "agentDetail.access.webApp.accessUrl": "رابط الوصول",+ "agentDetail.access.webApp.actions.customFrontend": "واجهة أمامية مخصصة",+ "agentDetail.access.webApp.actions.embedIntoSite": "تضمين في الموقع",+ "agentDetail.access.webApp.actions.open": "فتح",+ "agentDetail.access.webApp.actions.settings": "الإعدادات",+ "agentDetail.access.webApp.description": "تجربة ويب عامة",+ "agentDetail.access.webApp.qrCode.download": "تحميل رمز الاستجابة السريعة",+ "agentDetail.access.webApp.qrCode.scanToShare": "مسح للمشاركة","agentDetail.access.webApp.refreshUrl": "تحديث رابط الوصول",- "agentDetail.access.webApp.ssoEnabled": "SSO ممكّن",+ "agentDetail.access.webApp.showQrCode": "عرض رمز QR","agentDetail.access.webApp.title": "تطبيق الويب","agentDetail.access.workflow.description": "يُستخدم كعقدة داخل سير العمل","agentDetail.access.workflow.empty": "لا توجد مراجع سير عمل بعد.",diff --git a/web/i18n/ar-TN/deployments.json b/web/i18n/ar-TN/deployments.jsonindex 376a307540f..6951e5402b5 100644--- a/web/i18n/ar-TN/deployments.json+++ b/web/i18n/ar-TN/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "المزيد من الإجراءات","deployTab.redeploy": "إعادة النشر","deployTab.undeploy": "إلغاء النشر",+ "deployTab.undeployUnavailable": "لا يمكن إلغاء النشر لأن الإصدار الحالي غير متاح.","health.ENVIRONMENT_STATUS_FAILED": "غير متاح","list.emptyTitle": "لا توجد عمليات نشر بعد","overview.chip.latest": "الأحدث",@@ -66,11 +67,14 @@"studio.environments": "البيئات","studio.environmentsInUse": "{{used}} من أصل {{total}} بيئة قيد الاستخدام","studio.lastActivity": "آخر نشاط",+ "studio.latestVersionLoadFailed": "فشل الحصول على أحدث إصدار.","studio.liveVersion": "الإصدار النشط","studio.moreEnvironments": "المزيد من البيئات","studio.noCredentialsYet": "لا توجد بيانات اعتماد بعد","studio.noCredentialsYetDescription": "أضف بيانات اعتماد في عمليات التكامل أو إعدادات العقدة","studio.precheck.description": "يحتوي على أنواع عقد غير مدعومة بعد:",+ "studio.precheck.from": "من",+ "studio.precheck.nodeCount_other": "{{count}} عقد","studio.precheck.supportMessage": "سيتوفر دعم أنواع العقد هذه في إصدار مستقبلي.","studio.precheck.title": "لا يمكن نشر هذا الإصدار في هذه البيئة","studio.publisher.deployingVersion": "جاري النشر: {{version}}",diff --git a/web/i18n/de-DE/agent-v-2.json b/web/i18n/de-DE/agent-v-2.jsonindex a3a645b7652..19818a58f51 100644--- a/web/i18n/de-DE/agent-v-2.json+++ b/web/i18n/de-DE/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Veröffentliche den Agenten, um dies zu aktivieren.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Serverseitiger API-Endpunkt","agentDetail.access.serviceApi.endpoint": "Service-API-Endpunkt","agentDetail.access.serviceApi.title": "Backend-Service-API","agentDetail.access.status.inService": "In Betrieb","agentDetail.access.status.outOfService": "Außer Betrieb",+ "agentDetail.access.status.unavailable": "Nicht verfügbar","agentDetail.access.title": "Zugangspunkt","agentDetail.access.toggleSurface": "Zugriff von {{name}} umschalten",- "agentDetail.access.webApp.accessUrl": "Webapp-URL",- "agentDetail.access.webApp.actions.accessControl": "Zugriffskontrolle",- "agentDetail.access.webApp.actions.customize": "Benutzerdefiniertes Frontend",- "agentDetail.access.webApp.actions.embedded": "Eingebettet",- "agentDetail.access.webApp.actions.launch": "Starten",- "agentDetail.access.webApp.actions.settings": "Branding",+ "agentDetail.access.webApp.accessUrl": "Zugriffs-URL",+ "agentDetail.access.webApp.actions.customFrontend": "Benutzerdefiniertes Frontend",+ "agentDetail.access.webApp.actions.embedIntoSite": "In Website einbetten",+ "agentDetail.access.webApp.actions.open": "Öffnen",+ "agentDetail.access.webApp.actions.settings": "Einstellungen",+ "agentDetail.access.webApp.description": "Öffentliches Web-Erlebnis",+ "agentDetail.access.webApp.qrCode.download": "QR-Code herunterladen",+ "agentDetail.access.webApp.qrCode.scanToShare": "Scannen zum Teilen","agentDetail.access.webApp.refreshUrl": "Zugriffs-URL aktualisieren",- "agentDetail.access.webApp.ssoEnabled": "SSO aktiviert",+ "agentDetail.access.webApp.showQrCode": "QR-Code anzeigen","agentDetail.access.webApp.title": "Webapp","agentDetail.access.workflow.description": "Wird als Knoten innerhalb des Workflows verwendet","agentDetail.access.workflow.empty": "Noch keine Workflow-Referenzen.",diff --git a/web/i18n/de-DE/deployments.json b/web/i18n/de-DE/deployments.jsonindex 9b2cb74ec73..5e8e411e2ab 100644--- a/web/i18n/de-DE/deployments.json+++ b/web/i18n/de-DE/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Weitere Aktionen","deployTab.redeploy": "Erneut bereitstellen","deployTab.undeploy": "Bereitstellung aufheben",+ "deployTab.undeployUnavailable": "Die Bereitstellung kann nicht aufgehoben werden, da die aktuelle Version nicht verfügbar ist.","health.ENVIRONMENT_STATUS_FAILED": "Nicht verfügbar","list.emptyTitle": "Noch keine Bereitstellungen","overview.chip.latest": "neueste",@@ -66,11 +67,14 @@"studio.environments": "Umgebungen","studio.environmentsInUse": "{{used}} von {{total}} Umgebungen in Verwendung","studio.lastActivity": "Letzte Aktivität",+ "studio.latestVersionLoadFailed": "Die neueste Version konnte nicht abgerufen werden.","studio.liveVersion": "Live-Version","studio.moreEnvironments": "Weitere Umgebungen","studio.noCredentialsYet": "Noch keine Anmeldedaten","studio.noCredentialsYetDescription": "Fügen Sie Anmeldedaten in Integrationen oder den Knoteneinstellungen hinzu","studio.precheck.description": "Sie enthält Knotentypen, die noch nicht unterstützt werden:",+ "studio.precheck.from": "Von",+ "studio.precheck.nodeCount_other": "{{count}} Knoten","studio.precheck.supportMessage": "Die Unterstützung für diese Knotentypen wird in einer zukünftigen Version verfügbar sein.","studio.precheck.title": "Diese Version kann nicht in dieser Umgebung bereitgestellt werden","studio.publisher.deployingVersion": "Wird bereitgestellt: {{version}}",diff --git a/web/i18n/en-US/agent-v-2.json b/web/i18n/en-US/agent-v-2.jsonindex fd66a0f0f5b..236834f23fb 100644--- a/web/i18n/en-US/agent-v-2.json+++ b/web/i18n/en-US/agent-v-2.json@@ -7,21 +7,25 @@"agentDetail.access.publishRequired": "Publish the agent to turn this on.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Server-side API endpoint","agentDetail.access.serviceApi.endpoint": "Service API Endpoint",- "agentDetail.access.serviceApi.title": "Backend Service API",+ "agentDetail.access.serviceApi.title": "Backend service API","agentDetail.access.status.inService": "In service","agentDetail.access.status.outOfService": "Out of service",+ "agentDetail.access.status.unavailable": "Unavailable","agentDetail.access.title": "Access Point","agentDetail.access.toggleSurface": "Toggle {{name}} access",- "agentDetail.access.webApp.accessUrl": "Web App URL",- "agentDetail.access.webApp.actions.accessControl": "Access Control",- "agentDetail.access.webApp.actions.customize": "Custom Frontend",- "agentDetail.access.webApp.actions.embedded": "Embedded",- "agentDetail.access.webApp.actions.launch": "Launch",- "agentDetail.access.webApp.actions.settings": "Branding",+ "agentDetail.access.webApp.accessUrl": "Access URL",+ "agentDetail.access.webApp.actions.customFrontend": "Custom frontend",+ "agentDetail.access.webApp.actions.embedIntoSite": "Embed Into Site",+ "agentDetail.access.webApp.actions.open": "Open",+ "agentDetail.access.webApp.actions.settings": "Settings",+ "agentDetail.access.webApp.description": "Public web experience",+ "agentDetail.access.webApp.qrCode.download": "Download QR Code",+ "agentDetail.access.webApp.qrCode.scanToShare": "Scan to share","agentDetail.access.webApp.refreshUrl": "Refresh access URL",- "agentDetail.access.webApp.ssoEnabled": "SSO Enabled",- "agentDetail.access.webApp.title": "Web App",+ "agentDetail.access.webApp.showQrCode": "Show QR code",+ "agentDetail.access.webApp.title": "Web app","agentDetail.access.workflow.description": "Used as a node inside the workflow","agentDetail.access.workflow.empty": "No workflow references yet.","agentDetail.access.workflow.loadFailed": "Failed to load workflow references.",diff --git a/web/i18n/en-US/deployments.json b/web/i18n/en-US/deployments.jsonindex b09ce1ec8bf..dbc046fb923 100644--- a/web/i18n/en-US/deployments.json+++ b/web/i18n/en-US/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "More actions","deployTab.redeploy": "Redeploy","deployTab.undeploy": "Undeploy",+ "deployTab.undeployUnavailable": "Cannot undeploy because the current version is unavailable.","health.ENVIRONMENT_STATUS_FAILED": "Unavailable","list.emptyTitle": "No deployments yet","overview.chip.latest": "latest",@@ -66,11 +67,14 @@"studio.environments": "Environments","studio.environmentsInUse": "{{used}} of {{total}} environments in use","studio.lastActivity": "Last activity",+ "studio.latestVersionLoadFailed": "Failed to get the latest version.","studio.liveVersion": "Live version","studio.moreEnvironments": "More environments","studio.noCredentialsYet": "No credentials yet","studio.noCredentialsYetDescription": "Add credentials in Integrations or node settings","studio.precheck.description": "It contains node types that are not yet supported:",+ "studio.precheck.from": "From",+ "studio.precheck.nodeCount_other": "{{count}} nodes","studio.precheck.supportMessage": "Support for these node types is coming in a future release.","studio.precheck.title": "This version can't be deployed to this environment","studio.publisher.deployingVersion": "Deploying: {{version}}",diff --git a/web/i18n/es-ES/agent-v-2.json b/web/i18n/es-ES/agent-v-2.jsonindex 358d64d45b4..9972e093003 100644--- a/web/i18n/es-ES/agent-v-2.json+++ b/web/i18n/es-ES/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Publica el agente para activar esta opción.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Endpoint de API del lado del servidor","agentDetail.access.serviceApi.endpoint": "Endpoint de la API de servicio","agentDetail.access.serviceApi.title": "API de servicio backend","agentDetail.access.status.inService": "En servicio","agentDetail.access.status.outOfService": "Fuera de servicio",+ "agentDetail.access.status.unavailable": "No disponible","agentDetail.access.title": "Punto de acceso","agentDetail.access.toggleSurface": "Alternar acceso de {{name}}",- "agentDetail.access.webApp.accessUrl": "URL de la aplicación web",- "agentDetail.access.webApp.actions.accessControl": "Control de Acceso",- "agentDetail.access.webApp.actions.customize": "Frontend personalizado",- "agentDetail.access.webApp.actions.embedded": "Incrustado",- "agentDetail.access.webApp.actions.launch": "Iniciar",- "agentDetail.access.webApp.actions.settings": "Marca",+ "agentDetail.access.webApp.accessUrl": "URL de acceso",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend personalizado",+ "agentDetail.access.webApp.actions.embedIntoSite": "Insertar en el sitio",+ "agentDetail.access.webApp.actions.open": "Abrir",+ "agentDetail.access.webApp.actions.settings": "Configuración",+ "agentDetail.access.webApp.description": "Experiencia web pública",+ "agentDetail.access.webApp.qrCode.download": "Descargar código QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Escanear para compartir","agentDetail.access.webApp.refreshUrl": "Actualizar URL de acceso",- "agentDetail.access.webApp.ssoEnabled": "SSO habilitado",+ "agentDetail.access.webApp.showQrCode": "Mostrar código QR","agentDetail.access.webApp.title": "Aplicación web","agentDetail.access.workflow.description": "Usado como un nodo dentro del flujo de trabajo","agentDetail.access.workflow.empty": "Aún no hay referencias de flujo de trabajo.",diff --git a/web/i18n/es-ES/deployments.json b/web/i18n/es-ES/deployments.jsonindex a5c23989579..c106c952abd 100644--- a/web/i18n/es-ES/deployments.json+++ b/web/i18n/es-ES/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Más acciones","deployTab.redeploy": "Volver a desplegar","deployTab.undeploy": "Retirar despliegue",+ "deployTab.undeployUnavailable": "No se puede retirar el despliegue porque la versión actual no está disponible.","health.ENVIRONMENT_STATUS_FAILED": "No disponible","list.emptyTitle": "Aún no hay despliegues","overview.chip.latest": "última",@@ -66,11 +67,14 @@"studio.environments": "Entornos","studio.environmentsInUse": "{{used}} de {{total}} entornos en uso","studio.lastActivity": "Última actividad",+ "studio.latestVersionLoadFailed": "No se pudo obtener la versión más reciente.","studio.liveVersion": "Versión activa","studio.moreEnvironments": "Más entornos","studio.noCredentialsYet": "Aún no hay credenciales","studio.noCredentialsYetDescription": "Añade credenciales en Integraciones o en la configuración del nodo","studio.precheck.description": "Contiene tipos de nodos que aún no son compatibles:",+ "studio.precheck.from": "De",+ "studio.precheck.nodeCount_other": "{{count}} nodos","studio.precheck.supportMessage": "La compatibilidad con estos tipos de nodos estará disponible en una versión futura.","studio.precheck.title": "Esta versión no se puede implementar en este entorno","studio.publisher.deployingVersion": "Desplegando: {{version}}",diff --git a/web/i18n/fa-IR/agent-v-2.json b/web/i18n/fa-IR/agent-v-2.jsonindex d30c1d85a28..de8b71226c7 100644--- a/web/i18n/fa-IR/agent-v-2.json+++ b/web/i18n/fa-IR/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "برای فعال کردن این گزینه، عامل را منتشر کنید.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "نقطه پایانی API سمت سرور","agentDetail.access.serviceApi.endpoint": "نقطه پایانی API سرویس","agentDetail.access.serviceApi.title": "API سرویس بکاند","agentDetail.access.status.inService": "در حال سرویسدهی","agentDetail.access.status.outOfService": "خارج از سرویس",+ "agentDetail.access.status.unavailable": "در دسترس نیست","agentDetail.access.title": "نقطه دسترسی","agentDetail.access.toggleSurface": "تغییر دسترسی {{name}}",- "agentDetail.access.webApp.accessUrl": "نشانی URL برنامه وب",- "agentDetail.access.webApp.actions.accessControl": "کنترل دسترسی",- "agentDetail.access.webApp.actions.customize": "فرانتاند سفارشی",- "agentDetail.access.webApp.actions.embedded": "تعبیهشده",- "agentDetail.access.webApp.actions.launch": "راهاندازی",- "agentDetail.access.webApp.actions.settings": "برندسازی",+ "agentDetail.access.webApp.accessUrl": "نشانی دسترسی",+ "agentDetail.access.webApp.actions.customFrontend": "فرانتاند سفارشی",+ "agentDetail.access.webApp.actions.embedIntoSite": "جاسازی در سایت",+ "agentDetail.access.webApp.actions.open": "باز کردن",+ "agentDetail.access.webApp.actions.settings": "تنظیمات",+ "agentDetail.access.webApp.description": "تجربه وب عمومی",+ "agentDetail.access.webApp.qrCode.download": "دانلود کد QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "اسکن برای اشتراکگذاری","agentDetail.access.webApp.refreshUrl": "تازهسازی URL دسترسی",- "agentDetail.access.webApp.ssoEnabled": "SSO فعال",+ "agentDetail.access.webApp.showQrCode": "نمایش کد QR","agentDetail.access.webApp.title": "برنامه وب","agentDetail.access.workflow.description": "به عنوان یک گره در داخل گردش کار استفاده میشود","agentDetail.access.workflow.empty": "هنوز مرجع گردش کاری وجود ندارد.",diff --git a/web/i18n/fa-IR/deployments.json b/web/i18n/fa-IR/deployments.jsonindex cfc24ffa3be..a92a966c5ca 100644--- a/web/i18n/fa-IR/deployments.json+++ b/web/i18n/fa-IR/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "اقدامات بیشتر","deployTab.redeploy": "استقرار مجدد","deployTab.undeploy": "لغو استقرار",+ "deployTab.undeployUnavailable": "بهدلیل در دسترس نبودن نسخه فعلی، لغو استقرار امکانپذیر نیست.","health.ENVIRONMENT_STATUS_FAILED": "در دسترس نیست","list.emptyTitle": "هنوز استقراری وجود ندارد","overview.chip.latest": "آخرین",@@ -66,11 +67,14 @@"studio.environments": "محیطها","studio.environmentsInUse": "{{used}} از {{total}} محیط در حال استفاده","studio.lastActivity": "آخرین فعالیت",+ "studio.latestVersionLoadFailed": "دریافت آخرین نسخه ناموفق بود.","studio.liveVersion": "نسخه فعال","studio.moreEnvironments": "محیطهای بیشتر","studio.noCredentialsYet": "هنوز اعتبارنامهای وجود ندارد","studio.noCredentialsYetDescription": "اعتبارنامهها را در بخش یکپارچهسازیها یا تنظیمات گره اضافه کنید","studio.precheck.description": "این نسخه شامل انواع گرهای است که هنوز پشتیبانی نمیشوند:",+ "studio.precheck.from": "از",+ "studio.precheck.nodeCount_other": "{{count}} گره","studio.precheck.supportMessage": "پشتیبانی از این انواع گره در نسخهای آینده ارائه خواهد شد.","studio.precheck.title": "این نسخه را نمیتوان در این محیط مستقر کرد","studio.publisher.deployingVersion": "در حال استقرار: {{version}}",diff --git a/web/i18n/fr-FR/agent-v-2.json b/web/i18n/fr-FR/agent-v-2.jsonindex c1c76c2dcfd..59d030e5131 100644--- a/web/i18n/fr-FR/agent-v-2.json+++ b/web/i18n/fr-FR/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Publiez l’agent pour activer cette option.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Point de terminaison d’API côté serveur","agentDetail.access.serviceApi.endpoint": "Point de terminaison de l’API de service","agentDetail.access.serviceApi.title": "API de service backend","agentDetail.access.status.inService": "En service","agentDetail.access.status.outOfService": "Hors service",+ "agentDetail.access.status.unavailable": "Indisponible","agentDetail.access.title": "Point d’accès","agentDetail.access.toggleSurface": "Basculer l’accès de {{name}}",- "agentDetail.access.webApp.accessUrl": "URL de l’application web",- "agentDetail.access.webApp.actions.accessControl": "Contrôle d'accès",- "agentDetail.access.webApp.actions.customize": "Frontend personnalisé",- "agentDetail.access.webApp.actions.embedded": "Intégré",- "agentDetail.access.webApp.actions.launch": "Lancer",- "agentDetail.access.webApp.actions.settings": "Image de marque",+ "agentDetail.access.webApp.accessUrl": "URL d’accès",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend personnalisé",+ "agentDetail.access.webApp.actions.embedIntoSite": "Intégrer au site",+ "agentDetail.access.webApp.actions.open": "Ouvrir",+ "agentDetail.access.webApp.actions.settings": "Paramètres",+ "agentDetail.access.webApp.description": "Expérience web publique",+ "agentDetail.access.webApp.qrCode.download": "Télécharger le code QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Scanner pour partager","agentDetail.access.webApp.refreshUrl": "Actualiser l’URL d’accès",- "agentDetail.access.webApp.ssoEnabled": "SSO activé",+ "agentDetail.access.webApp.showQrCode": "Afficher le code QR","agentDetail.access.webApp.title": "Application web","agentDetail.access.workflow.description": "Utilisé en tant que nœud à l’intérieur du workflow","agentDetail.access.workflow.empty": "Aucune référence de workflow pour l’instant.",diff --git a/web/i18n/fr-FR/deployments.json b/web/i18n/fr-FR/deployments.jsonindex c0a04e4685e..f8944a8329f 100644--- a/web/i18n/fr-FR/deployments.json+++ b/web/i18n/fr-FR/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Plus d'actions","deployTab.redeploy": "Redéployer","deployTab.undeploy": "Annuler le déploiement",+ "deployTab.undeployUnavailable": "Impossible d'annuler le déploiement car la version actuelle n'est pas disponible.","health.ENVIRONMENT_STATUS_FAILED": "Indisponible","list.emptyTitle": "Aucun déploiement pour le moment","overview.chip.latest": "dernière",@@ -66,11 +67,14 @@"studio.environments": "Environnements","studio.environmentsInUse": "{{used}} environnements sur {{total}} utilisés","studio.lastActivity": "Dernière activité",+ "studio.latestVersionLoadFailed": "Impossible de récupérer la dernière version.","studio.liveVersion": "Version active","studio.moreEnvironments": "Plus d’environnements","studio.noCredentialsYet": "Aucun identifiant pour le moment","studio.noCredentialsYetDescription": "Ajoutez des identifiants dans Intégrations ou dans les paramètres du nœud","studio.precheck.description": "Elle contient des types de nœuds qui ne sont pas encore pris en charge :",+ "studio.precheck.from": "De",+ "studio.precheck.nodeCount_other": "{{count}} nœuds","studio.precheck.supportMessage": "La prise en charge de ces types de nœuds sera disponible dans une prochaine version.","studio.precheck.title": "Cette version ne peut pas être déployée dans cet environnement","studio.publisher.deployingVersion": "Déploiement en cours : {{version}}",diff --git a/web/i18n/hi-IN/agent-v-2.json b/web/i18n/hi-IN/agent-v-2.jsonindex 27d1644c182..2e9ac346919 100644--- a/web/i18n/hi-IN/agent-v-2.json+++ b/web/i18n/hi-IN/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "इसे चालू करने के लिए एजेंट प्रकाशित करें।","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "सर्वर-साइड API एंडपॉइंट","agentDetail.access.serviceApi.endpoint": "सेवा API एंडपॉइंट","agentDetail.access.serviceApi.title": "बैकएंड सेवा API","agentDetail.access.status.inService": "सेवा में","agentDetail.access.status.outOfService": "सेवा से बाहर",+ "agentDetail.access.status.unavailable": "अनुपलब्ध","agentDetail.access.title": "एक्सेस पॉइंट","agentDetail.access.toggleSurface": "{{name}} एक्सेस टॉगल करें",- "agentDetail.access.webApp.accessUrl": "वेब ऐप URL",- "agentDetail.access.webApp.actions.accessControl": "पहुँच नियंत्रण",- "agentDetail.access.webApp.actions.customize": "कस्टम फ्रंटएंड",- "agentDetail.access.webApp.actions.embedded": "एम्बेडेड",- "agentDetail.access.webApp.actions.launch": "लॉन्च करें",- "agentDetail.access.webApp.actions.settings": "ब्रांडिंग",+ "agentDetail.access.webApp.accessUrl": "एक्सेस URL",+ "agentDetail.access.webApp.actions.customFrontend": "कस्टम फ्रंटएंड",+ "agentDetail.access.webApp.actions.embedIntoSite": "साइट में एम्बेड करें",+ "agentDetail.access.webApp.actions.open": "खोलें",+ "agentDetail.access.webApp.actions.settings": "सेटिंग्स",+ "agentDetail.access.webApp.description": "सार्वजनिक वेब अनुभव",+ "agentDetail.access.webApp.qrCode.download": "क्यूआर कोड डाउनलोड करें",+ "agentDetail.access.webApp.qrCode.scanToShare": "साझा करने के लिए स्कैन करें","agentDetail.access.webApp.refreshUrl": "एक्सेस URL रीफ़्रेश करें",- "agentDetail.access.webApp.ssoEnabled": "SSO सक्षम",+ "agentDetail.access.webApp.showQrCode": "QR कोड दिखाएँ","agentDetail.access.webApp.title": "वेब ऐप","agentDetail.access.workflow.description": "वर्कफ़्लो के अंदर एक नोड के रूप में उपयोग किया जाता है","agentDetail.access.workflow.empty": "अभी तक कोई वर्कफ़्लो संदर्भ नहीं।",diff --git a/web/i18n/hi-IN/deployments.json b/web/i18n/hi-IN/deployments.jsonindex 39e0fd5ac5c..2ee9198915f 100644--- a/web/i18n/hi-IN/deployments.json+++ b/web/i18n/hi-IN/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "अधिक क्रियाएँ","deployTab.redeploy": "पुनः डिप्लॉय करें","deployTab.undeploy": "अनडिप्लॉय करें",+ "deployTab.undeployUnavailable": "वर्तमान संस्करण उपलब्ध नहीं होने के कारण अनडिप्लॉय नहीं किया जा सकता।","health.ENVIRONMENT_STATUS_FAILED": "अनुपलब्ध","list.emptyTitle": "अभी तक कोई डिप्लॉयमेंट नहीं","overview.chip.latest": "नवीनतम",@@ -66,11 +67,14 @@"studio.environments": "एनवायरनमेंट","studio.environmentsInUse": "{{total}} में से {{used}} एनवायरनमेंट उपयोग में","studio.lastActivity": "पिछली गतिविधि",+ "studio.latestVersionLoadFailed": "नवीनतम संस्करण प्राप्त नहीं हो सका।","studio.liveVersion": "लाइव वर्शन","studio.moreEnvironments": "अधिक एनवायरनमेंट","studio.noCredentialsYet": "अभी तक कोई क्रेडेंशियल नहीं","studio.noCredentialsYetDescription": "इंटीग्रेशन या नोड सेटिंग में क्रेडेंशियल जोड़ें","studio.precheck.description": "इसमें ऐसे नोड प्रकार हैं जो अभी समर्थित नहीं हैं:",+ "studio.precheck.from": "से",+ "studio.precheck.nodeCount_other": "{{count}} नोड","studio.precheck.supportMessage": "इन नोड प्रकारों के लिए समर्थन भविष्य के रिलीज़ में उपलब्ध होगा।","studio.precheck.title": "इस संस्करण को इस परिवेश में डिप्लॉय नहीं किया जा सकता","studio.publisher.deployingVersion": "डिप्लॉय हो रहा है: {{version}}",diff --git a/web/i18n/id-ID/agent-v-2.json b/web/i18n/id-ID/agent-v-2.jsonindex d8309d747b4..0076eedfaf3 100644--- a/web/i18n/id-ID/agent-v-2.json+++ b/web/i18n/id-ID/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Publikasikan agen untuk mengaktifkannya.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Endpoint API sisi server","agentDetail.access.serviceApi.endpoint": "Endpoint API Layanan","agentDetail.access.serviceApi.title": "API layanan backend","agentDetail.access.status.inService": "Beroperasi","agentDetail.access.status.outOfService": "Tidak beroperasi",+ "agentDetail.access.status.unavailable": "Tidak tersedia","agentDetail.access.title": "Titik Akses","agentDetail.access.toggleSurface": "Alihkan akses {{name}}",- "agentDetail.access.webApp.accessUrl": "URL Aplikasi Web",- "agentDetail.access.webApp.actions.accessControl": "Kontrol Akses",- "agentDetail.access.webApp.actions.customize": "Frontend Kustom",- "agentDetail.access.webApp.actions.embedded": "Tertanam",- "agentDetail.access.webApp.actions.launch": "Luncurkan",- "agentDetail.access.webApp.actions.settings": "Branding",+ "agentDetail.access.webApp.accessUrl": "URL akses",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend kustom",+ "agentDetail.access.webApp.actions.embedIntoSite": "Sematkan ke situs",+ "agentDetail.access.webApp.actions.open": "Buka",+ "agentDetail.access.webApp.actions.settings": "Pengaturan",+ "agentDetail.access.webApp.description": "Pengalaman web publik",+ "agentDetail.access.webApp.qrCode.download": "Unduh Kode QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Pindai untuk berbagi","agentDetail.access.webApp.refreshUrl": "Segarkan URL akses",- "agentDetail.access.webApp.ssoEnabled": "SSO Diaktifkan",+ "agentDetail.access.webApp.showQrCode": "Tampilkan kode QR","agentDetail.access.webApp.title": "Aplikasi Web","agentDetail.access.workflow.description": "Digunakan sebagai simpul di dalam alur kerja","agentDetail.access.workflow.empty": "Belum ada referensi alur kerja.",diff --git a/web/i18n/id-ID/deployments.json b/web/i18n/id-ID/deployments.jsonindex d819f7f8ac7..7b1acc4817c 100644--- a/web/i18n/id-ID/deployments.json+++ b/web/i18n/id-ID/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Aksi lainnya","deployTab.redeploy": "Terapkan Ulang","deployTab.undeploy": "Batalkan Penerapan",+ "deployTab.undeployUnavailable": "Tidak dapat membatalkan penerapan karena versi saat ini tidak tersedia.","health.ENVIRONMENT_STATUS_FAILED": "Tidak tersedia","list.emptyTitle": "Belum ada penerapan","overview.chip.latest": "terbaru",@@ -66,11 +67,14 @@"studio.environments": "Lingkungan","studio.environmentsInUse": "{{used}} dari {{total}} lingkungan digunakan","studio.lastActivity": "Aktivitas terakhir",+ "studio.latestVersionLoadFailed": "Gagal mendapatkan versi terbaru.","studio.liveVersion": "Versi aktif","studio.moreEnvironments": "Lingkungan lainnya","studio.noCredentialsYet": "Belum ada kredensial","studio.noCredentialsYetDescription": "Tambahkan kredensial di Integrasi atau pengaturan node","studio.precheck.description": "Versi ini berisi jenis node yang belum didukung:",+ "studio.precheck.from": "Dari",+ "studio.precheck.nodeCount_other": "{{count}} simpul","studio.precheck.supportMessage": "Dukungan untuk jenis node ini akan tersedia dalam rilis mendatang.","studio.precheck.title": "Versi ini tidak dapat diterapkan ke lingkungan ini","studio.publisher.deployingVersion": "Menerapkan: {{version}}",diff --git a/web/i18n/it-IT/agent-v-2.json b/web/i18n/it-IT/agent-v-2.jsonindex 1191c6b30e5..7d6b291432e 100644--- a/web/i18n/it-IT/agent-v-2.json+++ b/web/i18n/it-IT/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Pubblica l’agente per attivare questa opzione.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Endpoint API lato server","agentDetail.access.serviceApi.endpoint": "Endpoint dell’API di servizio","agentDetail.access.serviceApi.title": "API di servizio backend","agentDetail.access.status.inService": "In servizio","agentDetail.access.status.outOfService": "Fuori servizio",+ "agentDetail.access.status.unavailable": "Non disponibile","agentDetail.access.title": "Punto di accesso","agentDetail.access.toggleSurface": "Attiva/disattiva accesso di {{name}}",- "agentDetail.access.webApp.accessUrl": "URL dell’app web",- "agentDetail.access.webApp.actions.accessControl": "Controllo di accesso",- "agentDetail.access.webApp.actions.customize": "Frontend personalizzato",- "agentDetail.access.webApp.actions.embedded": "Incorporato",- "agentDetail.access.webApp.actions.launch": "Avvia",- "agentDetail.access.webApp.actions.settings": "Branding",+ "agentDetail.access.webApp.accessUrl": "URL di accesso",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend personalizzato",+ "agentDetail.access.webApp.actions.embedIntoSite": "Incorpora nel sito",+ "agentDetail.access.webApp.actions.open": "Apri",+ "agentDetail.access.webApp.actions.settings": "Impostazioni",+ "agentDetail.access.webApp.description": "Esperienza web pubblica",+ "agentDetail.access.webApp.qrCode.download": "Scarica Codice QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Scansiona per condividere","agentDetail.access.webApp.refreshUrl": "Aggiorna URL di accesso",- "agentDetail.access.webApp.ssoEnabled": "SSO abilitato",+ "agentDetail.access.webApp.showQrCode": "Mostra codice QR","agentDetail.access.webApp.title": "App web","agentDetail.access.workflow.description": "Usato come nodo all’interno del workflow","agentDetail.access.workflow.empty": "Nessun riferimento al workflow al momento.",diff --git a/web/i18n/it-IT/deployments.json b/web/i18n/it-IT/deployments.jsonindex 412bc2b0221..ce823dc8737 100644--- a/web/i18n/it-IT/deployments.json+++ b/web/i18n/it-IT/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Altre azioni","deployTab.redeploy": "Ridistribuisci","deployTab.undeploy": "Annulla distribuzione",+ "deployTab.undeployUnavailable": "Impossibile annullare la distribuzione perché la versione corrente non è disponibile.","health.ENVIRONMENT_STATUS_FAILED": "Non disponibile","list.emptyTitle": "Ancora nessuna distribuzione","overview.chip.latest": "più recente",@@ -66,11 +67,14 @@"studio.environments": "Ambienti","studio.environmentsInUse": "{{used}} ambienti su {{total}} in uso","studio.lastActivity": "Ultima attività",+ "studio.latestVersionLoadFailed": "Impossibile recuperare la versione più recente.","studio.liveVersion": "Versione attiva","studio.moreEnvironments": "Altri ambienti","studio.noCredentialsYet": "Nessuna credenziale per ora","studio.noCredentialsYetDescription": "Aggiungi le credenziali in Integrazioni o nelle impostazioni del nodo","studio.precheck.description": "Contiene tipi di nodi non ancora supportati:",+ "studio.precheck.from": "Da",+ "studio.precheck.nodeCount_other": "{{count}} nodi","studio.precheck.supportMessage": "Il supporto per questi tipi di nodi sarà disponibile in una versione futura.","studio.precheck.title": "Questa versione non può essere distribuita in questo ambiente","studio.publisher.deployingVersion": "Distribuzione in corso: {{version}}",diff --git a/web/i18n/ja-JP/agent-v-2.json b/web/i18n/ja-JP/agent-v-2.jsonindex e77ea7dd9c7..df7c3c9220d 100644--- a/web/i18n/ja-JP/agent-v-2.json+++ b/web/i18n/ja-JP/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Agent を公開すると有効にできます。","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "サーバー側 API エンドポイント","agentDetail.access.serviceApi.endpoint": "サービス API エンドポイント","agentDetail.access.serviceApi.title": "バックエンドサービス API","agentDetail.access.status.inService": "稼働中","agentDetail.access.status.outOfService": "停止中",+ "agentDetail.access.status.unavailable": "利用不可","agentDetail.access.title": "アクセスポイント","agentDetail.access.toggleSurface": "{{name}} のアクセスを切り替え",- "agentDetail.access.webApp.accessUrl": "Web アプリ URL",- "agentDetail.access.webApp.actions.accessControl": "アクセス制御",- "agentDetail.access.webApp.actions.customize": "カスタムフロントエンド",- "agentDetail.access.webApp.actions.embedded": "埋め込み",- "agentDetail.access.webApp.actions.launch": "起動",- "agentDetail.access.webApp.actions.settings": "ブランディング",+ "agentDetail.access.webApp.accessUrl": "アクセス URL",+ "agentDetail.access.webApp.actions.customFrontend": "カスタムフロントエンド",+ "agentDetail.access.webApp.actions.embedIntoSite": "サイトに埋め込む",+ "agentDetail.access.webApp.actions.open": "開く",+ "agentDetail.access.webApp.actions.settings": "設定",+ "agentDetail.access.webApp.description": "公開 Web エクスペリエンス",+ "agentDetail.access.webApp.qrCode.download": "QR コードをダウンロード",+ "agentDetail.access.webApp.qrCode.scanToShare": "スキャンして共有","agentDetail.access.webApp.refreshUrl": "アクセス URL を更新",- "agentDetail.access.webApp.ssoEnabled": "SSO 有効",+ "agentDetail.access.webApp.showQrCode": "QR コードを表示","agentDetail.access.webApp.title": "Web アプリ","agentDetail.access.workflow.description": "ワークフロー内のノードとして使用","agentDetail.access.workflow.empty": "ワークフロー参照はまだありません。",diff --git a/web/i18n/ja-JP/deployments.json b/web/i18n/ja-JP/deployments.jsonindex 43989764a20..8d2c18aca21 100644--- a/web/i18n/ja-JP/deployments.json+++ b/web/i18n/ja-JP/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "その他のアクション","deployTab.redeploy": "再デプロイ","deployTab.undeploy": "アンデプロイ",+ "deployTab.undeployUnavailable": "現在のバージョンを取得できないため、アンデプロイできません。","health.ENVIRONMENT_STATUS_FAILED": "利用不可","list.emptyTitle": "デプロイはまだありません","overview.chip.latest": "最新",@@ -66,11 +67,14 @@"studio.environments": "環境","studio.environmentsInUse": "{{total}} 環境中 {{used}} 環境を使用中","studio.lastActivity": "最近のアクティビティ",+ "studio.latestVersionLoadFailed": "最新バージョンの取得に失敗しました。","studio.liveVersion": "稼働中のバージョン","studio.moreEnvironments": "その他の環境","studio.noCredentialsYet": "認証情報はまだありません","studio.noCredentialsYetDescription": "連携またはノード設定で認証情報を追加してください","studio.precheck.description": "まだサポートされていないノードタイプが含まれています:",+ "studio.precheck.from": "参照元",+ "studio.precheck.nodeCount_other": "{{count}} ノード","studio.precheck.supportMessage": "これらのノードタイプは今後のリリースでサポートされる予定です。","studio.precheck.title": "このバージョンはこの環境にデプロイできません","studio.publisher.deployingVersion": "デプロイ中:{{version}}",diff --git a/web/i18n/ko-KR/agent-v-2.json b/web/i18n/ko-KR/agent-v-2.jsonindex 5d108fe67b0..d053b4b681c 100644--- a/web/i18n/ko-KR/agent-v-2.json+++ b/web/i18n/ko-KR/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "이 기능을 켜려면 에이전트를 게시하세요.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "서버 측 API 엔드포인트","agentDetail.access.serviceApi.endpoint": "서비스 API 엔드포인트","agentDetail.access.serviceApi.title": "백엔드 서비스 API","agentDetail.access.status.inService": "서비스 중","agentDetail.access.status.outOfService": "서비스 중지됨",+ "agentDetail.access.status.unavailable": "사용 불가","agentDetail.access.title": "액세스 지점","agentDetail.access.toggleSurface": "{{name}} 액세스 전환",- "agentDetail.access.webApp.accessUrl": "웹 앱 URL",- "agentDetail.access.webApp.actions.accessControl": "접근 제어",- "agentDetail.access.webApp.actions.customize": "커스텀 프런트엔드",- "agentDetail.access.webApp.actions.embedded": "임베드",- "agentDetail.access.webApp.actions.launch": "실행",- "agentDetail.access.webApp.actions.settings": "브랜딩",+ "agentDetail.access.webApp.accessUrl": "액세스 URL",+ "agentDetail.access.webApp.actions.customFrontend": "사용자 지정 프런트엔드",+ "agentDetail.access.webApp.actions.embedIntoSite": "사이트에 임베드",+ "agentDetail.access.webApp.actions.open": "열기",+ "agentDetail.access.webApp.actions.settings": "설정",+ "agentDetail.access.webApp.description": "공개 웹 환경",+ "agentDetail.access.webApp.qrCode.download": "QR 코드 다운로드",+ "agentDetail.access.webApp.qrCode.scanToShare": "스캔하여 공유","agentDetail.access.webApp.refreshUrl": "액세스 URL 새로 고침",- "agentDetail.access.webApp.ssoEnabled": "SSO 사용 가능",+ "agentDetail.access.webApp.showQrCode": "QR 코드 표시","agentDetail.access.webApp.title": "웹 앱","agentDetail.access.workflow.description": "워크플로 내 노드로 사용","agentDetail.access.workflow.empty": "워크플로 참조가 없습니다.",diff --git a/web/i18n/ko-KR/deployments.json b/web/i18n/ko-KR/deployments.jsonindex b9dbfaa2d7e..e7235629114 100644--- a/web/i18n/ko-KR/deployments.json+++ b/web/i18n/ko-KR/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "더 많은 작업","deployTab.redeploy": "재배포","deployTab.undeploy": "배포 취소",+ "deployTab.undeployUnavailable": "현재 버전을 사용할 수 없어 배포를 취소할 수 없습니다.","health.ENVIRONMENT_STATUS_FAILED": "사용 불가","list.emptyTitle": "아직 배포가 없습니다","overview.chip.latest": "최신",@@ -66,11 +67,14 @@"studio.environments": "환경","studio.environmentsInUse": "환경 {{total}}개 중 {{used}}개 사용 중","studio.lastActivity": "최근 활동",+ "studio.latestVersionLoadFailed": "최신 버전을 가져오지 못했습니다.","studio.liveVersion": "라이브 버전","studio.moreEnvironments": "더 많은 환경","studio.noCredentialsYet": "아직 자격 증명이 없습니다","studio.noCredentialsYetDescription": "통합 또는 노드 설정에서 자격 증명을 추가하세요","studio.precheck.description": "아직 지원되지 않는 노드 유형이 포함되어 있습니다:",+ "studio.precheck.from": "출처",+ "studio.precheck.nodeCount_other": "노드 {{count}}개","studio.precheck.supportMessage": "이러한 노드 유형은 향후 릴리스에서 지원될 예정입니다.","studio.precheck.title": "이 버전은 이 환경에 배포할 수 없습니다","studio.publisher.deployingVersion": "배포 중: {{version}}",diff --git a/web/i18n/lo-LA/agent-v-2.json b/web/i18n/lo-LA/agent-v-2.jsonindex 759aa15e84c..ecf9660c091 100644--- a/web/i18n/lo-LA/agent-v-2.json+++ b/web/i18n/lo-LA/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "ເຜີຍແຜ່ Agent ເພື່ອເປີດໃຊ້ງານ.","agentDetail.access.serviceApi.actions.apiKey": "ຄີ API","agentDetail.access.serviceApi.actions.apiReference": "ການອ້າງອີງ API",+ "agentDetail.access.serviceApi.description": "ຈຸດປາຍ API ຝັ່ງເຊີບເວີ","agentDetail.access.serviceApi.endpoint": "ຈຸດເຊື່ອມຕໍ່ API ຂອງບໍລິການ","agentDetail.access.serviceApi.title": "API ບໍລິການສ່ວນຫຼັງ","agentDetail.access.status.inService": "ກຳລັງໃຫ້ບໍລິການ","agentDetail.access.status.outOfService": "ຢຸດໃຫ້ບໍລິການ",+ "agentDetail.access.status.unavailable": "ໃຊ້ງານບໍ່ໄດ້","agentDetail.access.title": "ຈຸດເຂົ້າເຖິງ","agentDetail.access.toggleSurface": "ເປີດ/ປິດ ການເຂົ້າເຖິງ {{name}}",- "agentDetail.access.webApp.accessUrl": "URL ເວັບແອັບ",- "agentDetail.access.webApp.actions.accessControl": "ການຄວບຄຸມການເຂົ້າເຖິງ",- "agentDetail.access.webApp.actions.customize": "ປັບແຕ່ງສ່ວນໜ້າເວັບ",- "agentDetail.access.webApp.actions.embedded": "ຝັງໄວ້ໃນເວັບໄຊ",- "agentDetail.access.webApp.actions.launch": "ເປີດໃຊ້ງານ",- "agentDetail.access.webApp.actions.settings": "ການສ້າງແບຣນ",+ "agentDetail.access.webApp.accessUrl": "URL ເຂົ້າເຖິງ",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend ກຳນົດເອງ",+ "agentDetail.access.webApp.actions.embedIntoSite": "ຝັງໄວ້ໃນເວັບໄຊ",+ "agentDetail.access.webApp.actions.open": "ເປີດ",+ "agentDetail.access.webApp.actions.settings": "ການຕັ້ງຄ່າ",+ "agentDetail.access.webApp.description": "ປະສົບການເວັບສາທາລະນະ",+ "agentDetail.access.webApp.qrCode.download": "ດາວໂຫລດ QR Code",+ "agentDetail.access.webApp.qrCode.scanToShare": "ສະແກນເພື່ອແຊຣ໌","agentDetail.access.webApp.refreshUrl": "ໂຫຼດ URL ການເຂົ້າເຖິງຄືນໃໝ່",- "agentDetail.access.webApp.ssoEnabled": "ເປີດໃຊ້ SSO ແລ້ວ",+ "agentDetail.access.webApp.showQrCode": "ສະແດງ QR code","agentDetail.access.webApp.title": "ເວັບແອັບ","agentDetail.access.workflow.description": "ໃຊ້ເປັນໂນດ (Node) ພາຍໃນເວີກໂຟລ","agentDetail.access.workflow.empty": "ຍັງບໍ່ມີການອ້າງອີງເວີກໂຟລເທື່ອ.",diff --git a/web/i18n/lo-LA/deployments.json b/web/i18n/lo-LA/deployments.jsonindex 343c3ad394a..e6fca869da3 100644--- a/web/i18n/lo-LA/deployments.json+++ b/web/i18n/lo-LA/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "ການຈັດການເພີ່ມເຕີມ","deployTab.redeploy": "ຕິດຕັ້ງໃໝ່","deployTab.undeploy": "ຖອນການຕິດຕັ້ງ",+ "deployTab.undeployUnavailable": "ບໍ່ສາມາດຖອນການຕິດຕັ້ງໄດ້ ເນື່ອງຈາກເວີຊັນປັດຈຸບັນບໍ່ພ້ອມໃຊ້ງານ.","health.ENVIRONMENT_STATUS_FAILED": "ໃຊ້ງານບໍ່ໄດ້","list.emptyTitle": "ຍັງບໍ່ມີການຕິດຕັ້ງ","overview.chip.latest": "ຫຼ້າສຸດ",@@ -66,11 +67,14 @@"studio.environments": "ສະພາບແວດລ້ອມ","studio.environmentsInUse": "ໃຊ້ງານແລ້ວ {{used}} ຈາກ {{total}} ສະພາບແວດລ້ອມ","studio.lastActivity": "ກິດຈະກຳຫຼ້າສຸດ",+ "studio.latestVersionLoadFailed": "ບໍ່ສາມາດດຶງເວີຊັນລ່າສຸດໄດ້.","studio.liveVersion": "ເວີຊັນທີ່ໃຊ້ງານຢູ່","studio.moreEnvironments": "ສະພາບແວດລ້ອມເພີ່ມເຕີມ","studio.noCredentialsYet": "ຍັງບໍ່ມີຂໍ້ມູນການເຂົ້າລະບົບ","studio.noCredentialsYetDescription": "ເພີ່ມຂໍ້ມູນການເຂົ້າລະບົບໃນ Integrations ຫຼື ການຕັ້ງຄ່າໂນດ","studio.precheck.description": "ມັນມີປະເພດໂນດທີ່ຍັງບໍ່ຮອງຮັບ:",+ "studio.precheck.from": "ຈາກ",+ "studio.precheck.nodeCount_other": "{{count}} ໂນດ","studio.precheck.supportMessage": "ຈະຮອງຮັບປະເພດໂນດເຫຼົ່ານີ້ໃນລຸ້ນທີ່ຈະມາເຖິງ.","studio.precheck.title": "ບໍ່ສາມາດນຳເວີຊັນນີ້ໄປປັບໃຊ້ໃນສະພາບແວດລ້ອມນີ້ໄດ້","studio.publisher.deployingVersion": "ກຳລັງຕິດຕັ້ງ: {{version}}",diff --git a/web/i18n/nl-NL/agent-v-2.json b/web/i18n/nl-NL/agent-v-2.jsonindex d2b3bb3de7c..a667e70215a 100644--- a/web/i18n/nl-NL/agent-v-2.json+++ b/web/i18n/nl-NL/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Publiceer de agent om dit in te schakelen.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Server-side API-eindpunt","agentDetail.access.serviceApi.endpoint": "Service-API-endpoint","agentDetail.access.serviceApi.title": "Backend service-API","agentDetail.access.status.inService": "In gebruik","agentDetail.access.status.outOfService": "Buiten gebruik",+ "agentDetail.access.status.unavailable": "Niet beschikbaar","agentDetail.access.title": "Toegangspunt","agentDetail.access.toggleSurface": "Toegang van {{name}} schakelen",- "agentDetail.access.webApp.accessUrl": "Webapp-URL",- "agentDetail.access.webApp.actions.accessControl": "Toegangsbeheer",- "agentDetail.access.webApp.actions.customize": "Aangepaste frontend",- "agentDetail.access.webApp.actions.embedded": "Ingesloten",- "agentDetail.access.webApp.actions.launch": "Starten",- "agentDetail.access.webApp.actions.settings": "Branding",+ "agentDetail.access.webApp.accessUrl": "Toegangs-URL",+ "agentDetail.access.webApp.actions.customFrontend": "Aangepaste frontend",+ "agentDetail.access.webApp.actions.embedIntoSite": "In site insluiten",+ "agentDetail.access.webApp.actions.open": "Openen",+ "agentDetail.access.webApp.actions.settings": "Instellingen",+ "agentDetail.access.webApp.description": "Openbare webervaring",+ "agentDetail.access.webApp.qrCode.download": "Download QR Code",+ "agentDetail.access.webApp.qrCode.scanToShare": "Scannen om te delen","agentDetail.access.webApp.refreshUrl": "Toegangs-URL vernieuwen",- "agentDetail.access.webApp.ssoEnabled": "SSO ingeschakeld",+ "agentDetail.access.webApp.showQrCode": "QR-code tonen","agentDetail.access.webApp.title": "Webapp","agentDetail.access.workflow.description": "Gebruikt als knooppunt binnen de workflow","agentDetail.access.workflow.empty": "Nog geen workflowreferenties.",diff --git a/web/i18n/nl-NL/deployments.json b/web/i18n/nl-NL/deployments.jsonindex 00cf67272a1..f41bf709f36 100644--- a/web/i18n/nl-NL/deployments.json+++ b/web/i18n/nl-NL/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Meer acties","deployTab.redeploy": "Opnieuw implementeren","deployTab.undeploy": "Implementatie ongedaan maken",+ "deployTab.undeployUnavailable": "De implementatie kan niet ongedaan worden gemaakt omdat de huidige versie niet beschikbaar is.","health.ENVIRONMENT_STATUS_FAILED": "Niet beschikbaar","list.emptyTitle": "Nog geen implementaties","overview.chip.latest": "nieuwste",@@ -66,11 +67,14 @@"studio.environments": "Omgevingen","studio.environmentsInUse": "{{used}} van {{total}} omgevingen in gebruik","studio.lastActivity": "Laatste activiteit",+ "studio.latestVersionLoadFailed": "Kan de nieuwste versie niet ophalen.","studio.liveVersion": "Liveversie","studio.moreEnvironments": "Meer omgevingen","studio.noCredentialsYet": "Nog geen inloggegevens","studio.noCredentialsYetDescription": "Voeg inloggegevens toe in Integraties of de knooppuntinstellingen","studio.precheck.description": "Deze versie bevat knooppunttypen die nog niet worden ondersteund:",+ "studio.precheck.from": "Van",+ "studio.precheck.nodeCount_other": "{{count}} knooppunten","studio.precheck.supportMessage": "Ondersteuning voor deze knooppunttypen komt in een toekomstige release.","studio.precheck.title": "Deze versie kan niet in deze omgeving worden geïmplementeerd","studio.publisher.deployingVersion": "Implementeren: {{version}}",diff --git a/web/i18n/pl-PL/agent-v-2.json b/web/i18n/pl-PL/agent-v-2.jsonindex a5a5a385289..a46161802f9 100644--- a/web/i18n/pl-PL/agent-v-2.json+++ b/web/i18n/pl-PL/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Opublikuj agenta, aby to włączyć.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Punkt końcowy API po stronie serwera","agentDetail.access.serviceApi.endpoint": "Punkt końcowy API usługi","agentDetail.access.serviceApi.title": "Backendowe API usługi","agentDetail.access.status.inService": "W użyciu","agentDetail.access.status.outOfService": "Poza użyciem",+ "agentDetail.access.status.unavailable": "Niedostępne","agentDetail.access.title": "Punkt dostępu","agentDetail.access.toggleSurface": "Przełącz dostęp {{name}}",- "agentDetail.access.webApp.accessUrl": "Adres URL aplikacji webowej",- "agentDetail.access.webApp.actions.accessControl": "Kontrola dostępu",- "agentDetail.access.webApp.actions.customize": "Niestandardowy frontend",- "agentDetail.access.webApp.actions.embedded": "Osadzony",- "agentDetail.access.webApp.actions.launch": "Uruchom",- "agentDetail.access.webApp.actions.settings": "Branding",+ "agentDetail.access.webApp.accessUrl": "Adres URL dostępu",+ "agentDetail.access.webApp.actions.customFrontend": "Niestandardowy frontend",+ "agentDetail.access.webApp.actions.embedIntoSite": "Osadź w witrynie",+ "agentDetail.access.webApp.actions.open": "Otwórz",+ "agentDetail.access.webApp.actions.settings": "Ustawienia",+ "agentDetail.access.webApp.description": "Publiczne środowisko internetowe",+ "agentDetail.access.webApp.qrCode.download": "Pobierz kod QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Zeskanuj, aby udostępnić","agentDetail.access.webApp.refreshUrl": "Odśwież URL dostępu",- "agentDetail.access.webApp.ssoEnabled": "SSO włączone",+ "agentDetail.access.webApp.showQrCode": "Pokaż kod QR","agentDetail.access.webApp.title": "Aplikacja webowa","agentDetail.access.workflow.description": "Używany jako węzeł wewnątrz workflow","agentDetail.access.workflow.empty": "Brak jeszcze odniesień do workflow.",diff --git a/web/i18n/pl-PL/deployments.json b/web/i18n/pl-PL/deployments.jsonindex c472e3403c9..0ba09b657c3 100644--- a/web/i18n/pl-PL/deployments.json+++ b/web/i18n/pl-PL/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Więcej akcji","deployTab.redeploy": "Ponownie wdróż","deployTab.undeploy": "Wycofaj wdrożenie",+ "deployTab.undeployUnavailable": "Nie można wycofać wdrożenia, ponieważ bieżąca wersja jest niedostępna.","health.ENVIRONMENT_STATUS_FAILED": "Niedostępne","list.emptyTitle": "Brak wdrożeń","overview.chip.latest": "najnowsze",@@ -66,11 +67,14 @@"studio.environments": "Środowiska","studio.environmentsInUse": "Używane środowiska: {{used}} z {{total}}","studio.lastActivity": "Ostatnia aktywność",+ "studio.latestVersionLoadFailed": "Nie udało się pobrać najnowszej wersji.","studio.liveVersion": "Wersja aktywna","studio.moreEnvironments": "Więcej środowisk","studio.noCredentialsYet": "Brak poświadczeń","studio.noCredentialsYetDescription": "Dodaj poświadczenia w Integracjach lub ustawieniach węzła","studio.precheck.description": "Zawiera ona typy węzłów, które nie są jeszcze obsługiwane:",+ "studio.precheck.from": "Z",+ "studio.precheck.nodeCount_other": "{{count}} węzłów","studio.precheck.supportMessage": "Obsługa tych typów węzłów pojawi się w przyszłej wersji.","studio.precheck.title": "Nie można wdrożyć tej wersji w tym środowisku","studio.publisher.deployingVersion": "Wdrażanie: {{version}}",diff --git a/web/i18n/pt-BR/agent-v-2.json b/web/i18n/pt-BR/agent-v-2.jsonindex 592f72b6b49..0c68840cc91 100644--- a/web/i18n/pt-BR/agent-v-2.json+++ b/web/i18n/pt-BR/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Publique o agente para ativar esta opção.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Endpoint de API do lado do servidor","agentDetail.access.serviceApi.endpoint": "Endpoint da API de serviço","agentDetail.access.serviceApi.title": "API de serviço de backend","agentDetail.access.status.inService": "Em serviço","agentDetail.access.status.outOfService": "Fora de serviço",+ "agentDetail.access.status.unavailable": "Indisponível","agentDetail.access.title": "Ponto de acesso","agentDetail.access.toggleSurface": "Alternar acesso de {{name}}",- "agentDetail.access.webApp.accessUrl": "URL do aplicativo web",- "agentDetail.access.webApp.actions.accessControl": "Controle de Acesso",- "agentDetail.access.webApp.actions.customize": "Frontend personalizado",- "agentDetail.access.webApp.actions.embedded": "Incorporado",- "agentDetail.access.webApp.actions.launch": "Iniciar",- "agentDetail.access.webApp.actions.settings": "Marca",+ "agentDetail.access.webApp.accessUrl": "URL de acesso",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend personalizado",+ "agentDetail.access.webApp.actions.embedIntoSite": "Incorporar ao site",+ "agentDetail.access.webApp.actions.open": "Abrir",+ "agentDetail.access.webApp.actions.settings": "Configurações",+ "agentDetail.access.webApp.description": "Experiência web pública",+ "agentDetail.access.webApp.qrCode.download": "Baixar código QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Escanear para compartilhar","agentDetail.access.webApp.refreshUrl": "Atualizar URL de acesso",- "agentDetail.access.webApp.ssoEnabled": "SSO ativado",+ "agentDetail.access.webApp.showQrCode": "Mostrar QR code","agentDetail.access.webApp.title": "Aplicativo web","agentDetail.access.workflow.description": "Usado como um nó dentro do workflow","agentDetail.access.workflow.empty": "Ainda não há referências de workflow.",diff --git a/web/i18n/pt-BR/deployments.json b/web/i18n/pt-BR/deployments.jsonindex 5ba7ffe1c1e..8818f88bb72 100644--- a/web/i18n/pt-BR/deployments.json+++ b/web/i18n/pt-BR/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Mais ações","deployTab.redeploy": "Reimplantar","deployTab.undeploy": "Desimplantar",+ "deployTab.undeployUnavailable": "Não é possível desimplantar porque a versão atual não está disponível.","health.ENVIRONMENT_STATUS_FAILED": "Indisponível","list.emptyTitle": "Nenhuma implantação ainda","overview.chip.latest": "mais recente",@@ -66,11 +67,14 @@"studio.environments": "Ambientes","studio.environmentsInUse": "{{used}} de {{total}} ambientes em uso","studio.lastActivity": "Última atividade",+ "studio.latestVersionLoadFailed": "Não foi possível obter a versão mais recente.","studio.liveVersion": "Versão ativa","studio.moreEnvironments": "Mais ambientes","studio.noCredentialsYet": "Ainda não há credenciais","studio.noCredentialsYetDescription": "Adicione credenciais em Integrações ou nas configurações do nó","studio.precheck.description": "Ela contém tipos de nós que ainda não são compatíveis:",+ "studio.precheck.from": "De",+ "studio.precheck.nodeCount_other": "{{count}} nós","studio.precheck.supportMessage": "O suporte a esses tipos de nós estará disponível em uma versão futura.","studio.precheck.title": "Esta versão não pode ser implantada neste ambiente","studio.publisher.deployingVersion": "Implantando: {{version}}",diff --git a/web/i18n/ro-RO/agent-v-2.json b/web/i18n/ro-RO/agent-v-2.jsonindex 160308fc298..ba160bd4e74 100644--- a/web/i18n/ro-RO/agent-v-2.json+++ b/web/i18n/ro-RO/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Publicați agentul pentru a activa această opțiune.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Endpoint API pe partea de server","agentDetail.access.serviceApi.endpoint": "Endpoint API serviciu","agentDetail.access.serviceApi.title": "API de serviciu backend","agentDetail.access.status.inService": "În serviciu","agentDetail.access.status.outOfService": "Scos din serviciu",+ "agentDetail.access.status.unavailable": "Indisponibil","agentDetail.access.title": "Punct de acces","agentDetail.access.toggleSurface": "Comută accesul pentru {{name}}",- "agentDetail.access.webApp.accessUrl": "URL aplicație web",- "agentDetail.access.webApp.actions.accessControl": "Controlul Accesului",- "agentDetail.access.webApp.actions.customize": "Frontend personalizat",- "agentDetail.access.webApp.actions.embedded": "Încorporat",- "agentDetail.access.webApp.actions.launch": "Lansează",- "agentDetail.access.webApp.actions.settings": "Branding",+ "agentDetail.access.webApp.accessUrl": "URL de acces",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend personalizat",+ "agentDetail.access.webApp.actions.embedIntoSite": "Încorporează în site",+ "agentDetail.access.webApp.actions.open": "Deschide",+ "agentDetail.access.webApp.actions.settings": "Setări",+ "agentDetail.access.webApp.description": "Experiență web publică",+ "agentDetail.access.webApp.qrCode.download": "Descărcați codul QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Scanați pentru a partaja","agentDetail.access.webApp.refreshUrl": "Reîmprospătează URL-ul de acces",- "agentDetail.access.webApp.ssoEnabled": "SSO activat",+ "agentDetail.access.webApp.showQrCode": "Afișează codul QR","agentDetail.access.webApp.title": "Aplicație web","agentDetail.access.workflow.description": "Utilizat ca nod în cadrul workflow-ului","agentDetail.access.workflow.empty": "Nu există încă referințe de workflow.",diff --git a/web/i18n/ro-RO/deployments.json b/web/i18n/ro-RO/deployments.jsonindex b30f5b08038..22efe318f8f 100644--- a/web/i18n/ro-RO/deployments.json+++ b/web/i18n/ro-RO/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Mai multe acțiuni","deployTab.redeploy": "Reimplementează","deployTab.undeploy": "Anulează implementarea",+ "deployTab.undeployUnavailable": "Implementarea nu poate fi anulată deoarece versiunea curentă nu este disponibilă.","health.ENVIRONMENT_STATUS_FAILED": "Indisponibil","list.emptyTitle": "Nicio implementare încă","overview.chip.latest": "cea mai recentă",@@ -66,11 +67,14 @@"studio.environments": "Medii","studio.environmentsInUse": "{{used}} din {{total}} medii utilizate","studio.lastActivity": "Ultima activitate",+ "studio.latestVersionLoadFailed": "Nu s-a putut obține cea mai recentă versiune.","studio.liveVersion": "Versiune activă","studio.moreEnvironments": "Mai multe medii","studio.noCredentialsYet": "Încă nu există acreditări","studio.noCredentialsYetDescription": "Adăugați acreditări în Integrări sau în setările nodului","studio.precheck.description": "Conține tipuri de noduri care nu sunt încă acceptate:",+ "studio.precheck.from": "Din",+ "studio.precheck.nodeCount_other": "{{count}} noduri","studio.precheck.supportMessage": "Suportul pentru aceste tipuri de noduri va fi disponibil într-o versiune viitoare.","studio.precheck.title": "Această versiune nu poate fi implementată în acest mediu","studio.publisher.deployingVersion": "Se implementează: {{version}}",diff --git a/web/i18n/ru-RU/agent-v-2.json b/web/i18n/ru-RU/agent-v-2.jsonindex 47b19b94578..f383b2f11f0 100644--- a/web/i18n/ru-RU/agent-v-2.json+++ b/web/i18n/ru-RU/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Опубликуйте агента, чтобы включить эту функцию.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Серверная конечная точка API","agentDetail.access.serviceApi.endpoint": "Конечная точка API сервиса","agentDetail.access.serviceApi.title": "Бэкенд API сервиса","agentDetail.access.status.inService": "В работе","agentDetail.access.status.outOfService": "Не в работе",+ "agentDetail.access.status.unavailable": "Недоступно","agentDetail.access.title": "Точка доступа","agentDetail.access.toggleSurface": "Переключить доступ {{name}}",- "agentDetail.access.webApp.accessUrl": "URL веб-приложения",- "agentDetail.access.webApp.actions.accessControl": "Управление доступом",- "agentDetail.access.webApp.actions.customize": "Пользовательский фронтенд",- "agentDetail.access.webApp.actions.embedded": "Встроить",- "agentDetail.access.webApp.actions.launch": "Запустить",- "agentDetail.access.webApp.actions.settings": "Брендинг",+ "agentDetail.access.webApp.accessUrl": "URL доступа",+ "agentDetail.access.webApp.actions.customFrontend": "Пользовательский фронтенд",+ "agentDetail.access.webApp.actions.embedIntoSite": "Встроить на сайт",+ "agentDetail.access.webApp.actions.open": "Открыть",+ "agentDetail.access.webApp.actions.settings": "Настройки",+ "agentDetail.access.webApp.description": "Общедоступный веб-интерфейс",+ "agentDetail.access.webApp.qrCode.download": "Скачать QR-код",+ "agentDetail.access.webApp.qrCode.scanToShare": "Сканировать, чтобы поделиться","agentDetail.access.webApp.refreshUrl": "Обновить URL доступа",- "agentDetail.access.webApp.ssoEnabled": "SSO включено",+ "agentDetail.access.webApp.showQrCode": "Показать QR-код","agentDetail.access.webApp.title": "Веб-приложение","agentDetail.access.workflow.description": "Используется как узел внутри рабочего процесса","agentDetail.access.workflow.empty": "Пока нет ссылок на рабочие процессы.",diff --git a/web/i18n/ru-RU/deployments.json b/web/i18n/ru-RU/deployments.jsonindex d0bdf6e7af3..a15eff066d2 100644--- a/web/i18n/ru-RU/deployments.json+++ b/web/i18n/ru-RU/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Дополнительные действия","deployTab.redeploy": "Повторно развернуть","deployTab.undeploy": "Свернуть развертывание",+ "deployTab.undeployUnavailable": "Невозможно отменить развертывание, поскольку текущая версия недоступна.","health.ENVIRONMENT_STATUS_FAILED": "Недоступно","list.emptyTitle": "Пока нет развертываний","overview.chip.latest": "последний",@@ -66,11 +67,14 @@"studio.environments": "Среды","studio.environmentsInUse": "Используется сред: {{used}} из {{total}}","studio.lastActivity": "Последняя активность",+ "studio.latestVersionLoadFailed": "Не удалось получить последнюю версию.","studio.liveVersion": "Активная версия","studio.moreEnvironments": "Другие среды","studio.noCredentialsYet": "Учётных данных пока нет","studio.noCredentialsYetDescription": "Добавьте учётные данные в разделе «Интеграции» или в настройках узла","studio.precheck.description": "Она содержит типы узлов, которые пока не поддерживаются:",+ "studio.precheck.from": "Из",+ "studio.precheck.nodeCount_other": "{{count}} узлов","studio.precheck.supportMessage": "Поддержка этих типов узлов появится в одном из будущих выпусков.","studio.precheck.title": "Эту версию нельзя развернуть в этой среде","studio.publisher.deployingVersion": "Развертывание: {{version}}",diff --git a/web/i18n/sl-SI/agent-v-2.json b/web/i18n/sl-SI/agent-v-2.jsonindex 80cda491d42..7555c1f2d17 100644--- a/web/i18n/sl-SI/agent-v-2.json+++ b/web/i18n/sl-SI/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Objavite agenta, da to omogočite.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Strežniška končna točka API","agentDetail.access.serviceApi.endpoint": "Končna točka storitvenega API","agentDetail.access.serviceApi.title": "Zaledni storitveni API","agentDetail.access.status.inService": "V uporabi","agentDetail.access.status.outOfService": "Izven uporabe",+ "agentDetail.access.status.unavailable": "Nedosegljivo","agentDetail.access.title": "Dostopna točka","agentDetail.access.toggleSurface": "Preklopi dostop {{name}}",- "agentDetail.access.webApp.accessUrl": "URL spletne aplikacije",- "agentDetail.access.webApp.actions.accessControl": "Nadzor dostopa",- "agentDetail.access.webApp.actions.customize": "Frontend po meri",- "agentDetail.access.webApp.actions.embedded": "Vgrajeno",- "agentDetail.access.webApp.actions.launch": "Zaženi",- "agentDetail.access.webApp.actions.settings": "Znamčenje",+ "agentDetail.access.webApp.accessUrl": "URL za dostop",+ "agentDetail.access.webApp.actions.customFrontend": "Frontend po meri",+ "agentDetail.access.webApp.actions.embedIntoSite": "Vdelaj v spletno mesto",+ "agentDetail.access.webApp.actions.open": "Odpri",+ "agentDetail.access.webApp.actions.settings": "Nastavitve",+ "agentDetail.access.webApp.description": "Javna spletna izkušnja",+ "agentDetail.access.webApp.qrCode.download": "Prenesi QR kodo",+ "agentDetail.access.webApp.qrCode.scanToShare": "Skeniraj za deljenje","agentDetail.access.webApp.refreshUrl": "Osveži URL dostopa",- "agentDetail.access.webApp.ssoEnabled": "SSO omogočeno",+ "agentDetail.access.webApp.showQrCode": "Pokaži QR kodo","agentDetail.access.webApp.title": "Spletna aplikacija","agentDetail.access.workflow.description": "Uporabljeno kot vozlišče znotraj poteka dela","agentDetail.access.workflow.empty": "Še ni sklicev na potek dela.",diff --git a/web/i18n/sl-SI/deployments.json b/web/i18n/sl-SI/deployments.jsonindex f3c4f21fc77..1a53ea271d3 100644--- a/web/i18n/sl-SI/deployments.json+++ b/web/i18n/sl-SI/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Več dejanj","deployTab.redeploy": "Ponovno uvedi","deployTab.undeploy": "Razveljavi uvedbo",+ "deployTab.undeployUnavailable": "Uvedbe ni mogoče razveljaviti, ker trenutna različica ni na voljo.","health.ENVIRONMENT_STATUS_FAILED": "Nedosegljivo","list.emptyTitle": "Še ni uvedb","overview.chip.latest": "najnovejša",@@ -66,11 +67,14 @@"studio.environments": "Okolja","studio.environmentsInUse": "V uporabi je {{used}} od {{total}} okolij","studio.lastActivity": "Zadnja dejavnost",+ "studio.latestVersionLoadFailed": "Najnovejše različice ni bilo mogoče pridobiti.","studio.liveVersion": "Aktivna različica","studio.moreEnvironments": "Več okolij","studio.noCredentialsYet": "Poverilnic še ni","studio.noCredentialsYetDescription": "Dodajte poverilnice v Integracijah ali nastavitvah vozlišča","studio.precheck.description": "Vsebuje vrste vozlišč, ki še niso podprte:",+ "studio.precheck.from": "Iz",+ "studio.precheck.nodeCount_other": "{{count}} vozlišč","studio.precheck.supportMessage": "Podpora za te vrste vozlišč bo na voljo v prihodnji izdaji.","studio.precheck.title": "Te različice ni mogoče uvesti v to okolje","studio.publisher.deployingVersion": "Uvajanje: {{version}}",diff --git a/web/i18n/th-TH/agent-v-2.json b/web/i18n/th-TH/agent-v-2.jsonindex b279c824146..36838e041db 100644--- a/web/i18n/th-TH/agent-v-2.json+++ b/web/i18n/th-TH/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "เผยแพร่ Agent เพื่อเปิดใช้งาน","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "ปลายทาง API ฝั่งเซิร์ฟเวอร์","agentDetail.access.serviceApi.endpoint": "ปลายทาง API ของบริการ","agentDetail.access.serviceApi.title": "API บริการแบ็กเอนด์","agentDetail.access.status.inService": "พร้อมให้บริการ","agentDetail.access.status.outOfService": "ไม่พร้อมให้บริการ",+ "agentDetail.access.status.unavailable": "ไม่พร้อมใช้งาน","agentDetail.access.title": "จุดเข้าถึง","agentDetail.access.toggleSurface": "สลับการเข้าถึง {{name}}",- "agentDetail.access.webApp.accessUrl": "URL เว็บแอป",- "agentDetail.access.webApp.actions.accessControl": "การควบคุมการเข้าถึง",- "agentDetail.access.webApp.actions.customize": "ฟรอนต์เอนด์ที่กำหนดเอง",- "agentDetail.access.webApp.actions.embedded": "ฝัง",- "agentDetail.access.webApp.actions.launch": "เปิดใช้",- "agentDetail.access.webApp.actions.settings": "การสร้างแบรนด์",+ "agentDetail.access.webApp.accessUrl": "URL การเข้าถึง",+ "agentDetail.access.webApp.actions.customFrontend": "ฟรอนต์เอนด์ที่กำหนดเอง",+ "agentDetail.access.webApp.actions.embedIntoSite": "ฝังในเว็บไซต์",+ "agentDetail.access.webApp.actions.open": "เปิด",+ "agentDetail.access.webApp.actions.settings": "การตั้งค่า",+ "agentDetail.access.webApp.description": "ประสบการณ์เว็บสาธารณะ",+ "agentDetail.access.webApp.qrCode.download": "ดาวน์โหลด QR Code",+ "agentDetail.access.webApp.qrCode.scanToShare": "สแกนเพื่อแบ่งปัน","agentDetail.access.webApp.refreshUrl": "รีเฟรช URL การเข้าถึง",- "agentDetail.access.webApp.ssoEnabled": "เปิดใช้งาน SSO",+ "agentDetail.access.webApp.showQrCode": "แสดง QR Code","agentDetail.access.webApp.title": "เว็บแอป","agentDetail.access.workflow.description": "ใช้เป็นโหนดภายในเวิร์กโฟลว์","agentDetail.access.workflow.empty": "ยังไม่มีการอ้างอิงเวิร์กโฟลว์",diff --git a/web/i18n/th-TH/deployments.json b/web/i18n/th-TH/deployments.jsonindex 1948b1293c7..d323d910bae 100644--- a/web/i18n/th-TH/deployments.json+++ b/web/i18n/th-TH/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "การดำเนินการเพิ่มเติม","deployTab.redeploy": "ปรับใช้ใหม่","deployTab.undeploy": "ยกเลิกการปรับใช้",+ "deployTab.undeployUnavailable": "ไม่สามารถยกเลิกการปรับใช้ได้เนื่องจากเวอร์ชันปัจจุบันไม่พร้อมใช้งาน","health.ENVIRONMENT_STATUS_FAILED": "ไม่พร้อมใช้งาน","list.emptyTitle": "ยังไม่มีการปรับใช้","overview.chip.latest": "ล่าสุด",@@ -66,11 +67,14 @@"studio.environments": "สภาพแวดล้อม","studio.environmentsInUse": "ใช้งาน {{used}} จาก {{total}} สภาพแวดล้อม","studio.lastActivity": "กิจกรรมล่าสุด",+ "studio.latestVersionLoadFailed": "ไม่สามารถดึงข้อมูลเวอร์ชันล่าสุดได้","studio.liveVersion": "เวอร์ชันที่ใช้งาน","studio.moreEnvironments": "สภาพแวดล้อมเพิ่มเติม","studio.noCredentialsYet": "ยังไม่มีข้อมูลรับรอง","studio.noCredentialsYetDescription": "เพิ่มข้อมูลรับรองในการผสานรวมหรือการตั้งค่าโหนด","studio.precheck.description": "เวอร์ชันนี้มีประเภทโหนดที่ยังไม่รองรับ:",+ "studio.precheck.from": "จาก",+ "studio.precheck.nodeCount_other": "{{count}} โหนด","studio.precheck.supportMessage": "การรองรับประเภทโหนดเหล่านี้จะพร้อมใช้งานในรุ่นถัดไป","studio.precheck.title": "ไม่สามารถปรับใช้เวอร์ชันนี้ในสภาพแวดล้อมนี้ได้","studio.publisher.deployingVersion": "กำลังปรับใช้: {{version}}",diff --git a/web/i18n/tr-TR/agent-v-2.json b/web/i18n/tr-TR/agent-v-2.jsonindex 58ebcbf4d99..355838f92e8 100644--- a/web/i18n/tr-TR/agent-v-2.json+++ b/web/i18n/tr-TR/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Bunu etkinleştirmek için ajanı yayınlayın.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Sunucu tarafı API uç noktası","agentDetail.access.serviceApi.endpoint": "Servis API Uç Noktası","agentDetail.access.serviceApi.title": "Arka uç servis API","agentDetail.access.status.inService": "Hizmette","agentDetail.access.status.outOfService": "Hizmet Dışı",+ "agentDetail.access.status.unavailable": "Kullanılamıyor","agentDetail.access.title": "Erişim Noktası","agentDetail.access.toggleSurface": "{{name}} erişimini değiştir",- "agentDetail.access.webApp.accessUrl": "Web Uygulaması URL'si",- "agentDetail.access.webApp.actions.accessControl": "Erişim Kontrolü",- "agentDetail.access.webApp.actions.customize": "Özel Ön Yüz",- "agentDetail.access.webApp.actions.embedded": "Gömülü",- "agentDetail.access.webApp.actions.launch": "Başlat",- "agentDetail.access.webApp.actions.settings": "Markalama",+ "agentDetail.access.webApp.accessUrl": "Erişim URL’si",+ "agentDetail.access.webApp.actions.customFrontend": "Özel ön yüz",+ "agentDetail.access.webApp.actions.embedIntoSite": "Siteye göm",+ "agentDetail.access.webApp.actions.open": "Aç",+ "agentDetail.access.webApp.actions.settings": "Ayarlar",+ "agentDetail.access.webApp.description": "Herkese açık web deneyimi",+ "agentDetail.access.webApp.qrCode.download": "QR Kodu İndir",+ "agentDetail.access.webApp.qrCode.scanToShare": "Paylaşmak için tara","agentDetail.access.webApp.refreshUrl": "Erişim URL'sini yenile",- "agentDetail.access.webApp.ssoEnabled": "SSO Etkin",+ "agentDetail.access.webApp.showQrCode": "QR kodunu göster","agentDetail.access.webApp.title": "Web Uygulaması","agentDetail.access.workflow.description": "İş akışı içinde bir düğüm olarak kullanılır","agentDetail.access.workflow.empty": "Henüz iş akışı referansı yok.",diff --git a/web/i18n/tr-TR/deployments.json b/web/i18n/tr-TR/deployments.jsonindex 9ffacd0b907..091192ed63a 100644--- a/web/i18n/tr-TR/deployments.json+++ b/web/i18n/tr-TR/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Daha fazla işlem","deployTab.redeploy": "Yeniden Dağıt","deployTab.undeploy": "Dağıtımı Geri Al",+ "deployTab.undeployUnavailable": "Geçerli sürüm kullanılamadığı için dağıtım geri alınamıyor.","health.ENVIRONMENT_STATUS_FAILED": "Kullanılamıyor","list.emptyTitle": "Henüz dağıtım yok","overview.chip.latest": "en son",@@ -66,11 +67,14 @@"studio.environments": "Ortamlar","studio.environmentsInUse": "{{total}} ortamdan {{used}} tanesi kullanımda","studio.lastActivity": "Son etkinlik",+ "studio.latestVersionLoadFailed": "En son sürüm alınamadı.","studio.liveVersion": "Canlı sürüm","studio.moreEnvironments": "Daha fazla ortam","studio.noCredentialsYet": "Henüz kimlik bilgisi yok","studio.noCredentialsYetDescription": "Entegrasyonlar veya düğüm ayarlarından kimlik bilgisi ekleyin","studio.precheck.description": "Henüz desteklenmeyen düğüm türleri içeriyor:",+ "studio.precheck.from": "Kaynak",+ "studio.precheck.nodeCount_other": "{{count}} düğüm","studio.precheck.supportMessage": "Bu düğüm türleri gelecek bir sürümde desteklenecektir.","studio.precheck.title": "Bu sürüm bu ortama dağıtılamaz","studio.publisher.deployingVersion": "Dağıtılıyor: {{version}}",diff --git a/web/i18n/uk-UA/agent-v-2.json b/web/i18n/uk-UA/agent-v-2.jsonindex b58588b0511..72bc0a8a9f9 100644--- a/web/i18n/uk-UA/agent-v-2.json+++ b/web/i18n/uk-UA/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Опублікуйте агента, щоб увімкнути цю функцію.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Серверна кінцева точка API","agentDetail.access.serviceApi.endpoint": "Кінцева точка API сервісу","agentDetail.access.serviceApi.title": "Бекенд API сервісу","agentDetail.access.status.inService": "В роботі","agentDetail.access.status.outOfService": "Не в роботі",+ "agentDetail.access.status.unavailable": "Недоступно","agentDetail.access.title": "Точка доступу","agentDetail.access.toggleSurface": "Перемкнути доступ {{name}}",- "agentDetail.access.webApp.accessUrl": "URL вебзастосунку",- "agentDetail.access.webApp.actions.accessControl": "Контроль доступу",- "agentDetail.access.webApp.actions.customize": "Користувацький фронтенд",- "agentDetail.access.webApp.actions.embedded": "Вбудувати",- "agentDetail.access.webApp.actions.launch": "Запустити",- "agentDetail.access.webApp.actions.settings": "Брендинг",+ "agentDetail.access.webApp.accessUrl": "URL доступу",+ "agentDetail.access.webApp.actions.customFrontend": "Користувацький фронтенд",+ "agentDetail.access.webApp.actions.embedIntoSite": "Вбудувати на сайт",+ "agentDetail.access.webApp.actions.open": "Відкрити",+ "agentDetail.access.webApp.actions.settings": "Налаштування",+ "agentDetail.access.webApp.description": "Загальнодоступний вебінтерфейс",+ "agentDetail.access.webApp.qrCode.download": "Завантажити QR-код",+ "agentDetail.access.webApp.qrCode.scanToShare": "Сканувати, щоб поділитися","agentDetail.access.webApp.refreshUrl": "Оновити URL доступу",- "agentDetail.access.webApp.ssoEnabled": "SSO увімкнено",+ "agentDetail.access.webApp.showQrCode": "Показати QR-код","agentDetail.access.webApp.title": "Вебзастосунок","agentDetail.access.workflow.description": "Використовується як вузол у робочому процесі","agentDetail.access.workflow.empty": "Поки що немає посилань на робочі процеси.",diff --git a/web/i18n/uk-UA/deployments.json b/web/i18n/uk-UA/deployments.jsonindex 40dde1ef9a5..e26ac378db5 100644--- a/web/i18n/uk-UA/deployments.json+++ b/web/i18n/uk-UA/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Більше дій","deployTab.redeploy": "Перерозгорнути","deployTab.undeploy": "Скасувати розгортання",+ "deployTab.undeployUnavailable": "Неможливо скасувати розгортання, оскільки поточна версія недоступна.","health.ENVIRONMENT_STATUS_FAILED": "Недоступно","list.emptyTitle": "Поки що немає розгортань","overview.chip.latest": "останній",@@ -66,11 +67,14 @@"studio.environments": "Середовища","studio.environmentsInUse": "Використовується середовищ: {{used}} із {{total}}","studio.lastActivity": "Остання активність",+ "studio.latestVersionLoadFailed": "Не вдалося отримати останню версію.","studio.liveVersion": "Активна версія","studio.moreEnvironments": "Інші середовища","studio.noCredentialsYet": "Облікових даних ще немає","studio.noCredentialsYetDescription": "Додайте облікові дані в розділі «Інтеграції» або в налаштуваннях вузла","studio.precheck.description": "Вона містить типи вузлів, які ще не підтримуються:",+ "studio.precheck.from": "З",+ "studio.precheck.nodeCount_other": "{{count}} вузлів","studio.precheck.supportMessage": "Підтримка цих типів вузлів з’явиться в одному з майбутніх випусків.","studio.precheck.title": "Цю версію не можна розгорнути в цьому середовищі","studio.publisher.deployingVersion": "Розгортання: {{version}}",diff --git a/web/i18n/vi-VN/agent-v-2.json b/web/i18n/vi-VN/agent-v-2.jsonindex 6af2be0594c..cf18b7e0e7a 100644--- a/web/i18n/vi-VN/agent-v-2.json+++ b/web/i18n/vi-VN/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "Phát hành Agent để bật tính năng này.","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "Điểm cuối API phía máy chủ","agentDetail.access.serviceApi.endpoint": "Điểm cuối API dịch vụ","agentDetail.access.serviceApi.title": "API dịch vụ phía sau","agentDetail.access.status.inService": "Đang hoạt động","agentDetail.access.status.outOfService": "Ngưng hoạt động",+ "agentDetail.access.status.unavailable": "Không khả dụng","agentDetail.access.title": "Điểm truy cập","agentDetail.access.toggleSurface": "Bật/tắt truy cập {{name}}",- "agentDetail.access.webApp.accessUrl": "URL ứng dụng web",- "agentDetail.access.webApp.actions.accessControl": "Kiểm soát truy cập",- "agentDetail.access.webApp.actions.customize": "Giao diện tùy chỉnh",- "agentDetail.access.webApp.actions.embedded": "Nhúng",- "agentDetail.access.webApp.actions.launch": "Khởi chạy",- "agentDetail.access.webApp.actions.settings": "Thương hiệu",+ "agentDetail.access.webApp.accessUrl": "URL truy cập",+ "agentDetail.access.webApp.actions.customFrontend": "Giao diện tùy chỉnh",+ "agentDetail.access.webApp.actions.embedIntoSite": "Nhúng vào trang web",+ "agentDetail.access.webApp.actions.open": "Mở",+ "agentDetail.access.webApp.actions.settings": "Cài đặt",+ "agentDetail.access.webApp.description": "Trải nghiệm web công khai",+ "agentDetail.access.webApp.qrCode.download": "Tải xuống mã QR",+ "agentDetail.access.webApp.qrCode.scanToShare": "Quét để chia sẻ","agentDetail.access.webApp.refreshUrl": "Làm mới URL truy cập",- "agentDetail.access.webApp.ssoEnabled": "SSO đã bật",+ "agentDetail.access.webApp.showQrCode": "Hiển thị mã QR","agentDetail.access.webApp.title": "Ứng dụng web","agentDetail.access.workflow.description": "Được dùng như một nút bên trong quy trình làm việc","agentDetail.access.workflow.empty": "Chưa có tham chiếu quy trình làm việc nào.",diff --git a/web/i18n/vi-VN/deployments.json b/web/i18n/vi-VN/deployments.jsonindex 4f1d65e92b0..d870942fdef 100644--- a/web/i18n/vi-VN/deployments.json+++ b/web/i18n/vi-VN/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "Thêm thao tác","deployTab.redeploy": "Triển khai lại","deployTab.undeploy": "Hủy triển khai",+ "deployTab.undeployUnavailable": "Không thể hủy triển khai vì phiên bản hiện tại không khả dụng.","health.ENVIRONMENT_STATUS_FAILED": "Không khả dụng","list.emptyTitle": "Chưa có triển khai nào","overview.chip.latest": "mới nhất",@@ -66,11 +67,14 @@"studio.environments": "Môi trường","studio.environmentsInUse": "Đang dùng {{used}} trong {{total}} môi trường","studio.lastActivity": "Hoạt động gần nhất",+ "studio.latestVersionLoadFailed": "Không thể tải phiên bản mới nhất.","studio.liveVersion": "Phiên bản đang chạy","studio.moreEnvironments": "Thêm môi trường","studio.noCredentialsYet": "Chưa có thông tin xác thực","studio.noCredentialsYetDescription": "Thêm thông tin xác thực trong phần Tích hợp hoặc cài đặt nút","studio.precheck.description": "Phiên bản này chứa các loại nút chưa được hỗ trợ:",+ "studio.precheck.from": "Từ",+ "studio.precheck.nodeCount_other": "{{count}} nút","studio.precheck.supportMessage": "Các loại nút này sẽ được hỗ trợ trong một bản phát hành trong tương lai.","studio.precheck.title": "Không thể triển khai phiên bản này vào môi trường này","studio.publisher.deployingVersion": "Đang triển khai: {{version}}",diff --git a/web/i18n/zh-Hans/agent-v-2.json b/web/i18n/zh-Hans/agent-v-2.jsonindex d916191e0b0..7aa268f2ad9 100644--- a/web/i18n/zh-Hans/agent-v-2.json+++ b/web/i18n/zh-Hans/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "发布 Agent 后即可启用。","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "服务端 API 端点","agentDetail.access.serviceApi.endpoint": "服务 API 端点","agentDetail.access.serviceApi.title": "后端服务 API","agentDetail.access.status.inService": "服务中","agentDetail.access.status.outOfService": "已停用",+ "agentDetail.access.status.unavailable": "不可用","agentDetail.access.title": "访问点","agentDetail.access.toggleSurface": "切换 {{name}} 访问状态",- "agentDetail.access.webApp.accessUrl": "Web 应用 URL",- "agentDetail.access.webApp.actions.accessControl": "访问控制",- "agentDetail.access.webApp.actions.customize": "自定义前端",- "agentDetail.access.webApp.actions.embedded": "嵌入",- "agentDetail.access.webApp.actions.launch": "启动",- "agentDetail.access.webApp.actions.settings": "品牌设置",+ "agentDetail.access.webApp.accessUrl": "访问 URL",+ "agentDetail.access.webApp.actions.customFrontend": "自定义前端",+ "agentDetail.access.webApp.actions.embedIntoSite": "嵌入网站",+ "agentDetail.access.webApp.actions.open": "打开",+ "agentDetail.access.webApp.actions.settings": "设置",+ "agentDetail.access.webApp.description": "公开 Web 体验",+ "agentDetail.access.webApp.qrCode.download": "下载二维码",+ "agentDetail.access.webApp.qrCode.scanToShare": "扫码分享","agentDetail.access.webApp.refreshUrl": "刷新访问 URL",- "agentDetail.access.webApp.ssoEnabled": "已启用 SSO",+ "agentDetail.access.webApp.showQrCode": "显示二维码","agentDetail.access.webApp.title": "Web 应用","agentDetail.access.workflow.description": "作为工作流内的节点使用","agentDetail.access.workflow.empty": "暂无工作流引用。",diff --git a/web/i18n/zh-Hans/deployments.json b/web/i18n/zh-Hans/deployments.jsonindex e72c56c386c..fe2ef3ad1ff 100644--- a/web/i18n/zh-Hans/deployments.json+++ b/web/i18n/zh-Hans/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "更多操作","deployTab.redeploy": "重新部署","deployTab.undeploy": "下线",+ "deployTab.undeployUnavailable": "当前版本不可用,无法下线。","health.ENVIRONMENT_STATUS_FAILED": "不可用","list.emptyTitle": "暂无部署","overview.chip.latest": "最新",@@ -66,11 +67,14 @@"studio.environments": "环境","studio.environmentsInUse": "已使用 {{used}} / {{total}} 个环境","studio.lastActivity": "最近活动",+ "studio.latestVersionLoadFailed": "获取最新版本失败。","studio.liveVersion": "线上版本","studio.moreEnvironments": "更多环境","studio.noCredentialsYet": "暂无凭据","studio.noCredentialsYetDescription": "在集成或节点设置中添加凭据","studio.precheck.description": "它包含尚不支持的节点类型:",+ "studio.precheck.from": "来自",+ "studio.precheck.nodeCount_other": "{{count}} 个节点","studio.precheck.supportMessage": "未来版本将支持这些节点类型。","studio.precheck.title": "此版本无法部署到该环境","studio.publisher.deployingVersion": "部署中:{{version}}",diff --git a/web/i18n/zh-Hant/agent-v-2.json b/web/i18n/zh-Hant/agent-v-2.jsonindex 79aa11e50f3..22832f1a700 100644--- a/web/i18n/zh-Hant/agent-v-2.json+++ b/web/i18n/zh-Hant/agent-v-2.json@@ -7,20 +7,24 @@"agentDetail.access.publishRequired": "發布 Agent 後即可啟用。","agentDetail.access.serviceApi.actions.apiKey": "API Key","agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.description": "伺服器端 API 端點","agentDetail.access.serviceApi.endpoint": "服務 API 端點","agentDetail.access.serviceApi.title": "後端服務 API","agentDetail.access.status.inService": "服務中","agentDetail.access.status.outOfService": "已停止服務",+ "agentDetail.access.status.unavailable": "不可用","agentDetail.access.title": "存取點","agentDetail.access.toggleSurface": "切換 {{name}} 存取狀態",- "agentDetail.access.webApp.accessUrl": "Web 應用程式 URL",- "agentDetail.access.webApp.actions.accessControl": "存取控制",- "agentDetail.access.webApp.actions.customize": "自訂前端",- "agentDetail.access.webApp.actions.embedded": "嵌入",- "agentDetail.access.webApp.actions.launch": "啟動",- "agentDetail.access.webApp.actions.settings": "品牌設定",+ "agentDetail.access.webApp.accessUrl": "存取 URL",+ "agentDetail.access.webApp.actions.customFrontend": "自訂前端",+ "agentDetail.access.webApp.actions.embedIntoSite": "嵌入網站",+ "agentDetail.access.webApp.actions.open": "開啟",+ "agentDetail.access.webApp.actions.settings": "設定",+ "agentDetail.access.webApp.description": "公開 Web 體驗",+ "agentDetail.access.webApp.qrCode.download": "下載二維碼",+ "agentDetail.access.webApp.qrCode.scanToShare": "掃碼分享","agentDetail.access.webApp.refreshUrl": "重新整理存取 URL",- "agentDetail.access.webApp.ssoEnabled": "已啟用 SSO",+ "agentDetail.access.webApp.showQrCode": "顯示 QR 碼","agentDetail.access.webApp.title": "Web 應用程式","agentDetail.access.workflow.description": "作為工作流程內的節點使用","agentDetail.access.workflow.empty": "暫無工作流程引用。",diff --git a/web/i18n/zh-Hant/deployments.json b/web/i18n/zh-Hant/deployments.jsonindex 07da529f2ed..32d9da399be 100644--- a/web/i18n/zh-Hant/deployments.json+++ b/web/i18n/zh-Hant/deployments.json@@ -22,6 +22,7 @@"deployTab.moreActions": "更多操作","deployTab.redeploy": "重新部署","deployTab.undeploy": "下線",+ "deployTab.undeployUnavailable": "目前版本無法使用,無法下線。","health.ENVIRONMENT_STATUS_FAILED": "不可用","list.emptyTitle": "尚無部署","overview.chip.latest": "最新",@@ -66,11 +67,14 @@"studio.environments": "環境","studio.environmentsInUse": "已使用 {{used}} / {{total}} 個環境","studio.lastActivity": "最近活動",+ "studio.latestVersionLoadFailed": "取得最新版本失敗。","studio.liveVersion": "線上版本","studio.moreEnvironments": "更多環境","studio.noCredentialsYet": "尚無憑證","studio.noCredentialsYetDescription": "在整合或節點設定中新增憑證","studio.precheck.description": "它包含尚未支援的節點類型:",+ "studio.precheck.from": "來自",+ "studio.precheck.nodeCount_other": "{{count}} 個節點","studio.precheck.supportMessage": "未來版本將支援這些節點類型。","studio.precheck.title": "此版本無法部署到此環境","studio.publisher.deployingVersion": "部署中:{{version}}",diff --git a/web/service/__tests__/base-request.spec.ts b/web/service/__tests__/base-request.spec.tsindex 0da529bc10c..423232f1069 100644--- a/web/service/__tests__/base-request.spec.ts+++ b/web/service/__tests__/base-request.spec.ts@@ -5,12 +5,16 @@ import {REGISTRATION_SUCCESS_STORAGE_KEY,} from '@/app/components/base/amplitude/registration-session-state'// oxlint-disable-next-line no-restricted-imports -- This spec directly tests the legacy request owner.-import { request } from '../base'+import { request, ssePost, upload } from '../base'const mocks = vi.hoisted(() => ({isClient: true,baseFetch: vi.fn(),+ beginWebAppAuthorizationRecovery: vi.fn(),+ clearWebAppPassport: vi.fn(),+ completeWebAppAuthorizationRecovery: vi.fn(),refreshAccessTokenOrReLogin: vi.fn(),+ resolveWebAppAddress: vi.fn(),}))vi.mock('@/utils/client', () => ({@@ -41,6 +45,18 @@ vi.mock('../refresh-token', () => ({refreshAccessTokenOrReLogin: mocks.refreshAccessTokenOrReLogin,}))+vi.mock('../webapp-address', () => ({+ getWebAppPublicApiPath: (_address: unknown, path: string) => path,+ resolveWebAppAddress: mocks.resolveWebAppAddress,+}))++vi.mock('../webapp-auth', () => ({+ beginWebAppAuthorizationRecovery: mocks.beginWebAppAuthorizationRecovery,+ clearWebAppPassport: mocks.clearWebAppPassport,+ completeWebAppAuthorizationRecovery: mocks.completeWebAppAuthorizationRecovery,+ getWebAppPassport: vi.fn(() => ''),+}))+const createUnauthorizedResponse = () =>new Response(JSON.stringify({@@ -87,7 +103,12 @@ describe('request 401 handling', () => {beforeEach(() => {mocks.isClient = truemocks.baseFetch.mockReset()+ mocks.beginWebAppAuthorizationRecovery.mockReset()+ mocks.beginWebAppAuthorizationRecovery.mockReturnValue(true)+ mocks.clearWebAppPassport.mockReset()+ mocks.completeWebAppAuthorizationRecovery.mockReset()mocks.refreshAccessTokenOrReLogin.mockReset()+ mocks.resolveWebAppAddress.mockReset()Object.defineProperty(globalThis, 'location', {value: {origin: 'https://example.com',@@ -180,4 +201,160 @@ describe('request 401 handling', () => {expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBe('console-marker')})++ it('should reload an environment webapp after its passport becomes unauthorized', async () => {+ const address = { kind: 'environment', code: 'environment-code' } as const+ const response = new Response(+ JSON.stringify({+ code: 401,+ reason: 'APPDEPLOY_UNAUTHORIZED',+ message: 'Unauthorized',+ }),+ { status: 401, headers: { 'Content-Type': 'application/json' } },+ )+ mocks.resolveWebAppAddress.mockReturnValue(address)+ arrangeClientRequest({ response })++ await expect(request('/messages')).rejects.toBe(response)++ expect(mocks.clearWebAppPassport).toHaveBeenCalledWith(address)+ expect(globalThis.location.reload).toHaveBeenCalledOnce()+ expect(mocks.refreshAccessTokenOrReLogin).not.toHaveBeenCalled()+ })++ it('should complete authorization recovery after an environment request succeeds', async () => {+ const address = { kind: 'environment', code: 'environment-code' } as const+ mocks.resolveWebAppAddress.mockReturnValue(address)+ mocks.baseFetch.mockResolvedValue({ app_id: 'app-id' })++ await request('/site', {}, { isPublicAPI: true })++ expect(mocks.completeWebAppAuthorizationRecovery).toHaveBeenCalledWith(address)+ })++ it('should keep authorization recovery pending after passport succeeds', async () => {+ const address = { kind: 'environment', code: 'environment-code' } as const+ mocks.resolveWebAppAddress.mockReturnValue(address)+ mocks.baseFetch.mockResolvedValue({ access_token: 'passport' })++ await request('/passport', {}, { isPublicAPI: true })++ expect(mocks.completeWebAppAuthorizationRecovery).not.toHaveBeenCalled()+ })++ it('should show forbidden when an environment SSE request is denied', async () => {+ const address = { kind: 'environment', code: 'environment-code' } as const+ mocks.resolveWebAppAddress.mockReturnValue(address)+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ code: 401,+ reason: 'APPDEPLOY_WEB_APP_ACCESS_DENIED',+ message: 'You do not have permission to access this web app.',+ }),+ { status: 401, headers: { 'Content-Type': 'application/json' } },+ ),+ )++ ssePost('/chat-messages', { body: { query: 'hello' } }, { isPublicAPI: true })++ await vi.waitFor(() => {+ expect(globalThis.location.href).toContain('/webapp-signin?')+ expect(globalThis.location.href).toContain('code=403')+ })+ expect(mocks.clearWebAppPassport).not.toHaveBeenCalled()+ expect(globalThis.location.reload).not.toHaveBeenCalled()+ })++ it('should stop reloading when environment authorization does not recover', async () => {+ const address = { kind: 'environment', code: 'environment-code' } as const+ const response = new Response(+ JSON.stringify({+ code: 401,+ reason: 'APPDEPLOY_UNAUTHORIZED',+ message: 'Unauthorized',+ }),+ { status: 401, headers: { 'Content-Type': 'application/json' } },+ )+ mocks.resolveWebAppAddress.mockReturnValue(address)+ mocks.beginWebAppAuthorizationRecovery.mockReturnValue(false)+ arrangeClientRequest({ response })++ await expect(request('/site')).rejects.toBe(response)++ expect(mocks.clearWebAppPassport).not.toHaveBeenCalled()+ expect(globalThis.location.reload).not.toHaveBeenCalled()+ expect(globalThis.location.href).toContain('/webapp-signin?')+ expect(globalThis.location.href).toContain('message=Unauthorized')+ })++ it('should report a public SSE 403 that is not recoverable', async () => {+ const onError = vi.fn()+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ code: 'web_app_disabled',+ message: 'webapp is disabled',+ }),+ { status: 403, headers: { 'Content-Type': 'application/json' } },+ ),+ )++ ssePost('/chat-messages', { body: { query: 'hello' } }, { isPublicAPI: true, onError })++ await vi.waitFor(() => {+ expect(onError).toHaveBeenCalledWith('webapp is disabled', 'web_app_disabled')+ })+ expect(mocks.beginWebAppAuthorizationRecovery).not.toHaveBeenCalled()+ })++ it('should show forbidden when an environment request is denied', async () => {+ const address = { kind: 'environment', code: 'environment-code' } as const+ const response = new Response(+ JSON.stringify({+ code: 401,+ reason: 'APPDEPLOY_WEB_APP_ACCESS_DENIED',+ message: 'You do not have permission to access this web app.',+ }),+ { status: 401, headers: { 'Content-Type': 'application/json' } },+ )+ mocks.resolveWebAppAddress.mockReturnValue(address)+ arrangeClientRequest({ response })++ await expect(request('/messages', {}, { isPublicAPI: true })).rejects.toBe(response)++ expect(globalThis.location.href).toContain('/webapp-signin?')+ expect(globalThis.location.href).toContain('code=403')+ expect(mocks.clearWebAppPassport).not.toHaveBeenCalled()+ expect(globalThis.location.reload).not.toHaveBeenCalled()+ })++ it('should show forbidden when an environment upload is denied', async () => {+ const address = { kind: 'environment', code: 'environment-code' } as const+ mocks.resolveWebAppAddress.mockReturnValue(address)+ const xhr = {+ open: vi.fn(),+ setRequestHeader: vi.fn(),+ send: vi.fn(function (this: { onreadystatechange?: () => void }) {+ this.onreadystatechange?.()+ }),+ status: 401,+ response: {+ code: 401,+ reason: 'APPDEPLOY_WEB_APP_ACCESS_DENIED',+ message: 'You do not have permission to access this web app.',+ },+ readyState: 4,+ upload: {},+ withCredentials: false,+ responseType: '',+ } as unknown as XMLHttpRequest++ await expect(upload({ xhr, data: new FormData() }, true)).rejects.toBe(xhr)++ expect(globalThis.location.href).toContain('/webapp-signin?')+ expect(globalThis.location.href).toContain('code=403')+ expect(mocks.clearWebAppPassport).not.toHaveBeenCalled()+ expect(globalThis.location.reload).not.toHaveBeenCalled()+ })})diff --git a/web/service/__tests__/use-workflow.spec.tsx b/web/service/__tests__/use-workflow.spec.tsxindex d915493928f..9d37b902c40 100644--- a/web/service/__tests__/use-workflow.spec.tsx+++ b/web/service/__tests__/use-workflow.spec.tsx@@ -1,9 +1,33 @@+import type {+ WorkflowPaginationResponse,+ WorkflowResponse,+} from '@dify/contracts/api/console/apps/types.gen'+import type {+ EnvironmentDeployment,+ GetEnvironmentDeploymentResponse,+ ListEnvironmentDeploymentsResponse,+ WorkflowVersion,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { InfiniteData } from '@tanstack/react-query'import type { ReactNode } from 'react'+import {+ DeploymentOperationStatus,+ DeploymentOperationType,+ EnvironmentStatus,+ OperatorType,+ RuntimeState,+} from '@dify/contracts/enterprise-app-deploy/types.gen'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { AppModeEnum } from '@/types/app'+import { consoleQuery } from '../client'import { useUpdateWorkflow } from '../use-workflow'-import { appWorkflowVersionsInfiniteQueryKey } from '../workflow-queries'+import {+ appWorkflowQueryOptions,+ appWorkflowVersionsInfiniteQueryKey,+ appWorkflowVersionsInfiniteQueryOptions,+} from '../workflow-queries'const mockPatch = vi.hoisted(() => vi.fn())@@ -20,6 +44,71 @@ const createWrapper = (queryClient: QueryClient) =>return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>}+const createQueryClient = () =>+ new QueryClient({+ defaultOptions: {+ mutations: { retry: false },+ queries: { retry: false },+ },+ })++const createWorkflow = (overrides: Partial<WorkflowResponse> = {}): WorkflowResponse => ({+ conversation_variables: [],+ created_at: 1_710_000_100,+ environment_variables: [],+ features: {},+ graph: {},+ hash: 'hash-workflow-1',+ id: 'workflow-1',+ marked_comment: 'Old notes',+ marked_name: 'Old release',+ rag_pipeline_variables: [],+ tool_published: false,+ updated_at: 1_710_000_100,+ version: '2026-08-21.1',+ version_number: 1,+ ...overrides,+})++const createEnvironmentDeployment = ({+ currentVersion,+ environmentId,+ targetVersion,+}: {+ currentVersion?: WorkflowVersion+ environmentId: string+ targetVersion?: WorkflowVersion+}): EnvironmentDeployment => ({+ access: {+ enable_api: false,+ enable_site: false,+ },+ deployment: {+ current_version: currentVersion,+ latest_operation: targetVersion+ ? {+ activity_at: 1_710_000_200,+ id: `operation-${environmentId}`,+ operator: {+ display_name: 'Alice',+ id: 'user-1',+ type: OperatorType.OPERATOR_TYPE_ACCOUNT,+ },+ status: DeploymentOperationStatus.DEPLOYMENT_OPERATION_STATUS_SUCCEEDED,+ target_version: targetVersion,+ type: DeploymentOperationType.DEPLOYMENT_OPERATION_TYPE_DEPLOY,+ }+ : undefined,+ runtimeState: RuntimeState.RUNTIME_STATE_RUNNING,+ },+ environment: {+ description: `${environmentId} environment`,+ display_name: environmentId,+ id: environmentId,+ status: EnvironmentStatus.ENVIRONMENT_STATUS_READY,+ },+})+describe('useUpdateWorkflow', () => {beforeEach(() => {vi.clearAllMocks()@@ -27,12 +116,7 @@ describe('useUpdateWorkflow', () => {})it('should invalidate workflow version history after updating version information', async () => {- const queryClient = new QueryClient({- defaultOptions: {- mutations: { retry: false },- queries: { retry: false },- },- })+ const queryClient = createQueryClient()const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')const { result } = renderHook(() => useUpdateWorkflow(), {wrapper: createWrapper(queryClient),@@ -53,4 +137,266 @@ describe('useUpdateWorkflow', () => {queryKey: appWorkflowVersionsInfiniteQueryKey(),})})++ it.each([AppModeEnum.WORKFLOW, AppModeEnum.ADVANCED_CHAT])(+ 'should synchronize every cached app deployment reference to the updated workflow version (%s)',+ async (appMode) => {+ const queryClient = createQueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ const oldVersion: WorkflowVersion = {+ id: 'workflow-1',+ marked_comment: 'Old notes',+ marked_name: 'Old release',+ version: '2026-08-21.1',+ version_number: 1,+ }+ const unrelatedVersion: WorkflowVersion = {+ id: 'workflow-2',+ marked_comment: 'Keep these notes',+ marked_name: 'Keep this release',+ version: '2026-08-20.1',+ version_number: 2,+ }+ const updatedWorkflow = createWorkflow({+ marked_comment: '',+ marked_name: '',+ updated_at: 1_710_000_300,+ })+ const workflowVersionsQuery = appWorkflowVersionsInfiniteQueryOptions('app-1')+ const publishedWorkflowQuery = appWorkflowQueryOptions('app-1')+ const deploymentsQuery =+ consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions(+ {+ input: {+ params: {+ app_id: 'app-1',+ },+ },+ },+ )+ const deploymentDetailQuery =+ consoleQuery.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.queryOptions({+ input: {+ params: {+ app_id: 'app-1',+ environment_id: 'staging',+ },+ },+ })+ const stagingDeployment = createEnvironmentDeployment({+ currentVersion: oldVersion,+ environmentId: 'staging',+ targetVersion: oldVersion,+ })+ const productionDeployment = createEnvironmentDeployment({+ currentVersion: unrelatedVersion,+ environmentId: 'production',+ targetVersion: oldVersion,+ })++ queryClient.setQueryData(publishedWorkflowQuery.queryKey, createWorkflow())+ queryClient.setQueryData<InfiniteData<WorkflowPaginationResponse>>(+ workflowVersionsQuery.queryKey,+ {+ pageParams: [1],+ pages: [+ {+ has_more: false,+ items: [createWorkflow(), createWorkflow({ id: 'workflow-2' })],+ limit: 10,+ page: 1,+ },+ ],+ },+ )+ queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(deploymentsQuery.queryKey, {+ environment_deployments: [stagingDeployment, productionDeployment],+ })+ queryClient.setQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey, {+ environment_deployment: stagingDeployment,+ })+ mockPatch.mockResolvedValueOnce(updatedWorkflow)+ const { result } = renderHook(() => useUpdateWorkflow(), {+ wrapper: createWrapper(queryClient),+ })++ await act(async () => {+ await result.current.mutateAsync({+ appId: 'app-1',+ appMode,+ url: '/apps/app-1/workflows/workflow-1',+ title: '',+ releaseNotes: '',+ })+ })++ expect(queryClient.getQueryData<WorkflowResponse>(publishedWorkflowQuery.queryKey)).toEqual(+ updatedWorkflow,+ )+ expect(+ queryClient.getQueryData<InfiniteData<WorkflowPaginationResponse>>(+ workflowVersionsQuery.queryKey,+ )?.pages[0]?.items,+ ).toEqual([updatedWorkflow, createWorkflow({ id: 'workflow-2' })])++ const deployments = queryClient.getQueryData<ListEnvironmentDeploymentsResponse>(+ deploymentsQuery.queryKey,+ )?.environment_deployments+ expect(deployments?.[0]?.deployment?.current_version).toEqual({+ ...oldVersion,+ marked_comment: '',+ marked_name: '',+ })+ expect(deployments?.[0]?.deployment?.latest_operation?.target_version).toEqual({+ ...oldVersion,+ marked_comment: '',+ marked_name: '',+ })+ expect(deployments?.[1]?.deployment?.current_version).toBe(unrelatedVersion)+ expect(deployments?.[1]?.deployment?.latest_operation?.target_version).toEqual({+ ...oldVersion,+ marked_comment: '',+ marked_name: '',+ })++ expect(+ queryClient.getQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey)+ ?.environment_deployment.deployment?.current_version,+ ).toEqual({+ ...oldVersion,+ marked_comment: '',+ marked_name: '',+ })+ expect(+ queryClient.getQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey)+ ?.environment_deployment.deployment?.latest_operation?.target_version,+ ).toEqual({+ ...oldVersion,+ marked_comment: '',+ marked_name: '',+ })+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: deploymentsQuery.queryKey,+ })+ },+ )++ it('should keep the latest published workflow when editing an older app version', async () => {+ const queryClient = createQueryClient()+ const latestWorkflow = createWorkflow({+ id: 'workflow-2',+ marked_comment: 'Latest notes',+ marked_name: 'Latest release',+ })+ const publishedWorkflowQuery = appWorkflowQueryOptions('app-1')+ queryClient.setQueryData(publishedWorkflowQuery.queryKey, latestWorkflow)+ mockPatch.mockResolvedValueOnce(+ createWorkflow({ marked_comment: 'Updated notes', marked_name: 'Updated release' }),+ )+ const { result } = renderHook(() => useUpdateWorkflow(), {+ wrapper: createWrapper(queryClient),+ })++ await act(async () => {+ await result.current.mutateAsync({+ appId: 'app-1',+ url: '/apps/app-1/workflows/workflow-1',+ title: 'Updated release',+ releaseNotes: 'Updated notes',+ })+ })++ expect(queryClient.getQueryData(publishedWorkflowQuery.queryKey)).toBe(latestWorkflow)+ })++ it('should skip deployment caches when editing a non-workflow app version', async () => {+ const queryClient = createQueryClient()+ const oldVersion: WorkflowVersion = {+ id: 'workflow-1',+ marked_comment: 'Old notes',+ marked_name: 'Old release',+ }+ const deployment = createEnvironmentDeployment({+ currentVersion: oldVersion,+ environmentId: 'staging',+ targetVersion: oldVersion,+ })+ const cachedDeployments: ListEnvironmentDeploymentsResponse = {+ environment_deployments: [deployment],+ }+ const deploymentsQuery =+ consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: {+ app_id: 'app-1',+ },+ },+ })+ const publishedWorkflowQuery = appWorkflowQueryOptions('app-1')+ const updatedWorkflow = createWorkflow({+ marked_comment: 'New notes',+ marked_name: 'New release',+ })+ queryClient.setQueryData(deploymentsQuery.queryKey, cachedDeployments)+ queryClient.setQueryData(publishedWorkflowQuery.queryKey, createWorkflow())+ mockPatch.mockResolvedValueOnce(updatedWorkflow)+ const { result } = renderHook(() => useUpdateWorkflow(), {+ wrapper: createWrapper(queryClient),+ })++ await act(async () => {+ await result.current.mutateAsync({+ appId: 'app-1',+ appMode: AppModeEnum.CHAT,+ url: '/apps/app-1/workflows/workflow-1',+ title: 'New release',+ releaseNotes: 'New notes',+ })+ })++ expect(queryClient.getQueryData(deploymentsQuery.queryKey)).toBe(cachedDeployments)+ expect(queryClient.getQueryData(publishedWorkflowQuery.queryKey)).toEqual(updatedWorkflow)+ })++ it('should leave app deployment caches unchanged for non-app workflow updates', async () => {+ const queryClient = createQueryClient()+ const oldVersion: WorkflowVersion = {+ id: 'workflow-1',+ marked_comment: 'Old notes',+ marked_name: 'Old release',+ }+ const deployment = createEnvironmentDeployment({+ currentVersion: oldVersion,+ environmentId: 'staging',+ })+ const deploymentsQuery =+ consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: {+ app_id: 'app-1',+ },+ },+ })+ queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(deploymentsQuery.queryKey, {+ environment_deployments: [deployment],+ })+ mockPatch.mockResolvedValueOnce(+ createWorkflow({ marked_comment: 'New notes', marked_name: 'New release' }),+ )+ const { result } = renderHook(() => useUpdateWorkflow(), {+ wrapper: createWrapper(queryClient),+ })++ await act(async () => {+ await result.current.mutateAsync({+ url: '/snippets/snippet-1/workflows/workflow-1',+ title: 'New release',+ releaseNotes: 'New notes',+ })+ })++ expect(+ queryClient.getQueryData<ListEnvironmentDeploymentsResponse>(deploymentsQuery.queryKey),+ ).toEqual({ environment_deployments: [deployment] })+ })})diff --git a/web/service/base.spec.ts b/web/service/base.spec.tsindex d4ee867810c..2360eefc26a 100644--- a/web/service/base.spec.ts+++ b/web/service/base.spec.ts@@ -701,7 +701,7 @@ describe('ssePost and sseGet', () => {})it('uses the environment webapp API for workflow runs and stops', async () => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }))@@ -709,17 +709,19 @@ describe('ssePost and sseGet', () => {await ssePost('/workflows/run', { body: { inputs: {} } }, { isPublicAPI: true })await postPublic('/workflows/tasks/task-1/stop')- expect(fetchSpy.mock.calls[0]![0]).toBe(`${PUBLIC_API_PREFIX}/env/workflow-app/workflows/run`)+ expect(fetchSpy.mock.calls[0]![0]).toBe(+ `${PUBLIC_API_PREFIX}/environment/workflow-app/workflows/run`,+ )const stopRequest = fetchSpy.mock.calls[1]![0]expect(stopRequest).toBeInstanceOf(Request)if (!(stopRequest instanceof Request)) throw new TypeError('Expected a request')expect(stopRequest.url).toBe(- `${PUBLIC_API_PREFIX}/env/workflow-app/workflows/tasks/task-1/stop`,+ `${PUBLIC_API_PREFIX}/environment/workflow-app/workflows/tasks/task-1/stop`,)})it('uses the environment webapp API for local and remote uploads', async () => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')const urls: string[] = []const createXhr = () => {const xhr = {@@ -742,8 +744,8 @@ describe('ssePost and sseGet', () => {await upload({ xhr: createXhr(), data: new FormData() }, true, '/remote-files/upload')expect(urls).toEqual([- `${PUBLIC_API_PREFIX}/env/workflow-app/files/upload`,- `${PUBLIC_API_PREFIX}/env/workflow-app/remote-files/upload`,+ `${PUBLIC_API_PREFIX}/environment/workflow-app/files/upload`,+ `${PUBLIC_API_PREFIX}/environment/workflow-app/remote-files/upload`,])})})diff --git a/web/service/base.ts b/web/service/base.tsindex ea2435fdb6b..4d0d2f9c9f9 100644--- a/web/service/base.ts+++ b/web/service/base.ts@@ -46,10 +46,54 @@ import { basePath } from '@/utils/var'import { base, ContentType, getBaseOptions } from './fetch'import { refreshAccessTokenOrReLogin } from './refresh-token'import { getWebAppPublicApiPath, resolveWebAppAddress } from './webapp-address'-import { getWebAppPassport } from './webapp-auth'+import {+ beginWebAppAuthorizationRecovery,+ clearWebAppPassport,+ completeWebAppAuthorizationRecovery,+ getWebAppPassport,+} from './webapp-auth'const TIME_OUT = 100000+const isWebAppAuthorizationEndpoint = (url: string) =>+ /\/(?:login(?:\/|\?|$)|passport(?:\?|$))/.test(url)++const recoverEnvironmentWebAppAuthorization = (+ error: { code?: string | number; message?: string; reason?: string },+ url?: string,+) => {+ const address = resolveWebAppAddress()+ if (+ address?.kind !== 'environment' ||+ (error.reason !== 'APPDEPLOY_UNAUTHORIZED' && error.code !== 'unauthorized') ||+ (url && isWebAppAuthorizationEndpoint(url))+ )+ return false++ if (!beginWebAppAuthorizationRecovery(address)) {+ requiredWebSSOLogin(error.message, 403)+ return true+ }++ clearWebAppPassport(address)+ window.location.reload()+ return true+}++const handleWebAppAuthorizationError = (+ error: { code?: string | number; message?: string; reason?: string },+ url?: string,+) => {+ if (+ error.reason === 'APPDEPLOY_WEB_APP_ACCESS_DENIED' ||+ error.code === 'web_app_access_denied'+ ) {+ requiredWebSSOLogin(error.message, 403)+ return true+ }+ return recoverEnvironmentWebAppAuthorization(error, url)+}+const isAbortError = (error: unknown) => {if (typeof error === 'string') return error === 'AbortError' || error.startsWith('AbortError:')@@ -106,6 +150,31 @@ const reportStreamResponseError = async (}}+const handlePublicStreamResponseError = async (+ response: Response,+ onError: IOnError | undefined,+ onNotifyError: IOnError | undefined,+ silent: boolean | undefined,+) => {+ let data: { code?: string; message?: string; reason?: string } | undefined+ try {+ data = (await response.clone().json()) as typeof data+ } catch {}++ if (data) {+ if (handleWebAppAuthorizationError(data)) return+ if (data.code === 'web_sso_auth_required' || data.code === 'unauthorized') {+ requiredWebSSOLogin()+ return+ }+ }++ if (onNotifyError && !silent) await reportStreamResponseError(response, onError, onNotifyError)+ else if (!silent)+ await reportStreamResponseError(response, onError, (message) => toast.error(message))+ else await reportStreamResponseError(response, onError)+}+type UnhandledEventError = {conversationId?: stringerrorCode?: string@@ -558,7 +627,16 @@ export const upload = async (xhr.onreadystatechange = function () {if (xhr.readyState === 4) {if (xhr.status === 201) resolve(xhr.response)- else reject(xhr)+ else {+ if (+ isPublicAPI &&+ (xhr.status === 401 || xhr.status === 403) &&+ typeof xhr.response === 'object' &&+ xhr.response !== null+ )+ handleWebAppAuthorizationError(xhr.response)+ reject(xhr)+ }}}if (mergedOptions.onprogress) xhr.upload.onprogress = mergedOptions.onprogress@@ -647,17 +725,9 @@ export const ssePost = async (.fetch(urlWithPrefix, options as RequestInit).then((res) => {if (!/^[23]\d{2}$/.test(String(res.status))) {- if (res.status === 401) {+ if (res.status === 401 || (res.status === 403 && isPublicAPI)) {if (isPublicAPI) {- res.json().then((data: { code?: string; message?: string }) => {- if (isPublicAPI) {- if (data.code === 'web_app_access_denied') requiredWebSSOLogin(data.message, 403)-- if (data.code === 'web_sso_auth_required') requiredWebSSOLogin()-- if (data.code === 'unauthorized') requiredWebSSOLogin()- }- })+ void handlePublicStreamResponseError(res, onError, onNotifyError, silent)} else {refreshAccessTokenOrReLogin(TIME_OUT).then(() => {@@ -810,17 +880,9 @@ export const sseGet = async (.fetch(urlWithPrefix, options as RequestInit).then((res) => {if (!/^[23]\d{2}$/.test(String(res.status))) {- if (res.status === 401) {+ if (res.status === 401 || (res.status === 403 && isPublicAPI)) {if (isPublicAPI) {- res.json().then((data: { code?: string; message?: string }) => {- if (isPublicAPI) {- if (data.code === 'web_app_access_denied') requiredWebSSOLogin(data.message, 403)-- if (data.code === 'web_sso_auth_required') requiredWebSSOLogin()-- if (data.code === 'unauthorized') requiredWebSSOLogin()- }- })+ void handlePublicStreamResponseError(res, onError, onNotifyError, silent)} else {refreshAccessTokenOrReLogin(TIME_OUT).then(() => {@@ -1009,37 +1071,41 @@ export const sseGeneratorPost = (export const request = async <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {try {const otherOptionsForBaseFetch = otherOptions || {}+ const { isPublicAPI = false, silent } = otherOptionsForBaseFetchconst [err, resp] = await asyncRunSafe<T>(baseFetch(url, options, otherOptionsForBaseFetch))- if (err === null) return resp+ if (err === null) {+ const address = resolveWebAppAddress()+ if (isPublicAPI && address?.kind === 'environment' && !isWebAppAuthorizationEndpoint(url))+ completeWebAppAuthorizationRecovery(address)+ return resp+ }const errResp: Response = err as any- if (errResp.status === 401) {+ if (errResp.status === 401 || (errResp.status === 403 && isPublicAPI)) {if (!isClient) return Promise.reject(err)const [parseErr, errRespData] = await asyncRunSafe<ResponseError>(errResp.json())if (parseErr) {- discardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)- window.location.href = buildSigninUrlWithRedirect()+ if (errResp.status === 401) {+ discardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)+ window.location.href = buildSigninUrlWithRedirect()+ }return Promise.reject(err)}if (/\/login/.test(url)) return Promise.reject(errRespData)+ if (handleWebAppAuthorizationError(errRespData, url)) return Promise.reject(err)// special codeconst { code, message } = errRespData- // webapp sso- if (code === 'web_app_access_denied') {- requiredWebSSOLogin(message, 403)- return Promise.reject(err)- }if (code === 'web_sso_auth_required') {requiredWebSSOLogin()return Promise.reject(err)}+ if (errResp.status === 403) return Promise.reject(err)if (code === 'unauthorized_and_force_logout') {// Cookies will be cleared by the backenddiscardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)window.location.reload()return Promise.reject(err)}- const { isPublicAPI = false, silent } = otherOptionsForBaseFetchif (isPublicAPI && code === 'unauthorized') {requiredWebSSOLogin()return Promise.reject(err)diff --git a/web/service/client.spec.ts b/web/service/client.spec.tsindex 6179e5cf9e0..9c0ca738bdb 100644--- a/web/service/client.spec.ts+++ b/web/service/client.spec.ts@@ -1,6 +1,7 @@import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'import type { AppDetail, AppSiteResponse } from '@dify/contracts/api/console/apps/types.gen'import type { TagResponse as Tag } from '@dify/contracts/api/console/tags/types.gen'+import type { EnvironmentDeployment } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { DocumentProcessingTaskEvent } from '@dify/contracts/knowledge-fs/types.gen'import type { MutationFunctionContext, QueryFunctionContext } from '@tanstack/react-query'import type { consoleQuery as ConsoleQuery } from './client'@@ -1672,6 +1673,148 @@ describe('consoleQuery App Deploy mutation defaults', () => {vi.restoreAllMocks()})+ it('should synchronize environment access details and deployment summaries after toggles', async () => {+ const consoleQuery = await loadConsoleQuery()+ const queryClient = new QueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ const params = {+ app_id: 'app-1',+ environment_id: 'staging',+ }+ const siteQuery =+ consoleQuery.enterprise.appDeploy.accessService.getEnvironmentSite.queryOptions({+ input: { params },+ })+ const apiQuery = consoleQuery.enterprise.appDeploy.accessService.getEnvironmentApi.queryOptions(+ {+ input: { params },+ },+ )+ const deploymentsQuery =+ consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: {+ app_id: params.app_id,+ },+ },+ })+ const deploymentQuery =+ consoleQuery.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.queryOptions({+ input: { params },+ })+ const stagingDeployment: EnvironmentDeployment = {+ access: {+ enable_api: false,+ enable_site: false,+ },+ environment: {+ description: 'Staging environment',+ display_name: 'Staging',+ id: params.environment_id,+ status: 'ENVIRONMENT_STATUS_READY',+ },+ }+ const productionDeployment: EnvironmentDeployment = {+ access: {+ enable_api: false,+ enable_site: false,+ },+ environment: {+ description: 'Production environment',+ display_name: 'Production',+ id: 'production',+ status: 'ENVIRONMENT_STATUS_READY',+ },+ }+ const updatedSite = {+ access_mode: 'private',+ app_base_url: 'https://site.example.test',+ code: 'staging-code',+ enabled: true,+ }+ const updatedApi = {+ api_key_count: 2,+ base_url: 'https://api.example.test/v1',+ enabled: true,+ }++ queryClient.setQueryData(siteQuery.queryKey, { ...updatedSite, enabled: false })+ queryClient.setQueryData(apiQuery.queryKey, { ...updatedApi, enabled: false })+ queryClient.setQueryData(deploymentsQuery.queryKey, {+ environment_deployments: [stagingDeployment, productionDeployment],+ })+ queryClient.setQueryData(deploymentQuery.queryKey, {+ environment_deployment: stagingDeployment,+ })++ const siteMutation =+ consoleQuery.enterprise.appDeploy.accessService.updateEnvironmentSite.mutationOptions()+ await siteMutation.onSuccess?.(+ updatedSite,+ { body: { enabled: true }, params },+ undefined,+ createMutationContext(queryClient),+ )++ expect(queryClient.getQueryData(siteQuery.queryKey)).toEqual(updatedSite)+ expect(queryClient.getQueryData(deploymentsQuery.queryKey)).toEqual({+ environment_deployments: [+ {+ ...stagingDeployment,+ access: {+ enable_api: false,+ enable_site: true,+ },+ },+ productionDeployment,+ ],+ })+ expect(queryClient.getQueryData(deploymentQuery.queryKey)).toEqual({+ environment_deployment: {+ ...stagingDeployment,+ access: {+ enable_api: false,+ enable_site: true,+ },+ },+ })++ const apiMutation =+ consoleQuery.enterprise.appDeploy.accessService.updateEnvironmentApi.mutationOptions()+ await apiMutation.onSuccess?.(+ updatedApi,+ { body: { enabled: true }, params },+ undefined,+ createMutationContext(queryClient),+ )++ expect(queryClient.getQueryData(apiQuery.queryKey)).toEqual(updatedApi)+ expect(queryClient.getQueryData(deploymentsQuery.queryKey)).toEqual({+ environment_deployments: [+ {+ ...stagingDeployment,+ access: {+ enable_api: true,+ enable_site: true,+ },+ },+ productionDeployment,+ ],+ })+ expect(queryClient.getQueryData(deploymentQuery.queryKey)).toEqual({+ environment_deployment: {+ ...stagingDeployment,+ access: {+ enable_api: true,+ enable_site: true,+ },+ },+ })+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: deploymentsQuery.queryKey })+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: deploymentQuery.queryKey })+ expect(invalidateQueries).toHaveBeenCalledTimes(4)+ })+it('should invalidate the environment key list and API summary after creating or deleting a key', async () => {const consoleQuery = await loadConsoleQuery()const queryClient = new QueryClient()@@ -1772,7 +1915,7 @@ describe('consoleQuery App Deploy mutation defaults', () => {consoleQuery.enterprise.appDeploy.deploymentService.deployWorkflow.mutationOptions()await deployOptions.onSuccess?.(response,- { body: {}, params },+ { body: { environment_variable_groups: [] }, params },undefined,createMutationContext(queryClient),)diff --git a/web/service/client.ts b/web/service/client.tsindex 55905882b78..a5a4a6a684c 100644--- a/web/service/client.ts+++ b/web/service/client.ts@@ -5,6 +5,11 @@ import type {import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'import type { TagResponse as Tag, TagType } from '@dify/contracts/api/console/tags/types.gen'import type { consoleRouterContract } from '@dify/contracts/console'+import type {+ EnvironmentAccess,+ GetEnvironmentDeploymentResponse,+ ListEnvironmentDeploymentsResponse,+} from '@dify/contracts/enterprise-app-deploy/types.gen'import type {GetReleaseResponse,ListReleasesResponse,@@ -181,27 +186,40 @@ function invalidateEnvironmentApiKeyQueries(])}-function invalidateWorkflowDeploymentQueries(+function environmentDeploymentQueries(query: ConsoleQueryUtils,- client: QueryClient,params: { app_id: string; environment_id: string },- { appEnvironments }: { appEnvironments: boolean },) {const environmentParams = {app_id: params.app_id,environment_id: params.environment_id,}- const queryKeys: QueryKey[] = [- query.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({- input: {- params: {- app_id: params.app_id,- },- },- }).queryKey,- query.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.queryOptions({++ return {+ deployment: query.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.queryOptions({input: { params: environmentParams },- }).queryKey,+ }),+ deployments:+ query.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: {+ app_id: params.app_id,+ },+ },+ }),+ }+}++function invalidateEnvironmentDeploymentQueries(+ query: ConsoleQueryUtils,+ client: QueryClient,+ params: { app_id: string; environment_id: string },+ { appEnvironments }: { appEnvironments: boolean },+) {+ const environmentQueries = environmentDeploymentQueries(query, params)+ const queryKeys: QueryKey[] = [+ environmentQueries.deployments.queryKey,+ environmentQueries.deployment.queryKey,]if (appEnvironments) {@@ -219,6 +237,65 @@ function invalidateWorkflowDeploymentQueries(return invalidateQueryKeys(client, queryKeys)}+function syncEnvironmentAccessCaches(+ query: ConsoleQueryUtils,+ client: QueryClient,+ params: { app_id: string; environment_id: string },+ accessPatch: Partial<EnvironmentAccess>,+) {+ const environmentQueries = environmentDeploymentQueries(query, params)++ client.setQueryData<ListEnvironmentDeploymentsResponse>(+ environmentQueries.deployments.queryKey,+ (current) => {+ if (+ !current?.environment_deployments.some(+ (deployment) => deployment.environment.id === params.environment_id,+ )+ )+ return current++ return {+ ...current,+ environment_deployments: current.environment_deployments.map((deployment) =>+ deployment.environment.id === params.environment_id+ ? {+ ...deployment,+ access: {+ ...deployment.access,+ ...accessPatch,+ },+ }+ : deployment,+ ),+ }+ },+ )+ client.setQueryData<GetEnvironmentDeploymentResponse>(+ environmentQueries.deployment.queryKey,+ (current) => {+ if (!current || current.environment_deployment.environment.id !== params.environment_id)+ return current++ return {+ ...current,+ environment_deployment: {+ ...current.environment_deployment,+ access: {+ ...current.environment_deployment.access,+ ...accessPatch,+ },+ },+ }+ },+ )++ return invalidateQueryKeys(client, [+ environmentQueries.deployments.queryKey,+ environmentQueries.deployment.queryKey,+ ])+}+function appInstanceQueryKey(query: ConsoleQueryUtils, appInstanceId: string) {return query.enterprise.appInstanceService.getAppInstance.key({type: 'query',@@ -1311,12 +1388,52 @@ export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQue},},},+ updateEnvironmentApi: {+ mutationOptions: {+ onSuccess: (updatedApi, variables, _result, context) => {+ context.client.setQueryData(+ consoleQuery.enterprise.appDeploy.accessService.getEnvironmentApi.queryOptions({+ input: { params: variables.params },+ }).queryKey,+ updatedApi,+ )++ return syncEnvironmentAccessCaches(+ consoleQuery,+ context.client,+ variables.params,+ { enable_api: updatedApi.enabled },+ )+ },+ },+ },+ updateEnvironmentSite: {+ mutationOptions: {+ onSuccess: (updatedSite, variables, _result, context) => {+ context.client.setQueryData(+ consoleQuery.enterprise.appDeploy.accessService.getEnvironmentSite.queryOptions(+ {+ input: { params: variables.params },+ },+ ).queryKey,+ updatedSite,+ )++ return syncEnvironmentAccessCaches(+ consoleQuery,+ context.client,+ variables.params,+ { enable_site: updatedSite.enabled },+ )+ },+ },+ },},deploymentService: {deployWorkflow: {mutationOptions: {onSuccess: (_data, variables, _result, context) => {- return invalidateWorkflowDeploymentQueries(+ return invalidateEnvironmentDeploymentQueries(consoleQuery,context.client,variables.params,@@ -1328,7 +1445,7 @@ export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQueundeployWorkflow: {mutationOptions: {onSuccess: (_data, variables, _result, context) => {- return invalidateWorkflowDeploymentQueries(+ return invalidateEnvironmentDeploymentQueries(consoleQuery,context.client,variables.params,diff --git a/web/service/fetch.spec.ts b/web/service/fetch.spec.tsindex 9e9d1c832c3..55c7cc613cc 100644--- a/web/service/fetch.spec.ts+++ b/web/service/fetch.spec.ts@@ -59,7 +59,7 @@ describe('base', () => {it.each(['/passport', '/webapp/permission', '/workflows/run', 'parameters', 'meta'])('should route %s to the environment webapp API',async (path) => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ result: 'ok' })))@@ -70,18 +70,17 @@ describe('base', () => {if (!(request instanceof Request))throw new TypeError('Expected fetch to receive a Request')const expectedPath = path.startsWith('/') ? path : `/${path}`- expect(request.url).toBe(`${PUBLIC_API_PREFIX}/env/workflow-app${expectedPath}`)+ expect(request.url).toBe(`${PUBLIC_API_PREFIX}/environment/workflow-app${expectedPath}`)},)it.each([- '/login/status','/email-code-login/validity','/forgot-password','/forgot-password/validity','/enterprise/sso/members/oidc/login',])('should keep environment auth path %s on Dify public API', async (path) => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ result: 'ok' })))@@ -92,6 +91,19 @@ describe('base', () => {if (!(request instanceof Request)) throw new TypeError('Expected fetch to receive a Request')expect(request.url).toBe(`${PUBLIC_API_PREFIX}${path}`)})++ it('should route environment login status to the environment API', async () => {+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')+ const fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response(JSON.stringify({ logged_in: true, app_logged_in: false })))++ await base('/login/status', {}, { isPublicAPI: true })++ const [request] = fetchSpy.mock.calls[0]!+ if (!(request instanceof Request)) throw new TypeError('Expected fetch to receive a Request')+ expect(request.url).toBe(`${PUBLIC_API_PREFIX}/environment/workflow-app/login/status`)+ })})describe('Error responses', () => {diff --git a/web/service/fetch.ts b/web/service/fetch.tsindex d84a3064fab..7dfd5453da7 100644--- a/web/service/fetch.ts+++ b/web/service/fetch.ts@@ -48,6 +48,7 @@ export type ResponseError = {code: stringmessage: stringerror?: string+ reason?: stringstatus: number}diff --git a/web/service/share.spec.ts b/web/service/share.spec.tsnew file mode 100644index 00000000000..cb0e5b32e74--- /dev/null+++ b/web/service/share.spec.ts@@ -0,0 +1,88 @@+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'++const getMock = vi.hoisted(() => vi.fn())++vi.mock('./base', () => ({+ del: vi.fn(),+ delPublic: vi.fn(),+ get: vi.fn(),+ getPublic: getMock,+ patch: vi.fn(),+ patchPublic: vi.fn(),+ post: vi.fn(),+ postPublic: vi.fn(),+ ssePost: vi.fn(),+ upload: vi.fn(),+}))++vi.mock('./webapp-auth', () => ({+ getOrCreateWebAppSessionId: vi.fn(() => 'webapp-session-1'),+ getWebAppAccessToken: vi.fn(() => ''),+}))++const { fetchAccessToken } = await import('./share')++describe('fetchAccessToken', () => {+ beforeEach(() => {+ getMock.mockReset()+ })++ it('shares an in-flight passport request for the same environment', async () => {+ window.history.replaceState({}, '', '/environment/workflow/environment-app')+ let resolveRequest: (value: { access_token: string }) => void = () => {}+ getMock.mockReturnValue(+ new Promise((resolve) => {+ resolveRequest = resolve+ }),+ )++ const firstRequest = fetchAccessToken({ appCode: 'environment-app' })+ const secondRequest = fetchAccessToken({ appCode: 'environment-app' })++ expect(getMock).toHaveBeenCalledTimes(1)+ expect(getMock).toHaveBeenCalledWith('/passport?user_id=webapp-session-1', expect.anything())++ resolveRequest({ access_token: 'passport' })+ await expect(Promise.all([firstRequest, secondRequest])).resolves.toEqual([+ { access_token: 'passport' },+ { access_token: 'passport' },+ ])++ await fetchAccessToken({ appCode: 'environment-app' })+ expect(getMock).toHaveBeenCalledTimes(2)+ })++ it('does not coalesce ordinary Web App passport requests', async () => {+ window.history.replaceState({}, '', '/workflow/ordinary-app')+ getMock.mockResolvedValue({ access_token: 'passport' })++ await Promise.all([+ fetchAccessToken({ appCode: 'ordinary-app' }),+ fetchAccessToken({ appCode: 'ordinary-app' }),+ ])++ expect(getMock).toHaveBeenCalledTimes(2)+ })++ it('passes an embedded user id to the environment passport', async () => {+ window.history.replaceState({}, '', '/environment/workflow/environment-app')+ getMock.mockResolvedValue({ access_token: 'passport' })++ await fetchAccessToken({ appCode: 'environment-app', userId: 'iframe-user-123' })++ expect(getMock).toHaveBeenCalledWith('/passport?user_id=iframe-user-123', expect.anything())+ })++ it('starts a new environment passport request after a failure', async () => {+ window.history.replaceState({}, '', '/environment/workflow/environment-app')+ const error = new Response(null, { status: 401 })+ getMock.mockRejectedValueOnce(error).mockResolvedValueOnce({ access_token: 'passport' })++ await expect(fetchAccessToken({ appCode: 'environment-app' })).rejects.toBe(error)+ await expect(fetchAccessToken({ appCode: 'environment-app' })).resolves.toEqual({+ access_token: 'passport',+ })++ expect(getMock).toHaveBeenCalledTimes(2)+ })+})diff --git a/web/service/share.ts b/web/service/share.tsindex 2a58b8c215c..e398cf4a9fc 100644--- a/web/service/share.ts+++ b/web/service/share.ts@@ -17,7 +17,8 @@ import {ssePost,upload,} from './base'-import { getWebAppAccessToken } from './webapp-auth'+import { resolveWebAppAddress } from './webapp-address'+import { getOrCreateWebAppSessionId, getWebAppAccessToken } from './webapp-auth'export enum AppSourceType {webApp = 'webApp',@@ -411,13 +412,11 @@ export const textToAudioStream = (return getAction('post', appSourceType)(url, { body }, { needAllResponseContent: true })}-export const fetchAccessToken = async ({- userId,- appCode,-}: {- userId?: string- appCode: string-}) => {+type AccessTokenResponse = { access_token: string }++const environmentPassportRequests = new Map<string, Promise<AccessTokenResponse>>()++const requestAccessToken = ({ userId, appCode }: { userId?: string; appCode: string }) => {const headers = new Headers()headers.append(WEB_APP_SHARE_CODE_HEADER_NAME, appCode)const accessToken = getWebAppAccessToken()@@ -425,7 +424,29 @@ export const fetchAccessToken = async ({const params = new URLSearchParams()if (userId) params.append('user_id', userId)const url = `/passport?${params.toString()}`- return get<{ access_token: string }>(url, { headers }) as Promise<{ access_token: string }>+ return get<AccessTokenResponse>(url, { headers }) as Promise<AccessTokenResponse>+}++export const fetchAccessToken = (params: { userId?: string; appCode: string }) => {+ const address = resolveWebAppAddress()+ if (address?.kind !== 'environment') return requestAccessToken(params)++ const environmentParams = {+ ...params,+ userId: params.userId || getOrCreateWebAppSessionId(address),+ }++ const currentRequest = environmentPassportRequests.get(address.code)+ if (currentRequest) return currentRequest++ const request = requestAccessToken(environmentParams)+ environmentPassportRequests.set(address.code, request)+ const clearRequest = () => {+ if (environmentPassportRequests.get(address.code) === request)+ environmentPassportRequests.delete(address.code)+ }+ request.then(clearRequest, clearRequest)+ return request}export const getUserCanAccess = (appId: string, isInstalledApp: boolean) => {diff --git a/web/service/use-share.spec.tsx b/web/service/use-share.spec.tsxindex 4533962772a..366c4595c6a 100644--- a/web/service/use-share.spec.tsx+++ b/web/service/use-share.spec.tsx@@ -9,6 +9,7 @@ import {generationConversationName,} from './share'import {+ EnvironmentConversationNotFoundError,shareQueryKeys,useInvalidateShareConversations,useShareChatList,@@ -39,6 +40,7 @@ const createQueryClient = () =>defaultOptions: {queries: {retry: false,+ retryDelay: 0,},},})@@ -87,6 +89,11 @@ describe('shareQueryKeys', () => {shareQueryKeys.appParams(secondAddress),)expect(shareQueryKeys.appMeta(firstAddress)).not.toEqual(shareQueryKeys.appMeta(secondAddress))++ const params = { appSourceType: AppSourceType.webApp, appId: 'app-1' }+ expect(shareQueryKeys.conversationList(firstAddress, params)).not.toEqual(+ shareQueryKeys.conversationList(secondAddress, params),+ )})})@@ -125,7 +132,7 @@ describe('useShareConversations', () => {expect(result.current.data).toEqual(response)})expect(- queryClient.getQueryCache().find({ queryKey: shareQueryKeys.conversationList(params) }),+ queryClient.getQueryCache().find({ queryKey: shareQueryKeys.conversationList(null, params) }),).toBeDefined()})@@ -152,6 +159,7 @@ describe('useShareConversations', () => {describe('useShareChatList', () => {beforeEach(() => {vi.clearAllMocks()+ window.history.replaceState({}, '', '/')})it('should fetch chat list when conversationId is provided', async () => {@@ -200,6 +208,63 @@ describe('useShareChatList', () => {expect(mockFetchChatList).not.toHaveBeenCalled()})+ it('should translate a missing Environment conversation', async () => {+ window.history.replaceState({}, '', '/environment/workflow/environment-code')+ const params = {+ conversationId: 'stale-conversation',+ appId: 'app-1',+ appSourceType: AppSourceType.webApp,+ }+ const response = new Response(JSON.stringify({ reason: 'APPDEPLOY_CONVERSATION_NOT_FOUND' }), {+ status: 404,+ })+ mockFetchChatList.mockRejectedValue(response)++ const { result } = renderShareHook(() => useShareChatList(params))++ await waitFor(() => {+ expect(result.current.error).toBeInstanceOf(EnvironmentConversationNotFoundError)+ })+ expect(mockFetchChatList).toHaveBeenCalledTimes(1)+ })++ it('should preserve retries for other Environment errors', async () => {+ window.history.replaceState({}, '', '/environment/workflow/environment-code')+ const params = {+ conversationId: 'conversation-1',+ appId: 'app-1',+ appSourceType: AppSourceType.webApp,+ }+ const response = new Response(JSON.stringify({ reason: 'OTHER_ERROR' }), { status: 404 })+ mockFetchChatList.mockRejectedValue(response)++ const { result } = renderShareHook(() => useShareChatList(params))++ await waitFor(() => {+ expect(result.current.error).toBe(response)+ })+ expect(mockFetchChatList).toHaveBeenCalledTimes(1)+ })++ it('should preserve ordinary WebApp handling for the same 404 reason', async () => {+ window.history.replaceState({}, '', '/chatbot/webapp-code')+ const params = {+ conversationId: 'conversation-1',+ appSourceType: AppSourceType.webApp,+ }+ const response = new Response(JSON.stringify({ reason: 'APPDEPLOY_CONVERSATION_NOT_FOUND' }), {+ status: 404,+ })+ mockFetchChatList.mockRejectedValue(response)++ const { result } = renderShareHook(() => useShareChatList(params))++ await waitFor(() => {+ expect(result.current.error).toBe(response)+ })+ expect(mockFetchChatList).toHaveBeenCalledTimes(1)+ })+it('should always consider data stale to ensure fresh data on conversation switch (GitHub #30378)', async () => {// This test verifies that chat list data is always considered stale (staleTime: 0)// which ensures fresh data is fetched when switching back to a conversation.diff --git a/web/service/use-share.ts b/web/service/use-share.tsindex 1578349aab1..7f814230ac7 100644--- a/web/service/use-share.ts+++ b/web/service/use-share.ts@@ -45,6 +45,13 @@ type ShareQueryOptions = {refetchOnReconnect?: boolean}+export class EnvironmentConversationNotFoundError extends Error {+ constructor() {+ super('Environment conversation not found')+ this.name = 'EnvironmentConversationNotFoundError'+ }+}+export const shareQueryKeys = {appAccessMode: (address: WebAppAddress | null, code: string | null) =>[NAME_SPACE, 'appAccessMode', address, code] as const,@@ -52,11 +59,12 @@ export const shareQueryKeys = {appParams: (address: WebAppAddress | null) => [NAME_SPACE, address, 'appParams'] as const,appMeta: (address: WebAppAddress | null) => [NAME_SPACE, address, 'appMeta'] as const,conversations: [NAME_SPACE, 'conversations'] as const,- conversationList: (params: ShareConversationsParams) =>- [NAME_SPACE, 'conversations', params] as const,- chatList: (params: ShareChatListParams) => [NAME_SPACE, 'chatList', params] as const,- conversationName: (params: ShareConversationNameParams) =>- [NAME_SPACE, 'conversationName', params] as const,+ conversationList: (address: WebAppAddress | null, params: ShareConversationsParams) =>+ [NAME_SPACE, 'conversations', address, params] as const,+ chatList: (address: WebAppAddress | null, params: ShareChatListParams) =>+ [NAME_SPACE, 'chatList', address, params] as const,+ conversationName: (address: WebAppAddress | null, params: ShareConversationNameParams) =>+ [NAME_SPACE, 'conversationName', address, params] as const,humanInputForm: (token: string) => [NAME_SPACE, 'humanInputForm', token] as const,}@@ -105,13 +113,14 @@ export const useShareConversations = (params: ShareConversationsParams,options: ShareQueryOptions = {},) => {+ const address = resolveWebAppAddress()const { enabled = true, refetchOnReconnect, refetchOnWindowFocus } = optionsconst isEnabled =enabled &¶ms.appSourceType !== AppSourceType.tryApp &&(params.appSourceType !== AppSourceType.installedApp || !!params.appId)return useQuery<AppConversationData>({- queryKey: shareQueryKeys.conversationList(params),+ queryKey: shareQueryKeys.conversationList(address, params),queryFn: () =>fetchConversations(params.appSourceType,@@ -127,6 +136,7 @@ export const useShareConversations = (}export const useShareChatList = (params: ShareChatListParams, options: ShareQueryOptions = {}) => {+ const address = resolveWebAppAddress()const { enabled = true, refetchOnReconnect, refetchOnWindowFocus } = optionsconst isEnabled =enabled &&@@ -134,8 +144,19 @@ export const useShareChatList = (params: ShareChatListParams, options: ShareQuer(params.appSourceType !== AppSourceType.installedApp || !!params.appId) &&!!params.conversationIdreturn useQuery({- queryKey: shareQueryKeys.chatList(params),- queryFn: () => fetchChatList(params.conversationId, params.appSourceType, params.appId),+ queryKey: shareQueryKeys.chatList(address, params),+ queryFn: async () => {+ try {+ return await fetchChatList(params.conversationId, params.appSourceType, params.appId)+ } catch (error) {+ if (address?.kind === 'environment' && error instanceof Response && error.status === 404) {+ const data = (await error.clone().json()) as { reason?: string }+ if (data.reason === 'APPDEPLOY_CONVERSATION_NOT_FOUND')+ throw new EnvironmentConversationNotFoundError()+ }+ throw error+ }+ },enabled: isEnabled,refetchOnReconnect,refetchOnWindowFocus,@@ -150,13 +171,14 @@ export const useShareConversationName = (params: ShareConversationNameParams,options: ShareQueryOptions = {},) => {+ const address = resolveWebAppAddress()const { enabled = true, refetchOnReconnect, refetchOnWindowFocus } = optionsconst isEnabled =enabled &&(params.appSourceType !== AppSourceType.installedApp || !!params.appId) &&!!params.conversationIdreturn useQuery<ConversationItem>({- queryKey: shareQueryKeys.conversationName(params),+ queryKey: shareQueryKeys.conversationName(address, params),queryFn: () =>generationConversationName(params.appSourceType, params.appId, params.conversationId),enabled: isEnabled,diff --git a/web/service/use-tools.ts b/web/service/use-tools.tsindex 81fdacfd03a..a7e84ff1d5a 100644--- a/web/service/use-tools.ts+++ b/web/service/use-tools.ts@@ -208,7 +208,7 @@ export const useMCPServerDetail = (appID: string, enabled = true) => {export const useInvalidateMCPServerDetail = () => {const queryClient = useQueryClient()return (appID: string) => {- queryClient.invalidateQueries({+ return queryClient.invalidateQueries({queryKey: [NAME_SPACE, 'MCPServerDetail', appID],})}@@ -324,27 +324,12 @@ export const useAppTriggers = (export const useInvalidateAppTriggers = () => {const queryClient = useQueryClient()return (appId: string) => {- queryClient.invalidateQueries({+ return queryClient.invalidateQueries({queryKey: [NAME_SPACE, 'app-triggers', appId],})}}-export const useUpdateTriggerStatus = () => {- return useMutation({- mutationKey: [NAME_SPACE, 'update-trigger-status'],- mutationFn: (payload: { appId: string; triggerId: string; enableTrigger: boolean }) => {- const { appId, triggerId, enableTrigger } = payload- return post<AppTrigger>(`/apps/${appId}/trigger-enable`, {- body: {- trigger_id: triggerId,- enable_trigger: enableTrigger,- },- })- },- })-}-const workflowToolDetailByAppIDKey = (appId: string) => [NAME_SPACE,'workflowToolDetailByAppID',diff --git a/web/service/use-workflow.ts b/web/service/use-workflow.tsindex 6a887e110d0..f7cdef66528 100644--- a/web/service/use-workflow.ts+++ b/web/service/use-workflow.ts@@ -1,4 +1,14 @@-import type { UseQueryOptions } from '@tanstack/react-query'+import type {+ WorkflowPaginationResponse,+ WorkflowResponse,+} from '@dify/contracts/api/console/apps/types.gen'+import type {+ EnvironmentDeployment,+ GetEnvironmentDeploymentResponse,+ ListEnvironmentDeploymentsResponse,+ WorkflowVersion,+} from '@dify/contracts/enterprise-app-deploy/types.gen'+import type { InfiniteData, QueryClient, UseQueryOptions } from '@tanstack/react-query'import type { CommonResponse } from '@/models/common'import type { FlowType } from '@/types/common'import type {@@ -12,7 +22,9 @@ import type {WorkflowRunHistoryResponse,} from '@/types/workflow'import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { AppModeEnum } from '@/types/app'import { del, get, patch, post, put } from './base'+import { consoleQuery } from './client'import { useInvalid } from './use-base'import { getFlowPrefix } from './utils'import { appWorkflowQueryOptions, appWorkflowVersionsInfiniteQueryKey } from './workflow-queries'@@ -104,22 +116,185 @@ export const useResetWorkflowVersionHistory = () => {])}+function syncWorkflowVersionMetadata(+ version: WorkflowVersion | undefined,+ updatedWorkflow: WorkflowResponse,+) {+ if (!version || version.id !== updatedWorkflow.id) return version+ if (+ version.marked_name === updatedWorkflow.marked_name &&+ version.marked_comment === updatedWorkflow.marked_comment+ )+ return version++ return {+ ...version,+ marked_name: updatedWorkflow.marked_name,+ marked_comment: updatedWorkflow.marked_comment,+ }+}++function syncEnvironmentDeploymentVersion(+ environmentDeployment: EnvironmentDeployment,+ updatedWorkflow: WorkflowResponse,+) {+ const deployment = environmentDeployment.deployment+ if (!deployment) return environmentDeployment++ const currentVersion = syncWorkflowVersionMetadata(deployment.current_version, updatedWorkflow)+ const latestOperation = deployment.latest_operation+ const targetVersion = syncWorkflowVersionMetadata(+ latestOperation?.target_version,+ updatedWorkflow,+ )+ const currentVersionChanged = currentVersion !== deployment.current_version+ const targetVersionChanged = targetVersion !== latestOperation?.target_version++ if (!currentVersionChanged && !targetVersionChanged) return environmentDeployment++ return {+ ...environmentDeployment,+ deployment: {+ ...deployment,+ current_version: currentVersion,+ latest_operation:+ latestOperation && targetVersionChanged+ ? {+ ...latestOperation,+ target_version: targetVersion,+ }+ : latestOperation,+ },+ }+}++function syncWorkflowVersionPages(+ data: InfiniteData<WorkflowPaginationResponse> | undefined,+ updatedWorkflow: WorkflowResponse,+) {+ if (!data) return data++ let changed = false+ const pages = data.pages.map((page) => {+ let pageChanged = false+ const items = page.items.map((workflow) => {+ if (workflow.id !== updatedWorkflow.id) return workflow++ changed = true+ pageChanged = true+ return updatedWorkflow+ })++ return pageChanged ? { ...page, items } : page+ })++ return changed ? { ...data, pages } : data+}++function syncEnvironmentDeployments(+ data: ListEnvironmentDeploymentsResponse | undefined,+ updatedWorkflow: WorkflowResponse,+) {+ if (!data) return data++ let changed = false+ const environmentDeployments = data.environment_deployments.map((deployment) => {+ const updatedDeployment = syncEnvironmentDeploymentVersion(deployment, updatedWorkflow)+ if (updatedDeployment !== deployment) changed = true+ return updatedDeployment+ })++ return changed ? { ...data, environment_deployments: environmentDeployments } : data+}++function syncAppWorkflowVersionCaches(+ queryClient: QueryClient,+ appId: string,+ updatedWorkflow: WorkflowResponse,+) {+ const publishedWorkflowQuery = appWorkflowQueryOptions(appId)++ queryClient.setQueryData<WorkflowResponse>(publishedWorkflowQuery.queryKey, (workflow) =>+ workflow?.id === updatedWorkflow.id ? updatedWorkflow : workflow,+ )+ queryClient.setQueriesData<InfiniteData<WorkflowPaginationResponse>>(+ { queryKey: appWorkflowVersionsInfiniteQueryKey() },+ (data) => syncWorkflowVersionPages(data, updatedWorkflow),+ )+}++function syncWorkflowDeploymentCaches(+ queryClient: QueryClient,+ appId: string,+ updatedWorkflow: WorkflowResponse,+) {+ const environmentDeploymentsQuery =+ consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({+ input: {+ params: {+ app_id: appId,+ },+ },+ })++ queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(+ environmentDeploymentsQuery.queryKey,+ (data) => syncEnvironmentDeployments(data, updatedWorkflow),+ )+ queryClient.setQueriesData<GetEnvironmentDeploymentResponse>(+ {+ queryKey: consoleQuery.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.key({+ type: 'query',+ }),+ },+ (data) => {+ if (!data) return data++ const environmentDeployment = syncEnvironmentDeploymentVersion(+ data.environment_deployment,+ updatedWorkflow,+ )+ return environmentDeployment === data.environment_deployment+ ? data+ : { ...data, environment_deployment: environmentDeployment }+ },+ )++ return environmentDeploymentsQuery.queryKey+}+export const useUpdateWorkflow = () => {const queryClient = useQueryClient()return useMutation({mutationKey: [NAME_SPACE, 'update'],mutationFn: (params: UpdateWorkflowParams) =>- patch(params.url, {+ patch<WorkflowResponse>(params.url, {body: {marked_name: params.title,marked_comment: params.releaseNotes,},}),- onSuccess: () =>- Promise.all([+ onSuccess: (updatedWorkflow, params) => {+ if (params.appId) syncAppWorkflowVersionCaches(queryClient, params.appId, updatedWorkflow)++ const environmentDeploymentsQueryKey =+ params.appId &&+ (params.appMode === AppModeEnum.WORKFLOW || params.appMode === AppModeEnum.ADVANCED_CHAT)+ ? syncWorkflowDeploymentCaches(queryClient, params.appId, updatedWorkflow)+ : undefined+ const invalidations = [queryClient.invalidateQueries({ queryKey: [...WorkflowVersionHistoryKey] }),queryClient.invalidateQueries({ queryKey: appWorkflowVersionsInfiniteQueryKey() }),- ]),+ ]++ if (environmentDeploymentsQueryKey) {+ invalidations.push(+ queryClient.invalidateQueries({ queryKey: environmentDeploymentsQueryKey }),+ )+ }++ return Promise.all(invalidations)+ },})}diff --git a/web/service/webapp-address.spec.ts b/web/service/webapp-address.spec.tsindex aa24708cc08..4a1c07ff969 100644--- a/web/service/webapp-address.spec.ts+++ b/web/service/webapp-address.spec.ts@@ -1,5 +1,11 @@import { afterEach, describe, expect, it, vi } from 'vite-plus/test'-import { getWebAppApiPath, parseWebAppAddress, resolveWebAppAddress } from './webapp-address'+import {+ getWebAppApiPath,+ getWebAppConversationScopeId,+ getWebAppPublicApiPath,+ parseWebAppAddress,+ resolveWebAppAddress,+} from './webapp-address'describe('WebAppAddress', () => {afterEach(() => {@@ -11,30 +17,51 @@ describe('WebAppAddress', () => {kind: 'default',code: 'env-prefix-is-still-ordinary',})- expect(parseWebAppAddress('/env/workflow/workflow-app')).toEqual({+ expect(parseWebAppAddress('/environment/workflow/workflow-app')).toEqual({kind: 'environment',code: 'workflow-app',})})it('does not reinterpret an unsupported environment path as an ordinary webapp', () => {- expect(parseWebAppAddress('/env/workflow')).toBeNull()- expect(parseWebAppAddress('/env/not-a-mode/workflow-app')).toBeNull()+ expect(parseWebAppAddress('/environment/workflow')).toBeNull()+ expect(parseWebAppAddress('/environment/not-a-mode/workflow-app')).toBeNull()})it('accepts every webapp mode under the environment prefix', () => {- expect(parseWebAppAddress('/env/chat/chat-app')).toEqual({+ expect(parseWebAppAddress('/environment/chat/chat-app')).toEqual({kind: 'environment',code: 'chat-app',})})it('builds the environment upload and workflow URLs', () => {- const address = parseWebAppAddress('/env/workflow/workflow-app')- expect(getWebAppApiPath(address, '/files/upload')).toBe('/env/workflow-app/files/upload')- expect(getWebAppApiPath(address, '/workflows/run')).toBe('/env/workflow-app/workflows/run')+ const address = parseWebAppAddress('/environment/workflow/workflow-app')+ expect(getWebAppApiPath(address, '/files/upload')).toBe(+ '/environment/workflow-app/files/upload',+ )+ expect(getWebAppApiPath(address, '/workflows/run')).toBe(+ '/environment/workflow-app/workflows/run',+ )expect(getWebAppApiPath(address, '/workflows/tasks/task-1/stop')).toBe(- '/env/workflow-app/workflows/tasks/task-1/stop',+ '/environment/workflow-app/workflows/tasks/task-1/stop',+ )+ })++ it('routes only environment login status to the environment API', () => {+ const address = parseWebAppAddress('/environment/workflow/workflow-app')++ expect(getWebAppPublicApiPath(address, '/login/status?user_id=user-1')).toBe(+ '/environment/workflow-app/login/status?user_id=user-1',+ )+ expect(getWebAppPublicApiPath(address, '/login')).toBe('/login')+ expect(getWebAppPublicApiPath(address, '/logout')).toBe('/logout')+ expect(getWebAppPublicApiPath(address, '/email-code-login/validity')).toBe(+ '/email-code-login/validity',+ )+ expect(getWebAppPublicApiPath(address, '/forgot-password')).toBe('/forgot-password')+ expect(getWebAppPublicApiPath(address, '/enterprise/sso/members/oidc/login')).toBe(+ '/enterprise/sso/members/oidc/login',)})@@ -43,4 +70,14 @@ describe('WebAppAddress', () => {expect(resolveWebAppAddress()).toBeNull()})++ it('isolates Environment conversations without changing ordinary webapp storage', () => {+ expect(getWebAppConversationScopeId({ kind: 'default', code: 'webapp' }, 'app-1')).toBe('app-1')+ expect(+ getWebAppConversationScopeId({ kind: 'environment', code: 'environment-1' }, 'app-1'),+ ).toBe('environment:environment-1')+ expect(+ getWebAppConversationScopeId({ kind: 'environment', code: 'environment-2' }, 'app-1'),+ ).toBe('environment:environment-2')+ })})diff --git a/web/service/webapp-address.ts b/web/service/webapp-address.tsindex 14b4da745f7..3037cbbb8ca 100644--- a/web/service/webapp-address.ts+++ b/web/service/webapp-address.ts@@ -15,7 +15,7 @@ const normalizePath = (path: string) => (path.startsWith('/') ? path : `/${path}export const parseWebAppAddress = (pathname: string): WebAppAddress | null => {const segments = pathname.split('/').filter(Boolean)- if (segments[0] === 'env') {+ if (segments[0] === 'environment') {const [, route, code, ...rest] = segmentsif (!route || !code || rest.length > 0 || !WEB_APP_ROUTE_SEGMENTS.has(route)) return nullreturn { kind: 'environment', code }@@ -47,20 +47,27 @@ export const resolveWebAppAddress = (): WebAppAddress | null => {export const getWebAppApiPath = (address: WebAppAddress | null, path: string) => {const normalizedPath = normalizePath(path)if (!address || address.kind === 'default') return normalizedPath- return `/env/${address.code}${normalizedPath}`+ return `/environment/${address.code}${normalizedPath}`}-export const getWebAppPassportKey = (address: WebAppAddress) => {+export const getWebAppScopeKey = (address: WebAppAddress) => {if (address.kind === 'default') return address.codereturn `environment:${address.code}`}+export const getWebAppPassportKey = (address: WebAppAddress) => getWebAppScopeKey(address)++export const getWebAppConversationScopeId = (address: WebAppAddress | null, appId?: string) => {+ if (!appId) return ''+ if (address?.kind === 'environment') return getWebAppScopeKey(address)+ return appId+}+const isDifyWebAppAuthPath = (path: string) => {const pathname = normalizePath(path).split('?')[0] || ''return (pathname === '/login' ||pathname === '/logout' ||- pathname === '/login/status' ||pathname.startsWith('/email-code-login') ||pathname.startsWith('/forgot-password') ||pathname.startsWith('/enterprise/sso/')diff --git a/web/service/webapp-auth.spec.ts b/web/service/webapp-auth.spec.tsindex 4ce09688f45..5ea45247324 100644--- a/web/service/webapp-auth.spec.ts+++ b/web/service/webapp-auth.spec.ts@@ -1,6 +1,4 @@import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import { AccessMode } from '@/models/access-control'-const getPublicMock = vi.hoisted(() => vi.fn())vi.mock('./base', () => ({@@ -8,13 +6,21 @@ vi.mock('./base', () => ({postPublic: vi.fn(),}))-const { getWebAppPassport, setWebAppPassport, webAppLoginStatus } = await import('./webapp-auth')+const {+ beginWebAppAuthorizationRecovery,+ completeWebAppAuthorizationRecovery,+ getOrCreateWebAppSessionId,+ getWebAppPassport,+ setWebAppPassport,+ webAppLoginStatus,+} = await import('./webapp-auth')describe('webAppLoginStatus', () => {beforeEach(() => {getPublicMock.mockReset()getPublicMock.mockResolvedValue({ logged_in: true, app_logged_in: true })localStorage.clear()+ sessionStorage.clear()})it('keeps environment and ordinary passports for the same code separate', () => {@@ -36,50 +42,65 @@ describe('webAppLoginStatus', () => {expect(localStorage.getItem('passport-workflow-app')).toBe('passport')})- it('does not send an environment code to Dify login status', async () => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')+ it('keeps a stable user id for each environment', () => {+ const firstEnvironment = { kind: 'environment' as const, code: 'environment-1' }+ const secondEnvironment = { kind: 'environment' as const, code: 'environment-2' }++ const first = getOrCreateWebAppSessionId(firstEnvironment)++ expect(first).toMatch(/^[0-9a-f-]{36}$/i)+ expect(getOrCreateWebAppSessionId(firstEnvironment)).toBe(first)+ expect(getOrCreateWebAppSessionId(secondEnvironment)).not.toBe(first)+ expect(localStorage.getItem('session_id-environment:environment-1')).toBe(first)+ })++ it('allows one authorization recovery until an environment request succeeds', () => {+ const address = { kind: 'environment' as const, code: 'environment-1' }++ expect(beginWebAppAuthorizationRecovery(address)).toBe(true)+ expect(beginWebAppAuthorizationRecovery(address)).toBe(false)++ setWebAppPassport(address, 'renewed-passport')++ expect(beginWebAppAuthorizationRecovery(address)).toBe(false)++ completeWebAppAuthorizationRecovery(address)++ expect(beginWebAppAuthorizationRecovery(address)).toBe(true)+ })- await webAppLoginStatus('workflow-app', AccessMode.PUBLIC, 'user-1')+ it('does not add an app code query to environment login status', async () => {+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')++ await webAppLoginStatus('workflow-app', 'user-1')expect(getPublicMock).toHaveBeenCalledWith('/login/status?user_id=user-1')})- it('treats a public environment as logged in before its first passport', async () => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')+ it('uses the authoritative environment login state', async () => {+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')getPublicMock.mockResolvedValue({ logged_in: false, app_logged_in: false })- await expect(webAppLoginStatus('workflow-app', AccessMode.PUBLIC)).resolves.toEqual({- userLoggedIn: true,+ await expect(webAppLoginStatus('workflow-app')).resolves.toEqual({+ userLoggedIn: false,appLoggedIn: false,})})it('trusts the remote login state for an sso verified environment', async () => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')+ window.history.replaceState({}, '', '/environment/workflow/workflow-app')getPublicMock.mockResolvedValue({ logged_in: true, app_logged_in: false })- await expect(webAppLoginStatus('workflow-app', AccessMode.EXTERNAL_MEMBERS)).resolves.toEqual({+ await expect(webAppLoginStatus('workflow-app')).resolves.toEqual({userLoggedIn: true,appLoggedIn: false,})})- it('requires a Dify login for a private environment', async () => {- window.history.replaceState({}, '', '/env/workflow/workflow-app')- getPublicMock.mockResolvedValue({ logged_in: false, app_logged_in: false })-- await expect(- webAppLoginStatus('workflow-app', AccessMode.SPECIFIC_GROUPS_MEMBERS),- ).resolves.toEqual({- userLoggedIn: false,- appLoggedIn: false,- })- })-it('keeps the app code for ordinary webapps', async () => {window.history.replaceState({}, '', '/workflow/workflow-app')- await webAppLoginStatus('workflow-app', AccessMode.PUBLIC)+ await webAppLoginStatus('workflow-app')expect(getPublicMock).toHaveBeenCalledWith('/login/status?app_code=workflow-app')})diff --git a/web/service/webapp-auth.ts b/web/service/webapp-auth.tsindex b73bbda6d4f..39f58716c14 100644--- a/web/service/webapp-auth.ts+++ b/web/service/webapp-auth.ts@@ -1,8 +1,14 @@import type { WebAppAddress } from './webapp-address'+import { v4 as uuidV4 } from 'uuid'import { ACCESS_TOKEN_LOCAL_STORAGE_NAME, PASSPORT_LOCAL_STORAGE_NAME } from '@/config'-import { AccessMode } from '@/models/access-control'import { getPublic, postPublic } from './base'-import { getWebAppPassportKey, resolveWebAppAddress } from './webapp-address'+import { getWebAppPassportKey, getWebAppScopeKey, resolveWebAppAddress } from './webapp-address'++const WEB_APP_AUTHORIZATION_RECOVERY_KEY_PREFIX = 'webapp-authorization-recovery-'++function getWebAppAuthorizationRecoveryKey(address: WebAppAddress) {+ return `${WEB_APP_AUTHORIZATION_RECOVERY_KEY_PREFIX}${getWebAppScopeKey(address)}`+}export function setWebAppAccessToken(token: string) {localStorage.setItem(ACCESS_TOKEN_LOCAL_STORAGE_NAME, token)@@ -12,6 +18,18 @@ export function setWebAppPassport(address: WebAppAddress, token: string) {localStorage.setItem(PASSPORT_LOCAL_STORAGE_NAME(getWebAppPassportKey(address)), token)}+export function beginWebAppAuthorizationRecovery(address: WebAppAddress) {+ const key = getWebAppAuthorizationRecoveryKey(address)+ if (sessionStorage.getItem(key)) return false++ sessionStorage.setItem(key, 'pending')+ return true+}++export function completeWebAppAuthorizationRecovery(address: WebAppAddress) {+ sessionStorage.removeItem(getWebAppAuthorizationRecoveryKey(address))+}+export function getWebAppAccessToken() {return localStorage.getItem(ACCESS_TOKEN_LOCAL_STORAGE_NAME) || ''}@@ -21,11 +39,25 @@ export function getWebAppPassport(address: WebAppAddress | null) {return localStorage.getItem(PASSPORT_LOCAL_STORAGE_NAME(getWebAppPassportKey(address))) || ''}+export function getOrCreateWebAppSessionId(address: WebAppAddress) {+ if (address.kind !== 'environment') return ''++ const key = `session_id-${getWebAppScopeKey(address)}`+ // oxlint-disable-next-line no-restricted-globals -- Environment passport requests need a stable session ID synchronously.+ const sessionId = localStorage.getItem(key)+ if (sessionId) return sessionId++ const created = uuidV4()+ // oxlint-disable-next-line no-restricted-globals -- Environment passport requests need a stable session ID synchronously.+ localStorage.setItem(key, created)+ return created+}+function clearWebAppAccessToken() {localStorage.removeItem(ACCESS_TOKEN_LOCAL_STORAGE_NAME)}-function clearWebAppPassport(address: WebAppAddress | null) {+export function clearWebAppPassport(address: WebAppAddress | null) {if (!address) returnlocalStorage.removeItem(PASSPORT_LOCAL_STORAGE_NAME(getWebAppPassportKey(address)))}@@ -35,11 +67,7 @@ type isWebAppLogin = {app_logged_in: boolean}-export async function webAppLoginStatus(- shareCode: string,- accessMode: AccessMode,- userId?: string,-) {+export async function webAppLoginStatus(shareCode: string, userId?: string) {// always need to check login to prevent passport from being outdated// check remotely, the access token could be in cookie (enterprise SSO redirected with https)const address = resolveWebAppAddress()@@ -50,8 +78,7 @@ export async function webAppLoginStatus(`/login/status?${params.toString()}`,)return {- userLoggedIn:- address?.kind === 'environment' && accessMode === AccessMode.PUBLIC ? true : logged_in,+ userLoggedIn: logged_in,appLoggedIn: app_logged_in,}}diff --git a/web/types/workflow.ts b/web/types/workflow.tsindex 8aaaa96b655..ecafd1c1c79 100644--- a/web/types/workflow.ts+++ b/web/types/workflow.ts@@ -16,7 +16,7 @@ import type {WorkflowRunningStatus,} from '@/app/components/workflow/types'import type { RAGPipelineVariables } from '@/models/pipeline'-import type { TransferMethod } from '@/types/app'+import type { AppModeEnum, TransferMethod } from '@/types/app'export type AgentLogItem = {node_execution_id: string@@ -457,6 +457,8 @@ export type PublishWorkflowParams = {export type WorkflowKind = 'standard'export type UpdateWorkflowParams = {+ appId?: string+ appMode?: AppModeEnumurl: stringtitle: stringreleaseNotes: string