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(api): support New Agent Beta for inline Workflow agents (#41215)

非法操作1afac216902a
diff --git a/api/services/agent/workflow_publish_service.py b/api/services/agent/workflow_publish_service.py
index 50b2d1dc5bf..55778f015c1 100644
--- a/api/services/agent/workflow_publish_service.py
+++ b/api/services/agent/workflow_publish_service.py
@@ -576,18 +576,19 @@ class WorkflowAgentPublishService:
session: Session,
draft_workflow: Workflow,
published_workflow: Workflow,
- ) -> None:
+ ) -> bool:
"""Copy all draft Roster and inline bindings to a published version.
Only copied inline bindings add owners for workflow-only Agents.
Publishing does not release existing draft or historical inline owners,
- produces no retirement candidates, and returns ``None``.
+ produces no retirement candidates. The return value reports whether
+ the published Workflow contains an inline Agent binding.
"""
node_ids = {
node_id for node_id, _node_data in WorkflowAgentNodeValidator.iter_agent_v2_nodes(draft_workflow.graph_dict)
}
if not node_ids:
- return
+ return False
bindings = session.scalars(
select(WorkflowAgentNodeBinding).where(
@@ -599,9 +600,15 @@ class WorkflowAgentPublishService:
)
).all()
if not bindings:
- return
+ return False
+ has_inline_agent = False
for binding in bindings:
+ has_inline_agent = has_inline_agent or (
+ binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT
+ and binding.agent_id is not None
+ and binding.current_snapshot_id is not None
+ )
current_snapshot_id = binding.current_snapshot_id
if binding.binding_type == WorkflowAgentBindingType.ROSTER_AGENT and binding.agent_id:
_, current_snapshot_id = cls._resolve_roster_agent_graph_binding(
@@ -624,6 +631,7 @@ class WorkflowAgentPublishService:
updated_by=binding.updated_by,
)
session.add(copied)
+ return has_inline_agent
@classmethod
def restore_agent_node_bindings_to_draft(
diff --git a/api/services/billing_service.py b/api/services/billing_service.py
index a76bc148b00..8edc33a581d 100644
--- a/api/services/billing_service.py
+++ b/api/services/billing_service.py
@@ -240,6 +240,10 @@ class BillingService:
def ensure_new_agent_beta_revision(cls, revision_id: str) -> None:
cls._send_request("POST", f"/new-agent-beta/revisions/{revision_id}/ensure")
+ @classmethod
+ def ensure_new_agent_beta_workflow(cls, workflow_id: str) -> None:
+ cls._send_request("POST", f"/new-agent-beta/workflows/{workflow_id}/ensure")
+
@classmethod
def get_info(cls, tenant_id: str, exclude_vector_space: bool = False) -> BillingInfo:
params = {"tenant_id": tenant_id}
diff --git a/api/services/workflow_service.py b/api/services/workflow_service.py
index 7a267427338..d7e8a2c1614 100644
--- a/api/services/workflow_service.py
+++ b/api/services/workflow_service.py
@@ -94,6 +94,7 @@ from services.errors.app import (
WorkflowHashNotEqualError,
WorkflowNotFoundError,
)
+from tasks.new_agent_beta_task import register_new_agent_beta_workflow_publish_after_commit
@dataclass(frozen=True)
@@ -748,11 +749,17 @@ class WorkflowService:
# commit db session changes
session.add(workflow)
- WorkflowAgentPublishService.copy_agent_node_bindings_to_published(
+ has_inline_agent = WorkflowAgentPublishService.copy_agent_node_bindings_to_published(
session=session,
draft_workflow=draft_workflow,
published_workflow=workflow,
)
+ if has_inline_agent:
+ register_new_agent_beta_workflow_publish_after_commit(
+ session=session,
+ published_workflow_id=workflow.id,
+ published_at=workflow.created_at,
+ )
# trigger app workflow events
app_published_workflow_was_updated.send(app_model, published_workflow=workflow)
diff --git a/api/tasks/new_agent_beta_task.py b/api/tasks/new_agent_beta_task.py
index e8febca9e45..b0b3f57bcf3 100644
--- a/api/tasks/new_agent_beta_task.py
+++ b/api/tasks/new_agent_beta_task.py
@@ -80,6 +80,35 @@ def register_new_agent_beta_publish_after_commit(
)
+def register_new_agent_beta_workflow_publish_after_commit(
+ *, session: Session, published_workflow_id: str, published_at: datetime
+) -> None:
+ """Best-effort registration for a committed App Workflow publish."""
+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
+ return
+
+ try:
+ if not _is_publish_in_activity_window(published_at):
+ return
+ cancelled = False
+
+ def cancel_on_rollback(_session: Session) -> None:
+ nonlocal cancelled
+ cancelled = True
+
+ def dispatch_after_commit(_session: Session) -> None:
+ if not cancelled:
+ schedule_new_agent_beta_workflow_ensure(published_workflow_id)
+
+ event.listen(session, "after_rollback", cancel_on_rollback, once=True)
+ event.listen(session, "after_commit", dispatch_after_commit, once=True)
+ except Exception:
+ logger.exception(
+ "Failed to register New Agent Beta Workflow publish event, published_workflow_id=%s",
+ published_workflow_id,
+ )
+
+
@shared_task(
queue=NEW_AGENT_BETA_QUEUE,
bind=True,
@@ -88,19 +117,30 @@ def register_new_agent_beta_publish_after_commit(
acks_late=True,
reject_on_worker_lost=True,
)
-def ensure_new_agent_beta_participation_task(self, revision_id: str) -> None:
+def ensure_new_agent_beta_participation_task(self, source_id: str, source_type: str) -> None:
+ if source_type not in {"revision", "workflow"}:
+ raise ValueError(f"Unsupported New Agent Beta source type: {source_type}")
+
try:
- BillingService.ensure_new_agent_beta_revision(revision_id)
+ if source_type == "revision":
+ BillingService.ensure_new_agent_beta_revision(source_id)
+ else:
+ BillingService.ensure_new_agent_beta_workflow(source_id)
except Exception as exc:
if self.request.retries >= _MAX_RETRIES:
- logger.exception("New Agent Beta eligibility retry budget exhausted, revision_id=%s", revision_id)
+ logger.exception(
+ "New Agent Beta eligibility retry budget exhausted, source_type=%s, source_id=%s",
+ source_type,
+ source_id,
+ )
raise
logger.warning(
- "New Agent Beta eligibility request failed, scheduling retry %d/%d, revision_id=%s",
+ "New Agent Beta eligibility request failed, scheduling retry %d/%d, source_type=%s, source_id=%s",
self.request.retries + 1,
_MAX_RETRIES,
- revision_id,
+ source_type,
+ source_id,
exc_info=True,
)
countdown = min(_RETRY_DELAY_SECONDS * (2**self.request.retries), _MAX_RETRY_DELAY_SECONDS)
@@ -109,6 +149,16 @@ def ensure_new_agent_beta_participation_task(self, revision_id: str) -> None:
def schedule_new_agent_beta_ensure(revision_id: str) -> None:
try:
- ensure_new_agent_beta_participation_task.delay(revision_id)
+ ensure_new_agent_beta_participation_task.delay(revision_id, "revision")
except Exception:
logger.exception("Failed to dispatch New Agent Beta eligibility task, revision_id=%s", revision_id)
+
+
+def schedule_new_agent_beta_workflow_ensure(published_workflow_id: str) -> None:
+ try:
+ ensure_new_agent_beta_participation_task.delay(published_workflow_id, "workflow")
+ except Exception:
+ logger.exception(
+ "Failed to dispatch New Agent Beta Workflow eligibility task, published_workflow_id=%s",
+ published_workflow_id,
+ )
diff --git a/api/tests/unit_tests/services/agent/test_workflow_publish_service.py b/api/tests/unit_tests/services/agent/test_workflow_publish_service.py
index 66f06b5ab78..74031c57844 100644
--- a/api/tests/unit_tests/services/agent/test_workflow_publish_service.py
+++ b/api/tests/unit_tests/services/agent/test_workflow_publish_service.py
@@ -5,7 +5,12 @@ import pytest
from sqlalchemy import select
from sqlalchemy.orm import Session
-from models.agent import Agent, AgentScope, WorkflowAgentBindingType, WorkflowAgentNodeBinding
+from models.agent import (
+ Agent,
+ AgentScope,
+ WorkflowAgentBindingType,
+ WorkflowAgentNodeBinding,
+)
from models.enums import AppStatus
from models.model import App, AppMode
from models.workflow import Workflow, WorkflowType
@@ -194,12 +199,13 @@ def test_publish_copy_uses_current_roster_snapshot() -> None:
session.scalar.return_value = active_agent
session.scalars.return_value = SimpleNamespace(all=lambda: [binding])
- WorkflowAgentPublishService.copy_agent_node_bindings_to_published(
+ has_inline_agent = WorkflowAgentPublishService.copy_agent_node_bindings_to_published(
session=session,
draft_workflow=draft_workflow,
published_workflow=published_workflow,
)
+ assert has_inline_agent is False
copied = session.add.call_args.args[0]
assert copied.agent_id == "roster-agent"
assert copied.current_snapshot_id == "active-snapshot"
@@ -279,7 +285,7 @@ def test_publish_binding_copy_keeps_previous_published_owner(
published_workflow=published_workflow,
)
- assert result is None
+ assert result is True
assert sqlite_session.get(WorkflowAgentNodeBinding, previous_inline_binding.id) is previous_inline_binding
assert sqlite_session.get(WorkflowAgentNodeBinding, previous_roster_binding.id) is previous_roster_binding
copied = sqlite_session.scalar(
diff --git a/api/tests/unit_tests/services/test_workflow_service.py b/api/tests/unit_tests/services/test_workflow_service.py
index 6b77c96e568..16357514227 100644
--- a/api/tests/unit_tests/services/test_workflow_service.py
+++ b/api/tests/unit_tests/services/test_workflow_service.py
@@ -1273,6 +1273,9 @@ class TestWorkflowService:
with (
patch("services.workflow_service.app_published_workflow_was_updated"),
patch("services.workflow_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY),
+ patch(
+ "services.workflow_service.register_new_agent_beta_workflow_publish_after_commit"
+ ) as register_workflow_publish,
):
result = workflow_service.publish_workflow(
session=sqlite_session,
@@ -1287,6 +1290,42 @@ class TestWorkflowService:
assert result.version != Workflow.VERSION_DRAFT
assert result.marked_name == "Version 1"
assert result.marked_comment == "Initial release"
+ register_workflow_publish.assert_not_called()
+
+ def test_publish_workflow_registers_inline_agent_after_commit(
+ self, workflow_service: WorkflowService, sqlite_session: Session
+ ) -> None:
+ app = TestWorkflowAssociatedDataFactory.create_app()
+ account = TestWorkflowAssociatedDataFactory.create_account()
+ draft = TestWorkflowAssociatedDataFactory.create_workflow(
+ version=Workflow.VERSION_DRAFT,
+ graph=TestWorkflowAssociatedDataFactory.create_valid_workflow_graph(),
+ )
+ sqlite_session.add(draft)
+ sqlite_session.commit()
+
+ with (
+ patch("services.workflow_service.app_published_workflow_was_updated"),
+ patch("services.workflow_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY),
+ patch(
+ "services.agent.workflow_publish_service.WorkflowAgentPublishService.copy_agent_node_bindings_to_published",
+ return_value=True,
+ ),
+ patch(
+ "services.workflow_service.register_new_agent_beta_workflow_publish_after_commit"
+ ) as register_workflow_publish,
+ ):
+ published = workflow_service.publish_workflow(
+ session=sqlite_session,
+ app_model=app,
+ account=account,
+ )
+
+ register_workflow_publish.assert_called_once_with(
+ session=sqlite_session,
+ published_workflow_id=published.id,
+ published_at=published.created_at,
+ )
def test_publish_workflow_numbers_versions_from_one(
self, workflow_service: WorkflowService, sqlite_session: Session
diff --git a/api/tests/unit_tests/tasks/test_new_agent_beta_task.py b/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
index d3833f7b269..f6fba0cb7ed 100644
--- a/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
+++ b/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import UTC, datetime
from typing import Protocol, cast
from unittest.mock import MagicMock
@@ -13,7 +14,9 @@ from tasks.new_agent_beta_task import (
NEW_AGENT_BETA_QUEUE,
ensure_new_agent_beta_participation_task,
register_new_agent_beta_publish_after_commit,
+ register_new_agent_beta_workflow_publish_after_commit,
schedule_new_agent_beta_ensure,
+ schedule_new_agent_beta_workflow_ensure,
)
@@ -90,6 +93,44 @@ def test_rolled_back_publish_is_never_dispatched(monkeypatch: pytest.MonkeyPatch
dispatch.assert_not_called()
+def test_workflow_publish_event_is_dispatched_only_after_commit(
+ monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+) -> None:
+ _configure_cloud_publish(monkeypatch)
+ dispatch = MagicMock()
+ monkeypatch.setattr(task_module, "schedule_new_agent_beta_workflow_ensure", dispatch)
+ sqlite_session.begin()
+
+ register_new_agent_beta_workflow_publish_after_commit(
+ session=sqlite_session,
+ published_workflow_id="workflow-1",
+ published_at=datetime(2026, 8, 12, 1, 0),
+ )
+
+ dispatch.assert_not_called()
+ sqlite_session.commit()
+ dispatch.assert_called_once_with("workflow-1")
+
+
+def test_rolled_back_workflow_publish_is_never_dispatched(
+ monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+) -> None:
+ _configure_cloud_publish(monkeypatch)
+ dispatch = MagicMock()
+ monkeypatch.setattr(task_module, "schedule_new_agent_beta_workflow_ensure", dispatch)
+ sqlite_session.begin()
+
+ register_new_agent_beta_workflow_publish_after_commit(
+ session=sqlite_session,
+ published_workflow_id="workflow-1",
+ published_at=datetime(2026, 8, 12, 1, 0),
+ )
+ sqlite_session.rollback()
+ sqlite_session.commit()
+
+ dispatch.assert_not_called()
+
+
def test_non_cloud_publish_skips_revision_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(task_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
session = MagicMock()
@@ -127,24 +168,47 @@ def test_publish_activity_window_is_inclusive_start_exclusive_end(
def test_broker_failure_does_not_propagate(monkeypatch: pytest.MonkeyPatch) -> None:
+ delay = MagicMock(side_effect=RuntimeError("broker unavailable"))
monkeypatch.setattr(
ensure_new_agent_beta_participation_task,
"delay",
- MagicMock(side_effect=RuntimeError("broker unavailable")),
+ delay,
)
schedule_new_agent_beta_ensure("revision-1")
+ delay.assert_called_once_with("revision-1", "revision")
+
+
+def test_workflow_broker_failure_does_not_propagate(monkeypatch: pytest.MonkeyPatch) -> None:
+ delay = MagicMock(side_effect=RuntimeError("broker unavailable"))
+ monkeypatch.setattr(
+ ensure_new_agent_beta_participation_task,
+ "delay",
+ delay,
+ )
+
+ schedule_new_agent_beta_workflow_ensure("workflow-1")
+ delay.assert_called_once_with("workflow-1", "workflow")
def test_task_calls_billing_with_revision_id(monkeypatch: pytest.MonkeyPatch) -> None:
ensure = MagicMock()
monkeypatch.setattr(BillingService, "ensure_new_agent_beta_revision", ensure)
- ensure_new_agent_beta_participation_task.run("revision-1")
+ ensure_new_agent_beta_participation_task.run("revision-1", "revision")
ensure.assert_called_once_with("revision-1")
+def test_workflow_task_calls_billing_with_published_workflow_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ ensure = MagicMock()
+ monkeypatch.setattr(BillingService, "ensure_new_agent_beta_workflow", ensure)
+
+ ensure_new_agent_beta_participation_task.run("workflow-1", "workflow")
+
+ ensure.assert_called_once_with("workflow-1")
+
+
def test_task_is_redelivered_when_worker_is_lost() -> None:
task = cast(_TaskWithQueue, ensure_new_agent_beta_participation_task)
@@ -161,11 +225,34 @@ def test_task_retries_billing_failure(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(ensure_new_agent_beta_participation_task, "retry", retry)
with pytest.raises(RuntimeError, match="retry scheduled"):
- ensure_new_agent_beta_participation_task.run("revision-1")
+ ensure_new_agent_beta_participation_task.run("revision-1", "revision")
retry.assert_called_once_with(exc=error, countdown=30)
+def test_workflow_task_retries_billing_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ error = RuntimeError("billing unavailable")
+ monkeypatch.setattr(BillingService, "ensure_new_agent_beta_workflow", MagicMock(side_effect=error))
+ retry = MagicMock(side_effect=RuntimeError("retry scheduled"))
+ monkeypatch.setattr(ensure_new_agent_beta_participation_task, "retry", retry)
+
+ with pytest.raises(RuntimeError, match="retry scheduled"):
+ ensure_new_agent_beta_participation_task.run("workflow-1", "workflow")
+
+ retry.assert_called_once_with(exc=error, countdown=30)
+
+
+def test_task_rejects_unknown_source_type() -> None:
+ with pytest.raises(ValueError, match="Unsupported New Agent Beta source type"):
+ ensure_new_agent_beta_participation_task.run("source-1", "unknown")
+
+
+def test_task_requires_source_type() -> None:
+ run_without_source_type = cast(Callable[[str], None], ensure_new_agent_beta_participation_task.run)
+ with pytest.raises(TypeError, match="source_type"):
+ run_without_source_type("source-1")
+
+
def test_task_caps_exponential_retry_delay(monkeypatch: pytest.MonkeyPatch) -> None:
error = RuntimeError("billing unavailable")
monkeypatch.setattr(BillingService, "ensure_new_agent_beta_revision", MagicMock(side_effect=error))
@@ -174,7 +261,7 @@ def test_task_caps_exponential_retry_delay(monkeypatch: pytest.MonkeyPatch) -> N
monkeypatch.setattr(ensure_new_agent_beta_participation_task, "retry", retry)
with pytest.raises(RuntimeError, match="retry scheduled"):
- ensure_new_agent_beta_participation_task.run("revision-1")
+ ensure_new_agent_beta_participation_task.run("revision-1", "revision")
retry.assert_called_once_with(exc=error, countdown=900)
@@ -189,3 +276,15 @@ def test_billing_contract_uses_internal_ensure_endpoint(monkeypatch: pytest.Monk
"POST",
"/new-agent-beta/revisions/revision-1/ensure",
)
+
+
+def test_billing_workflow_contract_uses_internal_ensure_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
+ send_request = MagicMock(return_value={"status": "issued"})
+ monkeypatch.setattr(BillingService, "_send_request", send_request)
+
+ BillingService.ensure_new_agent_beta_workflow("workflow-1")
+
+ send_request.assert_called_once_with(
+ "POST",
+ "/new-agent-beta/workflows/workflow-1/ensure",
+ )