Compare commits

..
25 changed files with 863 additions and 459 deletions
-15
View File
@@ -139,21 +139,6 @@ jobs:
exit 1
fi
teardown_external_runtime() {
local run_status=$?
trap - EXIT
if ! vp run e2e:middleware:down; then
echo "::error title=E2E teardown failed::External runtime middleware did not shut down cleanly."
if [[ "$run_status" -eq 0 ]]; then
run_status=1
fi
fi
exit "$run_status"
}
trap teardown_external_runtime EXIT
vp run e2e:middleware:up
vp run e2e:post-merge:prepare
vp run e2e:post-merge
- name: Upload Cucumber report
+40 -10
View File
@@ -43,7 +43,7 @@ from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
from models.base import TypeBase
def _patch_redis_clients_on_loaded_modules():
def _patch_redis_clients_on_loaded_modules() -> None:
"""Ensure any module-level redis_client references point to the shared redis_mock."""
import sys
@@ -51,10 +51,9 @@ def _patch_redis_clients_on_loaded_modules():
for module in list(sys.modules.values()):
if module is None:
continue
if hasattr(module, "redis_client"):
module.redis_client = redis_mock
if hasattr(module, "_pubsub_redis_client"):
module.pubsub_redis_client = redis_mock
for client_attribute in ("redis_client", "_pubsub_redis_client"):
if hasattr(module, client_attribute):
setattr(module, client_attribute, redis_mock)
@pytest.fixture
@@ -63,13 +62,13 @@ def app() -> Flask:
@pytest.fixture(autouse=True)
def _provide_app_context(app: Flask):
def _provide_app_context(app: Flask) -> Iterator[None]:
with app.app_context():
yield
@pytest.fixture(autouse=True)
def _patch_redis_clients():
def _patch_redis_clients() -> Iterator[None]:
"""Patch redis_client to MagicMock only for unit test executions."""
with (
@@ -81,7 +80,7 @@ def _patch_redis_clients():
@pytest.fixture(autouse=True)
def reset_redis_mock():
def reset_redis_mock() -> None:
"""reset the Redis mock before each test"""
redis_mock.reset_mock()
redis_mock.get.return_value = None
@@ -91,7 +90,7 @@ def reset_redis_mock():
redis_mock.exists.return_value = False
redis_mock.set.return_value = None
redis_mock.expire.return_value = None
redis_mock.hgetall.return_value = {}
redis_mock.hgetall.return_value = dict[bytes, bytes]()
redis_mock.hdel.return_value = None
redis_mock.incr.return_value = 1
@@ -100,7 +99,7 @@ def reset_redis_mock():
@pytest.fixture(autouse=True)
def reset_secret_key():
def reset_secret_key() -> Iterator[None]:
"""Ensure SECRET_KEY-dependent logic sees an empty config value by default."""
from configs import dify_config
@@ -153,6 +152,18 @@ def _sqlite_session_factory(
return factory
@pytest.fixture
def _unbound_session_factory(
_sqlite_session_factory: sessionmaker[Session],
monkeypatch: pytest.MonkeyPatch,
) -> sessionmaker[Session]:
"""Create one unbound factory and install it as the global test factory."""
factory = sessionmaker()
monkeypatch.setattr(session_factory_module, "_session_maker", factory)
return factory
@pytest.fixture
def sqlite_engine(_sqlite_engine: Engine) -> Engine:
"""Expose the pristine full-schema SQLite engine to tests."""
@@ -179,6 +190,25 @@ def sqlite_session(_sqlite_session_factory: sessionmaker[Session]) -> Iterator[S
yield session
@pytest.fixture
def unbound_session_factory(_unbound_session_factory: sessionmaker[Session]) -> sessionmaker[Session]:
"""Expose an unbound factory for paths that must not require persistence."""
return _unbound_session_factory
@pytest.fixture
def unbound_session(_unbound_session_factory: sessionmaker[Session]) -> Iterator[Session]:
"""Yield an unbound Session for paths that must not require persistence.
Bind-requiring database access fails, while bind-free Session operations can
still succeed.
"""
with _unbound_session_factory() as session:
yield session
def persist_service_api_tenant_owner(session: Session, tenant: Tenant, owner: Account) -> TenantAccountJoin:
"""Persist the owner identity resolved by service-API app authentication.
@@ -11,7 +11,8 @@ from sqlalchemy.orm import Session, sessionmaker
from core.app.entities.app_invoke_entities import ChatAppGenerateEntity
from core.entities.provider_entities import ProviderQuotaType, QuotaUnit
from events.event_handlers import update_provider_when_message_created
from models import TenantCreditPool
from models import Message, TenantCreditPool
from models.enums import ProviderQuotaType as ModelProviderQuotaType
from models.provider import ProviderType
@@ -30,7 +31,7 @@ def test_message_created_trial_credit_accounting_does_not_raise_when_balance_is_
pool_id = str(uuid4())
pool = TenantCreditPool(
tenant_id=tenant_id,
pool_type=ProviderQuotaType.TRIAL,
pool_type=ModelProviderQuotaType.TRIAL,
quota_limit=10,
quota_used=9,
)
@@ -61,7 +62,7 @@ def test_message_created_trial_credit_accounting_does_not_raise_when_balance_is_
),
),
)
message = SimpleNamespace(message_tokens=2, answer_tokens=1)
message = Message(message_tokens=2, answer_tokens=1)
with (
patch.object(update_provider_when_message_created, "_execute_provider_updates"),
@@ -102,7 +103,7 @@ def test_message_created_paid_credit_accounting_uses_paid_pool() -> None:
),
),
)
message = SimpleNamespace(message_tokens=2, answer_tokens=1)
message = Message(message_tokens=2, answer_tokens=1)
with (
patch.object(update_provider_when_message_created, "_deduct_credit_pool_quota_capped") as mock_deduct,
-3
View File
@@ -28,7 +28,6 @@ project-excludes = [
"configs/test_dify_config.py",
"configs/test_env_consistency.py",
"configs/test_nacos_http_client.py",
"conftest.py",
"controllers/common/test_agent_app_parameters.py",
"controllers/common/test_app_access.py",
"controllers/common/test_errors.py",
@@ -652,7 +651,6 @@ project-excludes = [
"events/event_handlers/test_delete_tool_parameters_cache_when_sync_draft_workflow.py",
"events/test_app_event_signals.py",
"events/test_events_package_compat.py",
"events/test_update_provider_when_message_created.py",
"extensions/logstore/repositories/test_logstore_api_workflow_node_execution_repository.py",
"extensions/logstore/test_sql_escape.py",
"extensions/otel/conftest.py",
@@ -863,7 +861,6 @@ project-excludes = [
"services/test_file_service.py",
"services/test_human_input_delivery_test_service.py",
"services/test_human_input_file_upload_service.py",
"services/test_human_input_service.py",
"services/test_knowledge_retrieval_inner_service.py",
"services/test_knowledge_service.py",
"services/test_message_service.py",
@@ -4,6 +4,7 @@ from datetime import datetime, timedelta
from unittest.mock import MagicMock
import pytest
from pydantic import JsonValue
from pytest_mock import MockerFixture
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session, sessionmaker
@@ -40,12 +41,6 @@ from services.human_input_service import (
)
@pytest.fixture
def unbound_session_factory() -> sessionmaker[Session]:
"""Supply the required constructor dependency without enabling database access."""
return sessionmaker()
def _make_app(mode: AppMode) -> App:
return App(
id="app-id",
@@ -61,7 +56,7 @@ def _make_app(mode: AppMode) -> App:
@pytest.fixture
def sample_form_record():
def sample_form_record() -> HumanInputFormRecord:
return HumanInputFormRecord(
form_id="form-id",
workflow_run_id="workflow-run-id",
@@ -95,7 +90,7 @@ def sample_form_record():
def test_enqueue_resume_dispatches_task_for_workflow(
mocker: MockerFixture,
sqlite_session_factory: sessionmaker[Session],
):
) -> None:
service = HumanInputService(sqlite_session_factory)
workflow_run = MagicMock()
@@ -121,8 +116,10 @@ def test_enqueue_resume_dispatches_task_for_workflow(
def test_ensure_form_active_respects_global_timeout(
monkeypatch, sample_form_record: HumanInputFormRecord, unbound_session_factory
):
monkeypatch: pytest.MonkeyPatch,
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
service = HumanInputService(unbound_session_factory)
expired_record = dataclasses.replace(
sample_form_record,
@@ -138,7 +135,7 @@ def test_ensure_form_active_respects_global_timeout(
def test_enqueue_resume_dispatches_task_for_advanced_chat(
mocker: MockerFixture,
sqlite_session_factory: sessionmaker[Session],
):
) -> None:
service = HumanInputService(sqlite_session_factory)
workflow_run = MagicMock()
@@ -166,7 +163,7 @@ def test_enqueue_resume_dispatches_task_for_advanced_chat(
def test_enqueue_resume_skips_unsupported_app_mode(
mocker: MockerFixture,
sqlite_session_factory: sessionmaker[Session],
):
) -> None:
service = HumanInputService(sqlite_session_factory)
workflow_run = MagicMock()
@@ -190,8 +187,9 @@ def test_enqueue_resume_skips_unsupported_app_mode(
def test_get_form_definition_by_token_for_console_uses_repository(
sample_form_record: HumanInputFormRecord, unbound_session_factory
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
console_record = dataclasses.replace(sample_form_record, recipient_type=RecipientType.CONSOLE)
repo.get_by_token.return_value = console_record
@@ -232,8 +230,10 @@ def _build_resumption_context_state(*, options: list[str], workflow_run_id: str)
def test_resolve_form_inputs_uses_runtime_select_options(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
configured_input = SelectInputConfig(
output_variable_name="decision",
option_source=StringListSource(
@@ -270,8 +270,10 @@ def test_resolve_form_inputs_uses_runtime_select_options(
def test_submit_form_by_token_calls_repository_and_enqueue(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = sample_form_record
repo.mark_submitted.return_value = sample_form_record
@@ -298,8 +300,10 @@ def test_submit_form_by_token_calls_repository_and_enqueue(
def test_submit_form_by_token_enqueues_agent_app_resume_for_conversation_form(
sample_form_record, unbound_session_factory, mocker: MockerFixture
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
# ENG-635: a conversation-owned (Agent v2 chat) form routes to the chat
# resume, not the workflow resume.
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
@@ -327,8 +331,10 @@ def test_submit_form_by_token_enqueues_agent_app_resume_for_conversation_form(
def test_submit_form_by_token_skips_enqueue_for_delivery_test(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
test_record = dataclasses.replace(
sample_form_record,
@@ -351,8 +357,10 @@ def test_submit_form_by_token_skips_enqueue_for_delivery_test(
def test_submit_form_by_token_passes_submission_user_id(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = sample_form_record
repo.mark_submitted.return_value = sample_form_record
@@ -373,7 +381,10 @@ def test_submit_form_by_token_passes_submission_user_id(
enqueue_spy.assert_called_once_with(sample_form_record.workflow_run_id)
def test_submit_form_by_token_invalid_action(sample_form_record: HumanInputFormRecord, unbound_session_factory):
def test_submit_form_by_token_invalid_action(
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = dataclasses.replace(sample_form_record)
service = HumanInputService(unbound_session_factory, form_repository=repo)
@@ -390,7 +401,10 @@ def test_submit_form_by_token_invalid_action(sample_form_record: HumanInputFormR
repo.mark_submitted.assert_not_called()
def test_submit_form_by_token_missing_inputs(sample_form_record: HumanInputFormRecord, unbound_session_factory):
def test_submit_form_by_token_missing_inputs(
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
definition_with_input = FormDefinition(
@@ -465,12 +479,12 @@ def test_submit_form_by_token_missing_inputs(sample_form_record: HumanInputFormR
],
)
def test_validate_human_input_submission_rejects_invalid_select_and_file_payloads(
sample_form_record,
unbound_session_factory,
input_definition,
submitted_value,
expected_message,
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
input_definition: dict[str, JsonValue],
submitted_value: JsonValue,
expected_message: str,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
definition = FormDefinition.model_validate(
{
@@ -489,14 +503,14 @@ def test_validate_human_input_submission_rejects_invalid_select_and_file_payload
recipient_type=RecipientType.STANDALONE_WEB_APP,
form_token="token",
selected_action_id="submit",
form_data={input_definition["output_variable_name"]: submitted_value},
form_data={definition.inputs[0].output_variable_name: submitted_value},
)
assert expected_message in str(exc_info.value)
repo.mark_submitted.assert_not_called()
def test_form_properties(sample_form_record: HumanInputFormRecord):
def test_form_properties(sample_form_record: HumanInputFormRecord) -> None:
form = Form(sample_form_record)
assert form.id == "form-id"
assert form.workflow_run_id == "workflow-run-id"
@@ -510,20 +524,20 @@ def test_form_properties(sample_form_record: HumanInputFormRecord):
assert isinstance(form.expiration_time, datetime)
def test_form_submitted_error_init():
def test_form_submitted_error_init() -> None:
error = FormSubmittedError(form_id="test-form")
assert error.description == "This form has already been submitted by another user, form_id=test-form"
assert error.code == 412
def test_human_input_service_init_with_engine(sqlite_engine: Engine):
def test_human_input_service_init_with_engine(sqlite_engine: Engine) -> None:
service = HumanInputService(session_factory=sqlite_engine)
assert isinstance(service._session_factory, sessionmaker)
assert service._session_factory.kw["bind"] is sqlite_engine
def test_get_form_by_token_none(unbound_session_factory):
def test_get_form_by_token_none(unbound_session_factory: sessionmaker[Session]) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = None
@@ -531,7 +545,10 @@ def test_get_form_by_token_none(unbound_session_factory):
assert service.get_form_by_token("invalid") is None
def test_get_form_definition_by_token_mismatch(sample_form_record: HumanInputFormRecord, unbound_session_factory):
def test_get_form_definition_by_token_mismatch(
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = sample_form_record
@@ -540,7 +557,10 @@ def test_get_form_definition_by_token_mismatch(sample_form_record: HumanInputFor
assert service.get_form_definition_by_token(RecipientType.CONSOLE, "token") is None
def test_get_form_definition_by_token_success(sample_form_record: HumanInputFormRecord, unbound_session_factory):
def test_get_form_definition_by_token_success(
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = sample_form_record
@@ -551,8 +571,9 @@ def test_get_form_definition_by_token_success(sample_form_record: HumanInputForm
def test_get_form_definition_by_token_for_console_mismatch(
sample_form_record: HumanInputFormRecord, unbound_session_factory
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = sample_form_record # is STANDALONE_WEB_APP
@@ -560,7 +581,9 @@ def test_get_form_definition_by_token_for_console_mismatch(
assert service.get_form_definition_by_token_for_console("token") is None
def test_submit_form_by_token_delivery_not_enabled(unbound_session_factory):
def test_submit_form_by_token_delivery_not_enabled(
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = None
@@ -570,8 +593,10 @@ def test_submit_form_by_token_delivery_not_enabled(unbound_session_factory):
def test_submit_form_by_token_no_workflow_run_id(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
):
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
repo.get_by_token.return_value = sample_form_record
@@ -586,7 +611,10 @@ def test_submit_form_by_token_no_workflow_run_id(
enqueue_spy.assert_not_called()
def test_ensure_form_active_errors(sample_form_record: HumanInputFormRecord, unbound_session_factory):
def test_ensure_form_active_errors(
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
service = HumanInputService(unbound_session_factory)
# Submitted
@@ -607,7 +635,10 @@ def test_ensure_form_active_errors(sample_form_record: HumanInputFormRecord, unb
service.ensure_form_active(Form(expired_time_record))
def test_ensure_not_submitted_raises(sample_form_record: HumanInputFormRecord, unbound_session_factory):
def test_ensure_not_submitted_raises(
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
service = HumanInputService(unbound_session_factory)
submitted_record = dataclasses.replace(sample_form_record, submitted_at=naive_utc_now())
@@ -615,7 +646,10 @@ def test_ensure_not_submitted_raises(sample_form_record: HumanInputFormRecord, u
service._ensure_not_submitted(Form(submitted_record))
def test_enqueue_resume_workflow_not_found(mocker: MockerFixture, unbound_session_factory):
def test_enqueue_resume_workflow_not_found(
mocker: MockerFixture,
unbound_session_factory: sessionmaker[Session],
) -> None:
service = HumanInputService(unbound_session_factory)
workflow_run_repo = MagicMock()
@@ -631,10 +665,10 @@ def test_enqueue_resume_workflow_not_found(mocker: MockerFixture, unbound_sessio
def test_enqueue_resume_app_not_found(
mocker,
mocker: MockerFixture,
sqlite_session_factory: sessionmaker[Session],
caplog: pytest.LogCaptureFixture,
):
) -> None:
service = HumanInputService(sqlite_session_factory)
workflow_run = MagicMock()
@@ -660,8 +694,10 @@ def test_enqueue_resume_app_not_found(
def test_is_globally_expired_zero_timeout(
monkeypatch: pytest.MonkeyPatch, sample_form_record: HumanInputFormRecord, unbound_session_factory
):
monkeypatch: pytest.MonkeyPatch,
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
service = HumanInputService(unbound_session_factory)
monkeypatch.setattr(human_input_service_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 0)
@@ -669,7 +705,9 @@ def test_is_globally_expired_zero_timeout(
def test_submit_form_by_token_normalizes_select_and_files(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
definition = FormDefinition(
@@ -751,7 +789,8 @@ def test_submit_form_by_token_normalizes_select_and_files(
def test_submit_form_by_token_invalid_select_value(
sample_form_record: HumanInputFormRecord, unbound_session_factory
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
definition = FormDefinition(
@@ -779,7 +818,8 @@ def test_submit_form_by_token_invalid_select_value(
def test_submit_form_by_token_invalid_file_list_item(
sample_form_record: HumanInputFormRecord, unbound_session_factory
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
definition = FormDefinition(
@@ -805,7 +845,9 @@ def test_submit_form_by_token_invalid_file_list_item(
def test_submit_form_by_token_rejects_cross_tenant_file(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
definition = FormDefinition(
@@ -837,7 +879,9 @@ def test_submit_form_by_token_rejects_cross_tenant_file(
def test_submit_form_by_token_rejects_cross_tenant_file_list(
sample_form_record: HumanInputFormRecord, unbound_session_factory, mocker: MockerFixture
sample_form_record: HumanInputFormRecord,
unbound_session_factory: sessionmaker[Session],
mocker: MockerFixture,
) -> None:
repo = MagicMock(spec=HumanInputFormSubmissionRepository)
definition = FormDefinition(
@@ -5,6 +5,7 @@ from threading import Barrier
import pytest
from sqlalchemy import create_engine, inspect, text
from sqlalchemy.engine import URL, Engine
from sqlalchemy.exc import UnboundExecutionError
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.pool import QueuePool
@@ -58,6 +59,25 @@ def test_core_session_factory_uses_the_shared_sqlite_session_factory(
assert session.scalar(text("SELECT value FROM global_factory_probe")) == 42
def test_unbound_session_factory_disables_explicit_and_global_database_access(
unbound_session_factory: sessionmaker[Session],
) -> None:
assert session_factory_module.session_factory.get_session_maker() is unbound_session_factory
with unbound_session_factory() as session:
with pytest.raises(UnboundExecutionError):
session.get_bind()
with session_factory_module.session_factory.create_session() as session:
with pytest.raises(UnboundExecutionError):
session.execute(text("SELECT 1"))
def test_unbound_session_rejects_database_access(unbound_session: Session) -> None:
with pytest.raises(UnboundExecutionError):
unbound_session.scalar(text("SELECT 1"))
def test_sqlite_session_factory_shares_one_database_across_worker_sessions(
sqlite_session_factory: sessionmaker[Session],
) -> None:
+2
View File
@@ -40,6 +40,7 @@ RUN apt-get update \
openssh-client \
procps \
ripgrep \
tini \
tmux \
unzip \
xz-utils \
@@ -79,4 +80,5 @@ WORKDIR /home/dify
EXPOSE 5004
ENTRYPOINT ["/usr/bin/tini", "-g", "--"]
CMD ["shellctl", "serve", "--listen", "0.0.0.0:5004"]
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env bash
set -euo pipefail
readonly DEFAULT_TEMPLATE_NAME='dify-agent-local-sandbox'
readonly DEFAULT_IMAGE_REPOSITORY='langgenius/dify-agent-local-sandbox'
readonly DEFAULT_PLATFORM='linux/amd64'
readonly DEFAULT_E2B_CLI_VERSION='2.13.3'
readonly DEFAULT_WAIT_SECONDS='600'
readonly DEFAULT_POLL_SECONDS='10'
readonly DEFAULT_CPU_COUNT='2'
readonly DEFAULT_MEMORY_MB='1024'
readonly START_COMMAND='/usr/bin/env SHELLCTL_ENABLE_PATH_ISOLATION=true /usr/local/bin/shellctl serve --listen 0.0.0.0:5004'
readonly READY_COMMAND='curl -fsS http://localhost:5004/healthz'
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
usage() {
cat <<EOF
Usage: $(basename "$0") [options]
Synchronize an E2B Template with the published Dify agent runtime image for a
Git commit. The image is resolved to an immutable platform-specific digest and
its OCI revision label must match the source commit before E2B is updated.
Options:
--source-ref REF Git ref whose commit should be synchronized (default: HEAD)
--image-repository IMAGE Published image repository (default: ${DEFAULT_IMAGE_REPOSITORY})
--image-tag TAG Published image tag (default: full source commit SHA)
--template-name NAME E2B Template name (default: ${DEFAULT_TEMPLATE_NAME})
--platform OS/ARCH Image platform consumed by E2B (default: ${DEFAULT_PLATFORM})
--wait-seconds SECONDS Maximum time to wait for the image tag (default: ${DEFAULT_WAIT_SECONDS})
--poll-seconds SECONDS Delay between registry checks (default: ${DEFAULT_POLL_SECONDS})
--cpu-count COUNT Template vCPU count (default: ${DEFAULT_CPU_COUNT})
--memory-mb MIB Template memory in MiB (default: ${DEFAULT_MEMORY_MB})
--no-cache Disable E2B build cache
--dry-run Validate and print the build without changing E2B
-h, --help Show this help
Environment:
E2B_API_KEY Required unless --dry-run is used
E2B_CLI_VERSION E2B CLI version (default: ${DEFAULT_E2B_CLI_VERSION})
E2B_TEMPLATE_NAME Default value for --template-name
E2B_BASE_IMAGE_REPOSITORY Default value for --image-repository
EOF
}
die() {
echo "Error: $*" >&2
exit 1
}
require_command() {
command -v "$1" >/dev/null 2>&1 || die "required command not found: $1"
}
require_non_negative_integer() {
local name="$1"
local value="$2"
[[ "${value}" =~ ^[0-9]+$ ]] || die "${name} must be a non-negative integer: ${value}"
}
require_positive_integer() {
local name="$1"
local value="$2"
require_non_negative_integer "${name}" "${value}"
(( value > 0 )) || die "${name} must be greater than zero"
}
print_command() {
printf 'Command:'
printf ' %q' "$@"
printf '\n'
}
source_ref='HEAD'
image_repository="${E2B_BASE_IMAGE_REPOSITORY:-${DEFAULT_IMAGE_REPOSITORY}}"
image_tag=''
template_name="${E2B_TEMPLATE_NAME:-${DEFAULT_TEMPLATE_NAME}}"
platform="${DEFAULT_PLATFORM}"
e2b_cli_version="${E2B_CLI_VERSION:-${DEFAULT_E2B_CLI_VERSION}}"
wait_seconds="${DEFAULT_WAIT_SECONDS}"
poll_seconds="${DEFAULT_POLL_SECONDS}"
cpu_count="${DEFAULT_CPU_COUNT}"
memory_mb="${DEFAULT_MEMORY_MB}"
dry_run=false
no_cache=false
while (( $# > 0 )); do
case "$1" in
--source-ref)
(( $# >= 2 )) || die '--source-ref requires a value'
source_ref="$2"
shift 2
;;
--image-repository)
(( $# >= 2 )) || die '--image-repository requires a value'
image_repository="$2"
shift 2
;;
--image-tag)
(( $# >= 2 )) || die '--image-tag requires a value'
image_tag="$2"
shift 2
;;
--template-name)
(( $# >= 2 )) || die '--template-name requires a value'
template_name="$2"
shift 2
;;
--platform)
(( $# >= 2 )) || die '--platform requires a value'
platform="$2"
shift 2
;;
--wait-seconds)
(( $# >= 2 )) || die '--wait-seconds requires a value'
wait_seconds="$2"
shift 2
;;
--poll-seconds)
(( $# >= 2 )) || die '--poll-seconds requires a value'
poll_seconds="$2"
shift 2
;;
--cpu-count)
(( $# >= 2 )) || die '--cpu-count requires a value'
cpu_count="$2"
shift 2
;;
--memory-mb)
(( $# >= 2 )) || die '--memory-mb requires a value'
memory_mb="$2"
shift 2
;;
--no-cache)
no_cache=true
shift
;;
--dry-run)
dry_run=true
shift
;;
-h|--help)
usage
exit 0
;;
*)
die "unknown option: $1"
;;
esac
done
[[ -n "${image_repository}" ]] || die 'image repository cannot be empty'
[[ -n "${template_name}" ]] || die 'template name cannot be empty'
[[ "${platform}" == */* ]] || die "platform must use OS/ARCH form: ${platform}"
require_non_negative_integer 'wait-seconds' "${wait_seconds}"
require_positive_integer 'poll-seconds' "${poll_seconds}"
require_positive_integer 'cpu-count' "${cpu_count}"
require_positive_integer 'memory-mb' "${memory_mb}"
require_command git
require_command docker
require_command jq
require_command mktemp
source_sha="$(git -C "${SCRIPT_DIR}" rev-parse --verify "${source_ref}^{commit}" 2>/dev/null)" \
|| die "cannot resolve source ref: ${source_ref}"
[[ -n "${image_tag}" ]] || image_tag="${source_sha}"
image_ref="${image_repository}:${image_tag}"
platform_os="${platform%%/*}"
platform_arch="${platform#*/}"
deadline=$((SECONDS + wait_seconds))
manifest_json=''
inspect_error=''
while true; do
if manifest_json="$(docker buildx imagetools inspect --format '{{json .Manifest}}' "${image_ref}" 2>&1)"; then
break
fi
inspect_error="${manifest_json}"
manifest_json=''
(( SECONDS < deadline )) || die "image is not available: ${image_ref}${inspect_error:+ (${inspect_error})}"
echo "Waiting for published image ${image_ref}..." >&2
sleep "${poll_seconds}"
done
platform_digest="$(
jq -r \
--arg os "${platform_os}" \
--arg arch "${platform_arch}" \
'[.manifests[]? | select(.platform.os == $os and .platform.architecture == $arch) | .digest][0] // empty' \
<<<"${manifest_json}"
)"
[[ "${platform_digest}" == sha256:* ]] \
|| die "image ${image_ref} does not contain platform ${platform}"
resolved_image="${image_repository}@${platform_digest}"
image_json="$(docker buildx imagetools inspect --format '{{json .Image}}' "${resolved_image}")" \
|| die "cannot inspect resolved image: ${resolved_image}"
actual_os="$(jq -r '.os // empty' <<<"${image_json}")"
actual_arch="$(jq -r '.architecture // empty' <<<"${image_json}")"
actual_revision="$(jq -r '.config.Labels["org.opencontainers.image.revision"] // empty' <<<"${image_json}")"
[[ "${actual_os}/${actual_arch}" == "${platform}" ]] \
|| die "resolved image platform ${actual_os}/${actual_arch} does not match ${platform}"
[[ "${actual_revision}" == "${source_sha}" ]] \
|| die "image revision ${actual_revision:-<missing>} does not match source commit ${source_sha}"
tmp_dir="$(mktemp -d)"
cleanup() {
rm -rf "${tmp_dir}"
}
trap cleanup EXIT
dockerfile="${tmp_dir}/e2b.Dockerfile"
printf 'FROM %s\nUSER dify\nWORKDIR /home/dify\n' "${resolved_image}" > "${dockerfile}"
e2b_command=(
npx --yes "@e2b/cli@${e2b_cli_version}"
template create "${template_name}"
--path "${tmp_dir}"
--dockerfile e2b.Dockerfile
--cmd "${START_COMMAND}"
--ready-cmd "${READY_COMMAND}"
--cpu-count "${cpu_count}"
--memory-mb "${memory_mb}"
)
if [[ "${no_cache}" == true ]]; then
e2b_command+=(--no-cache)
fi
echo "Source commit: ${source_sha}"
echo "Published image: ${image_ref}"
echo "Resolved image: ${resolved_image} (${platform})"
echo "E2B Template: ${template_name}"
print_command "${e2b_command[@]}"
if [[ "${dry_run}" == true ]]; then
echo 'Dry run; E2B Template was not changed.'
exit 0
fi
require_command npx
[[ -n "${E2B_API_KEY:-}" ]] || die 'E2B_API_KEY is required'
"${e2b_command[@]}"
echo "E2B Template synchronized: ${template_name} <- ${resolved_image}"
+2
View File
@@ -22,6 +22,8 @@ E2E_MODEL_PROVIDER_CREDENTIALS_JSON='{"openai_api_key":"replace-with-real-key"}'
# from @external-model because other external-model scenarios may not use dify-agent.
# When enabled, the E2E runner also starts the shellctl local sandbox required by
# dify-agent's dify.shell/config runtime layer.
# Use E2E_AGENT_BACKEND_URL only for an already-running backend; do not set it
# together with E2E_START_AGENT_BACKEND.
# E2E_START_AGENT_BACKEND=1
# E2E_AGENT_BACKEND_PORT=5050
# E2E_AGENT_BACKEND_URL=http://127.0.0.1:5050
+8 -3
View File
@@ -8,9 +8,11 @@ Run commands from the repository root. Install dependencies and browsers once wi
- Existing initialized instance: `pnpm -C e2e e2e`
- Reset, initialize, and run deterministic scenarios: `pnpm -C e2e e2e:full`
- Prepare and run scenarios backed by shared fixtures: `E2E_START_AGENT_BACKEND=1 pnpm -C e2e e2e:prepared`
- Tagged subset: `pnpm -C e2e e2e -- --tags @smoke`
- Headed debugging: `pnpm -C e2e e2e:headed -- --tags @smoke`
- External runtime preparation and run: `pnpm -C e2e e2e:external:prepare`, then `pnpm -C e2e e2e:external`
- Prepare and run external runtime scenarios: `E2E_START_AGENT_BACKEND=1 pnpm -C e2e e2e:external`
- Seed against existing middleware without running Cucumber: `pnpm -C e2e seed -- --profile <prepared|external-runtime|post-merge>`
- Reset persisted E2E state: `pnpm -C e2e e2e:reset`
- Middleware lifecycle: `pnpm -C e2e e2e:middleware:up` and `pnpm -C e2e e2e:middleware:down`
- Scoped static checks: `vp check e2e`
@@ -20,7 +22,8 @@ The runner reuses `web/.next/BUILD_ID` when present. Set `E2E_FORCE_WEB_BUILD=1`
## Runtime Ownership
- `scripts/setup.ts` owns reset, middleware, backend, and frontend startup.
- `scripts/run-cucumber.ts` owns E2E orchestration and Cucumber invocation.
- `scripts/run-cucumber.ts` is the only E2E runtime orchestrator. It owns service lifetime, optional seed execution, Cucumber invocation, and teardown.
- `scripts/seed-runner.ts` owns fixture creation and verification against an already-running runtime; it never starts services.
- `support/web-server.ts` owns frontend reuse, readiness, and shutdown.
- `features/support/hooks.ts` owns shared auth bootstrap, scenario lifecycle, and diagnostics.
- `features/support/world.ts` owns `DifyWorld`, the per-scenario behavior `BrowserContext`, and its authenticated setup and cleanup client. Browser and API identities remain separate so unauthenticated and logout journeys cannot invalidate fixture ownership.
@@ -33,12 +36,14 @@ An uninitialized instance is installed and authenticated lazily; an initialized
## Tags And External Runtime
- Default scenarios use shared authenticated storage state. `@unauthenticated` creates a clean context; `@authenticated` is an intent and selection tag only.
- `@prepared` requires the strict post-merge seed profile.
- `@prepared` requires the prepared fixtures; the post-merge seed profile includes them.
- `@external-model` and `@external-tool` identify scenarios that call real external runtimes. Deterministic commands exclude these tags; external commands are opt-in.
- `@microphone` uses the checked-in fake audio fixture and an isolated Chromium context.
- `@browser-smoke` runs focused keyboard and navigation coverage in Chromium and WebKit CI lanes.
- Feature-owned services use their own tags. Agent v2 runtime scenarios use `@agent-backend-runtime` and require the explicit runtime-availability step. Set `E2E_START_AGENT_BACKEND=1` to start it locally, or provide `E2E_AGENT_BACKEND_URL` / `AGENT_BACKEND_BASE_URL`.
Seed and Cucumber must share one runtime lifecycle. Combined commands own reset, middleware, services, seed, Cucumber, and teardown; CI must not reproduce that lifecycle in workflow YAML. `E2E_START_AGENT_BACKEND=1` starts a managed local backend before the API; it is mutually exclusive with an explicit Agent backend URL.
Do not overload runtime tags to imply unrelated services or silently skip behavior when a required fixture is missing.
## Browser, API, And Contract Boundaries
+3 -4
View File
@@ -48,16 +48,15 @@ Use `the Agent v2 configuration should be saved automatically` for Configure aut
## Seed and fixture contract
Seed scripts create or update environment-owned models, plugins, datasets, Agents, and workflows. `fixtures.steps.ts` resolves and validates those resources before a dependent behavior runs. Missing, inactive, unindexed, or drifted fixtures must throw and fail the scenario; never return `skipped`.
Seed tasks create or update environment-owned models, plugins, datasets, Agents, and workflows. `fixtures.steps.ts` resolves and validates those resources before a dependent behavior runs. Missing, inactive, unindexed, or drifted fixtures must throw and fail the scenario; never return `skipped`.
`@prepared` scenarios are excluded from deterministic PR core. Post-merge runs:
```bash
pnpm -C e2e e2e:post-merge:prepare
pnpm -C e2e e2e:post-merge
E2E_START_AGENT_BACKEND=1 pnpm -C e2e e2e:post-merge
```
The strict seed must finish without blocked tasks. The concrete resource inventory and defaults belong to the seed profile and environment configuration rather than this guidance.
The command owns runtime setup, strict seed, Cucumber, and teardown. The strict seed must finish without blocked tasks. The concrete resource inventory and defaults belong to the seed profile and environment configuration rather than this guidance.
Organize fixture helpers by the product resource or infrastructure capability they own, not by the feature file that happens to consume them. Keep runtime readiness adapters separate from Console resource fixtures, and keep all fixture state in the current `SeedContext` or scenario `DifyWorld` rather than module globals.
@@ -247,11 +247,12 @@ Then('I should see the Agent v2 tool state fixture tools', async function (this:
const toolsSection = page.getByRole('region', { name: 'Tools' })
await expect(toolsSection).toBeVisible({ timeout: 30_000 })
await expect(
toolsSection.getByRole('button', { exact: true, name: 'Not authorized' }),
).toHaveCount(2)
const { action: jsonReplaceAction, tool: jsonTool } = await expectProviderToolActionVisible(
const {
action: jsonReplaceAction,
provider: jsonProvider,
tool: jsonTool,
} = await expectProviderToolActionVisible(
toolsSection,
agentBuilderPreseededResources.jsonReplaceTool,
)
@@ -269,10 +270,16 @@ Then('I should see the Agent v2 tool state fixture tools', async function (this:
}),
).toBeVisible()
await expectProviderToolActionVisible(
const { provider: tavilyProvider } = await expectProviderToolActionVisible(
toolsSection,
agentBuilderPreseededResources.tavilySearchTool,
)
await expect(
tavilyProvider.locator('..').getByRole('button', { exact: true, name: 'Not authorized' }),
).toBeVisible()
await expect(
jsonProvider.locator('..').getByRole('button', { exact: true, name: 'Not authorized' }),
).toHaveCount(0)
})
Then('I should see the Agent v2 dual retrieval fixture settings', async function (this: DifyWorld) {
@@ -276,7 +276,7 @@ export const expectProviderToolActionVisible = async (
const action = toolsSection.getByText(tool.actionName, { exact: true })
await expect(action).toBeVisible()
return { action, tool }
return { action, provider, tool }
}
export const openAgentKnowledgeRetrievalDialog = async (
+5 -3
View File
@@ -5,7 +5,7 @@
"scripts": {
"e2e": "tsx ./scripts/run-cucumber.ts",
"e2e:external": "tsx ./scripts/run-external-runtime.ts",
"e2e:external:prepare": "tsx ./scripts/prepare-external-runtime.ts",
"e2e:external:prepare": "tsx ./scripts/run-cucumber.ts --seed-only --profile external-runtime",
"e2e:full": "tsx ./scripts/run-cucumber.ts --full",
"e2e:full:headed": "tsx ./scripts/run-cucumber.ts --full --headed",
"e2e:headed": "tsx ./scripts/run-cucumber.ts --headed",
@@ -13,9 +13,11 @@
"e2e:middleware:down": "tsx ./scripts/setup.ts middleware-down",
"e2e:middleware:up": "tsx ./scripts/setup.ts middleware-up",
"e2e:post-merge": "tsx ./scripts/run-post-merge.ts",
"e2e:post-merge:prepare": "tsx ./scripts/seed.ts --pack agent-v2 --profile post-merge",
"e2e:post-merge:prepare": "tsx ./scripts/run-cucumber.ts --seed-only --profile post-merge",
"e2e:prepared": "tsx ./scripts/run-prepared.ts",
"e2e:prepared:prepare": "tsx ./scripts/run-cucumber.ts --seed-only --profile prepared",
"e2e:reset": "tsx ./scripts/setup.ts reset",
"seed": "tsx ./scripts/seed.ts",
"seed": "tsx ./scripts/run-cucumber.ts --seed-only",
"test:unit": "vitest run",
"type-check": "tsc"
},
-17
View File
@@ -1,17 +0,0 @@
import { e2eDir, isMainModule, runCommandOrThrow } from './common'
import './env-register'
const main = async () => {
await runCommandOrThrow({
command: 'npx',
args: ['tsx', './scripts/seed.ts', '--pack', 'agent-v2', '--profile', 'external-runtime'],
cwd: e2eDir,
})
}
if (isMainModule(import.meta.url)) {
void main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error))
process.exit(1)
})
}
+125 -173
View File
@@ -7,56 +7,16 @@ import { startLoggedProcess, stopManagedProcess, waitForUrl } from '../support/p
import { startWebServer, stopWebServer } from '../support/web-server'
import { apiURL, baseURL, reuseExistingWebServer } from '../test-env'
import { e2eDir, isMainModule, runCommand } from './common'
import { parseRunOptions, shouldStartManagedAgentBackend } from './run-options'
import { runSeed } from './seed-runner'
import { resetState, startMiddleware, stopMiddleware } from './setup'
import './env-register'
type RunOptions = {
forwardArgs: string[]
full: boolean
headed: boolean
}
const parseArgs = (argv: string[]): RunOptions => {
let full = false
let headed = false
const forwardArgs: string[] = []
for (const [index, arg] of argv.entries()) {
if (arg === '--') {
forwardArgs.push(...argv.slice(index + 1))
return { forwardArgs, full, headed }
}
if (arg === '--full') {
full = true
continue
}
if (arg === '--headed') {
headed = true
continue
}
forwardArgs.push(arg)
}
return { forwardArgs, full, headed }
}
const hasCustomTags = (forwardArgs: string[]) =>
forwardArgs.some((arg) => arg === '--tags' || arg.startsWith('--tags='))
const fullNonExternalTags = 'not @prepared and not @external-model and not @external-tool'
const isTruthyEnv = (value: string | undefined) => value === '1' || value === 'true'
const shouldStartAgentBackend = () => {
if (isTruthyEnv(process.env.E2E_START_AGENT_BACKEND)) return true
if (process.env.E2E_AGENT_BACKEND_URL || process.env.AGENT_BACKEND_BASE_URL) return false
return false
}
const seedCeleryQueues = 'dataset,priority_dataset,workflow_based_app_execution'
const readLogTail = async (logFilePath: string) => {
const content = await readFile(logFilePath, 'utf8').catch(() => '')
@@ -87,65 +47,41 @@ const waitForUnexpectedProcessExit = async (
throw new Error(`${label} exited before becoming ready. See ${logFilePath}.${logTailMessage}`)
}
const waitForManagedProcess = async ({
errorMessage,
managedProcess,
url,
}: {
errorMessage: string
managedProcess: ManagedProcess
url: string
}) => {
let waiting = true
try {
await Promise.race([
waitForUrl(url, 180_000, 1_000),
waitForUnexpectedProcessExit(managedProcess, () => !waiting),
])
} catch (error) {
if (error instanceof Error && error.message.includes('exited before becoming ready'))
throw error
throw new Error(`${errorMessage} See ${managedProcess.logFilePath}.`)
} finally {
waiting = false
}
}
const main = async () => {
const { forwardArgs, full, headed } = parseArgs(process.argv.slice(2))
const startMiddlewareForRun = full
const resetStateForRun = full
const startAgentBackendForRun = shouldStartAgentBackend()
if (resetStateForRun) await resetState()
if (startMiddlewareForRun) await startMiddleware()
const { forwardArgs, full, headed, seed, seedOnly } = parseRunOptions(process.argv.slice(2))
const startAgentBackendForRun = shouldStartManagedAgentBackend()
const cucumberReportDir = path.join(e2eDir, 'cucumber-report')
const logDir = path.join(e2eDir, '.logs')
await rm(cucumberReportDir, { force: true, recursive: true })
await mkdir(logDir, { recursive: true })
const shellctlProcess = startAgentBackendForRun
? await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'shellctl-sandbox'],
cwd: e2eDir,
label: 'shellctl sandbox',
logFilePath: path.join(logDir, 'cucumber-shellctl-sandbox.log'),
})
: undefined
const difyAgentProcess = startAgentBackendForRun
? await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'agent-backend'],
cwd: e2eDir,
env: {
E2E_START_AGENT_BACKEND: '1',
},
label: 'agent backend',
logFilePath: path.join(logDir, 'cucumber-agent-backend.log'),
})
: undefined
const apiProcess = await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'api'],
cwd: e2eDir,
env: startAgentBackendForRun
? {
E2E_START_AGENT_BACKEND: '1',
}
: undefined,
label: 'api server',
logFilePath: path.join(logDir, 'cucumber-api.log'),
})
const celeryProcess = await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'celery'],
cwd: e2eDir,
label: 'celery worker',
logFilePath: path.join(logDir, 'cucumber-celery.log'),
})
let apiProcess: ManagedProcess | undefined
let celeryProcess: ManagedProcess | undefined
let difyAgentProcess: ManagedProcess | undefined
let middlewareStarted = false
let shellctlProcess: ManagedProcess | undefined
let cleanupPromise: Promise<void> | undefined
const cleanup = async () => {
@@ -157,7 +93,7 @@ const main = async () => {
{ label: 'Stop API server', run: () => stopManagedProcess(apiProcess) },
{ label: 'Stop agent backend', run: () => stopManagedProcess(difyAgentProcess) },
{ label: 'Stop shellctl sandbox', run: () => stopManagedProcess(shellctlProcess) },
...(startMiddlewareForRun ? [{ label: 'Stop middleware', run: stopMiddleware }] : []),
...(middlewareStarted ? [{ label: 'Stop middleware', run: stopMiddleware }] : []),
])
if (cleanupErrors.length > 0)
@@ -182,60 +118,73 @@ const main = async () => {
process.once('SIGTERM', onTerminate)
try {
if (shellctlProcess) {
let waitingForShellctl = true
try {
const shellctlPort = process.env.E2E_SHELLCTL_PORT || '5004'
await Promise.race([
waitForUrl(`http://127.0.0.1:${shellctlPort}/healthz`, 180_000, 1_000),
waitForUnexpectedProcessExit(shellctlProcess, () => !waitingForShellctl),
])
} catch (error) {
if (error instanceof Error && error.message.includes('exited before becoming ready'))
throw error
if (full) await resetState()
throw new Error(
`Shellctl sandbox did not become ready. See ${shellctlProcess.logFilePath}.`,
)
} finally {
waitingForShellctl = false
}
if (full) {
middlewareStarted = true
await startMiddleware()
}
if (difyAgentProcess) {
let waitingForAgentBackend = true
try {
const agentBackendPort = process.env.E2E_AGENT_BACKEND_PORT || '5050'
await Promise.race([
waitForUrl(`http://127.0.0.1:${agentBackendPort}/openapi.json`, 180_000, 1_000),
waitForUnexpectedProcessExit(difyAgentProcess, () => !waitingForAgentBackend),
])
} catch (error) {
if (error instanceof Error && error.message.includes('exited before becoming ready'))
throw error
if (!seedOnly) await rm(cucumberReportDir, { force: true, recursive: true })
await mkdir(logDir, { recursive: true })
throw new Error(`Agent backend did not become ready. See ${difyAgentProcess.logFilePath}.`)
} finally {
waitingForAgentBackend = false
}
if (startAgentBackendForRun) {
shellctlProcess = await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'shellctl-sandbox'],
cwd: e2eDir,
label: 'shellctl sandbox',
logFilePath: path.join(logDir, 'cucumber-shellctl-sandbox.log'),
})
const shellctlPort = process.env.E2E_SHELLCTL_PORT || '5004'
await waitForManagedProcess({
errorMessage: 'Shellctl sandbox did not become ready.',
managedProcess: shellctlProcess,
url: `http://127.0.0.1:${shellctlPort}/healthz`,
})
difyAgentProcess = await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'agent-backend'],
cwd: e2eDir,
env: { E2E_START_AGENT_BACKEND: '1' },
label: 'agent backend',
logFilePath: path.join(logDir, 'cucumber-agent-backend.log'),
})
const agentBackendPort = process.env.E2E_AGENT_BACKEND_PORT || '5050'
await waitForManagedProcess({
errorMessage: 'Agent backend did not become ready.',
managedProcess: difyAgentProcess,
url: `http://127.0.0.1:${agentBackendPort}/openapi.json`,
})
}
let waitingForApi = true
try {
await Promise.race([
waitForUrl(`${apiURL}/health`, 180_000, 1_000),
waitForUnexpectedProcessExit(apiProcess, () => !waitingForApi),
])
} catch (error) {
if (error instanceof Error && error.message.includes('exited before becoming ready'))
throw error
apiProcess = await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'api'],
cwd: e2eDir,
env: startAgentBackendForRun ? { E2E_START_AGENT_BACKEND: '1' } : undefined,
label: 'api server',
logFilePath: path.join(logDir, 'cucumber-api.log'),
})
await waitForManagedProcess({
errorMessage: `API did not become ready at ${apiURL}/health.`,
managedProcess: apiProcess,
url: `${apiURL}/health`,
})
throw new Error(
`API did not become ready at ${apiURL}/health. See ${apiProcess.logFilePath}.`,
)
} finally {
waitingForApi = false
}
celeryProcess = await startLoggedProcess({
command: 'npx',
args: [
'tsx',
'./scripts/setup.ts',
'celery',
...(seed ? ['--queues', seedCeleryQueues] : []),
],
cwd: e2eDir,
label: 'celery worker',
logFilePath: path.join(logDir, 'cucumber-celery.log'),
})
await startWebServer({
baseURL,
@@ -247,33 +196,36 @@ const main = async () => {
timeoutMs: 300_000,
})
const cucumberEnv: NodeJS.ProcessEnv = {
...process.env,
CUCUMBER_HEADLESS: headed ? '0' : '1',
if (seed) await runSeed(seed)
if (!seedOnly) {
const cucumberEnv: NodeJS.ProcessEnv = {
...process.env,
CUCUMBER_HEADLESS: headed ? '0' : '1',
}
if (full && !hasCustomTags(forwardArgs)) cucumberEnv.E2E_CUCUMBER_TAGS = fullNonExternalTags
const result = await runCommand({
command: 'npx',
args: [
'tsx',
'./node_modules/@cucumber/cucumber/bin/cucumber.js',
'--config',
'./cucumber.config.ts',
...forwardArgs,
],
cwd: e2eDir,
env: cucumberEnv,
})
if (result.exitCode === 0) {
const messages = await readFile(path.join(cucumberReportDir, 'report.ndjson'), 'utf8')
assertCucumberScenariosStarted(messages)
}
process.exitCode = result.exitCode
}
if (startMiddlewareForRun && !hasCustomTags(forwardArgs))
cucumberEnv.E2E_CUCUMBER_TAGS = fullNonExternalTags
const result = await runCommand({
command: 'npx',
args: [
'tsx',
'./node_modules/@cucumber/cucumber/bin/cucumber.js',
'--config',
'./cucumber.config.ts',
...forwardArgs,
],
cwd: e2eDir,
env: cucumberEnv,
})
if (result.exitCode === 0) {
const messages = await readFile(path.join(cucumberReportDir, 'report.ndjson'), 'utf8')
assertCucumberScenariosStarted(messages)
}
process.exitCode = result.exitCode
} finally {
process.off('SIGINT', onTerminate)
process.off('SIGTERM', onTerminate)
+10 -1
View File
@@ -6,7 +6,16 @@ const defaultExternalRuntimeTags = '@external-model or @external-tool'
const main = async () => {
await runForegroundProcess({
command: 'npx',
args: ['tsx', './scripts/run-cucumber.ts', '--', '--tags', defaultExternalRuntimeTags],
args: [
'tsx',
'./scripts/run-cucumber.ts',
'--full',
'--profile',
'external-runtime',
'--',
'--tags',
defaultExternalRuntimeTags,
],
cwd: e2eDir,
})
}
+122
View File
@@ -0,0 +1,122 @@
import type { SeedOptions } from './seed-runner'
export type RunOptions = {
forwardArgs: string[]
full: boolean
headed: boolean
seed?: SeedOptions
seedOnly: boolean
}
const readOptionValue = (argv: string[], index: number, option: string) => {
const value = argv[index + 1]
if (!value || value.startsWith('--')) throw new Error(`${option} requires a value.`)
return value
}
export const parseRunOptions = (argv: string[]): RunOptions => {
let allowBlocked = false
let dryRun = false
let full = false
let headed = false
let pack = 'agent-v2'
let profile: string | undefined
let seedOnly = false
const forwardArgs: string[] = []
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index]!
if (arg === '--') {
forwardArgs.push(...argv.slice(index + 1))
break
}
if (arg === '--full') {
full = true
continue
}
if (arg === '--headed') {
headed = true
continue
}
if (arg === '--seed-only') {
seedOnly = true
continue
}
if (arg === '--allow-blocked') {
allowBlocked = true
continue
}
if (arg === '--dry-run') {
dryRun = true
continue
}
if (arg === '--pack') {
pack = readOptionValue(argv, index, '--pack')
index += 1
continue
}
if (arg.startsWith('--pack=')) {
pack = arg.slice('--pack='.length)
if (!pack) throw new Error('--pack requires a value.')
continue
}
if (arg === '--profile') {
profile = readOptionValue(argv, index, '--profile')
index += 1
continue
}
if (arg.startsWith('--profile=')) {
profile = arg.slice('--profile='.length)
if (!profile) throw new Error('--profile requires a value.')
continue
}
forwardArgs.push(arg)
}
const shouldSeed = seedOnly || profile !== undefined
if (!shouldSeed && (allowBlocked || dryRun || pack !== 'agent-v2'))
throw new Error('Seed options require --seed-only or --profile.')
if (dryRun && !seedOnly) throw new Error('--dry-run requires --seed-only.')
return {
forwardArgs,
full,
headed,
seed: shouldSeed
? {
allowBlocked,
dryRun,
pack,
profile: profile ?? 'post-merge',
}
: undefined,
seedOnly,
}
}
const isTruthyEnv = (value: string | undefined) => value === '1' || value === 'true'
export const shouldStartManagedAgentBackend = (env: NodeJS.ProcessEnv = process.env) => {
const shouldStart = isTruthyEnv(env.E2E_START_AGENT_BACKEND)
const externalUrl = env.E2E_AGENT_BACKEND_URL?.trim() || env.AGENT_BACKEND_BASE_URL?.trim()
if (shouldStart && externalUrl) {
throw new Error(
'E2E_START_AGENT_BACKEND cannot be enabled when E2E_AGENT_BACKEND_URL or AGENT_BACKEND_BASE_URL is set.',
)
}
return shouldStart
}
+10 -1
View File
@@ -6,7 +6,16 @@ const postMergeTags = '@prepared or @external-model or @external-tool'
const main = async () => {
await runForegroundProcess({
command: 'npx',
args: ['tsx', './scripts/run-cucumber.ts', '--', '--tags', postMergeTags],
args: [
'tsx',
'./scripts/run-cucumber.ts',
'--full',
'--profile',
'post-merge',
'--',
'--tags',
postMergeTags,
],
cwd: e2eDir,
})
}
+23
View File
@@ -0,0 +1,23 @@
import { e2eDir, isMainModule, runForegroundProcess } from './common'
import './env-register'
const preparedTags = '@prepared'
const main = async () => {
await runForegroundProcess({
command: 'npx',
args: [
'tsx',
'./scripts/run-cucumber.ts',
'--full',
'--profile',
'prepared',
'--',
'--tags',
preparedTags,
],
cwd: e2eDir,
})
}
if (isMainModule(import.meta.url)) void main()
+54
View File
@@ -0,0 +1,54 @@
import { chromium } from '@playwright/test'
import { createAgentV2SeedTasks } from '../features/agent-v2/support/seed'
import { ensureAuthenticatedState } from '../fixtures/auth'
import { createStandaloneConsoleSession } from '../support/api/console-session'
import { runSeedTasks, writeSeedReport } from '../support/seed'
import { baseURL } from '../test-env'
export type SeedOptions = {
allowBlocked: boolean
dryRun: boolean
pack: string
profile: string
}
const getTasks = (pack: string, profile: string) => {
if (pack === 'agent-v2') return createAgentV2SeedTasks(profile)
throw new Error(`Unknown seed pack "${pack}".`)
}
const ensureAuth = async () => {
const browser = await chromium.launch({ headless: true })
try {
await ensureAuthenticatedState(browser, baseURL)
} finally {
await browser.close()
}
}
export const runSeed = async ({ allowBlocked, dryRun, pack, profile }: SeedOptions) => {
console.warn(`[seed] bootstrapping auth state against ${baseURL}`)
await ensureAuth()
const consoleSession = await createStandaloneConsoleSession()
try {
const results = await runSeedTasks(getTasks(pack, profile), {
consoleClient: consoleSession.client,
dryRun,
resources: new Map(),
})
const reportName = `${pack}-${profile}`
const reportPath = await writeSeedReport(reportName, results)
const blockedCount = results.filter((result) => result.status === 'blocked').length
console.warn(`[seed] report ${reportPath}`)
if (blockedCount > 0 && !allowBlocked) {
throw new Error(
`${blockedCount} seed task${blockedCount === 1 ? '' : 's'} blocked. Re-run with --allow-blocked only when partial readiness is intentional.`,
)
}
} finally {
await consoleSession.dispose()
}
}
-163
View File
@@ -1,163 +0,0 @@
import type { ManagedProcess } from '../support/process'
import { mkdir } from 'node:fs/promises'
import path from 'node:path'
import { chromium } from '@playwright/test'
import { createAgentV2SeedTasks } from '../features/agent-v2/support/seed'
import { ensureAuthenticatedState } from '../fixtures/auth'
import { createStandaloneConsoleSession } from '../support/api/console-session'
import { startLoggedProcess, stopManagedProcess, waitForUrl } from '../support/process'
import { runSeedTasks, writeSeedReport } from '../support/seed'
import { startWebServer, stopWebServer } from '../support/web-server'
import { apiURL, baseURL, reuseExistingWebServer } from '../test-env'
import { e2eDir, isMainModule } from './common'
import './env-register'
type SeedOptions = {
allowBlocked: boolean
dryRun: boolean
pack: string
profile: string
}
const parseArgs = (argv: string[]): SeedOptions => {
const options: SeedOptions = {
allowBlocked: false,
dryRun: false,
pack: 'agent-v2',
profile: 'post-merge',
}
for (const [index, arg] of argv.entries()) {
if (arg === '--pack') {
options.pack = argv[index + 1] || options.pack
continue
}
if (arg.startsWith('--pack=')) {
options.pack = arg.slice('--pack='.length)
continue
}
if (arg === '--dry-run') options.dryRun = true
if (arg === '--allow-blocked') options.allowBlocked = true
if (arg === '--profile') {
options.profile = argv[index + 1] || options.profile
continue
}
if (arg.startsWith('--profile=')) {
options.profile = arg.slice('--profile='.length)
continue
}
}
return options
}
const getTasks = (pack: string, profile: string) => {
if (pack === 'agent-v2') return createAgentV2SeedTasks(profile)
throw new Error(`Unknown seed pack "${pack}".`)
}
const ensureAuth = async () => {
const browser = await chromium.launch({ headless: true })
try {
await ensureAuthenticatedState(browser, baseURL)
} finally {
await browser.close()
}
}
const startApiProcess = async (logDir: string) => {
try {
await waitForUrl(`${apiURL}/health`, 1_000, 250, 1_000)
return undefined
} catch {
// Start a local API process below.
}
const apiProcess = await startLoggedProcess({
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'api'],
cwd: e2eDir,
label: 'api server',
logFilePath: path.join(logDir, 'seed-api.log'),
})
try {
await waitForUrl(`${apiURL}/health`, 180_000, 1_000)
return apiProcess
} catch (error) {
await stopManagedProcess(apiProcess)
throw error
}
}
const startCeleryProcess = async (logDir: string) =>
startLoggedProcess({
command: 'npx',
args: [
'tsx',
'./scripts/setup.ts',
'celery',
'--queues',
'dataset,priority_dataset,workflow_based_app_execution',
],
cwd: e2eDir,
label: 'celery worker',
logFilePath: path.join(logDir, 'seed-celery.log'),
})
const main = async () => {
const options = parseArgs(process.argv.slice(2))
const logDir = path.join(e2eDir, '.logs')
let apiProcess: ManagedProcess | undefined
let celeryProcess: ManagedProcess | undefined
let consoleSession: Awaited<ReturnType<typeof createStandaloneConsoleSession>> | undefined
await mkdir(logDir, { recursive: true })
try {
apiProcess = await startApiProcess(logDir)
celeryProcess = await startCeleryProcess(logDir)
await startWebServer({
baseURL,
command: 'npx',
args: ['tsx', './scripts/setup.ts', 'web'],
cwd: e2eDir,
logFilePath: path.join(logDir, 'seed-web.log'),
reuseExistingServer: reuseExistingWebServer,
timeoutMs: 300_000,
})
console.warn(`[seed] bootstrapping auth state against ${baseURL}`)
await ensureAuth()
consoleSession = await createStandaloneConsoleSession()
const results = await runSeedTasks(getTasks(options.pack, options.profile), {
consoleClient: consoleSession.client,
dryRun: options.dryRun,
resources: new Map(),
})
const reportName = `${options.pack}-${options.profile}`
const reportPath = await writeSeedReport(reportName, results)
const blockedCount = results.filter((result) => result.status === 'blocked').length
console.warn(`[seed] report ${reportPath}`)
if (blockedCount > 0 && !options.allowBlocked) {
throw new Error(
`${blockedCount} seed task${blockedCount === 1 ? '' : 's'} blocked. Re-run with --allow-blocked only when partial readiness is intentional.`,
)
}
} finally {
await consoleSession?.dispose()
await stopWebServer()
await stopManagedProcess(celeryProcess)
await stopManagedProcess(apiProcess)
}
}
if (isMainModule(import.meta.url)) {
void main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error))
process.exit(1)
})
}
+1
View File
@@ -27,6 +27,7 @@ import {
waitForCondition,
webDir,
} from './common'
import './env-register'
const buildIdPath = path.join(webDir, '.next', 'BUILD_ID')
const webBuildStampPath = path.join(webDir, '.next', 'e2e-web-build.sha256')
+2
View File
@@ -1,3 +1,5 @@
import './scripts/env-register'
export const defaultBaseURL = 'http://127.0.0.1:3000'
export const defaultApiURL = 'http://127.0.0.1:5001'
export const defaultLocale = 'en-US'
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, it } from 'vitest'
import { parseRunOptions, shouldStartManagedAgentBackend } from '../scripts/run-options'
describe('E2E run options', () => {
it('forwards Cucumber arguments without requesting seed data', () => {
expect(parseRunOptions(['--tags', '@smoke'])).toEqual({
forwardArgs: ['--tags', '@smoke'],
full: false,
headed: false,
seed: undefined,
seedOnly: false,
})
})
it('uses the post-merge profile for the default seed command', () => {
expect(parseRunOptions(['--seed-only'])).toMatchObject({
forwardArgs: [],
seed: {
allowBlocked: false,
dryRun: false,
pack: 'agent-v2',
profile: 'post-merge',
},
seedOnly: true,
})
})
it('seeds a named profile before forwarding Cucumber arguments', () => {
expect(parseRunOptions(['--profile', 'prepared', '--', '--tags', '@prepared'])).toMatchObject({
forwardArgs: ['--tags', '@prepared'],
seed: { profile: 'prepared' },
seedOnly: false,
})
})
it('rejects seed-only options when no seed was requested', () => {
expect(() => parseRunOptions(['--allow-blocked'])).toThrow(
'Seed options require --seed-only or --profile.',
)
expect(() => parseRunOptions(['--dry-run', '--profile', 'prepared'])).toThrow(
'--dry-run requires --seed-only.',
)
})
})
describe('managed Agent backend selection', () => {
it.each(['1', 'true'])('starts a managed backend for %s', (value) => {
expect(shouldStartManagedAgentBackend({ E2E_START_AGENT_BACKEND: value })).toBe(true)
})
it('uses an explicitly configured backend without starting a managed one', () => {
expect(
shouldStartManagedAgentBackend({ E2E_AGENT_BACKEND_URL: 'http://agent.example.test' }),
).toBe(false)
})
it('rejects two Agent backend owners', () => {
expect(() =>
shouldStartManagedAgentBackend({
AGENT_BACKEND_BASE_URL: 'http://agent.example.test',
E2E_START_AGENT_BACKEND: '1',
}),
).toThrow('E2E_START_AGENT_BACKEND cannot be enabled')
})
})