Skip to content

armgit / dify

Public Imported from GitHub
0

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

feat(agent): support exporting published versions (#42485)

林玮 (Jade Lin)db6a4f5cd375
diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.py
index 28baa5b01a5..d24e34317f9 100644
--- a/api/controllers/console/app/app.py
+++ b/api/controllers/console/app/app.py
@@ -2,7 +2,7 @@ import logging
import uuid
from collections.abc import Sequence
from datetime import datetime
-from typing import Any, Literal
+from typing import Any, Literal, Self
from flask import send_file
from flask_restx import Resource
@@ -44,6 +44,7 @@ from core.ops.ops_trace_manager import OpsTraceManager
from core.rag.entities import PreProcessingRule, Rule, Segmentation
from core.rag.retrieval.retrieval_methods import RetrievalMethod
from core.trigger.constants import TRIGGER_NODE_TYPES
+from enums import DeploymentEdition
from extensions.ext_application_services import application_services
from extensions.ext_database import db
from fields.base import ResponseModel
@@ -80,6 +81,7 @@ from services.entities.knowledge_entities.knowledge_entities import (
WeightVectorSetting,
)
from services.errors.account import NoPermissionError
+from services.feature_service import FeatureService
from services.system_feature_service import SystemFeatureService
from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task
@@ -188,6 +190,19 @@ class AppExportQuery(BaseModel):
)
include_secret: bool = Field(default=False, description="Include secrets in export")
workflow_id: str | None = Field(default=None, description="Specific workflow ID to export")
+ version_id: uuid.UUID | None = Field(
+ default=None,
+ description=(
+ "Published Agent version ID to export; requires a paid plan on Cloud. "
+ "If omitted, exports the shared draft, falling back to the active snapshot when no draft exists."
+ ),
+ )
+
+ @model_validator(mode="after")
+ def validate_version_selectors(self) -> Self:
+ if self.version_id is not None and self.workflow_id is not None:
+ raise ValueError("version_id and workflow_id cannot be used together")
+ return self
class AppNamePayload(BaseModel):
@@ -1052,13 +1067,24 @@ class AppExportApi(Resource):
def get(self, req_data: AppExportQuery, app_model: App):
"""Export app"""
+ if req_data.version_id is not None:
+ if app_model.mode != AppMode.AGENT:
+ raise BadRequest("version_id is only available for Agent Apps")
+ if (
+ dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD
+ and not FeatureService.get_workspace_plan(app_model.tenant_id).is_paid
+ ):
+ raise Forbidden("This feature requires a paid plan.")
+
if req_data.format == "ifpkg" or (req_data.format is None and app_model.mode == AppMode.AGENT):
if app_model.mode != AppMode.AGENT:
raise BadRequest("The ifpkg format is only available for Agent Apps")
agent_id = app_model.bound_agent_id_with_session(session=db.session())
if agent_id is None:
raise NotFound("Agent not found")
- exported = RosterAgentPackageExporter().export(tenant_id=app_model.tenant_id, agent_id=agent_id)
+ exported = RosterAgentPackageExporter().export(
+ tenant_id=app_model.tenant_id, agent_id=agent_id, version_id=req_data.version_id
+ )
try:
archive_response = send_file(
exported.archive, mimetype="application/zip", as_attachment=True, download_name=exported.filename
@@ -1075,6 +1101,7 @@ class AppExportApi(Resource):
session=db.session(),
include_secret=req_data.include_secret,
workflow_id=req_data.workflow_id,
+ version_id=req_data.version_id,
)
)
return response.model_dump(mode="json")
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 57d3a9ff43a..e872f44fa76 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -2675,6 +2675,7 @@ Export application configuration as DSL
| app_id | path | Application ID to export | Yes | string (uuid) |
| format | query | Export format; defaults to ifpkg for Agent Apps and yaml for other Apps | No | string, <br>**Available values:** "ifpkg", "yaml" |
| include_secret | query | Include secrets in export | No | boolean |
+| version_id | query | Published Agent version ID to export; requires a paid plan on Cloud. If omitted, exports the shared draft, falling back to the active snapshot when no draft exists. | No | string (uuid) |
| workflow_id | query | Specific workflow ID to export | No | string |
#### Responses
@@ -15780,6 +15781,7 @@ This class is used to store the schema information of an api based tool.
| ---- | ---- | ----------- | -------- |
| format | string, <br>**Available values:** "ifpkg", "yaml" | Export format; defaults to ifpkg for Agent Apps and yaml for other Apps | No |
| include_secret | boolean | Include secrets in export | No |
+| version_id | string | Published Agent version ID to export; requires a paid plan on Cloud. If omitted, exports the shared draft, falling back to the active snapshot when no draft exists. | No |
| workflow_id | string | Specific workflow ID to export | No |
#### AppExportResponse
diff --git a/api/services/agent/dsl_service.py b/api/services/agent/dsl_service.py
index a03f25ef14d..722db771a7a 100644
--- a/api/services/agent/dsl_service.py
+++ b/api/services/agent/dsl_service.py
@@ -12,6 +12,7 @@ import copy
import json
from collections.abc import Mapping
from typing import Any, cast
+from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import func, select
@@ -72,8 +73,8 @@ class AgentDslService:
def __init__(self, session: Session) -> None:
self.session = session
- def export_agent_app(self, *, app: App) -> tuple[str, dict[str, AgentPackage]]:
- """Export the editable shared Agent draft, falling back to the active snapshot."""
+ def export_agent_app(self, *, app: App, version_id: UUID | None) -> tuple[str, dict[str, AgentPackage]]:
+ """Export a visible version, or the shared draft with an active snapshot fallback."""
agent = self.session.scalar(
select(Agent)
@@ -89,31 +90,40 @@ class AgentDslService:
if agent is None:
raise ValueError("Agent App has no active backing Agent.")
- draft = self.session.scalar(
- select(AgentConfigDraft)
- .where(
- AgentConfigDraft.tenant_id == app.tenant_id,
- AgentConfigDraft.agent_id == agent.id,
- AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
- AgentConfigDraft.draft_owner_key == "",
+ draft = None
+ snapshot_id = agent.active_config_snapshot_id
+ if version_id is not None:
+ snapshot = AgentRosterService(self.session).get_visible_agent_version_snapshot(
+ tenant_id=app.tenant_id, agent_id=agent.id, version_id=version_id
)
- .limit(1)
- )
- if draft is not None:
- soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ snapshot_id = snapshot.id
+ soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)
else:
- snapshot = self._require_snapshot(
- tenant_id=app.tenant_id,
- agent_id=agent.id,
- snapshot_id=agent.active_config_snapshot_id,
+ draft = self.session.scalar(
+ select(AgentConfigDraft)
+ .where(
+ AgentConfigDraft.tenant_id == app.tenant_id,
+ AgentConfigDraft.agent_id == agent.id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
+ AgentConfigDraft.draft_owner_key == "",
+ )
+ .limit(1)
)
- soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)
+ if draft is not None:
+ soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ else:
+ snapshot = self._require_snapshot(
+ tenant_id=app.tenant_id,
+ agent_id=agent.id,
+ snapshot_id=snapshot_id,
+ )
+ soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)
package_ref = "agent_1"
workspace_skills = self._workspace_skills_for_export(
tenant_id=app.tenant_id,
agent_id=agent.id,
- snapshot_id=agent.active_config_snapshot_id,
+ snapshot_id=snapshot_id,
include_draft=draft is not None,
)
return package_ref, {package_ref: make_portable_agent_package(agent, soul, workspace_skills=workspace_skills)}
diff --git a/api/services/agent/roster_package_exporter.py b/api/services/agent/roster_package_exporter.py
index 05d4f93e447..de9d4331213 100644
--- a/api/services/agent/roster_package_exporter.py
+++ b/api/services/agent/roster_package_exporter.py
@@ -10,6 +10,7 @@ import zipfile
from collections.abc import Callable, Generator, Sequence
from dataclasses import dataclass
from typing import BinaryIO, Literal, Protocol, cast
+from uuid import UUID
import yaml
from sqlalchemy import or_, select
@@ -55,6 +56,7 @@ from services.agent.roster_package_entities import (
RosterAgentPackageManifest,
RosterAgentPackageSkill,
)
+from services.agent.roster_service import AgentRosterService
from services.agent.skill_package_service import SkillPackageError, SkillPackageService
from services.plugin.dependencies_analysis import DependenciesAnalysisService
from services.skill_management_service import RuntimeAgentSkillArchive, SkillManagementService
@@ -97,7 +99,8 @@ class RosterAgentPackageExporter:
self._storage = storage_backend
self._dependency_provider = dependency_provider or DependenciesAnalysisService.generate_dependencies
- def export(self, *, tenant_id: str, agent_id: str) -> RosterAgentPackageExport:
+ def export(self, *, tenant_id: str, agent_id: str, version_id: UUID | None) -> RosterAgentPackageExport:
+ """Export a visible version, or the shared draft with an active snapshot fallback."""
with session_factory.create_session() as session:
row = session.execute(
select(Agent, App)
@@ -122,31 +125,40 @@ class RosterAgentPackageExporter:
raise AgentNotFoundError()
agent, app_model = row
- draft = session.scalar(
- select(AgentConfigDraft)
- .where(
- AgentConfigDraft.tenant_id == tenant_id,
- AgentConfigDraft.agent_id == agent.id,
- AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
- AgentConfigDraft.draft_owner_key == "",
+ draft = None
+ snapshot_id = agent.active_config_snapshot_id
+ if version_id is not None:
+ snapshot = AgentRosterService(session).get_visible_agent_version_snapshot(
+ tenant_id=tenant_id, agent_id=agent.id, version_id=version_id
)
- .limit(1)
- )
- if draft is not None:
- soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ snapshot_id = snapshot.id
+ soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)
else:
- snapshot = session.scalar(
- select(AgentConfigSnapshot)
+ draft = session.scalar(
+ select(AgentConfigDraft)
.where(
- AgentConfigSnapshot.id == agent.active_config_snapshot_id,
- AgentConfigSnapshot.tenant_id == tenant_id,
- AgentConfigSnapshot.agent_id == agent.id,
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent.id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
+ AgentConfigDraft.draft_owner_key == "",
)
.limit(1)
)
- if snapshot is None:
- raise AgentVersionNotFoundError()
- soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)
+ if draft is not None:
+ soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ else:
+ active_snapshot = session.scalar(
+ select(AgentConfigSnapshot)
+ .where(
+ AgentConfigSnapshot.id == snapshot_id,
+ AgentConfigSnapshot.tenant_id == tenant_id,
+ AgentConfigSnapshot.agent_id == agent.id,
+ )
+ .limit(1)
+ )
+ if active_snapshot is None:
+ raise AgentVersionNotFoundError()
+ soul = AgentSoulConfig.model_validate(active_snapshot.config_snapshot_dict)
resource_soul, skill_sources, file_sources = self._collect_payloads(
session=session,
@@ -162,6 +174,7 @@ class RosterAgentPackageExporter:
tenant_id=tenant_id,
agent_id=agent_id,
include_draft=draft is not None,
+ config_snapshot_id=snapshot_id,
)
skill_sources.extend(
self._workspace_skill_sources(
diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.py
index cb090cd7d7a..370e31c5323 100644
--- a/api/services/agent/roster_service.py
+++ b/api/services/agent/roster_service.py
@@ -1,6 +1,7 @@
import logging
from collections.abc import Sequence
from typing import Any, TypedDict
+from uuid import UUID
from sqlalchemy import and_, func, or_, select
from sqlalchemy.exc import IntegrityError
@@ -1379,6 +1380,24 @@ class AgentRosterService:
.subquery()
)
+ def get_visible_agent_version_snapshot(
+ self, *, tenant_id: str, agent_id: str, version_id: UUID
+ ) -> AgentConfigSnapshot:
+ """Resolve a version exposed in the roster history within its complete owner scope."""
+ agent = self._get_agent(tenant_id=tenant_id, agent_id=agent_id, roster_only=True)
+ visible_version_ids = self._visible_version_ids_stmt(tenant_id=tenant_id, agent_id=agent_id, agent=agent)
+ snapshot = self._session.scalar(
+ select(AgentConfigSnapshot).where(
+ AgentConfigSnapshot.tenant_id == tenant_id,
+ AgentConfigSnapshot.agent_id == agent_id,
+ AgentConfigSnapshot.id == str(version_id),
+ AgentConfigSnapshot.id.in_(select(visible_version_ids.c.current_snapshot_id)),
+ )
+ )
+ if snapshot is None:
+ raise AgentVersionNotFoundError()
+ return snapshot
+
def get_agent_version_detail(self, *, tenant_id: str, agent_id: str, version_id: str) -> dict[str, Any]:
agent = self._get_agent(tenant_id=tenant_id, agent_id=agent_id, roster_only=True)
visible_version_ids = self._visible_version_ids_stmt(tenant_id=tenant_id, agent_id=agent_id, agent=agent)
diff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.py
index 75b74b9a42e..146b74b3d12 100644
--- a/api/services/app_dsl_service.py
+++ b/api/services/app_dsl_service.py
@@ -751,6 +751,7 @@ class AppDslService:
session: Session,
include_secret: bool = False,
workflow_id: str | None = None,
+ version_id: uuid.UUID | None = None,
) -> str:
"""
Export app
@@ -758,6 +759,8 @@ class AppDslService:
:param session: Database session used to load export data
:param include_secret: Whether include secret variable
:param workflow_id: Optional published workflow version to export
+ :param version_id: Optional published Agent version to export
+ :raises AgentVersionNotFoundError: If the selected Agent version is unavailable or not visible in history
:raises WorkflowNotFoundError: If the selected workflow version does not exist
:raises IsDraftWorkflowError: If the selected workflow is a draft
:return:
@@ -765,7 +768,7 @@ class AppDslService:
app_mode = AppMode.value_of(app_model.mode)
if app_mode == AppMode.AGENT:
- package_ref, packages = AgentDslService(session).export_agent_app(app=app_model)
+ package_ref, packages = AgentDslService(session).export_agent_app(app=app_model, version_id=version_id)
dependencies = AgentDslService(session).extract_package_dependencies(packages)
export_data = make_agent_app_dsl(
app_model,
diff --git a/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py b/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py
index e8e13be6424..af3e60885e9 100644
--- a/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py
+++ b/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py
@@ -3,15 +3,18 @@ from collections.abc import Callable
from inspect import unwrap
from types import SimpleNamespace
from unittest.mock import Mock
+from uuid import UUID
import httpx
import pytest
from flask import Flask
+from pydantic import ValidationError
from werkzeug.exceptions import BadRequest, Forbidden
from controllers.console.app import app as app_module
from controllers.console.app import app_import as import_module
from core.rbac import RBACPermission
+from enums import CloudPlan, DeploymentEdition
from models.account import Account, Tenant
from models.model import App, AppMode
from services import app_import_source
@@ -271,8 +274,11 @@ def test_package_import_rejects_overwrite(
@pytest.mark.parametrize("query", [{}, {"format": "ifpkg"}])
def test_existing_export_route_returns_ifpkg_for_agent(
- app: Flask, monkeypatch: pytest.MonkeyPatch, query: dict[str, str]
+ app: Flask, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None], query: dict[str, str]
) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
+ get_plan = Mock(return_value=CloudPlan.SANDBOX)
+ monkeypatch.setattr(app_module.FeatureService, "get_workspace_plan", get_plan)
model = App(id="app-1", tenant_id="tenant-1", mode=AppMode.AGENT)
monkeypatch.setattr(App, "bound_agent_id_with_session", lambda _self, **_kwargs: "agent-1")
monkeypatch.setattr(app_module, "db", SimpleNamespace(session=lambda: object()))
@@ -289,7 +295,8 @@ def test_existing_export_route_returns_ifpkg_for_agent(
assert response.mimetype == "application/zip"
assert "agent.ifpkg" in response.headers["Content-Disposition"]
response.close()
- export.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1")
+ export.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1", version_id=None)
+ get_plan.assert_not_called()
close.assert_called_once_with()
@@ -299,6 +306,73 @@ def test_ifpkg_export_rejects_non_agent_apps() -> None:
unwrap(app_module.AppExportApi.get)(app_module.AppExportApi(), app_module.AppExportQuery(format="ifpkg"), model)
[email protected]("export_format", [None, "ifpkg", "yaml"])
+ ("edition", "plan", "allowed"),
+ [
+ (DeploymentEdition.CLOUD, CloudPlan.SANDBOX, False),
+ (DeploymentEdition.CLOUD, CloudPlan.PROFESSIONAL, True),
+ (DeploymentEdition.CLOUD, CloudPlan.TEAM, True),
+ (DeploymentEdition.COMMUNITY, CloudPlan.SANDBOX, True),
+ (DeploymentEdition.ENTERPRISE, CloudPlan.SANDBOX, True),
+ ],
+)
+def test_version_export_requires_cloud_paid_plan(
+ app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+ export_format: str | None,
+ edition: DeploymentEdition,
+ plan: CloudPlan,
+ allowed: bool,
+) -> None:
+ config_overrides(DEPLOYMENT_EDITION=edition)
+ get_plan = Mock(return_value=plan)
+ monkeypatch.setattr(app_module.FeatureService, "get_workspace_plan", get_plan)
+ model = App(id="app-1", tenant_id="tenant-1", mode=AppMode.AGENT)
+ monkeypatch.setattr(App, "bound_agent_id_with_session", lambda _self, **_kwargs: "agent-1")
+ monkeypatch.setattr(app_module, "db", SimpleNamespace(session=lambda: object()))
+ export = Mock(return_value=SimpleNamespace(archive=io.BytesIO(b"package"), filename="agent.ifpkg", close=Mock()))
+ monkeypatch.setattr(app_module, "RosterAgentPackageExporter", lambda: SimpleNamespace(export=export))
+ export_dsl = Mock(return_value="app: {}")
+ monkeypatch.setattr(app_module.AppDslService, "export_dsl", export_dsl)
+ version_id = "11111111-1111-4111-8111-111111111111"
+ query = app_module.AppExportQuery.model_validate({"format": export_format, "version_id": version_id})
+ with app.test_request_context("/console/api/apps/app-1/export"):
+ if not allowed:
+ with pytest.raises(Forbidden, match="paid plan"):
+ unwrap(app_module.AppExportApi.get)(app_module.AppExportApi(), query, model)
+ export.assert_not_called()
+ export_dsl.assert_not_called()
+ else:
+ response = unwrap(app_module.AppExportApi.get)(app_module.AppExportApi(), query, model)
+ if export_format == "yaml":
+ assert response == {"data": "app: {}"}
+ assert export_dsl.call_args.kwargs["version_id"] == UUID(version_id)
+ else:
+ export.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1", version_id=UUID(version_id))
+ response.close()
+ if edition == DeploymentEdition.CLOUD:
+ get_plan.assert_called_once_with("tenant-1")
+ else:
+ get_plan.assert_not_called()
+
+
+def test_export_query_rejects_conflicting_version_selectors() -> None:
+ with pytest.raises(ValidationError, match="version_id and workflow_id cannot be used together"):
+ app_module.AppExportQuery.model_validate(
+ {"version_id": "11111111-1111-4111-8111-111111111111", "workflow_id": "workflow-1"}
+ )
+
+
+def test_version_export_rejects_non_agent_apps() -> None:
+ query = app_module.AppExportQuery.model_validate({"version_id": "11111111-1111-4111-8111-111111111111"})
+ with pytest.raises(BadRequest):
+ unwrap(app_module.AppExportApi.get)(
+ app_module.AppExportApi(), query, App(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW)
+ )
+
+
@pytest.mark.parametrize(
("mode", "query"),
[(AppMode.AGENT, {"format": "yaml"}), (AppMode.WORKFLOW, {}), (AppMode.WORKFLOW, {"format": "yaml"})],
diff --git a/api/tests/unit_tests/services/agent/test_agent_dsl_service.py b/api/tests/unit_tests/services/agent/test_agent_dsl_service.py
index 085221a2f9a..8dd0754f460 100644
--- a/api/tests/unit_tests/services/agent/test_agent_dsl_service.py
+++ b/api/tests/unit_tests/services/agent/test_agent_dsl_service.py
@@ -310,7 +310,7 @@ def test_agent_package_rejects_unknown_schema_version() -> None:
def test_export_agent_app_requires_backing_agent(sqlite_session: Session) -> None:
with pytest.raises(ValueError, match="no active backing Agent"):
- AgentDslService(sqlite_session).export_agent_app(app=_app())
+ AgentDslService(sqlite_session).export_agent_app(app=_app(), version_id=None)
@pytest.mark.parametrize("use_draft", [True, False])
@@ -334,7 +334,7 @@ def test_export_agent_app_uses_draft_or_active_snapshot(sqlite_session: Session,
sqlite_session.add_all(rows)
sqlite_session.commit()
- package_ref, packages = AgentDslService(sqlite_session).export_agent_app(app=_app())
+ package_ref, packages = AgentDslService(sqlite_session).export_agent_app(app=_app(), version_id=None)
assert package_ref == "agent_1"
assert packages[package_ref].soul.config_note == ("draft" if use_draft else "snapshot")
diff --git a/api/tests/unit_tests/services/agent/test_roster_package_service.py b/api/tests/unit_tests/services/agent/test_roster_package_service.py
index eb07f2b8874..f6bc632a3a8 100644
--- a/api/tests/unit_tests/services/agent/test_roster_package_service.py
+++ b/api/tests/unit_tests/services/agent/test_roster_package_service.py
@@ -4,6 +4,7 @@ import hashlib
import io
import zipfile
from collections.abc import Callable, Generator
+from uuid import UUID
import pytest
import yaml
@@ -16,6 +17,8 @@ from models.agent import (
Agent,
AgentConfigDraft,
AgentConfigDraftType,
+ AgentConfigRevision,
+ AgentConfigRevisionOperation,
AgentConfigSnapshot,
AgentKind,
AgentScope,
@@ -30,6 +33,7 @@ from models.tools import ToolFile
from services.agent import roster_package_exporter as roster_package_exporter_module
from services.agent.dsl_entities import AgentAppDsl, AgentPackage, AgentPackageMetadata, make_agent_app_dsl
from services.agent.errors import (
+ AgentVersionNotFoundError,
InvalidRosterAgentPackageError,
RosterAgentPackageExportFailedError,
RosterAgentPackageImportFailedError,
@@ -922,7 +926,7 @@ def test_export_accepts_legacy_agent_and_preserves_caller_transaction(
app_model = sqlite_session.get(App, agent.app_id)
assert app_model is not None
standalone_dsl = yaml.safe_load(AppDslService.export_dsl(app_model, session=sqlite_session))
- with exporter.export(tenant_id="tenant-1", agent_id=agent.id) as exported:
+ with exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=None) as exported:
archive_bytes = exported.archive.read()
assert exported.filename == "research-agent.ifpkg"
with zipfile.ZipFile(io.BytesIO(archive_bytes)) as archive:
@@ -995,26 +999,26 @@ def test_export_accepts_legacy_agent_and_preserves_caller_transaction(
max_entries = dify_config.AGENT_PACKAGE_MAX_ENTRIES
max_manifest_bytes = dify_config.AGENT_PACKAGE_MAX_MANIFEST_BYTES
apply_config_overrides(monkeypatch, AGENT_PACKAGE_MAX_ENTRIES=4)
- with exporter.export(tenant_id="tenant-1", agent_id=agent.id) as exported:
+ with exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=None) as exported:
with zipfile.ZipFile(exported.archive) as archive:
assert len(archive.infolist()) == 4
reads_before_limit_check = storage.read_count
apply_config_overrides(monkeypatch, AGENT_PACKAGE_MAX_ENTRIES=3)
with pytest.raises(RosterAgentPackageTooLargeError):
- exporter.export(tenant_id="tenant-1", agent_id=agent.id)
+ exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=None)
assert storage.read_count == reads_before_limit_check
apply_config_overrides(monkeypatch, AGENT_PACKAGE_MAX_ENTRIES=max_entries)
apply_config_overrides(monkeypatch, AGENT_PACKAGE_MAX_MANIFEST_BYTES=1)
with pytest.raises(RosterAgentPackageTooLargeError):
- exporter.export(tenant_id="tenant-1", agent_id=agent.id)
+ exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=None)
apply_config_overrides(monkeypatch, AGENT_PACKAGE_MAX_MANIFEST_BYTES=max_manifest_bytes)
file_bytes_before_limit_check = storage.bytes_yielded["tools/guide.pdf"]
apply_config_overrides(monkeypatch, AGENT_PACKAGE_MAX_BYTES=len(skill_payload) + 1)
with pytest.raises(RosterAgentPackageTooLargeError):
- exporter.export(tenant_id="tenant-1", agent_id=agent.id)
+ exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=None)
assert storage.bytes_yielded["tools/guide.pdf"] - file_bytes_before_limit_check == 7
@@ -1022,6 +1026,7 @@ def test_export_uses_current_workspace_skill_bindings(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
) -> None:
+ monkeypatch.setattr(DependenciesAnalysisService, "generate_dependencies", lambda **_kwargs: [])
workspace_payload = _skill_archive("legacy-published")
storage = _MemoryStorage({"tools/workspace.zip": workspace_payload})
monkeypatch.setattr(
@@ -1109,7 +1114,7 @@ def test_export_uses_current_workspace_skill_bindings(
storage_backend=storage,
dependency_provider=lambda _tenant_id, _dependencies: [],
)
- with exporter.export(tenant_id="tenant-1", agent_id=agent.id) as exported:
+ with exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=None) as exported:
with RosterAgentPackageReader().read(exported.archive) as prepared:
assert len(prepared.manifest.skills) == 1
assert prepared.manifest.skills[0].scope == "workspace"
@@ -1143,11 +1148,105 @@ def test_export_uses_current_workspace_skill_bindings(
sqlite_session.add(draft)
sqlite_session.commit()
- with exporter.export(tenant_id="tenant-1", agent_id=agent.id) as exported:
+ with exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=None) as exported:
with RosterAgentPackageReader().read(exported.archive) as prepared:
assert prepared.apps["app.yaml"].package.soul.prompt.system_prompt == "current draft"
assert prepared.manifest.skills == []
+ historical_version_id = UUID(snapshot.id)
+ active_snapshot = AgentConfigSnapshot(
+ tenant_id="tenant-1",
+ agent_id=agent.id,
+ version=2,
+ config_snapshot=AgentSoulConfig.model_validate({"prompt": {"system_prompt": "current published"}}),
+ created_by="account-1",
+ )
+ sqlite_session.add(active_snapshot)
+ sqlite_session.flush()
+ agent.active_config_snapshot_id = active_snapshot.id
+ sqlite_session.add(
+ AgentConfigRevision(
+ tenant_id="tenant-1",
+ agent_id=agent.id,
+ current_snapshot_id=str(historical_version_id),
+ revision=1,
+ operation=AgentConfigRevisionOperation.PUBLISH_DRAFT,
+ created_by="account-1",
+ )
+ )
+ sqlite_session.commit()
+
+ with exporter.export(tenant_id="tenant-1", agent_id=agent.id, version_id=historical_version_id) as exported:
+ with RosterAgentPackageReader().read(exported.archive) as prepared:
+ assert prepared.apps["app.yaml"].package.soul.prompt.system_prompt == ""
+ assert prepared.manifest.skills[0].name == "legacy-published"
+ assert prepared.apps["app.yaml"].package.workspace_skills[0].priority == 0
+
+ app_model = sqlite_session.get(App, agent.app_id)
+ assert app_model is not None
+ dsl = AgentAppDsl.model_validate(
+ yaml.safe_load(AppDslService.export_dsl(app_model, session=sqlite_session, version_id=historical_version_id))
+ )
+ assert dsl.package.soul.prompt.system_prompt == ""
+ assert len(dsl.package.workspace_skills) == 1
+ assert dsl.package.workspace_skills[0].priority == 0
+
+
[email protected]("source", ["missing", "other_tenant", "other_agent", "internal_snapshot"])
[email protected]("export_format", ["ifpkg", "yaml"])
+def test_export_rejects_unavailable_agent_versions(sqlite_session: Session, source: str, export_format: str) -> None:
+ app_model = _app("44444444-4444-4444-8444-444444444444")
+ agent = Agent(
+ tenant_id="tenant-1",
+ name="Agent",
+ description="",
+ role="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ app_id=app_model.id,
+ backing_app_id=app_model.id,
+ status=AgentStatus.ACTIVE,
+ created_by="account-1",
+ updated_by="account-1",
+ )
+ agent.id = "55555555-5555-4555-8555-555555555555"
+ version_id = UUID("66666666-6666-4666-8666-666666666666")
+ sqlite_session.add_all([app_model, agent])
+ if source != "missing":
+ snapshot = AgentConfigSnapshot(
+ id=str(version_id),
+ tenant_id="other-tenant" if source == "other_tenant" else agent.tenant_id,
+ agent_id="other-agent" if source == "other_agent" else agent.id,
+ version=1,
+ config_snapshot=AgentSoulConfig(),
+ created_by="account-1",
+ )
+ sqlite_session.add_all(
+ [
+ snapshot,
+ AgentConfigRevision(
+ tenant_id=snapshot.tenant_id,
+ agent_id=snapshot.agent_id,
+ current_snapshot_id=snapshot.id,
+ revision=1,
+ operation=(
+ AgentConfigRevisionOperation.CREATE_VERSION
+ if source == "internal_snapshot"
+ else AgentConfigRevisionOperation.PUBLISH_DRAFT
+ ),
+ ),
+ ]
+ )
+ sqlite_session.commit()
+
+ if export_format == "ifpkg":
+ with pytest.raises(AgentVersionNotFoundError):
+ RosterAgentPackageExporter().export(tenant_id=agent.tenant_id, agent_id=agent.id, version_id=version_id)
+ else:
+ with pytest.raises(AgentVersionNotFoundError):
+ AppDslService.export_dsl(app_model, session=sqlite_session, version_id=version_id)
+
def test_manifest_yaml_is_strict() -> None:
skill_payload = _skill_archive()
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index bfd59c89666..b6d9858be73 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -4433,6 +4433,7 @@ export type GetAppsByAppIdExportData = {
query?: {
format?: 'ifpkg' | 'yaml'
include_secret?: boolean
+ version_id?: string
workflow_id?: string
}
url: '/apps/{app_id}/export'
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index 7b20baca4ea..e1df3fa9860 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -5058,6 +5058,7 @@ export const zGetAppsByAppIdExportPath = z.object({
export const zGetAppsByAppIdExportQuery = z.object({
format: z.enum(['ifpkg', 'yaml']).optional(),
include_secret: z.boolean().optional().default(false),
+ version_id: z.uuid().optional(),
workflow_id: z.string().optional(),
})
diff --git a/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx b/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx
index 05671d685b5..064bf6ab699 100644
--- a/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx
+++ b/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx
@@ -102,6 +102,78 @@ describe('useExportAppDsl', () => {
expect(mocks.getEnvironmentVariables).not.toHaveBeenCalled()
})
+ it('downloads the selected published Agent version as an ifpkg package', async () => {
+ const archive = new Blob(['published agent package'], { type: 'application/zip' })
+ mocks.exportAppDsl.mockResolvedValue(archive)
+ const { result } = renderHook(() => useExportAppDsl(), { wrapper: createWrapper() })
+
+ await act(async () => {
+ await expect(
+ result.current.exportAppDsl({
+ appId: 'agent-app-id',
+ appName: 'Support Agent',
+ versionId: '11111111-1111-4111-8111-111111111111',
+ format: 'ifpkg',
+ }),
+ ).resolves.toEqual({ status: 'downloaded' })
+ })
+
+ expect(mocks.exportAppDsl).toHaveBeenCalledWith(
+ {
+ params: { app_id: 'agent-app-id' },
+ query: {
+ include_secret: false,
+ version_id: '11111111-1111-4111-8111-111111111111',
+ format: 'ifpkg',
+ },
+ },
+ { context: { silent: true } },
+ )
+ expect(mocks.downloadBlob).toHaveBeenCalledWith({
+ data: archive,
+ fileName: 'Support Agent.ifpkg',
+ })
+ expect(mocks.getEnvironmentVariables).not.toHaveBeenCalled()
+ })
+
+ it('allows retrying a failed version export and downloads only the successful response', async () => {
+ const archive = new File(['published agent package'], 'published-agent.ifpkg', {
+ type: 'application/zip',
+ })
+ mocks.exportAppDsl.mockRejectedValueOnce(new Error('Export failed')).mockResolvedValue(archive)
+ const { result } = renderHook(() => useExportAppDsl(), { wrapper: createWrapper() })
+ const input = {
+ appId: 'agent-app-id',
+ appName: 'Support Agent',
+ versionId: '11111111-1111-4111-8111-111111111111',
+ }
+
+ await act(async () => {
+ await expect(result.current.exportAppDsl(input)).resolves.toEqual({ status: 'failed' })
+ })
+ await waitFor(() => expect(result.current.isExporting).toBe(false))
+ expect(mocks.downloadBlob).not.toHaveBeenCalled()
+
+ await act(async () => {
+ await expect(result.current.exportAppDsl(input)).resolves.toEqual({ status: 'downloaded' })
+ })
+ await waitFor(() => expect(result.current.isExporting).toBe(false))
+
+ expect(mocks.exportAppDsl).toHaveBeenCalledTimes(2)
+ expect(mocks.exportAppDsl).toHaveBeenLastCalledWith(
+ {
+ params: { app_id: input.appId },
+ query: { include_secret: false, version_id: input.versionId },
+ },
+ { context: { silent: true } },
+ )
+ expect(mocks.downloadBlob).toHaveBeenCalledTimes(1)
+ expect(mocks.downloadBlob).toHaveBeenCalledWith({
+ data: archive,
+ fileName: 'published-agent.ifpkg',
+ })
+ })
+
it('exports through the generated client and hands the YAML file to the browser', async () => {
mocks.exportAppDsl.mockResolvedValue({ data: 'kind: app\nversion: 0.1.5\n' })
const { result } = renderHook(() => useExportAppDsl(), { wrapper: createWrapper() })
diff --git a/web/app/components/app/use-export-app-dsl.ts b/web/app/components/app/use-export-app-dsl.ts
index 83d9df0e9a6..13db963ab79 100644
--- a/web/app/components/app/use-export-app-dsl.ts
+++ b/web/app/components/app/use-export-app-dsl.ts
@@ -15,6 +15,7 @@ type ExportAppDslInput = {
appId: string
appName: string
includeSecret?: boolean
+ versionId?: string
format?: NonNullable<GetAppsByAppIdExportData['query']>['format']
}
@@ -49,12 +50,17 @@ async function exportAppDslFile({
appId,
appName,
includeSecret = false,
+ versionId,
format,
}: ExportAppDslInput) {
const response = await consoleClient.apps.byAppId.export.get(
{
params: { app_id: appId },
- query: { include_secret: includeSecret, ...(format && { format }) },
+ query: {
+ include_secret: includeSecret,
+ ...(versionId ? { version_id: versionId } : {}),
+ ...(format && { format }),
+ },
},
{ context: { silent: true } },
)
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx
index 39515b8debb..2632cb2e455 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx
@@ -1,8 +1,42 @@
import type { AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'
import { fireEvent, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { renderWithAccountProfile as render } from '@/test/console/account-profile'
import { AgentPreviewVersionsPanel } from '../versions-panel'
+const exportState = vi.hoisted(() => ({
+ canExport: true,
+ isExporting: false,
+ edition: 'CLOUD',
+ plan: 'professional' as string | undefined,
+ exportAppDsl: vi.fn(),
+ setPricing: vi.fn(),
+}))
+
+vi.mock('@/features/agent-v2/permissions', () => ({
+ useAgentPermissions: () => ({
+ canImportExportDSL: exportState.canExport,
+ agentQuery: { data: { app_id: 'app-1', name: 'My agent' } },
+ }),
+}))
+
+vi.mock('@/app/components/app/use-export-app-dsl', () => ({
+ useExportAppDsl: () => ({
+ exportAppDsl: exportState.exportAppDsl,
+ isExporting: exportState.isExporting,
+ }),
+}))
+
+vi.mock('jotai', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('jotai')>()),
+ useAtomValue: () => exportState.edition,
+}))
+
+vi.mock('nuqs', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('nuqs')>()),
+ useQueryState: () => [null, exportState.setPricing],
+}))
+
const versions: AgentConfigSnapshotSummaryResponse[] = [
{
id: 'version-2',
@@ -32,10 +66,10 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {
return {
...actual,
- useQuery: () => ({
- data: { data: versions },
- isPending: false,
- }),
+ useQuery: (options: { queryKey: string[] }) =>
+ options.queryKey[0] === 'features'
+ ? { data: exportState.plan }
+ : { data: { data: versions }, isPending: false },
}
})
@@ -47,6 +81,7 @@ vi.mock('@/hooks/use-timestamp', () => ({
vi.mock('@/service/console', () => ({
consoleQuery: {
+ features: { get: { queryOptions: () => ({ queryKey: ['features'] }) } },
account: {
profile: {
get: {
@@ -69,6 +104,81 @@ vi.mock('@/service/console', () => ({
describe('AgentPreviewVersionsPanel', () => {
beforeEach(() => {
vi.clearAllMocks()
+ exportState.canExport = true
+ exportState.isExporting = false
+ exportState.edition = 'CLOUD'
+ exportState.plan = 'professional'
+ })
+
+ describe('Version export', () => {
+ const renderPanel = () => {
+ const onSelectVersion = vi.fn()
+ render(
+ <AgentPreviewVersionsPanel
+ agentId="agent-1"
+ activeVersionId="version-2"
+ onSelectVersion={onSelectVersion}
+ onClose={vi.fn()}
+ />,
+ )
+ return onSelectVersion
+ }
+
+ it('exports the version whose menu was opened without changing the selected version', async () => {
+ const user = userEvent.setup()
+ const onSelectVersion = renderPanel()
+ await user.click(screen.getByRole('button', { name: /moreActions.*Initial release/ }))
+ await user.click(screen.getByRole('menuitem', { name: /export/i }))
+ expect(exportState.exportAppDsl).toHaveBeenCalledWith({
+ appId: 'app-1',
+ appName: 'My agent',
+ versionId: 'version-0',
+ })
+ expect(onSelectVersion).not.toHaveBeenCalled()
+ })
+
+ it('hides version actions without export permission', () => {
+ exportState.canExport = false
+ renderPanel()
+ expect(screen.queryByRole('button', { name: /moreActions/ })).not.toBeInTheDocument()
+ })
+
+ it('opens pricing instead of exporting on the Cloud sandbox plan', async () => {
+ exportState.plan = 'sandbox'
+ const user = userEvent.setup()
+ renderPanel()
+ await user.click(screen.getByRole('button', { name: /moreActions.*Initial release/ }))
+ await user.click(screen.getByRole('menuitem', { name: /export/i }))
+ expect(exportState.setPricing).toHaveBeenCalledWith('open')
+ expect(exportState.exportAppDsl).not.toHaveBeenCalled()
+ })
+
+ it.each(['COMMUNITY', 'ENTERPRISE'])(
+ 'allows export on %s without a Cloud plan',
+ async (edition) => {
+ exportState.edition = edition
+ exportState.plan = undefined
+ const user = userEvent.setup()
+ renderPanel()
+ await user.click(screen.getByRole('button', { name: /moreActions.*Initial release/ }))
+ await user.click(screen.getByRole('menuitem', { name: /export/i }))
+ expect(exportState.exportAppDsl).toHaveBeenCalledWith(
+ expect.objectContaining({ versionId: 'version-0' }),
+ )
+ },
+ )
+
+ it.each(['loading-plan', 'exporting'])('disables export while %s', async (state) => {
+ if (state === 'loading-plan') exportState.plan = undefined
+ else exportState.isExporting = true
+ const user = userEvent.setup()
+ renderPanel()
+ await user.click(screen.getByRole('button', { name: /moreActions.*Initial release/ }))
+ const action = screen.getByRole('menuitem', { name: /export/i })
+ expect(action).toHaveAttribute('aria-disabled', 'true')
+ await user.click(action)
+ expect(exportState.exportAppDsl).not.toHaveBeenCalled()
+ })
})
describe('Version selection', () => {
@@ -85,7 +195,7 @@ describe('AgentPreviewVersionsPanel', () => {
{ accountProfile: { id: 'user-1', name: 'Alice', email: '[email protected]' } },
)
- fireEvent.click(screen.getByRole('button', { name: /Initial release/i }))
+ fireEvent.click(screen.getByRole('button', { name: /^Initial release/i }))
expect(handleSelectVersion).toHaveBeenCalledWith('version-0')
})
@@ -142,9 +252,13 @@ describe('AgentPreviewVersionsPanel', () => {
fireEvent.click(screen.getByRole('button', { name: /filter/i }))
fireEvent.click(screen.getByRole('button', { name: /onlyYours/i }))
- expect(screen.getByRole('button', { name: /Published update/i })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: /Initial release/i })).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /versionName.*1/i })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /^Published update/i })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /^Initial release/i })).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', {
+ name: /^agentV2.agentDetail.versionHistory.versionName.*1/i,
+ }),
+ ).not.toBeInTheDocument()
})
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/index.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/index.tsx
index af2b71b96a8..251d04f6a13 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/index.tsx
@@ -2,9 +2,18 @@
import type { AgentVersionFilter } from './filter'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { useAtomValue } from 'jotai'
+import { useQueryState } from 'nuqs'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { useExportAppDsl } from '@/app/components/app/use-export-app-dsl'
+import {
+ pricingQueryParamName,
+ pricingQueryParser,
+} from '@/app/components/billing/pricing/query-params'
import { userProfileQueryOptions } from '@/features/account-profile/client'
+import { useAgentPermissions } from '@/features/agent-v2/permissions'
+import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleQuery } from '@/service/console'
import { CurrentDraftItem } from './current-draft-item'
import { VersionFilter } from './filter'
@@ -31,6 +40,28 @@ export function AgentPreviewVersionsPanel({
...userProfileQueryOptions(),
select: (data) => data.profile,
})
+ const { agentQuery, canImportExportDSL } = useAgentPermissions(agentId)
+ const { exportAppDsl, isExporting } = useExportAppDsl()
+ const deploymentEdition = useAtomValue(deploymentEditionAtom)
+ const { data: plan } = useQuery(
+ consoleQuery.features.get.queryOptions({
+ enabled: deploymentEdition === 'CLOUD',
+ select: (data) => data.billing.subscription.plan,
+ }),
+ )
+ const [, setPricing] = useQueryState(pricingQueryParamName, pricingQueryParser)
+ const shouldShowUpgrade = deploymentEdition === 'CLOUD' && plan === 'sandbox'
+ const exportDisabled =
+ isExporting || (deploymentEdition === 'CLOUD' && plan === undefined) || !agentQuery.data?.app_id
+ const handleExport = (versionId: string) => {
+ const agent = agentQuery.data
+ if (!canImportExportDSL || exportDisabled || !agent?.app_id) return
+ if (shouldShowUpgrade) {
+ void setPricing('open')
+ return
+ }
+ void exportAppDsl({ appId: agent.app_id, appName: agent.name, versionId })
+ }
const [filterValue, setFilterValue] = useState<AgentVersionFilter>('all')
const versionsQuery = useQuery(
consoleQuery.agent.byAgentId.versions.get.queryOptions({
@@ -108,6 +139,9 @@ export function AgentPreviewVersionsPanel({
isFirst={false}
isLast={index === filteredVersions.length - 1}
onSelect={onSelectVersion}
+ onExport={canImportExportDSL ? handleExport : undefined}
+ exportDisabled={exportDisabled}
+ showUpgrade={shouldShowUpgrade}
/>
))}
</div>
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-item.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-item.tsx
index 096f5f499c3..a321be6c464 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-item.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel/version-item.tsx
@@ -1,6 +1,14 @@
import type { AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'
import { cn } from '@langgenius/dify-ui/cn'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@langgenius/dify-ui/dropdown-menu'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useTranslation } from 'react-i18next'
+import PremiumBadge from '@/app/components/base/premium-badge'
import useTimestamp from '@/hooks/use-timestamp'
import { VersionTimelineDot } from './version-timeline-dot'
@@ -30,6 +38,9 @@ export function VersionItem({
isFirst,
isLast,
onSelect,
+ onExport,
+ exportDisabled,
+ showUpgrade,
}: {
version: AgentConfigSnapshotSummaryResponse
activeVersionId?: string | null
@@ -37,6 +48,9 @@ export function VersionItem({
isFirst: boolean
isLast: boolean
onSelect: (versionId: string) => void
+ onExport?: (versionId: string) => void
+ exportDisabled?: boolean
+ showUpgrade?: boolean
}) {
const { t } = useTranslation('agentV2')
const { t: tWorkflow } = useTranslation('workflow')
@@ -46,39 +60,72 @@ export function VersionItem({
t(($) => $['agentDetail.versionHistory.versionName'], { version: version.version })
return (
- <button
- type="button"
- aria-current={isActive ? 'true' : undefined}
- onClick={() => onSelect(version.id)}
- className={cn(
- 'group relative flex w-full items-start gap-1 rounded-lg py-1 pr-1.5 pl-2 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
- isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
- )}
- >
- <VersionTimelineDot isActive={isActive} isFirst={isFirst} isLast={isLast} />
- <div className="min-w-0 flex-1 py-0.5">
- <div className="flex min-w-0 items-center gap-1">
- <p
- className={cn(
- 'truncate system-sm-semibold',
- isActive ? 'text-text-accent' : 'text-text-secondary',
+ <div className="group relative">
+ <button
+ type="button"
+ aria-current={isActive ? 'true' : undefined}
+ onClick={() => onSelect(version.id)}
+ className={cn(
+ 'group relative flex w-full items-start gap-1 rounded-lg py-1 pl-2 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
+ onExport ? 'pr-8' : 'pr-1.5',
+ isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
+ )}
+ >
+ <VersionTimelineDot isActive={isActive} isFirst={isFirst} isLast={isLast} />
+ <div className="min-w-0 flex-1 py-0.5">
+ <div className="flex min-w-0 items-center gap-1">
+ <p
+ className={cn(
+ 'truncate system-sm-semibold',
+ isActive ? 'text-text-accent' : 'text-text-secondary',
+ )}
+ >
+ {label}
+ </p>
+ {isLatest && (
+ <span className="shrink-0 rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-1.25 py-0.75 system-2xs-medium-uppercase text-text-accent-secondary">
+ {tWorkflow(($) => $['versionHistory.latest'])}
+ </span>
)}
- >
- {label}
- </p>
- {isLatest && (
- <span className="shrink-0 rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-1.25 py-0.75 system-2xs-medium-uppercase text-text-accent-secondary">
- {tWorkflow(($) => $['versionHistory.latest'])}
- </span>
+ </div>
+ {isActive && version.summary && (
+ <p className="mt-0.5 line-clamp-4 system-xs-regular text-text-secondary">
+ {version.summary}
+ </p>
)}
+ <VersionMetadata version={version} />
</div>
- {isActive && version.summary && (
- <p className="mt-0.5 line-clamp-4 system-xs-regular text-text-secondary">
- {version.summary}
- </p>
- )}
- <VersionMetadata version={version} />
- </div>
- </button>
+ </button>
+ {onExport && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ aria-label={t(($) => $['roster.moreActions'], { name: label })}
+ size="sm"
+ className="absolute top-1 right-1 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 data-popup-open:opacity-100 [@media(hover:none)]:opacity-100"
+ >
+ <span aria-hidden className="i-ri-more-fill size-4" />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent placement="bottom-end" className="min-w-40">
+ <DropdownMenuItem
+ disabled={exportDisabled}
+ onClick={() => onExport(version.id)}
+ className="gap-2"
+ >
+ <span aria-hidden className="i-ri-file-download-line size-4 shrink-0" />
+ <span className="flex-1">{t(($) => $.exportApp, { ns: 'app' })}</span>
+ {showUpgrade && (
+ <PremiumBadge size="s">
+ {t(($) => $['upgradeBtn.encourageShort'], { ns: 'billing' })}
+ </PremiumBadge>
+ )}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
)
}