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): introduce select, file and file list form input types to Human Input node (#36322)

QuantumGhost3c98f96ae81d
diff --git a/api/Dockerfile b/api/Dockerfile
index 493b40af67f..1823a8f6a35 100644
--- a/api/Dockerfile
+++ b/api/Dockerfile
@@ -17,7 +17,7 @@ FROM base AS packages
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
# basic environment
- g++ \
+ git g++ \
# for building gmpy2
libmpfr-dev libmpc-dev
diff --git a/api/controllers/common/human_input.py b/api/controllers/common/human_input.py
index 98fe2ce67bc..d9b8f8f9a37 100644
--- a/api/controllers/common/human_input.py
+++ b/api/controllers/common/human_input.py
@@ -1,10 +1,40 @@
import json
-from pydantic import BaseModel, JsonValue
+from pydantic import BaseModel, Field, JsonValue
+
+HUMAN_INPUT_FORM_INPUT_EXAMPLE = {
+ "decision": "approve",
+ "attachment": {
+ "transfer_method": "local_file",
+ "upload_file_id": "4e0d1b87-52f2-49f6-b8c6-95cd9c954b3e",
+ "type": "document",
+ },
+ "attachments": [
+ {
+ "transfer_method": "local_file",
+ "upload_file_id": "1a77f0df-c0e6-461c-987c-e72526f341ee",
+ "type": "document",
+ },
+ {
+ "transfer_method": "remote_url",
+ "url": "https://example.com/report.pdf",
+ "type": "document",
+ },
+ ],
+}
class HumanInputFormSubmitPayload(BaseModel):
- inputs: dict[str, JsonValue]
+ inputs: dict[str, JsonValue] = Field(
+ description=(
+ "Submitted human input values keyed by output variable name. "
+ "Use a string for paragraph or select input values, a file mapping for file inputs, "
+ "and a list of file mappings for file-list inputs. Local file mappings use "
+ "`transfer_method=local_file` with `upload_file_id`; remote file mappings use "
+ "`transfer_method=remote_url` with `url` or `remote_url`."
+ ),
+ examples=[HUMAN_INPUT_FORM_INPUT_EXAMPLE],
+ )
action: str
diff --git a/api/controllers/service_api/app/human_input_form.py b/api/controllers/service_api/app/human_input_form.py
index 2b38a84b0ec..87cdca49883 100644
--- a/api/controllers/service_api/app/human_input_form.py
+++ b/api/controllers/service_api/app/human_input_form.py
@@ -7,6 +7,7 @@ paused human input forms in workflow/chatflow runs.
import json
import logging
+from collections.abc import Sequence
from flask import Response
from flask_restx import Resource
@@ -18,6 +19,7 @@ from controllers.service_api import service_api_ns
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from core.workflow.human_input_policy import HumanInputSurface, is_recipient_type_allowed_for_surface
from extensions.ext_database import db
+from graphon.nodes.human_input.entities import FormInputConfig
from libs.helper import to_timestamp
from models.model import App, EndUser
from services.human_input_service import Form, FormNotFoundError, HumanInputService
@@ -28,11 +30,11 @@ logger = logging.getLogger(__name__)
register_schema_models(service_api_ns, HumanInputFormSubmitPayload)
-def _jsonify_form_definition(form: Form) -> Response:
- definition_payload = form.get_definition().model_dump()
+def _jsonify_form_definition(form: Form, *, inputs: Sequence[FormInputConfig] = ()) -> Response:
+ definition_payload = form.get_definition().model_dump(mode="json")
payload = {
"form_content": definition_payload["rendered_content"],
- "inputs": definition_payload["inputs"],
+ "inputs": [form_input.model_dump(mode="json") for form_input in inputs],
"resolved_default_values": stringify_form_default_values(definition_payload["default_values"]),
"user_actions": definition_payload["user_actions"],
"expiration_time": to_timestamp(form.expiration_time),
@@ -75,7 +77,8 @@ class WorkflowHumanInputFormApi(Resource):
_ensure_form_belongs_to_app(form, app_model)
_ensure_form_is_allowed_for_service_api(form)
service.ensure_form_active(form)
- return _jsonify_form_definition(form)
+ inputs = service.resolve_form_inputs(form)
+ return _jsonify_form_definition(form, inputs=inputs)
@service_api_ns.expect(service_api_ns.models[HumanInputFormSubmitPayload.__name__])
@service_api_ns.doc("submit_human_input_form")
diff --git a/api/controllers/web/__init__.py b/api/controllers/web/__init__.py
index cfa39e0dfd3..d4b0829dea3 100644
--- a/api/controllers/web/__init__.py
+++ b/api/controllers/web/__init__.py
@@ -23,6 +23,7 @@ from . import (
feature,
files,
forgot_password,
+ human_input_file_upload,
human_input_form,
login,
message,
@@ -46,6 +47,7 @@ __all__ = [
"feature",
"files",
"forgot_password",
+ "human_input_file_upload",
"human_input_form",
"login",
"message",
diff --git a/api/controllers/web/human_input_file_upload.py b/api/controllers/web/human_input_file_upload.py
new file mode 100644
index 00000000000..cbb4a785294
--- /dev/null
+++ b/api/controllers/web/human_input_file_upload.py
@@ -0,0 +1,212 @@
+"""HITL human input form file uploads.
+
+This controller exposes a single public upload endpoint for both local files and
+remote URLs. The caller always submits a multipart form: when a non-empty
+``url`` field is present, the request follows the remote fetch flow; otherwise it
+falls back to the local file upload flow.
+"""
+
+import httpx
+from flask import request
+from flask_restx import Resource
+from pydantic import BaseModel, ConfigDict, Field, HttpUrl
+from sqlalchemy.orm import sessionmaker
+
+import services
+from controllers.common import helpers
+from controllers.common.errors import (
+ BlockedFileExtensionError,
+ FileTooLargeError,
+ NoFileUploadedError,
+ RemoteFileUploadError,
+ TooManyFilesError,
+ UnsupportedFileTypeError,
+)
+from controllers.common.schema import register_schema_models
+from controllers.web import web_ns
+from core.helper import ssrf_proxy
+from extensions.ext_database import db
+from fields.file_fields import FileResponse, FileWithSignedUrl
+from graphon.file import helpers as file_helpers
+from libs.exception import BaseHTTPException
+from repositories.factory import DifyAPIRepositoryFactory
+from services.file_service import FileService
+from services.human_input_file_upload_service import (
+ HITL_UPLOAD_TOKEN_PREFIX,
+ HumanInputFileUploadService,
+ InvalidUploadTokenError,
+)
+
+
+class InvalidUploadTokenBadRequestError(BaseHTTPException):
+ error_code = "invalid_upload_token"
+ description = "Invalid upload token."
+ code = 400
+
+
+class InvalidUploadTokenUnauthorizedError(BaseHTTPException):
+ error_code = "invalid_upload_token"
+ description = "Upload token is required."
+ code = 401
+
+
+class InvalidUploadTokenForbiddenError(BaseHTTPException):
+ error_code = "invalid_upload_token"
+ description = "Upload token is invalid or expired."
+ code = 403
+
+
+class HumanInputFileUploadFormPayload(BaseModel):
+ """Parsed multipart form fields for HITL uploads."""
+
+ model_config = ConfigDict(extra="ignore")
+
+ url: HttpUrl | None = Field(default=None, description="Remote file URL")
+
+
+register_schema_models(web_ns, HumanInputFileUploadFormPayload, FileResponse, FileWithSignedUrl)
+
+
+def _create_upload_service() -> HumanInputFileUploadService:
+ session_factory = sessionmaker(bind=db.engine)
+ workflow_run_repository = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_factory)
+ return HumanInputFileUploadService(
+ session_factory=session_factory,
+ workflow_run_repository=workflow_run_repository,
+ )
+
+
+def _extract_hitl_upload_token() -> str:
+ """Read HITL upload token from Authorization without invoking other bearer auth chains."""
+
+ authorization = request.headers.get("Authorization")
+ if authorization is None:
+ raise InvalidUploadTokenUnauthorizedError()
+
+ parts = authorization.split()
+ if len(parts) != 2:
+ raise InvalidUploadTokenUnauthorizedError()
+
+ scheme, token = parts
+ if scheme.lower() != "bearer":
+ raise InvalidUploadTokenBadRequestError()
+ if not token:
+ raise InvalidUploadTokenUnauthorizedError()
+ if not token.startswith(HITL_UPLOAD_TOKEN_PREFIX):
+ raise InvalidUploadTokenBadRequestError()
+ return token
+
+
+def _validate_context(service: HumanInputFileUploadService, token: str):
+ try:
+ return service.validate_upload_token(token)
+ except InvalidUploadTokenError as exc:
+ raise InvalidUploadTokenForbiddenError() from exc
+
+
+def _parse_local_upload_file():
+ if "file" not in request.files:
+ raise NoFileUploadedError()
+ if len(request.files) > 1:
+ raise TooManyFilesError()
+
+ file = request.files["file"]
+ if not file.filename:
+ from controllers.common.errors import FilenameNotExistsError
+
+ raise FilenameNotExistsError()
+
+ return file
+
+
+def _parse_upload_form() -> HumanInputFileUploadFormPayload:
+ return HumanInputFileUploadFormPayload.model_validate(request.form.to_dict(flat=True))
+
+
+def _upload_local_file(context):
+ file = _parse_local_upload_file()
+
+ try:
+ upload_file = FileService(db.engine).upload_file(
+ filename=file.filename or "",
+ content=file.read(),
+ mimetype=file.mimetype,
+ user=context.owner,
+ source=None,
+ )
+ except services.errors.file.FileTooLargeError as file_too_large_error:
+ raise FileTooLargeError(file_too_large_error.description)
+ except services.errors.file.UnsupportedFileTypeError:
+ raise UnsupportedFileTypeError()
+ except services.errors.file.BlockedFileExtensionError as exc:
+ raise BlockedFileExtensionError() from exc
+
+ response = FileResponse.model_validate(upload_file, from_attributes=True)
+ return upload_file.id, response
+
+
+def _upload_remote_file(context, url: str):
+ try:
+ resp = ssrf_proxy.head(url=url)
+ if resp.status_code != httpx.codes.OK:
+ resp = ssrf_proxy.get(url=url, timeout=3, follow_redirects=True)
+ if resp.status_code != httpx.codes.OK:
+ raise RemoteFileUploadError(f"Failed to fetch file from {url}: {resp.text}")
+ except httpx.RequestError as exc:
+ raise RemoteFileUploadError(f"Failed to fetch file from {url}: {str(exc)}")
+
+ file_info = helpers.guess_file_info_from_response(resp)
+ if not FileService.is_file_size_within_limit(extension=file_info.extension, file_size=file_info.size):
+ raise FileTooLargeError()
+
+ content = resp.content if resp.request.method == "GET" else ssrf_proxy.get(url).content
+
+ try:
+ upload_file = FileService(db.engine).upload_file(
+ filename=file_info.filename,
+ content=content,
+ mimetype=file_info.mimetype,
+ user=context.owner,
+ source_url=url,
+ )
+ except services.errors.file.FileTooLargeError as file_too_large_error:
+ raise FileTooLargeError(file_too_large_error.description)
+ except services.errors.file.UnsupportedFileTypeError:
+ raise UnsupportedFileTypeError()
+ except services.errors.file.BlockedFileExtensionError as exc:
+ raise BlockedFileExtensionError() from exc
+
+ response = FileWithSignedUrl(
+ id=upload_file.id,
+ name=upload_file.name,
+ size=upload_file.size,
+ extension=upload_file.extension,
+ url=file_helpers.get_signed_file_url(upload_file_id=upload_file.id),
+ mime_type=upload_file.mime_type,
+ created_by=upload_file.created_by,
+ created_at=int(upload_file.created_at.timestamp()),
+ )
+ return upload_file.id, response
+
+
+@web_ns.route("/human-input-forms/files")
+@web_ns.response(201, "File uploaded successfully", web_ns.models[FileResponse.__name__])
+class HumanInputFileUploadApi(Resource):
+ def post(self):
+ """Upload one local file or remote URL file for a HITL human input form."""
+
+ token = _extract_hitl_upload_token()
+ upload_service = _create_upload_service()
+ context = _validate_context(upload_service, token)
+ form = _parse_upload_form()
+
+ # The browser always submits multipart/form-data. A non-empty `url`
+ # switches the endpoint into the remote-fetch flow; otherwise the
+ # request must carry a local `file`.
+ if form.url is not None:
+ file_id, response = _upload_remote_file(context=context, url=str(form.url))
+ else:
+ file_id, response = _upload_local_file(context=context)
+
+ upload_service.record_upload_file(context=context, file_id=file_id)
+ return response.model_dump(mode="json"), 201
diff --git a/api/controllers/web/human_input_form.py b/api/controllers/web/human_input_form.py
index 69297450c9a..113c39d3dd3 100644
--- a/api/controllers/web/human_input_form.py
+++ b/api/controllers/web/human_input_form.py
@@ -4,27 +4,42 @@ Web App Human Input Form APIs.
import json
import logging
+from collections.abc import Sequence
from typing import Any, NotRequired, TypedDict
from flask import Response, request
from flask_restx import Resource
+from pydantic import BaseModel
from sqlalchemy import select
+from sqlalchemy.orm import sessionmaker
from werkzeug.exceptions import Forbidden
from configs import dify_config
from controllers.common.human_input import HumanInputFormSubmitPayload, stringify_form_default_values
+from controllers.common.schema import register_schema_models
from controllers.web import web_ns
from controllers.web.error import NotFoundError, WebFormRateLimitExceededError
from controllers.web.site import serialize_app_site_payload
from extensions.ext_database import db
+from graphon.nodes.human_input.entities import FormInputConfig
from libs.helper import RateLimiter, extract_remote_ip, to_timestamp
from models.account import TenantStatus
from models.model import App, Site
+from repositories.factory import DifyAPIRepositoryFactory
+from services.human_input_file_upload_service import HumanInputFileUploadService
from services.human_input_service import Form, FormNotFoundError, HumanInputService
logger = logging.getLogger(__name__)
+class HumanInputUploadTokenResponse(BaseModel):
+ upload_token: str
+ expires_at: int
+
+
+register_schema_models(web_ns, HumanInputUploadTokenResponse)
+
+
_FORM_SUBMIT_RATE_LIMITER = RateLimiter(
prefix="web_form_submit_rate_limit",
max_attempts=dify_config.WEB_FORM_SUBMIT_RATE_LIMIT_MAX_ATTEMPTS,
@@ -35,6 +50,20 @@ _FORM_ACCESS_RATE_LIMITER = RateLimiter(
max_attempts=dify_config.WEB_FORM_SUBMIT_RATE_LIMIT_MAX_ATTEMPTS,
time_window=dify_config.WEB_FORM_SUBMIT_RATE_LIMIT_WINDOW_SECONDS,
)
+_FORM_UPLOAD_TOKEN_RATE_LIMITER = RateLimiter(
+ prefix="web_form_upload_token_rate_limit",
+ max_attempts=dify_config.WEB_FORM_SUBMIT_RATE_LIMIT_MAX_ATTEMPTS,
+ time_window=dify_config.WEB_FORM_SUBMIT_RATE_LIMIT_WINDOW_SECONDS,
+)
+
+
+def _create_upload_service() -> HumanInputFileUploadService:
+ session_factory = sessionmaker(bind=db.engine)
+ workflow_run_repository = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_factory)
+ return HumanInputFileUploadService(
+ session_factory=session_factory,
+ workflow_run_repository=workflow_run_repository,
+ )
class FormDefinitionPayload(TypedDict):
@@ -46,12 +75,17 @@ class FormDefinitionPayload(TypedDict):
site: NotRequired[dict]
-def _jsonify_form_definition(form: Form, site_payload: dict | None = None) -> Response:
+def _jsonify_form_definition(
+ form: Form,
+ *,
+ inputs: Sequence[FormInputConfig] = (),
+ site_payload: dict | None = None,
+) -> Response:
"""Return the form payload (optionally with site) as a JSON response."""
- definition_payload = form.get_definition().model_dump()
+ definition_payload = form.get_definition().model_dump(mode="json")
payload: FormDefinitionPayload = {
"form_content": definition_payload["rendered_content"],
- "inputs": definition_payload["inputs"],
+ "inputs": [i.model_dump(mode="json") for i in inputs],
"resolved_default_values": stringify_form_default_values(definition_payload["default_values"]),
"user_actions": definition_payload["user_actions"],
"expiration_time": to_timestamp(form.expiration_time),
@@ -61,6 +95,33 @@ def _jsonify_form_definition(form: Form, site_payload: dict | None = None) -> Re
return Response(json.dumps(payload, ensure_ascii=False), mimetype="application/json")
+@web_ns.route("/form/human_input/<string:form_token>/upload-token")
+class HumanInputFormUploadTokenApi(Resource):
+ """API for issuing HITL upload tokens for active human input forms."""
+
+ def post(self, form_token: str):
+ """
+ Issue an upload token for a human input form.
+
+ POST /api/form/human_input/<form_token>/upload-token
+ """
+ ip_address = extract_remote_ip(request)
+ if _FORM_UPLOAD_TOKEN_RATE_LIMITER.is_rate_limited(ip_address):
+ raise WebFormRateLimitExceededError()
+ _FORM_UPLOAD_TOKEN_RATE_LIMITER.increment_rate_limit(ip_address)
+
+ try:
+ token = _create_upload_service().issue_upload_token(form_token)
+ except FormNotFoundError:
+ raise NotFoundError("Form not found")
+
+ response = HumanInputUploadTokenResponse(
+ upload_token=token.upload_token,
+ expires_at=to_timestamp(token.expires_at),
+ )
+ return response.model_dump(mode="json"), 200
+
+
@web_ns.route("/form/human_input/<string:form_token>")
class HumanInputFormApi(Resource):
"""API for getting and submitting human input forms via the web app."""
@@ -89,8 +150,13 @@ class HumanInputFormApi(Resource):
service.ensure_form_active(form)
app_model, site = _get_app_site_from_form(form)
+ inputs = service.resolve_form_inputs(form)
- return _jsonify_form_definition(form, site_payload=serialize_app_site_payload(app_model, site, None))
+ return _jsonify_form_definition(
+ form,
+ inputs=inputs,
+ site_payload=serialize_app_site_payload(app_model, site, None),
+ )
# def post(self, _app_model: App, _end_user: EndUser, form_token: str):
def post(self, form_token: str):
diff --git a/api/core/app/apps/common/workflow_response_converter.py b/api/core/app/apps/common/workflow_response_converter.py
index 1d178fd428f..502b1907ba4 100644
--- a/api/core/app/apps/common/workflow_response_converter.py
+++ b/api/core/app/apps/common/workflow_response_converter.py
@@ -52,15 +52,11 @@ from core.tools.tool_manager import ToolManager
from core.trigger.constants import TRIGGER_PLUGIN_NODE_TYPE
from core.trigger.trigger_manager import TriggerManager
from core.workflow.human_input_forms import load_form_tokens_by_form_id
-from core.workflow.human_input_policy import HumanInputSurface, enrich_human_input_pause_reasons
-
-# Maps the entry surface a workflow was invoked from to the HITL surface that
-# its resume tokens must be filtered for. Surfaces not in this map fall back to
-# the general priority ordering (typically CONSOLE > BACKSTAGE).
-_INVOKE_FROM_TO_HITL_SURFACE: Mapping[InvokeFrom, HumanInputSurface] = {
- InvokeFrom.SERVICE_API: HumanInputSurface.SERVICE_API,
- InvokeFrom.OPENAPI: HumanInputSurface.OPENAPI,
-}
+from core.workflow.human_input_policy import (
+ HumanInputSurface,
+ enrich_human_input_pause_reasons,
+ resolve_human_input_pause_reason_inputs,
+)
from core.workflow.system_variables import SystemVariableKey, system_variables_to_mapping
from core.workflow.workflow_entry import WorkflowEntry
from extensions.ext_database import db
@@ -83,6 +79,14 @@ from models.human_input import HumanInputForm
from models.workflow import WorkflowRun
from services.variable_truncator import BaseTruncator, DummyVariableTruncator, VariableTruncator
+# Maps the entry surface a workflow was invoked from to the HITL surface that
+# its resume tokens must be filtered for. Surfaces not in this map fall back to
+# the general priority ordering (typically CONSOLE > BACKSTAGE).
+_INVOKE_FROM_TO_HITL_SURFACE: Mapping[InvokeFrom, HumanInputSurface] = {
+ InvokeFrom.SERVICE_API: HumanInputSurface.SERVICE_API,
+ InvokeFrom.OPENAPI: HumanInputSurface.OPENAPI,
+}
+
NodeExecutionId = NewType("NodeExecutionId", str)
logger = logging.getLogger(__name__)
@@ -327,8 +331,13 @@ class WorkflowResponseConverter:
encoded_outputs = self._encode_outputs(event.outputs) or {}
if self._application_generate_entity.invoke_from == InvokeFrom.SERVICE_API:
encoded_outputs = {}
- pause_reasons = [reason.model_dump(mode="json") for reason in event.reasons]
- human_input_form_ids = [reason.form_id for reason in event.reasons if isinstance(reason, HumanInputRequired)]
+ variable_pool = graph_runtime_state.variable_pool
+ resolved_reasons = resolve_human_input_pause_reason_inputs(
+ event.reasons,
+ variable_pool=variable_pool,
+ )
+ pause_reasons = [reason.model_dump(mode="json") for reason in resolved_reasons]
+ human_input_form_ids = [reason.form_id for reason in resolved_reasons if isinstance(reason, HumanInputRequired)]
expiration_times_by_form_id: dict[str, datetime] = {}
display_in_ui_by_form_id: dict[str, bool] = {}
form_token_by_form_id: dict[str, str] = {}
@@ -365,7 +374,7 @@ class WorkflowResponseConverter:
responses: list[StreamResponse] = []
- for reason in event.reasons:
+ for reason in resolved_reasons:
if isinstance(reason, HumanInputRequired):
expiration_time = expiration_times_by_form_id.get(reason.form_id)
if expiration_time is None:
@@ -413,17 +422,19 @@ class WorkflowResponseConverter:
self, *, event: QueueHumanInputFormFilledEvent, task_id: str
) -> HumanInputFormFilledResponse:
run_id = self._ensure_workflow_run_id()
- return HumanInputFormFilledResponse(
- task_id=task_id,
- workflow_run_id=run_id,
- data=HumanInputFormFilledResponse.Data(
- node_id=event.node_id,
- node_title=event.node_title,
- rendered_content=event.rendered_content,
- action_id=event.action_id,
- action_text=event.action_text,
- ),
+ data = HumanInputFormFilledResponse.Data(
+ node_id=event.node_id,
+ node_title=event.node_title,
+ rendered_content=event.rendered_content,
+ action_id=event.action_id,
+ action_text=event.action_text,
)
+ if event.submitted_data is not None:
+ runtime_type_converter = WorkflowRuntimeTypeConverter()
+
+ data.submitted_data = runtime_type_converter.value_to_json_encodable_recursive(event.submitted_data)
+
+ return HumanInputFormFilledResponse(task_id=task_id, workflow_run_id=run_id, data=data)
def human_input_form_timeout_to_stream_response(
self, *, event: QueueHumanInputFormTimeoutEvent, task_id: str
diff --git a/api/core/app/apps/workflow_app_runner.py b/api/core/app/apps/workflow_app_runner.py
index 84e9573416d..c7af6064193 100644
--- a/api/core/app/apps/workflow_app_runner.py
+++ b/api/core/app/apps/workflow_app_runner.py
@@ -435,6 +435,7 @@ class WorkflowBasedAppRunner:
rendered_content=event.rendered_content,
action_id=event.action_id,
action_text=event.action_text,
+ submitted_data=event.submitted_data,
)
)
case NodeRunHumanInputFormTimeoutEvent():
diff --git a/api/core/app/entities/queue_entities.py b/api/core/app/entities/queue_entities.py
index 221b7fb058b..a0e7881edeb 100644
--- a/api/core/app/entities/queue_entities.py
+++ b/api/core/app/entities/queue_entities.py
@@ -11,6 +11,7 @@ from graphon.entities import WorkflowStartReason
from graphon.entities.pause_reason import PauseReason
from graphon.enums import NodeType, WorkflowNodeExecutionMetadataKey
from graphon.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk
+from graphon.variables.segments import Segment
class QueueEvent(StrEnum):
@@ -508,6 +509,10 @@ class QueueHumanInputFormFilledEvent(AppQueueEvent):
action_id: str
action_text: str
+ # Keep the field name aligned with Graphon so the app-layer bridge does not
+ # need to translate between two equivalent payload names.
+ submitted_data: Mapping[str, Segment] | None = None
+
class QueueHumanInputFormTimeoutEvent(AppQueueEvent):
"""
diff --git a/api/core/app/entities/task_entities.py b/api/core/app/entities/task_entities.py
index 3a33899bdf2..defec9f9461 100644
--- a/api/core/app/entities/task_entities.py
+++ b/api/core/app/entities/task_entities.py
@@ -342,6 +342,8 @@ class HumanInputFormFilledResponse(StreamResponse):
action_id: str
action_text: str
+ submitted_data: Mapping[str, Any] | None = None
+
event: StreamEvent = StreamEvent.HUMAN_INPUT_FORM_FILLED
workflow_run_id: str
data: Data
diff --git a/api/core/entities/execution_extra_content.py b/api/core/entities/execution_extra_content.py
index f11c6700696..43252ccb2ce 100644
--- a/api/core/entities/execution_extra_content.py
+++ b/api/core/entities/execution_extra_content.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any, TypeAlias
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict, Field, JsonValue
from graphon.nodes.human_input.entities import FormInputConfig, UserActionConfig
from models.execution_extra_content import ExecutionContentType
@@ -19,6 +19,8 @@ class HumanInputFormDefinition(BaseModel):
inputs: Sequence[FormInputConfig] = Field(default_factory=list)
actions: Sequence[UserActionConfig] = Field(default_factory=list)
display_in_ui: bool = False
+
+ # `form_token` is `None` if the corresponding form has been submitted.
form_token: str | None = None
resolved_default_values: Mapping[str, Any] = Field(default_factory=dict)
expiration_time: int
@@ -29,16 +31,31 @@ class HumanInputFormSubmissionData(BaseModel):
node_id: str
node_title: str
+
+ # deprecate: the rendered_content is deprecated and only for historical reasons.
rendered_content: str
+
+ # The identifier of action user has chosen.
action_id: str
+ # The button text of the action user has chosen.
action_text: str
+ # submitted_data records the submitted form data.
+ # Keys correspond to `output_variable_name` of HumanInput inputs.
+ # Values are serialized JSON forms of runtime values, including file dictionaries.
+ #
+ # For form submitted before this field is introduced, this field is populated from
+ # the stored submission data.
+ submitted_data: Mapping[str, JsonValue] | None = None
+
class HumanInputContent(BaseModel):
model_config = ConfigDict(frozen=True)
workflow_run_id: str
submitted: bool
+ # Both the form_defintion and the form_submission_data are present in
+ # HumanInputContent. For historical records, the
form_definition: HumanInputFormDefinition | None = None
form_submission_data: HumanInputFormSubmissionData | None = None
type: ExecutionContentType = Field(default=ExecutionContentType.HUMAN_INPUT)
diff --git a/api/core/workflow/human_input_policy.py b/api/core/workflow/human_input_policy.py
index 8d231e24372..e95d753ae96 100644
--- a/api/core/workflow/human_input_policy.py
+++ b/api/core/workflow/human_input_policy.py
@@ -4,7 +4,11 @@ from collections.abc import Mapping, Sequence
from enum import StrEnum
from typing import Any
-from graphon.entities.pause_reason import PauseReasonType
+from graphon.entities.pause_reason import HumanInputRequired, PauseReason, PauseReasonType
+from graphon.nodes.human_input.entities import FormInputConfig, SelectInputConfig
+from graphon.nodes.human_input.enums import ValueSourceType
+from graphon.runtime.graph_runtime_state_protocol import ReadOnlyVariablePool
+from graphon.variables import ArrayStringSegment
from models.human_input import RecipientType
@@ -73,3 +77,69 @@ def enrich_human_input_pause_reasons(
updated["expiration_time"] = expiration_time
enriched.append(updated)
return enriched
+
+
+def resolve_variable_select_input_options(
+ inputs: Sequence[FormInputConfig],
+ *,
+ variable_pool: ReadOnlyVariablePool | None,
+) -> list[FormInputConfig]:
+ """Resolve variable-backed select options to runtime values."""
+
+ # This function replace the SelectInputConfig.option_source.value
+ # field with acutial runtime values when option_source.type is VARIABLE.
+ #
+ # This is a dirty hacks. However it does reduces the logic leaked to callers of
+ # the api.
+ resolved_inputs: list[FormInputConfig] = []
+
+ if variable_pool is None:
+ return list(inputs)
+
+ for form_input in inputs:
+ if not isinstance(form_input, SelectInputConfig):
+ resolved_inputs.append(form_input)
+ continue
+
+ option_source = form_input.option_source
+ if option_source.type != ValueSourceType.VARIABLE:
+ resolved_inputs.append(form_input)
+ continue
+
+ option_values = variable_pool.get(option_source.selector)
+ if option_values is None:
+ resolved_inputs.append(form_input)
+ continue
+ if not isinstance(option_values, ArrayStringSegment):
+ raise TypeError(f"expected ArrayStringSegment, got {type(option_values)}")
+
+ updated_option_source = option_source.model_copy(update={"value": option_values.value})
+ # Ensure frontend receives concrete select options instead of unresolved selectors.
+ resolved_inputs.append(
+ form_input.model_copy(
+ update={"option_source": updated_option_source},
+ )
+ )
+ return resolved_inputs
+
+
+def resolve_human_input_pause_reason_inputs(
+ reasons: Sequence[PauseReason],
+ *,
+ variable_pool: ReadOnlyVariablePool | None,
+) -> list[PauseReason]:
+ if variable_pool is None:
+ return list(reasons)
+
+ resolved_reasons: list[PauseReason] = []
+ for reason in reasons:
+ if not isinstance(reason, HumanInputRequired):
+ resolved_reasons.append(reason)
+ continue
+
+ resolved_inputs = resolve_variable_select_input_options(
+ reason.inputs,
+ variable_pool=variable_pool,
+ )
+ resolved_reasons.append(reason.model_copy(update={"inputs": resolved_inputs}))
+ return resolved_reasons
diff --git a/api/core/workflow/node_runtime.py b/api/core/workflow/node_runtime.py
index 7ea03a4a33c..be14aa92ec0 100644
--- a/api/core/workflow/node_runtime.py
+++ b/api/core/workflow/node_runtime.py
@@ -35,7 +35,7 @@ from core.tools.utils.message_transformer import ToolFileMessageTransformer
from core.workflow.file_reference import build_file_reference
from extensions.ext_database import db
from factories import file_factory
-from graphon.file import FileTransferMethod, FileType
+from graphon.file import File, FileTransferMethod, FileType
from graphon.model_runtime.entities import LLMMode
from graphon.model_runtime.entities.llm_entities import (
LLMResult,
@@ -47,7 +47,12 @@ from graphon.model_runtime.entities.llm_entities import (
from graphon.model_runtime.entities.message_entities import PromptMessage, PromptMessageTool
from graphon.model_runtime.entities.model_entities import AIModelEntity
from graphon.model_runtime.model_providers.base.large_language_model import LargeLanguageModel
-from graphon.nodes.human_input.entities import HumanInputNodeData
+from graphon.nodes.human_input.entities import (
+ FileInputConfig,
+ FileListInputConfig,
+ FormInputConfig,
+ HumanInputNodeData,
+)
from graphon.nodes.llm.runtime_protocols import (
LLMProtocol,
PromptMessageSerializerProtocol,
@@ -83,7 +88,6 @@ from .system_variables import SystemVariableKey, get_system_text
if TYPE_CHECKING:
from core.tools.__base.tool import Tool
from core.tools.entities.tool_entities import ToolInvokeMessage as CoreToolInvokeMessage
- from graphon.file import File
from graphon.nodes.llm.file_saver import LLMFileSaver
from graphon.nodes.tool.entities import ToolNodeData
@@ -682,6 +686,7 @@ class DifyHumanInputNodeRuntime(HumanInputNodeRuntimeProtocol):
self._run_context = resolve_dify_run_context(run_context)
self._workflow_execution_id_getter = workflow_execution_id_getter
self._form_repository = form_repository
+ self._file_reference_factory = DifyFileReferenceFactory(self._run_context)
def _invoke_source(self) -> str:
invoke_from = self._run_context.invoke_from
@@ -735,6 +740,23 @@ class DifyHumanInputNodeRuntime(HumanInputNodeRuntimeProtocol):
repo = self.build_form_repository()
return repo.get_form(node_id)
+ def restore_submitted_data(
+ self,
+ *,
+ node_data: HumanInputNodeData,
+ submitted_data: Mapping[str, Any],
+ ) -> Mapping[str, Any]:
+ restored_data: dict[str, Any] = dict(submitted_data)
+ for input_config in node_data.inputs:
+ output_variable_name = input_config.output_variable_name
+ if output_variable_name not in submitted_data:
+ continue
+ restored_data[output_variable_name] = self._restore_submitted_value(
+ input_config=input_config,
+ value=submitted_data[output_variable_name],
+ )
+ return restored_data
+
def create_form(
self,
*,
@@ -755,6 +777,55 @@ class DifyHumanInputNodeRuntime(HumanInputNodeRuntimeProtocol):
)
return repo.create_form(params)
+ def _restore_submitted_value(
+ self,
+ *,
+ input_config: FormInputConfig,
+ value: Any,
+ ) -> Any:
+ if isinstance(input_config, FileInputConfig):
+ return self._restore_submitted_file_value(
+ output_variable_name=input_config.output_variable_name,
+ value=value,
+ )
+ if isinstance(input_config, FileListInputConfig):
+ return self._restore_submitted_file_list_value(
+ output_variable_name=input_config.output_variable_name,
+ value=value,
+ )
+ return value
+
+ def _restore_submitted_file_value(
+ self,
+ *,
+ output_variable_name: str,
+ value: Any,
+ ) -> Any:
+ if not isinstance(value, Mapping):
+ msg = (
+ "HumanInput file submission must be persisted as a mapping, "
+ f"output_variable_name={output_variable_name}"
+ )
+ raise ValueError(msg)
+ return self._file_reference_factory.build_from_mapping(mapping=value)
+
+ def _restore_submitted_file_list_value(
+ self,
+ *,
+ output_variable_name: str,
+ value: Any,
+ ) -> list[Any]:
+ if not isinstance(value, list):
+ msg = (
+ "HumanInput file-list submission must be persisted as a list, "
+ f"output_variable_name={output_variable_name}"
+ )
+ raise ValueError(msg)
+ if any(not isinstance(item, Mapping) for item in value):
+ msg = f"HumanInput file-list submission must contain mappings, output_variable_name={output_variable_name}"
+ raise ValueError(msg)
+ return [self._file_reference_factory.build_from_mapping(mapping=item) for item in value]
+
def build_dify_llm_file_saver(
*,
diff --git a/api/factories/file_factory/builders.py b/api/factories/file_factory/builders.py
index 4fb976f0e74..7026af23b85 100644
--- a/api/factories/file_factory/builders.py
+++ b/api/factories/file_factory/builders.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import mimetypes
import uuid
from collections.abc import Mapping, Sequence
-from typing import Any
+from typing import Any, Literal, NotRequired, TypedDict, assert_never, cast
from sqlalchemy import select
@@ -19,10 +19,58 @@ from .common import resolve_mapping_file_id
from .remote import get_remote_file_info
from .validation import is_file_valid_with_config
+type FileTypeValue = FileType | Literal["image", "document", "audio", "video", "custom"]
+
+type _LocalFileTransferMethod = Literal["local_file", FileTransferMethod.LOCAL_FILE]
+type _RemoteUrlTransferMethod = Literal["remote_url", FileTransferMethod.REMOTE_URL]
+type _ToolFileTransferMethod = Literal["tool_file", FileTransferMethod.TOOL_FILE]
+type _DatasourceFileTransferMethod = Literal["datasource_file", FileTransferMethod.DATASOURCE_FILE]
+
+
+class LocalFileMapping(TypedDict):
+ transfer_method: _LocalFileTransferMethod
+ id: NotRequired[str | None] # Read as the graph-layer File.file_id.
+ type: NotRequired[FileTypeValue | None] # Read for type override and upload config validation.
+ upload_file_id: NotRequired[str | None] # File id lookup priority 1.
+ reference: NotRequired[str | None] # File id lookup priority 2; may be an opaque file reference.
+ related_id: NotRequired[str | None] # File id lookup priority 3; legacy persisted field.
+
+
+class RemoteUrlMapping(TypedDict):
+ transfer_method: _RemoteUrlTransferMethod
+ id: NotRequired[str | None] # Read as the graph-layer File.file_id.
+ type: NotRequired[FileTypeValue | None] # Read for type override and upload config validation.
+ upload_file_id: NotRequired[str | None] # Persisted UploadFile lookup priority 1.
+ reference: NotRequired[str | None] # Persisted UploadFile lookup priority 2; may be an opaque file reference.
+ related_id: NotRequired[str | None] # Persisted UploadFile lookup priority 3; legacy persisted field.
+ url: NotRequired[str | None] # External URL lookup priority 1 when no UploadFile id is resolved.
+ remote_url: NotRequired[str | None] # External URL lookup priority 2 when no UploadFile id is resolved.
+
+
+class ToolFileMapping(TypedDict):
+ transfer_method: _ToolFileTransferMethod
+ id: NotRequired[str | None] # Read as the graph-layer File.file_id.
+ type: NotRequired[FileTypeValue | None] # Read for type override and upload config validation.
+ tool_file_id: NotRequired[str | None] # ToolFile lookup priority 1.
+ reference: NotRequired[str | None] # ToolFile lookup priority 2; may be an opaque file reference.
+ related_id: NotRequired[str | None] # ToolFile lookup priority 3; legacy persisted field.
+
+
+class DatasourceFileMapping(TypedDict):
+ transfer_method: _DatasourceFileTransferMethod
+ type: NotRequired[FileTypeValue | None] # Read for type override and upload config validation.
+ datasource_file_id: NotRequired[str | None] # UploadFile lookup priority 1 for datasource-backed files.
+ reference: NotRequired[str | None] # UploadFile lookup priority 2; may be an opaque file reference.
+ related_id: NotRequired[str | None] # UploadFile lookup priority 3; legacy persisted field.
+
+
+type FileMapping = LocalFileMapping | RemoteUrlMapping | ToolFileMapping | DatasourceFileMapping
+type FileMappingInput = FileMapping | Mapping[str, Any]
+
def build_from_mapping(
*,
- mapping: Mapping[str, Any],
+ mapping: FileMappingInput,
tenant_id: str,
config: FileUploadConfig | None = None,
strict_type_validation: bool = False,
@@ -32,18 +80,45 @@ def build_from_mapping(
if not transfer_method_value:
raise ValueError("transfer_method is required in file mapping")
- transfer_method = FileTransferMethod.value_of(transfer_method_value)
- build_func = _get_build_function(transfer_method)
- file = build_func(
- mapping=mapping,
- tenant_id=tenant_id,
- transfer_method=transfer_method,
- strict_type_validation=strict_type_validation,
- access_controller=access_controller,
- )
+ transfer_method = FileTransferMethod.value_of(str(transfer_method_value))
+ match transfer_method:
+ case FileTransferMethod.LOCAL_FILE:
+ file = _build_from_local_file(
+ mapping=cast(LocalFileMapping, mapping),
+ tenant_id=tenant_id,
+ transfer_method=transfer_method,
+ strict_type_validation=strict_type_validation,
+ access_controller=access_controller,
+ )
+ case FileTransferMethod.REMOTE_URL:
+ file = _build_from_remote_url(
+ mapping=cast(RemoteUrlMapping, mapping),
+ tenant_id=tenant_id,
+ transfer_method=transfer_method,
+ strict_type_validation=strict_type_validation,
+ access_controller=access_controller,
+ )
+ case FileTransferMethod.TOOL_FILE:
+ file = _build_from_tool_file(
+ mapping=cast(ToolFileMapping, mapping),
+ tenant_id=tenant_id,
+ transfer_method=transfer_method,
+ strict_type_validation=strict_type_validation,
+ access_controller=access_controller,
+ )
+ case FileTransferMethod.DATASOURCE_FILE:
+ file = _build_from_datasource_file(
+ mapping=cast(DatasourceFileMapping, mapping),
+ tenant_id=tenant_id,
+ transfer_method=transfer_method,
+ strict_type_validation=strict_type_validation,
+ access_controller=access_controller,
+ )
+ case _:
+ assert_never(transfer_method)
if config and not is_file_valid_with_config(
- input_file_type=mapping.get("type", FileType.CUSTOM),
+ input_file_type=mapping.get("type") or FileType.CUSTOM,
file_extension=file.extension or "",
file_transfer_method=file.transfer_method,
config=config,
@@ -87,36 +162,33 @@ def build_from_mappings(
return files
-def _get_build_function(transfer_method: FileTransferMethod):
- build_functions = {
- FileTransferMethod.LOCAL_FILE: _build_from_local_file,
- FileTransferMethod.REMOTE_URL: _build_from_remote_url,
- FileTransferMethod.TOOL_FILE: _build_from_tool_file,
- FileTransferMethod.DATASOURCE_FILE: _build_from_datasource_file,
- }
- build_func = build_functions.get(transfer_method)
- if build_func is None:
- raise ValueError(f"Invalid file transfer method: {transfer_method}")
- return build_func
-
-
def _resolve_file_type(
*,
detected_file_type: FileType,
- specified_type: str | None,
+ specified_type: FileTypeValue | str | None,
strict_type_validation: bool,
) -> FileType:
- if strict_type_validation and specified_type and detected_file_type.value != specified_type:
+ """Resolve the graph file type from detected metadata and submitted form type.
+
+ ``custom`` is a configured extension bucket rather than a MIME-derived type,
+ so strict validation must leave extension checks to the upload config.
+ """
+ if not specified_type:
+ return detected_file_type
+
+ specified_file_type = FileType(specified_type)
+ if specified_file_type == FileType.CUSTOM:
+ return FileType.CUSTOM
+
+ if strict_type_validation and detected_file_type != specified_file_type:
raise ValueError("Detected file type does not match the specified type. Please verify the file.")
- if specified_type and specified_type != "custom":
- return FileType(specified_type)
- return detected_file_type
+ return specified_file_type
def _build_from_local_file(
*,
- mapping: Mapping[str, Any],
+ mapping: LocalFileMapping,
tenant_id: str,
transfer_method: FileTransferMethod,
strict_type_validation: bool = False,
@@ -143,7 +215,7 @@ def _build_from_local_file(
detected_file_type = standardize_file_type(extension="." + row.extension, mime_type=row.mime_type)
file_type = _resolve_file_type(
detected_file_type=detected_file_type,
- specified_type=mapping.get("type", "custom"),
+ specified_type=mapping.get("type"),
strict_type_validation=strict_type_validation,
)
@@ -163,7 +235,7 @@ def _build_from_local_file(
def _build_from_remote_url(
*,
- mapping: Mapping[str, Any],
+ mapping: RemoteUrlMapping,
tenant_id: str,
transfer_method: FileTransferMethod,
strict_type_validation: bool = False,
@@ -235,7 +307,7 @@ def _build_from_remote_url(
def _build_from_tool_file(
*,
- mapping: Mapping[str, Any],
+ mapping: ToolFileMapping,
tenant_id: str,
transfer_method: FileTransferMethod,
strict_type_validation: bool = False,
@@ -278,7 +350,7 @@ def _build_from_tool_file(
def _build_from_datasource_file(
*,
- mapping: Mapping[str, Any],
+ mapping: DatasourceFileMapping,
tenant_id: str,
transfer_method: FileTransferMethod,
strict_type_validation: bool = False,
diff --git a/api/migrations/versions/2026_06_03_1416-8d4c2a1b9f03_add_human_input_upload_tables.py b/api/migrations/versions/2026_06_03_1416-8d4c2a1b9f03_add_human_input_upload_tables.py
new file mode 100644
index 00000000000..416f4a28e28
--- /dev/null
+++ b/api/migrations/versions/2026_06_03_1416-8d4c2a1b9f03_add_human_input_upload_tables.py
@@ -0,0 +1,64 @@
+"""Add human input upload token and file association tables
+
+Revision ID: 8d4c2a1b9f03
+Revises: 121e7346074d
+Create Date: 2026-06-03 14:16:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+import models
+
+# revision identifiers, used by Alembic.
+revision = "8d4c2a1b9f03"
+down_revision = "121e7346074d"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_table(
+ "human_input_form_upload_tokens",
+ sa.Column("id", models.types.StringUUID(), nullable=False),
+ sa.Column("created_at", sa.DateTime(), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
+ sa.Column("updated_at", sa.DateTime(), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
+ sa.Column("tenant_id", models.types.StringUUID(), nullable=False),
+ sa.Column("app_id", models.types.StringUUID(), nullable=False),
+ sa.Column("form_id", models.types.StringUUID(), nullable=False),
+ sa.Column("recipient_id", models.types.StringUUID(), nullable=False),
+ sa.Column("token", sa.String(length=255), nullable=False),
+ sa.PrimaryKeyConstraint("id", name="human_input_form_upload_tokens_pkey"),
+ sa.UniqueConstraint("token", name="human_input_form_upload_tokens_token_key"),
+ )
+ with op.batch_alter_table("human_input_form_upload_tokens", schema=None) as batch_op:
+ batch_op.create_index("human_input_form_upload_tokens_form_id_idx", ["form_id"], unique=False)
+
+ op.create_table(
+ "human_input_form_upload_files",
+ sa.Column("id", models.types.StringUUID(), nullable=False),
+ sa.Column("created_at", sa.DateTime(), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
+ sa.Column("updated_at", sa.DateTime(), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
+ sa.Column("tenant_id", models.types.StringUUID(), nullable=False),
+ sa.Column("app_id", models.types.StringUUID(), nullable=False),
+ sa.Column("form_id", models.types.StringUUID(), nullable=False),
+ sa.Column("upload_file_id", models.types.StringUUID(), nullable=False),
+ sa.Column("upload_token_id", models.types.StringUUID(), nullable=False),
+ sa.PrimaryKeyConstraint("id", name="human_input_form_upload_files_pkey"),
+ sa.UniqueConstraint("upload_file_id", name="human_input_form_upload_files_upload_file_id_key"),
+ )
+ with op.batch_alter_table("human_input_form_upload_files", schema=None) as batch_op:
+ batch_op.create_index("human_input_form_upload_files_form_id_idx", ["form_id"], unique=False)
+ batch_op.create_index("human_input_form_upload_files_upload_token_id_idx", ["upload_token_id"], unique=False)
+
+
+def downgrade():
+ with op.batch_alter_table("human_input_form_upload_files", schema=None) as batch_op:
+ batch_op.drop_index("human_input_form_upload_files_upload_token_id_idx")
+ batch_op.drop_index("human_input_form_upload_files_form_id_idx")
+ op.drop_table("human_input_form_upload_files")
+
+ with op.batch_alter_table("human_input_form_upload_tokens", schema=None) as batch_op:
+ batch_op.drop_index("human_input_form_upload_tokens_form_id_idx")
+ op.drop_table("human_input_form_upload_tokens")
diff --git a/api/models/__init__.py b/api/models/__init__.py
index c1c4a17f416..44f3a6231b3 100644
--- a/api/models/__init__.py
+++ b/api/models/__init__.py
@@ -60,7 +60,7 @@ from .enums import (
WorkflowTriggerStatus,
)
from .execution_extra_content import ExecutionExtraContent, HumanInputContent
-from .human_input import HumanInputForm
+from .human_input import HumanInputForm, HumanInputFormUploadFile, HumanInputFormUploadToken
from .model import (
AccountTrialAppRecord,
ApiRequest,
@@ -202,6 +202,8 @@ __all__ = [
"ExternalKnowledgeBindings",
"HumanInputContent",
"HumanInputForm",
+ "HumanInputFormUploadFile",
+ "HumanInputFormUploadToken",
"IconType",
"InstalledApp",
"InvitationCode",
diff --git a/api/models/human_input.py b/api/models/human_input.py
index 7447d3efcb3..7b02e8d29d5 100644
--- a/api/models/human_input.py
+++ b/api/models/human_input.py
@@ -251,3 +251,55 @@ class HumanInputFormRecipient(DefaultFieldsMixin, Base):
access_token=_generate_token(),
)
return recipient_model
+
+
+class HumanInputFormUploadToken(DefaultFieldsMixin, Base):
+ """Upload authorization token bound to one human input form recipient.
+
+ HITL upload tokens are intentionally separate from app/service bearer tokens.
+ The token is stored as an opaque random value so upload endpoints can perform
+ a direct lookup without entering the normal Web App authentication chain.
+ Upload ownership is resolved from the form's workflow run initiator instead
+ of being persisted on the token row itself.
+ """
+
+ __tablename__ = "human_input_form_upload_tokens"
+ __table_args__ = (
+ sa.UniqueConstraint("token", name="human_input_form_upload_tokens_token_key"),
+ sa.Index("human_input_form_upload_tokens_form_id_idx", "form_id"),
+ )
+
+ tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ form_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ recipient_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ token: Mapped[str] = mapped_column(sa.String(255), nullable=False)
+
+ form: Mapped[HumanInputForm] = relationship(
+ "HumanInputForm",
+ uselist=False,
+ foreign_keys=[form_id],
+ primaryjoin="foreign(HumanInputFormUploadToken.form_id) == HumanInputForm.id",
+ lazy="raise",
+ )
+
+
+class HumanInputFormUploadFile(DefaultFieldsMixin, Base):
+ """Association between a human input form and a file uploaded through its token.
+
+ Ownership remains on ``UploadFile`` itself; this table only records the
+ durable form/token/file linkage needed by Human Input flows.
+ """
+
+ __tablename__ = "human_input_form_upload_files"
+ __table_args__ = (
+ sa.UniqueConstraint("upload_file_id", name="human_input_form_upload_files_upload_file_id_key"),
+ sa.Index("human_input_form_upload_files_form_id_idx", "form_id"),
+ sa.Index("human_input_form_upload_files_upload_token_id_idx", "upload_token_id"),
+ )
+
+ tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ form_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ upload_file_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ upload_token_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
diff --git a/api/openapi/markdown/console-swagger.md b/api/openapi/markdown/console-swagger.md
index 5324ab2a145..555b063e595 100644
--- a/api/openapi/markdown/console-swagger.md
+++ b/api/openapi/markdown/console-swagger.md
@@ -13979,6 +13979,7 @@ Request payload for bulk downloading documents as a zip archive.
| node_id | string | | Yes |
| node_title | string | | Yes |
| rendered_content | string | | Yes |
+| submitted_data | object | | No |
#### HumanInputFormSubmitPayload
diff --git a/api/openapi/markdown/openapi-swagger.md b/api/openapi/markdown/openapi-swagger.md
index 899e09ff4a9..181d867f4fb 100644
--- a/api/openapi/markdown/openapi-swagger.md
+++ b/api/openapi/markdown/openapi-swagger.md
@@ -597,7 +597,7 @@ mode is a closed enum.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| action | string | | Yes |
-| inputs | object | | Yes |
+| inputs | object | Submitted human input values keyed by output variable name. Use a string for paragraph or select input values, a file mapping for file inputs, and a list of file mappings for file-list inputs. Local file mappings use `transfer_method=local_file` with `upload_file_id`; remote file mappings use `transfer_method=remote_url` with `url` or `remote_url`. | Yes |
#### JsonValue
diff --git a/api/openapi/markdown/service-swagger.md b/api/openapi/markdown/service-swagger.md
index 5bdb5264450..3de701f3f33 100644
--- a/api/openapi/markdown/service-swagger.md
+++ b/api/openapi/markdown/service-swagger.md
@@ -2923,7 +2923,7 @@ Note: The SQLAlchemy model defines an `is_anonymous` property for Flask-Login se
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| action | string | | Yes |
-| inputs | object | | Yes |
+| inputs | object | Submitted human input values keyed by output variable name. Use a string for paragraph or select input values, a file mapping for file inputs, and a list of file mappings for file-list inputs. Local file mappings use `transfer_method=local_file` with `upload_file_id`; remote file mappings use `transfer_method=remote_url` with `url` or `remote_url`. | Yes |
#### IndexInfoResponse
diff --git a/api/openapi/markdown/web-swagger.md b/api/openapi/markdown/web-swagger.md
index a7585d5b147..eafccdc04b7 100644
--- a/api/openapi/markdown/web-swagger.md
+++ b/api/openapi/markdown/web-swagger.md
@@ -461,6 +461,42 @@ Request body:
| ---- | ----------- |
| 200 | Success |
+### /form/human_input/{form_token}/upload-token
+
+#### POST
+##### Summary
+
+Issue an upload token for a human input form
+
+##### Description
+
+POST /api/form/human_input/<form_token>/upload-token
+
+##### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| form_token | path | | Yes | string |
+
+##### Responses
+
+| Code | Description |
+| ---- | ----------- |
+| 200 | Success |
+
+### /human-input-forms/files
+
+#### POST
+##### Summary
+
+Upload one local file or remote URL file for a HITL human input form
+
+##### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | File uploaded successfully | [FileResponse](#fileresponse) |
+
### /login
#### POST
@@ -1188,6 +1224,21 @@ Returns Server-Sent Events stream.
| email | string | | Yes |
| language | string | | No |
+#### HumanInputFileUploadFormPayload
+
+Parsed multipart form fields for HITL uploads.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| url | string (uri) | Remote file URL | No |
+
+#### HumanInputUploadTokenResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| expires_at | integer | | Yes |
+| upload_token | string | | Yes |
+
#### LicenseLimitationModel
- enabled: whether this limit is enforced
diff --git a/api/repositories/sqlalchemy_execution_extra_content_repository.py b/api/repositories/sqlalchemy_execution_extra_content_repository.py
index 67f8795d3fd..65a1edbf2d1 100644
--- a/api/repositories/sqlalchemy_execution_extra_content_repository.py
+++ b/api/repositories/sqlalchemy_execution_extra_content_repository.py
@@ -117,7 +117,7 @@ class SQLAlchemyExecutionExtraContentRepository(ExecutionExtraContentRepository)
definition_payload["expiration_time"] = form.expiration_time
form_definition = FormDefinition.model_validate(definition_payload)
except ValueError:
- logger.warning("Failed to load form definition for HumanInputContent(id=%s)", model.id)
+ logger.warning("Failed to load form definition for HumanInputContent(id=%s)", model.id, exc_info=True)
return None
node_title = form_definition.node_title or form.node_id
display_in_ui = bool(form_definition.display_in_ui)
@@ -125,21 +125,26 @@ class SQLAlchemyExecutionExtraContentRepository(ExecutionExtraContentRepository)
submitted = form.submitted_at is not None or form.status == HumanInputFormStatus.SUBMITTED
if not submitted:
form_token = self._resolve_form_token(recipients_by_form_id.get(form.id, []))
+ else:
+ form_token = None
+ form_definition_domain_model = HumanInputFormDefinition(
+ form_id=form.id,
+ node_id=form.node_id,
+ node_title=node_title,
+ form_content=form.rendered_content,
+ inputs=form_definition.inputs,
+ actions=form_definition.user_actions,
+ display_in_ui=display_in_ui,
+ form_token=form_token,
+ resolved_default_values=form_definition.default_values,
+ expiration_time=int(form.expiration_time.timestamp()),
+ )
+
+ if not submitted:
return HumanInputContentDomainModel(
workflow_run_id=model.workflow_run_id,
submitted=False,
- form_definition=HumanInputFormDefinition(
- form_id=form.id,
- node_id=form.node_id,
- node_title=node_title,
- form_content=form.rendered_content,
- inputs=form_definition.inputs,
- actions=form_definition.user_actions,
- display_in_ui=display_in_ui,
- form_token=form_token,
- resolved_default_values=form_definition.default_values,
- expiration_time=int(form.expiration_time.timestamp()),
- ),
+ form_definition=form_definition_domain_model,
)
selected_action_id = form.selected_action_id
@@ -164,17 +169,20 @@ class SQLAlchemyExecutionExtraContentRepository(ExecutionExtraContentRepository)
form.rendered_content,
submitted_data,
_extract_output_field_names(form_definition.form_content),
+ form_definition.inputs,
)
return HumanInputContentDomainModel(
workflow_run_id=model.workflow_run_id,
- submitted=True,
+ submitted=submitted,
+ form_definition=form_definition_domain_model,
form_submission_data=HumanInputFormSubmissionData(
node_id=form.node_id,
node_title=node_title,
rendered_content=rendered_content,
action_id=selected_action_id,
action_text=action_text,
+ submitted_data=submitted_data,
),
)
diff --git a/api/services/human_input_file_upload_service.py b/api/services/human_input_file_upload_service.py
new file mode 100644
index 00000000000..fe8912a2616
--- /dev/null
+++ b/api/services/human_input_file_upload_service.py
@@ -0,0 +1,244 @@
+from __future__ import annotations
+
+import secrets
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+
+from sqlalchemy import Engine, select
+from sqlalchemy.orm import Session, selectinload, sessionmaker
+
+from configs import dify_config
+from graphon.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus
+from libs.datetime_utils import ensure_naive_utc, naive_utc_now
+from models.account import Account, Tenant
+from models.enums import CreatorUserRole
+from models.human_input import (
+ HumanInputForm,
+ HumanInputFormRecipient,
+ HumanInputFormUploadFile,
+ HumanInputFormUploadToken,
+)
+from models.model import App, EndUser
+from repositories.api_workflow_run_repository import APIWorkflowRunRepository
+from services.human_input_service import FormExpiredError, FormNotFoundError, FormSubmittedError
+
+HITL_UPLOAD_TOKEN_PREFIX = "hitl_upload_"
+_TOKEN_RANDOM_BYTES = 32
+_TOKEN_GENERATION_ATTEMPTS = 10
+
+
+@dataclass(frozen=True)
+class HumanInputUploadToken:
+ upload_token: str
+ expires_at: datetime
+
+
+@dataclass(frozen=True)
+class HumanInputUploadContext:
+ tenant_id: str
+ app_id: str
+ form_id: str
+ recipient_id: str
+ upload_token_id: str
+ owner: Account | EndUser
+
+
+class InvalidUploadTokenError(Exception):
+ pass
+
+
+class HumanInputFileUploadService:
+ """Coordinates HITL upload tokens, workflow-run owners, and form-file links.
+
+ Standalone HITL uploads must be owned by the original workflow/chatflow
+ initiator so that resume-time file restoration continues to flow through the
+ normal file access checks. Delivery-test forms have no workflow run, so their
+ uploads are scoped to the app creator account inside the form tenant.
+ """
+
+ _session_maker: sessionmaker[Session]
+ _workflow_run_repository: APIWorkflowRunRepository
+
+ def __init__(
+ self,
+ session_factory: sessionmaker[Session] | Engine,
+ workflow_run_repository: APIWorkflowRunRepository,
+ ) -> None:
+ if isinstance(session_factory, Engine):
+ session_factory = sessionmaker(bind=session_factory)
+ self._session_maker = session_factory
+ self._workflow_run_repository = workflow_run_repository
+
+ def issue_upload_token(self, form_token: str) -> HumanInputUploadToken:
+ """Create an upload token for an active human input recipient token."""
+
+ with self._session_maker() as session, session.begin():
+ recipient_model = session.scalar(
+ select(HumanInputFormRecipient)
+ .options(selectinload(HumanInputFormRecipient.form))
+ .where(HumanInputFormRecipient.access_token == form_token)
+ .limit(1)
+ )
+ if recipient_model is None or recipient_model.form is None:
+ raise FormNotFoundError()
+
+ form = recipient_model.form
+ self._ensure_form_model_active(form)
+ upload_token = self._generate_unique_upload_token()
+ token_model = HumanInputFormUploadToken(
+ tenant_id=form.tenant_id,
+ app_id=form.app_id,
+ form_id=form.id,
+ recipient_id=recipient_model.id,
+ token=upload_token,
+ )
+ session.add(token_model)
+ # Snapshot the expiry before commit so callers do not depend on the
+ # session factory's expire_on_commit policy.
+ token = HumanInputUploadToken(upload_token=upload_token, expires_at=form.expiration_time)
+
+ return token
+
+ def validate_upload_token(self, upload_token: str) -> HumanInputUploadContext:
+ """Resolve an upload token and ensure the bound form is still active."""
+
+ query = (
+ select(HumanInputFormUploadToken)
+ .options(selectinload(HumanInputFormUploadToken.form))
+ .where(HumanInputFormUploadToken.token == upload_token)
+ .limit(1)
+ )
+ with self._session_maker(expire_on_commit=False) as session:
+ token_model = session.scalars(query).first()
+ if token_model is None:
+ raise InvalidUploadTokenError()
+
+ form_model = token_model.form
+ if form_model is None:
+ raise InvalidUploadTokenError()
+ self._ensure_form_model_active(form_model)
+
+ owner = self._resolve_upload_owner(session=session, form_model=form_model)
+
+ return HumanInputUploadContext(
+ tenant_id=token_model.tenant_id,
+ app_id=token_model.app_id,
+ form_id=token_model.form_id,
+ recipient_id=token_model.recipient_id,
+ upload_token_id=token_model.id,
+ owner=owner,
+ )
+
+ def record_upload_file(self, *, context: HumanInputUploadContext, file_id: str) -> None:
+ """Record that a file was uploaded through a specific form upload token."""
+
+ with self._session_maker() as session, session.begin():
+ session.add(
+ HumanInputFormUploadFile(
+ tenant_id=context.tenant_id,
+ app_id=context.app_id,
+ form_id=context.form_id,
+ upload_file_id=file_id,
+ upload_token_id=context.upload_token_id,
+ )
+ )
+
+ def _generate_unique_upload_token(self) -> str:
+ return f"{HITL_UPLOAD_TOKEN_PREFIX}{secrets.token_urlsafe(_TOKEN_RANDOM_BYTES)}"
+
+ def _resolve_upload_owner(
+ self,
+ *,
+ session: Session,
+ form_model: HumanInputForm,
+ ) -> Account | EndUser:
+ if form_model.workflow_run_id is None:
+ if form_model.form_kind == HumanInputFormKind.DELIVERY_TEST:
+ return self._resolve_delivery_test_upload_owner(session=session, form_model=form_model)
+ raise InvalidUploadTokenError()
+
+ workflow_run = self._workflow_run_repository.get_workflow_run_by_id(
+ tenant_id=form_model.tenant_id,
+ app_id=form_model.app_id,
+ run_id=form_model.workflow_run_id,
+ )
+ if workflow_run is None:
+ raise InvalidUploadTokenError()
+
+ if workflow_run.created_by_role == CreatorUserRole.END_USER:
+ end_user = session.scalar(
+ select(EndUser)
+ .where(
+ EndUser.id == workflow_run.created_by,
+ EndUser.tenant_id == workflow_run.tenant_id,
+ EndUser.app_id == workflow_run.app_id,
+ )
+ .limit(1)
+ )
+ if end_user is None:
+ raise InvalidUploadTokenError()
+ return end_user
+
+ if workflow_run.created_by_role != CreatorUserRole.ACCOUNT:
+ raise InvalidUploadTokenError()
+
+ account = session.scalar(select(Account).where(Account.id == workflow_run.created_by).limit(1))
+ if account is None:
+ raise InvalidUploadTokenError()
+
+ tenant = session.scalar(select(Tenant).where(Tenant.id == workflow_run.tenant_id).limit(1))
+ if tenant is None:
+ raise InvalidUploadTokenError()
+
+ # HITL upload runs outside the normal account auth flow, so hydrate the
+ # account tenant context explicitly before delegating to FileService.
+ account.current_tenant = tenant
+ return account
+
+ def _resolve_delivery_test_upload_owner(
+ self,
+ *,
+ session: Session,
+ form_model: HumanInputForm,
+ ) -> Account:
+ app = session.scalar(
+ select(App)
+ .where(
+ App.id == form_model.app_id,
+ App.tenant_id == form_model.tenant_id,
+ )
+ .limit(1)
+ )
+ if app is None or app.created_by is None:
+ raise InvalidUploadTokenError()
+
+ account = session.scalar(select(Account).where(Account.id == app.created_by).limit(1))
+ if account is None:
+ raise InvalidUploadTokenError()
+
+ tenant = session.scalar(select(Tenant).where(Tenant.id == form_model.tenant_id).limit(1))
+ if tenant is None:
+ raise InvalidUploadTokenError()
+
+ account.current_tenant = tenant
+ if account.current_tenant_id != form_model.tenant_id:
+ raise InvalidUploadTokenError()
+ return account
+
+ @staticmethod
+ def _ensure_form_model_active(form: HumanInputForm) -> None:
+ if form.submitted_at is not None or form.status == HumanInputFormStatus.SUBMITTED:
+ raise FormSubmittedError(form.id)
+ if form.status in {HumanInputFormStatus.TIMEOUT, HumanInputFormStatus.EXPIRED}:
+ raise FormExpiredError(form.id)
+
+ now = naive_utc_now()
+ if ensure_naive_utc(form.expiration_time) <= now:
+ raise FormExpiredError(form.id)
+
+ global_timeout_seconds = dify_config.HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS
+ if global_timeout_seconds <= 0 or form.workflow_run_id is None:
+ return
+ global_deadline = ensure_naive_utc(form.created_at) + timedelta(seconds=global_timeout_seconds)
+ if global_deadline <= now:
+ raise FormExpiredError(form.id)
diff --git a/api/services/human_input_service.py b/api/services/human_input_service.py
index 76598d31ace..dcddfe0f2c6 100644
--- a/api/services/human_input_service.py
+++ b/api/services/human_input_service.py
@@ -1,22 +1,37 @@
import logging
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from datetime import datetime, timedelta
-from typing import Any
+from typing import Any, Protocol, cast
+from pydantic import JsonValue, TypeAdapter, ValidationError
from sqlalchemy import Engine, select
from sqlalchemy.orm import Session, sessionmaker
from configs import dify_config
+from core.app.file_access import DatabaseFileAccessController
+from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext
from core.repositories.human_input_repository import (
HumanInputFormRecord,
HumanInputFormSubmissionRepository,
)
+from core.workflow.human_input_policy import resolve_variable_select_input_options
+from factories.file_factory import build_from_mapping, build_from_mappings
+from graphon.file import FileUploadConfig
from graphon.nodes.human_input.entities import (
+ FileInputConfig,
+ FileListInputConfig,
FormDefinition,
+ FormInputConfig,
HumanInputSubmissionValidationError,
- validate_human_input_submission,
+ SelectInputConfig,
+ UserActionConfig,
)
-from graphon.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus
+from graphon.nodes.human_input.entities import (
+ validate_human_input_submission as graphon_validate_human_input_submission,
+)
+from graphon.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus, ValueSourceType
+from graphon.runtime import GraphRuntimeState
+from graphon.runtime.graph_runtime_state_protocol import ReadOnlyVariablePool
from libs.datetime_utils import ensure_naive_utc, naive_utc_now
from libs.exception import BaseHTTPException
from models.human_input import RecipientType
@@ -24,6 +39,13 @@ from models.model import App, AppMode
from repositories.factory import DifyAPIRepositoryFactory
from tasks.app_generate.workflow_execute_task import resume_app_execution
+_file_access_controller = DatabaseFileAccessController()
+
+
+_JsonObjectAdapter: TypeAdapter[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue])
+_JsonValueAdapter: TypeAdapter[JsonValue] = TypeAdapter(JsonValue)
+_MappingSequenceAdapter: TypeAdapter[Sequence[Mapping[str, Any]]] = TypeAdapter(Sequence[Mapping[str, Any]])
+
class Form:
def __init__(self, record: HumanInputFormRecord):
@@ -82,7 +104,7 @@ class HumanInputError(Exception):
pass
-class FormSubmittedError(HumanInputError, BaseHTTPException):
+class FormSubmittedError(BaseHTTPException, HumanInputError):
error_code = "human_input_form_submitted"
description = "This form has already been submitted by another user, form_id={form_id}"
code = 412
@@ -90,37 +112,48 @@ class FormSubmittedError(HumanInputError, BaseHTTPException):
def __init__(self, form_id: str):
template = self.description or "This form has already been submitted by another user, form_id={form_id}"
description = template.format(form_id=form_id)
- super().__init__(description=description)
+ BaseHTTPException.__init__(self, description=description)
-class FormNotFoundError(HumanInputError, BaseHTTPException):
+class FormNotFoundError(BaseHTTPException, HumanInputError):
error_code = "human_input_form_not_found"
code = 404
-class InvalidFormDataError(HumanInputError, BaseHTTPException):
+class InvalidFormDataError(BaseHTTPException, HumanInputError):
error_code = "invalid_form_data"
code = 400
def __init__(self, description: str):
- super().__init__(description=description)
+ BaseHTTPException.__init__(self, description=description)
class WebAppDeliveryNotEnabledError(HumanInputError, BaseException):
pass
-class FormExpiredError(HumanInputError, BaseHTTPException):
+class FormExpiredError(BaseHTTPException, HumanInputError):
error_code = "human_input_form_expired"
code = 412
def __init__(self, form_id: str):
- super().__init__(description=f"This form has expired, form_id={form_id}")
+ BaseHTTPException.__init__(
+ self,
+ description=f"This form has expired, form_id={form_id}",
+ )
logger = logging.getLogger(__name__)
+class FormDefinitionProtocol(Protocol):
+ @property
+ def inputs(self) -> Sequence[FormInputConfig]: ...
+
+ @property
+ def user_actions(self) -> Sequence[UserActionConfig]: ...
+
+
class HumanInputService:
def __init__(
self,
@@ -152,12 +185,19 @@ class HumanInputService:
self._ensure_not_submitted(form)
return form
+ def resolve_form_inputs(self, form: Form) -> Sequence[FormInputConfig]:
+ variable_pool = self._load_variable_pool_for_form(form)
+ return resolve_variable_select_input_options(
+ form.get_definition().inputs,
+ variable_pool=variable_pool,
+ )
+
def submit_form_by_token(
self,
recipient_type: RecipientType,
form_token: str,
selected_action_id: str,
- form_data: Mapping[str, Any],
+ form_data: Mapping[str, JsonValue],
submission_end_user_id: str | None = None,
submission_user_id: str | None = None,
):
@@ -166,13 +206,17 @@ class HumanInputService:
raise WebAppDeliveryNotEnabledError()
self.ensure_form_active(form)
- self._validate_submission(form=form, selected_action_id=selected_action_id, form_data=form_data)
+ normalized_form_data = self._validate_submission(
+ form=form,
+ selected_action_id=selected_action_id,
+ form_data=form_data,
+ )
result = self._form_repository.mark_submitted(
form_id=form.id,
recipient_id=form.recipient_id,
selected_action_id=selected_action_id,
- form_data=form_data,
+ form_data=normalized_form_data,
submission_user_id=submission_user_id,
submission_end_user_id=submission_end_user_id,
)
@@ -198,12 +242,17 @@ class HumanInputService:
if form.submitted:
raise FormSubmittedError(form.id)
- def _validate_submission(self, form: Form, selected_action_id: str, form_data: Mapping[str, Any]) -> None:
+ def _validate_submission(
+ self,
+ form: Form,
+ selected_action_id: str,
+ form_data: Mapping[str, Any],
+ ) -> dict[str, JsonValue]:
definition = form.get_definition()
try:
- validate_human_input_submission(
- inputs=definition.inputs,
- user_actions=definition.user_actions,
+ return self.validate_and_normalize_submission(
+ tenant_id=form.tenant_id,
+ form_definition=definition,
selected_action_id=selected_action_id,
form_data=form_data,
)
@@ -237,6 +286,22 @@ class HumanInputService:
logger.warning("App mode %s does not support resume for workflow run %s", app.mode, workflow_run_id)
+ def _load_variable_pool_for_form(self, form: Form) -> ReadOnlyVariablePool | None:
+ workflow_run_id = form.workflow_run_id
+ if workflow_run_id is None:
+ return None
+
+ workflow_run_repo = DifyAPIRepositoryFactory.create_api_workflow_run_repository(self._session_factory)
+ pause_entity = workflow_run_repo.get_workflow_pause(workflow_run_id)
+
+ if pause_entity is None or pause_entity.resumed_at is not None:
+ return None
+
+ resumption_context = WorkflowResumptionContext.loads(pause_entity.get_state().decode())
+ runtime_state = GraphRuntimeState.from_snapshot(resumption_context.serialized_graph_runtime_state)
+
+ return runtime_state.variable_pool
+
def _is_globally_expired(self, form: Form, *, now: datetime | None = None) -> bool:
global_timeout_seconds = dify_config.HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS
if global_timeout_seconds <= 0:
@@ -247,3 +312,176 @@ class HumanInputService:
created_at = ensure_naive_utc(form.created_at)
global_deadline = created_at + timedelta(seconds=global_timeout_seconds)
return global_deadline <= current
+
+ @classmethod
+ def validate_and_normalize_submission(
+ cls,
+ *,
+ tenant_id: str,
+ form_definition: FormDefinitionProtocol,
+ selected_action_id: str,
+ form_data: Mapping[str, Any],
+ ) -> dict[str, JsonValue]:
+ """
+ Normalize Dify-owned runtime payloads before delegating shape validation to graphon.
+
+ graphon owns the form schema and validation rules, while Dify owns tenant-aware file
+ reconstruction and persistence compatibility for submitted payloads.
+ """
+ normalized_form_data = cls.normalize_submission_data(
+ tenant_id=tenant_id,
+ form_definition=form_definition,
+ form_data=form_data,
+ )
+ graphon_validate_human_input_submission(
+ inputs=form_definition.inputs,
+ user_actions=form_definition.user_actions,
+ selected_action_id=selected_action_id,
+ form_data=normalized_form_data,
+ )
+ return normalized_form_data
+
+ @classmethod
+ def normalize_submission_data(
+ cls,
+ *,
+ tenant_id: str,
+ form_definition: FormDefinitionProtocol,
+ form_data: Mapping[str, Any],
+ ) -> dict[str, JsonValue]:
+ normalized_form_data: dict[str, JsonValue] = _JsonObjectAdapter.validate_python(form_data)
+ inputs_by_name = {form_input.output_variable_name: form_input for form_input in form_definition.inputs}
+ for name, form_input in inputs_by_name.items():
+ if name not in form_data:
+ continue
+ normalized_form_data[name] = cls._normalize_input_value(
+ tenant_id=tenant_id,
+ form_input=form_input,
+ value=form_data[name],
+ )
+
+ return normalized_form_data
+
+ @classmethod
+ def _normalize_input_value(
+ cls,
+ *,
+ tenant_id: str,
+ form_input: FormInputConfig,
+ value: Any,
+ ) -> JsonValue:
+ if isinstance(form_input, SelectInputConfig):
+ return cls._normalize_select_value(form_input=form_input, value=value)
+ if isinstance(form_input, FileInputConfig):
+ return cls._normalize_file_value(
+ tenant_id=tenant_id,
+ form_input=form_input,
+ value=value,
+ )
+ if isinstance(form_input, FileListInputConfig):
+ return cls._normalize_file_list_value(
+ tenant_id=tenant_id,
+ form_input=form_input,
+ value=value,
+ )
+ return _JsonValueAdapter.validate_python(value)
+
+ @classmethod
+ def _normalize_select_value(
+ cls,
+ *,
+ form_input: SelectInputConfig,
+ value: Any,
+ ) -> JsonValue:
+ if not isinstance(value, str):
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for select input '{form_input.output_variable_name}': expected string"
+ )
+ option_source = form_input.option_source
+ if option_source.type == ValueSourceType.CONSTANT and value not in option_source.value:
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for select input '{form_input.output_variable_name}': {value}"
+ )
+ return value
+
+ @classmethod
+ def _normalize_file_value(
+ cls,
+ *,
+ tenant_id: str,
+ form_input: FileInputConfig,
+ value: Any,
+ ) -> JsonValue:
+ if not isinstance(value, Mapping):
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for file input '{form_input.output_variable_name}': expected mapping"
+ )
+ upload_config = cls._build_file_upload_config(form_input=form_input, number_limits=1)
+ try:
+ # `build_from_mapping` enforces tenant ownership for persisted upload references.
+ file = build_from_mapping(
+ mapping=value,
+ tenant_id=tenant_id,
+ config=upload_config,
+ strict_type_validation=True,
+ access_controller=_file_access_controller,
+ )
+ except ValueError as exc:
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for file input '{form_input.output_variable_name}': {exc}"
+ ) from exc
+ return cast(JsonValue, file.to_dict())
+
+ @classmethod
+ def _normalize_file_list_value(
+ cls,
+ *,
+ tenant_id: str,
+ form_input: FileListInputConfig,
+ value: Any,
+ ) -> JsonValue:
+ try:
+ validated_value = _MappingSequenceAdapter.validate_python(value)
+ except ValidationError as exc:
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for file list input '{form_input.output_variable_name}': {exc}"
+ ) from exc
+ if not isinstance(value, list):
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for file list input '{form_input.output_variable_name}': expected list"
+ )
+ if any(not isinstance(item, Mapping) for item in value):
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for file list input '{form_input.output_variable_name}': expected list of mappings"
+ )
+ upload_config = cls._build_file_upload_config(
+ form_input=form_input,
+ number_limits=form_input.number_limits,
+ )
+ try:
+ # `build_from_mappings` performs the same tenant-aware ownership validation in batch.
+ files = build_from_mappings(
+ mappings=validated_value,
+ tenant_id=tenant_id,
+ config=upload_config,
+ strict_type_validation=True,
+ access_controller=_file_access_controller,
+ )
+ except ValueError as exc:
+ raise HumanInputSubmissionValidationError(
+ f"Invalid value for file list input '{form_input.output_variable_name}': {exc}"
+ ) from exc
+ return cast(JsonValue, [file.to_dict() for file in files])
+
+ @staticmethod
+ def _build_file_upload_config(
+ *,
+ form_input: FileInputConfig | FileListInputConfig,
+ number_limits: int,
+ ) -> FileUploadConfig:
+ return FileUploadConfig(
+ allowed_file_types=list(form_input.allowed_file_types),
+ allowed_file_extensions=list(form_input.allowed_file_extensions),
+ allowed_file_upload_methods=list(form_input.allowed_file_upload_methods),
+ number_limits=number_limits,
+ )
diff --git a/api/services/workflow_event_snapshot_service.py b/api/services/workflow_event_snapshot_service.py
index 94f88f8c497..dad7dff292e 100644
--- a/api/services/workflow_event_snapshot_service.py
+++ b/api/services/workflow_event_snapshot_service.py
@@ -24,11 +24,17 @@ from core.app.entities.task_entities import (
)
from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext
from core.workflow.human_input_forms import load_form_tokens_by_form_id
-from core.workflow.human_input_policy import HumanInputSurface, enrich_human_input_pause_reasons
+from core.workflow.human_input_policy import (
+ HumanInputSurface,
+ enrich_human_input_pause_reasons,
+ resolve_human_input_pause_reason_inputs,
+ resolve_variable_select_input_options,
+)
from graphon.entities import WorkflowStartReason
-from graphon.entities.pause_reason import PauseReasonType
+from graphon.entities.pause_reason import HumanInputRequired, PauseReasonType
from graphon.enums import WorkflowExecutionStatus, WorkflowNodeExecutionStatus
from graphon.runtime import GraphRuntimeState
+from graphon.runtime.graph_runtime_state_protocol import ReadOnlyVariablePool
from graphon.workflow_type_encoder import WorkflowRuntimeTypeConverter
from models.human_input import HumanInputForm
from models.model import AppMode, Message
@@ -220,6 +226,7 @@ def _build_snapshot_events(
human_input_surface: HumanInputSurface | None = None,
) -> list[Mapping[str, Any]]:
events: list[Mapping[str, Any]] = []
+ variable_pool = _load_variable_pool_from_resumption_context(resumption_context)
workflow_started = _build_workflow_started_event(
workflow_run=workflow_run,
@@ -258,6 +265,7 @@ def _build_snapshot_events(
pause_entity=pause_entity,
session_maker=session_maker,
human_input_surface=human_input_surface,
+ variable_pool=variable_pool,
):
_apply_message_context(human_input_event, message_context)
events.append(human_input_event)
@@ -344,15 +352,10 @@ def _build_human_input_required_events(
pause_entity: WorkflowPauseEntity,
session_maker: sessionmaker[Session] | None,
human_input_surface: HumanInputSurface | None,
+ variable_pool: ReadOnlyVariablePool | None,
) -> list[dict[str, Any]]:
- reasons = [reason.model_dump(mode="json") for reason in pause_entity.get_pause_reasons()]
- human_input_form_ids = [
- form_id
- for reason in reasons
- if reason.get("TYPE") == PauseReasonType.HUMAN_INPUT_REQUIRED
- for form_id in [reason.get("form_id")]
- if isinstance(form_id, str)
- ]
+ reasons = pause_entity.get_pause_reasons()
+ human_input_form_ids = [reason.form_id for reason in reasons if isinstance(reason, HumanInputRequired)]
expiration_times_by_form_id: dict[str, int] = {}
display_in_ui_by_form_id: dict[str, bool] = {}
@@ -377,47 +380,33 @@ def _build_human_input_required_events(
events: list[dict[str, Any]] = []
for reason in reasons:
- if reason.get("TYPE") != PauseReasonType.HUMAN_INPUT_REQUIRED:
+ if not isinstance(reason, HumanInputRequired):
continue
- form_id_raw = reason.get("form_id")
- node_id_raw = reason.get("node_id")
- node_title_raw = reason.get("node_title")
- form_content_raw = reason.get("form_content")
- if not isinstance(form_id_raw, str):
- continue
- if not isinstance(node_id_raw, str):
- continue
- if not isinstance(node_title_raw, str):
- continue
- if not isinstance(form_content_raw, str):
- continue
- form_id = form_id_raw
- node_id = node_id_raw
- node_title = node_title_raw
- form_content = form_content_raw
-
- inputs = reason.get("inputs")
- actions = reason.get("actions")
- resolved_default_values = reason.get("resolved_default_values")
+ form_id = reason.form_id
expiration_time = expiration_times_by_form_id.get(form_id)
if expiration_time is None:
continue
+ resolved_inputs = resolve_variable_select_input_options(
+ reason.inputs,
+ variable_pool=variable_pool,
+ )
+
response = HumanInputRequiredResponse(
task_id=task_id,
workflow_run_id=workflow_run_id,
data=HumanInputRequiredResponse.Data(
form_id=form_id,
- node_id=node_id,
- node_title=node_title,
- form_content=form_content,
- inputs=inputs if isinstance(inputs, list) else [],
- actions=actions if isinstance(actions, list) else [],
+ node_id=reason.node_id,
+ node_title=reason.node_title,
+ form_content=reason.form_content,
+ inputs=resolved_inputs,
+ actions=reason.actions,
display_in_ui=display_in_ui_by_form_id.get(form_id, False),
form_token=form_tokens_by_form_id.get(form_id),
- resolved_default_values=(resolved_default_values if isinstance(resolved_default_values, dict) else {}),
+ resolved_default_values=reason.resolved_default_values,
expiration_time=expiration_time,
),
)
@@ -428,6 +417,16 @@ def _build_human_input_required_events(
return events
+def _load_variable_pool_from_resumption_context(
+ resumption_context: WorkflowResumptionContext | None,
+) -> ReadOnlyVariablePool | None:
+ if resumption_context is None:
+ return None
+ state = GraphRuntimeState.from_snapshot(resumption_context.serialized_graph_runtime_state)
+
+ return state.variable_pool
+
+
def _build_node_finished_event(
*,
workflow_run_id: str,
@@ -475,12 +474,18 @@ def _build_pause_event(
) -> dict[str, Any] | None:
paused_nodes: list[str] = []
outputs: dict[str, Any] = {}
+ variable_pool: ReadOnlyVariablePool | None = None
if resumption_context is not None:
state = GraphRuntimeState.from_snapshot(resumption_context.serialized_graph_runtime_state)
paused_nodes = state.get_paused_nodes()
outputs = dict(WorkflowRuntimeTypeConverter().to_json_encodable(state.outputs or {}))
+ variable_pool = state.variable_pool
- reasons = [reason.model_dump(mode="json") for reason in pause_entity.get_pause_reasons()]
+ resolved_pause_reasons = resolve_human_input_pause_reason_inputs(
+ pause_entity.get_pause_reasons(),
+ variable_pool=variable_pool,
+ )
+ reasons = [reason.model_dump(mode="json") for reason in resolved_pause_reasons]
human_input_form_ids = [
form_id
for reason in reasons
diff --git a/api/services/workflow_service.py b/api/services/workflow_service.py
index 36b760d37ae..50dd977749b 100644
--- a/api/services/workflow_service.py
+++ b/api/services/workflow_service.py
@@ -59,7 +59,7 @@ from graphon.node_events import NodeRunResult
from graphon.nodes import BuiltinNodeTypes
from graphon.nodes.base.node import Node
from graphon.nodes.http_request import HTTP_REQUEST_CONFIG_FILTER_KEY, build_http_request_config
-from graphon.nodes.human_input.entities import HumanInputNodeData, validate_human_input_submission
+from graphon.nodes.human_input.entities import HumanInputNodeData
from graphon.nodes.human_input.enums import HumanInputFormKind
from graphon.nodes.human_input.human_input_node import HumanInputNode
from graphon.nodes.start.entities import StartNodeData
@@ -82,6 +82,7 @@ from services.errors.app import (
WorkflowHashNotEqualError,
WorkflowNotFoundError,
)
+from services.human_input_service import HumanInputService
from services.workflow.workflow_converter import WorkflowConverter
from .errors.workflow_service import DraftWorkflowDeletionError, WorkflowInUseError
@@ -1020,7 +1021,7 @@ class WorkflowService:
manual_inputs=inputs or {},
user_id=account.id,
)
- node = self._build_human_input_node(
+ node = self._build_human_input_node_for_debugging(
workflow=draft_workflow,
account=account,
node_config=node_config,
@@ -1080,7 +1081,7 @@ class WorkflowService:
manual_inputs=inputs or {},
user_id=account.id,
)
- node = self._build_human_input_node(
+ node = self._build_human_input_node_for_debugging(
workflow=draft_workflow,
account=account,
node_config=node_config,
@@ -1088,9 +1089,10 @@ class WorkflowService:
)
node_data = node.node_data
- validate_human_input_submission(
- inputs=node_data.inputs,
- user_actions=node_data.user_actions,
+ human_input_service = HumanInputService(session_factory=sessionmaker(db.engine))
+ normalized_form_inputs = human_input_service.validate_and_normalize_submission(
+ tenant_id=app_model.tenant_id,
+ form_definition=node_data,
selected_action_id=action,
form_data=form_inputs,
)
@@ -1100,11 +1102,14 @@ class WorkflowService:
(user_action for user_action in node_data.user_actions if user_action.id == action),
None,
)
- outputs: dict[str, Any] = dict(form_inputs)
+ outputs: dict[str, Any] = dict(normalized_form_inputs)
outputs["__action_id"] = action
outputs["__action_value"] = selected_action.title if selected_action else ""
outputs["__rendered_content"] = node.render_form_content_with_outputs(
- rendered_content, outputs, node_data.outputs_field_names()
+ rendered_content,
+ outputs,
+ node_data.outputs_field_names(),
+ node_data.inputs,
)
enclosing_node_type_and_id = draft_workflow.get_enclosing_node_type_and_id(node_config)
@@ -1164,7 +1169,7 @@ class WorkflowService:
manual_inputs=inputs or {},
user_id=account.id,
)
- node = self._build_human_input_node(
+ node = self._build_human_input_node_for_debugging(
workflow=draft_workflow,
account=account,
node_config=node_config,
@@ -1257,7 +1262,7 @@ class WorkflowService:
recipients_data.append(DeliveryTestEmailRecipient(email=email, form_token=recipient.access_token))
return recipients_data
- def _build_human_input_node(
+ def _build_human_input_node_for_debugging(
self,
*,
workflow: Workflow,
@@ -1289,8 +1294,8 @@ class WorkflowService:
data=node_data,
graph_init_params=graph_init_params,
graph_runtime_state=graph_runtime_state,
- file_reference_factory=DifyFileReferenceFactory(graph_init_params.run_context),
runtime=DifyHumanInputNodeRuntime(run_context),
+ file_reference_factory=DifyFileReferenceFactory(run_context),
)
return node
diff --git a/api/tests/test_containers_integration_tests/controllers/web/test_human_input_form.py b/api/tests/test_containers_integration_tests/controllers/web/test_human_input_form.py
new file mode 100644
index 00000000000..c93b3dcb487
--- /dev/null
+++ b/api/tests/test_containers_integration_tests/controllers/web/test_human_input_form.py
@@ -0,0 +1,239 @@
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime, timedelta
+from typing import override
+from uuid import uuid4
+
+import pytest
+from flask.testing import FlaskClient
+from sqlalchemy import Engine
+from sqlalchemy.orm import Session, sessionmaker
+
+from core.app.app_config.entities import WorkflowUIBasedAppConfig
+from core.app.entities.app_invoke_entities import InvokeFrom, WorkflowAppGenerateEntity
+from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext, _WorkflowGenerateEntityWrapper
+from core.workflow.human_input_adapter import DeliveryMethodType
+from graphon.entities import WorkflowExecution
+from graphon.entities.pause_reason import HumanInputRequired
+from graphon.enums import WorkflowExecutionStatus
+from graphon.nodes.human_input.entities import FormDefinition, SelectInputConfig, StringListSource, UserActionConfig
+from graphon.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus, ValueSourceType
+from graphon.runtime import GraphRuntimeState, VariablePool
+from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
+from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
+from models.human_input import (
+ HumanInputDelivery,
+ HumanInputForm,
+ HumanInputFormRecipient,
+ RecipientType,
+ StandaloneWebAppRecipientPayload,
+)
+from models.model import App, AppMode, CustomizeTokenStrategy, Site
+from models.workflow import WorkflowRun, WorkflowType
+from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
+from services.feature_service import FeatureModel
+
+
+class _TestWorkflowRunRepository(DifyAPISQLAlchemyWorkflowRunRepository):
+ """Concrete repository for tests where save() is not under test."""
+
+ @override
+ def save(self, execution: WorkflowExecution) -> None:
+ return None
+
+
+def _create_app_with_site(session: Session) -> tuple[App, Account]:
+ tenant = Tenant(name="Test Tenant")
+ account = Account(name="Tester", email=f"tester-{uuid4()}@example.com")
+ session.add_all([tenant, account])
+ session.flush()
+
+ session.add(
+ TenantAccountJoin(
+ tenant_id=tenant.id,
+ account_id=account.id,
+ current=True,
+ role=TenantAccountRole.OWNER,
+ )
+ )
+
+ app = App(
+ tenant_id=tenant.id,
+ name="Test App",
+ description="",
+ mode=AppMode.WORKFLOW.value,
+ icon_type="emoji",
+ icon="app",
+ icon_background="#ffffff",
+ enable_site=True,
+ enable_api=True,
+ created_by=account.id,
+ updated_by=account.id,
+ )
+ session.add(app)
+ session.flush()
+
+ site = Site(
+ app_id=app.id,
+ title="Test Site",
+ icon_type="emoji",
+ icon="robot",
+ icon_background="#ffffff",
+ description="desc",
+ default_language="en",
+ chat_color_theme="light",
+ chat_color_theme_inverted=False,
+ customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
+ code=f"code-{uuid4().hex[:8]}",
+ prompt_public=False,
+ show_workflow_steps=True,
+ use_icon_as_answer_icon=False,
+ )
+ session.add(site)
+ session.flush()
+ return app, account
+
+
+def _build_resumption_context(*, app: App, workflow_run: WorkflowRun, options: list[str]) -> WorkflowResumptionContext:
+ app_config = WorkflowUIBasedAppConfig(
+ tenant_id=app.tenant_id,
+ app_id=app.id,
+ app_mode=AppMode.WORKFLOW,
+ workflow_id=workflow_run.workflow_id,
+ )
+ generate_entity = WorkflowAppGenerateEntity(
+ task_id="task-1",
+ app_config=app_config,
+ inputs={},
+ files=[],
+ user_id=str(uuid4()),
+ stream=True,
+ invoke_from=InvokeFrom.WEB_APP,
+ call_depth=0,
+ workflow_execution_id=workflow_run.id,
+ )
+ runtime_state = GraphRuntimeState(variable_pool=VariablePool(), start_at=0.0)
+ runtime_state.variable_pool.add(("start", "options"), options)
+ return WorkflowResumptionContext(
+ generate_entity=_WorkflowGenerateEntityWrapper(entity=generate_entity),
+ serialized_graph_runtime_state=runtime_state.dumps(),
+ )
+
+
+def test_get_human_input_form_resolves_runtime_select_options(
+ db_session_with_containers: Session,
+ test_client_with_containers: FlaskClient,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app, account = _create_app_with_site(db_session_with_containers)
+ workflow_run = WorkflowRun(
+ tenant_id=app.tenant_id,
+ app_id=app.id,
+ workflow_id=str(uuid4()),
+ type=WorkflowType.WORKFLOW,
+ triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
+ version="v1",
+ graph=None,
+ inputs="{}",
+ status=WorkflowExecutionStatus.RUNNING,
+ outputs="{}",
+ error=None,
+ elapsed_time=0.0,
+ total_tokens=0,
+ total_steps=0,
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by=account.id,
+ created_at=datetime.now(UTC).replace(tzinfo=None),
+ )
+ db_session_with_containers.add(workflow_run)
+ db_session_with_containers.flush()
+
+ configured_input = SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=["configured"],
+ ),
+ )
+ expiration_time = datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)
+ form_definition = FormDefinition(
+ form_content="Choose",
+ rendered_content="Choose",
+ inputs=[configured_input],
+ user_actions=[UserActionConfig(id="approve", title="Approve")],
+ expiration_time=expiration_time,
+ )
+ form = HumanInputForm(
+ tenant_id=app.tenant_id,
+ app_id=app.id,
+ workflow_run_id=workflow_run.id,
+ form_kind=HumanInputFormKind.RUNTIME,
+ node_id="human-node",
+ form_definition=form_definition.model_dump_json(),
+ rendered_content="Choose",
+ status=HumanInputFormStatus.WAITING,
+ expiration_time=expiration_time,
+ )
+ db_session_with_containers.add(form)
+ db_session_with_containers.flush()
+
+ delivery = HumanInputDelivery(
+ form_id=form.id,
+ delivery_method_type=DeliveryMethodType.WEBAPP,
+ channel_payload="{}",
+ )
+ db_session_with_containers.add(delivery)
+ db_session_with_containers.flush()
+
+ access_token = f"hitl{uuid4().hex[:18]}"
+ recipient = HumanInputFormRecipient(
+ form_id=form.id,
+ delivery_id=delivery.id,
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ recipient_payload=StandaloneWebAppRecipientPayload().model_dump_json(),
+ access_token=access_token,
+ )
+ db_session_with_containers.add(recipient)
+ db_session_with_containers.commit()
+
+ context = _build_resumption_context(
+ app=app,
+ workflow_run=workflow_run,
+ options=["approve", "reject"],
+ )
+ reason = HumanInputRequired(
+ form_id=form.id,
+ form_content="Choose",
+ inputs=[configured_input],
+ actions=[UserActionConfig(id="approve", title="Approve")],
+ node_id="human-node",
+ node_title="Human Input",
+ )
+ engine = db_session_with_containers.get_bind()
+ assert isinstance(engine, Engine)
+ workflow_run_repo = _TestWorkflowRunRepository(session_maker=sessionmaker(bind=engine, expire_on_commit=False))
+ workflow_run_repo.create_workflow_pause(
+ workflow_run_id=workflow_run.id,
+ state_owner_user_id=account.id,
+ state=context.dumps(),
+ pause_reasons=[reason],
+ )
+
+ def mock_get_features(tenant_id: str, exclude_vector_space: bool = False) -> FeatureModel:
+ features = FeatureModel(can_replace_logo=True)
+ return features
+
+ monkeypatch.setattr(
+ "controllers.web.site.FeatureService.get_features",
+ mock_get_features,
+ )
+
+ response = test_client_with_containers.get(f"/api/form/human_input/{access_token}")
+
+ assert response.status_code == 200, response.get_data(as_text=True)
+ body = json.loads(response.get_data(as_text=True))
+ assert body["inputs"][0]["option_source"]["type"] == "variable"
+ assert body["inputs"][0]["option_source"]["selector"] == ["start", "options"]
+ assert body["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
diff --git a/api/tests/test_containers_integration_tests/helpers/execution_extra_content.py b/api/tests/test_containers_integration_tests/helpers/execution_extra_content.py
index 2a1638d1268..dc8b3827c6f 100644
--- a/api/tests/test_containers_integration_tests/helpers/execution_extra_content.py
+++ b/api/tests/test_containers_integration_tests/helpers/execution_extra_content.py
@@ -132,6 +132,7 @@ def create_human_input_message_fixture(db_session) -> HumanInputMessageFixture:
status=HumanInputFormStatus.SUBMITTED,
expiration_time=naive_utc_now() + timedelta(days=1),
selected_action_id=action_id,
+ submitted_data='{"name": "Alice"}',
)
db_session.add(form)
db_session.flush()
diff --git a/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py b/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py
index 1ffc84c1679..3f3b3eae525 100644
--- a/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py
+++ b/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py
@@ -642,7 +642,7 @@ class TestBuildHumanInputRequiredReason:
expiration_time = naive_utc_now()
form_definition = FormDefinition(
form_content="content",
- inputs=[ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="name")],
+ inputs=[ParagraphInputConfig(output_variable_name="name")],
user_actions=[UserActionConfig(id="approve", title="Approve")],
rendered_content="rendered",
expiration_time=expiration_time,
diff --git a/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_execution_extra_content_repository.py b/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_execution_extra_content_repository.py
index 7da6f4a32db..4ce6bb98c3b 100644
--- a/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_execution_extra_content_repository.py
+++ b/api/tests/test_containers_integration_tests/repositories/test_sqlalchemy_execution_extra_content_repository.py
@@ -5,6 +5,7 @@ Part of #32454 — replaces the mock-based unit tests with real database interac
from __future__ import annotations
+import json
from collections.abc import Generator
from dataclasses import dataclass
from datetime import timedelta
@@ -174,11 +175,15 @@ def _create_submitted_form(
action_id: str = "approve",
action_title: str = "Approve",
node_title: str = "Approval",
+ form_content: str = "content",
+ rendered_content: str | None = None,
+ inputs: list[dict] | None = None,
+ submitted_data: dict | None = None,
) -> HumanInputForm:
expiration_time = naive_utc_now() + timedelta(days=1)
form_definition = FormDefinition(
- form_content="content",
- inputs=[],
+ form_content=form_content,
+ inputs=inputs or [],
user_actions=[UserActionConfig(id=action_id, title=action_title)],
rendered_content="rendered",
expiration_time=expiration_time,
@@ -191,10 +196,12 @@ def _create_submitted_form(
workflow_run_id=workflow_run_id,
node_id="node-id",
form_definition=form_definition.model_dump_json(),
- rendered_content=f"Rendered {action_title}",
+ rendered_content=rendered_content or f"Rendered {action_title}",
status=HumanInputFormStatus.SUBMITTED,
expiration_time=expiration_time,
selected_action_id=action_id,
+ submitted_data=None if submitted_data is None else json.dumps(submitted_data),
+ submitted_at=naive_utc_now(),
)
session.add(form)
session.flush()
@@ -349,6 +356,127 @@ class TestGetByMessageIds:
# msg2 has no content
assert result[1] == []
+ def test_submitted_content_populates_submission_data_from_stored_form_data(
+ self,
+ db_session_with_containers: Session,
+ repository: SQLAlchemyExecutionExtraContentRepository,
+ test_scope: _TestScope,
+ ) -> None:
+ workflow_run_id = str(uuid4())
+ conversation = _create_conversation(db_session_with_containers, test_scope)
+ msg = _create_message(db_session_with_containers, test_scope, conversation.id, workflow_run_id)
+ stored_submission_data = {"decision": "approve", "comment": "Looks good"}
+ form = _create_submitted_form(
+ db_session_with_containers,
+ test_scope,
+ workflow_run_id=workflow_run_id,
+ submitted_data=stored_submission_data,
+ )
+ _create_human_input_content(
+ db_session_with_containers,
+ workflow_run_id=workflow_run_id,
+ message_id=msg.id,
+ form_id=form.id,
+ )
+ db_session_with_containers.commit()
+
+ result = repository.get_by_message_ids([msg.id])
+
+ content = result[0][0]
+ assert content.form_submission_data is not None
+ assert content.form_submission_data.submitted_data == stored_submission_data
+
+ def test_submitted_content_exposes_select_and_file_form_data(
+ self,
+ db_session_with_containers: Session,
+ repository: SQLAlchemyExecutionExtraContentRepository,
+ test_scope: _TestScope,
+ ) -> None:
+ workflow_run_id = str(uuid4())
+ conversation = _create_conversation(db_session_with_containers, test_scope)
+ msg = _create_message(db_session_with_containers, test_scope, conversation.id, workflow_run_id)
+ submitted_data = {
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/file.txt",
+ "filename": "file.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ "attachments": [
+ {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/first.txt",
+ "filename": "first.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/second.txt",
+ "filename": "second.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ ],
+ }
+ form = _create_submitted_form(
+ db_session_with_containers,
+ test_scope,
+ workflow_run_id=workflow_run_id,
+ form_content=(
+ "Decision: {{#$output.decision#}}\n"
+ "Attachment: {{#$output.attachment#}}\n"
+ "Attachments: {{#$output.attachments#}}"
+ ),
+ rendered_content=(
+ "Decision: {{#$output.decision#}}\n"
+ "Attachment: {{#$output.attachment#}}\n"
+ "Attachments: {{#$output.attachments#}}"
+ ),
+ inputs=[
+ {
+ "type": "select",
+ "output_variable_name": "decision",
+ "option_source": {"type": "constant", "value": ["approve", "reject"]},
+ },
+ {
+ "type": "file",
+ "output_variable_name": "attachment",
+ "allowed_file_types": ["document"],
+ "allowed_file_upload_methods": ["remote_url"],
+ },
+ {
+ "type": "file-list",
+ "output_variable_name": "attachments",
+ "allowed_file_types": ["document"],
+ "allowed_file_upload_methods": ["remote_url"],
+ "number_limits": 3,
+ },
+ ],
+ submitted_data=submitted_data,
+ )
+ _create_human_input_content(
+ db_session_with_containers,
+ workflow_run_id=workflow_run_id,
+ message_id=msg.id,
+ form_id=form.id,
+ )
+ db_session_with_containers.commit()
+
+ result = repository.get_by_message_ids([msg.id])
+
+ content = result[0][0]
+ assert content.form_submission_data is not None
+ assert content.form_submission_data.submitted_data == submitted_data
+ assert content.form_submission_data.rendered_content == (
+ "Decision: approve\nAttachment: [file]\nAttachments: [2 files]"
+ )
+
def test_returns_unsubmitted_form_definition(
self,
db_session_with_containers: Session,
diff --git a/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py b/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py
index 80f9083e815..3e5905efbba 100644
--- a/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py
+++ b/api/tests/test_containers_integration_tests/services/test_human_input_delivery_test.py
@@ -1,9 +1,15 @@
import json
import uuid
+from io import BytesIO
from unittest.mock import MagicMock
+import httpx
import pytest
+from flask.testing import FlaskClient
+from sqlalchemy import select
+from sqlalchemy.orm import Session
+import controllers.web.human_input_file_upload as human_input_file_upload_module
from core.workflow.human_input_adapter import (
EmailDeliveryConfig,
EmailDeliveryMethod,
@@ -11,14 +17,21 @@ from core.workflow.human_input_adapter import (
ExternalRecipient,
)
from graphon.enums import BuiltinNodeTypes
-from graphon.nodes.human_input.entities import HumanInputNodeData
+from graphon.nodes.human_input.entities import FileInputConfig, HumanInputNodeData
+from graphon.nodes.human_input.enums import HumanInputFormKind
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
-from models.model import App, AppMode
+from models.human_input import HumanInputForm, HumanInputFormRecipient, HumanInputFormUploadFile
+from models.model import App, AppMode, UploadFile
from models.workflow import Workflow, WorkflowType
from services.workflow_service import WorkflowService
-def _create_app_with_draft_workflow(session, *, delivery_method_id: uuid.UUID) -> tuple[App, Account]:
+def _create_app_with_draft_workflow(
+ session: Session,
+ *,
+ delivery_method_id: uuid.UUID,
+ include_file_input: bool = False,
+) -> tuple[App, Account]:
tenant = Tenant(name="Test Tenant")
account = Account(name="Tester", email="[email protected]")
session.add_all([tenant, account])
@@ -65,7 +78,7 @@ def _create_app_with_draft_workflow(session, *, delivery_method_id: uuid.UUID) -
title="Human Input",
delivery_methods=[email_method],
form_content="Hello Human Input",
- inputs=[],
+ inputs=[FileInputConfig(output_variable_name="attachment")] if include_file_input else [],
user_actions=[],
).model_dump(mode="json")
node_data["type"] = BuiltinNodeTypes.HUMAN_INPUT
@@ -110,3 +123,167 @@ def test_human_input_delivery_test_sends_email(
assert send_mock.call_count == 1
assert send_mock.call_args.kwargs["to"] == "[email protected]"
+
+
+def test_human_input_delivery_test_form_accepts_file_upload(
+ db_session_with_containers: Session,
+ test_client_with_containers: FlaskClient,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ delivery_method_id = uuid.uuid4()
+ app, account = _create_app_with_draft_workflow(
+ db_session_with_containers,
+ delivery_method_id=delivery_method_id,
+ include_file_input=True,
+ )
+
+ monkeypatch.setattr("services.human_input_delivery_test_service.mail.is_inited", lambda: True)
+ monkeypatch.setattr("services.human_input_delivery_test_service.mail.send", MagicMock())
+
+ WorkflowService().test_human_input_delivery(
+ app_model=app,
+ account=account,
+ node_id="human-node",
+ delivery_method_id=str(delivery_method_id),
+ )
+
+ form = db_session_with_containers.scalar(
+ select(HumanInputForm)
+ .where(
+ HumanInputForm.app_id == app.id,
+ HumanInputForm.form_kind == HumanInputFormKind.DELIVERY_TEST,
+ HumanInputForm.workflow_run_id.is_(None),
+ )
+ .limit(1)
+ )
+ assert form is not None
+ recipient = db_session_with_containers.scalar(
+ select(HumanInputFormRecipient).where(HumanInputFormRecipient.form_id == form.id).limit(1)
+ )
+ assert recipient is not None
+ assert recipient.access_token is not None
+
+ token_response = test_client_with_containers.post(f"/api/form/human_input/{recipient.access_token}/upload-token")
+ assert token_response.status_code == 200
+ upload_token = token_response.get_json()["upload_token"]
+
+ upload_response = test_client_with_containers.post(
+ "/api/human-input-forms/files",
+ data={"file": (BytesIO(b"delivery test content"), "evidence.txt")},
+ content_type="multipart/form-data",
+ headers={"Authorization": f"Bearer {upload_token}"},
+ )
+
+ assert upload_response.status_code == 201, upload_response.get_data(as_text=True)
+ upload_file_id = upload_response.get_json()["id"]
+
+ db_session_with_containers.expire_all()
+ upload_file = db_session_with_containers.get(UploadFile, upload_file_id)
+ assert upload_file is not None
+ assert upload_file.tenant_id == app.tenant_id
+ assert upload_file.created_by == account.id
+ link = db_session_with_containers.scalar(
+ select(HumanInputFormUploadFile)
+ .where(
+ HumanInputFormUploadFile.form_id == form.id,
+ HumanInputFormUploadFile.upload_file_id == upload_file_id,
+ )
+ .limit(1)
+ )
+ assert link is not None
+
+
+def test_human_input_delivery_test_form_accepts_remote_file_upload(
+ db_session_with_containers: Session,
+ test_client_with_containers: FlaskClient,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ delivery_method_id = uuid.uuid4()
+ app, account = _create_app_with_draft_workflow(
+ db_session_with_containers,
+ delivery_method_id=delivery_method_id,
+ include_file_input=True,
+ )
+
+ monkeypatch.setattr("services.human_input_delivery_test_service.mail.is_inited", lambda: True)
+ monkeypatch.setattr("services.human_input_delivery_test_service.mail.send", MagicMock())
+
+ WorkflowService().test_human_input_delivery(
+ app_model=app,
+ account=account,
+ node_id="human-node",
+ delivery_method_id=str(delivery_method_id),
+ )
+
+ form = db_session_with_containers.scalar(
+ select(HumanInputForm)
+ .where(
+ HumanInputForm.app_id == app.id,
+ HumanInputForm.form_kind == HumanInputFormKind.DELIVERY_TEST,
+ HumanInputForm.workflow_run_id.is_(None),
+ )
+ .limit(1)
+ )
+ assert form is not None
+ recipient = db_session_with_containers.scalar(
+ select(HumanInputFormRecipient).where(HumanInputFormRecipient.form_id == form.id).limit(1)
+ )
+ assert recipient is not None
+ assert recipient.access_token is not None
+
+ token_response = test_client_with_containers.post(f"/api/form/human_input/{recipient.access_token}/upload-token")
+ assert token_response.status_code == 200
+ upload_token = token_response.get_json()["upload_token"]
+
+ remote_url = "https://example.com/evidence.txt"
+ remote_content = b"delivery test remote content"
+ head_response = httpx.Response(
+ 200,
+ request=httpx.Request("HEAD", remote_url),
+ headers={
+ "Content-Length": str(len(remote_content)),
+ "Content-Type": "text/plain",
+ },
+ )
+ get_response = httpx.Response(
+ 200,
+ request=httpx.Request("GET", remote_url),
+ headers={
+ "Content-Length": str(len(remote_content)),
+ "Content-Type": "text/plain",
+ },
+ content=remote_content,
+ )
+ head_mock = MagicMock(return_value=head_response)
+ get_mock = MagicMock(return_value=get_response)
+ monkeypatch.setattr(human_input_file_upload_module.ssrf_proxy, "head", head_mock)
+ monkeypatch.setattr(human_input_file_upload_module.ssrf_proxy, "get", get_mock)
+
+ upload_response = test_client_with_containers.post(
+ "/api/human-input-forms/files",
+ data={"url": remote_url},
+ content_type="multipart/form-data",
+ headers={"Authorization": f"Bearer {upload_token}"},
+ )
+
+ assert upload_response.status_code == 201, upload_response.get_data(as_text=True)
+ upload_file_id = upload_response.get_json()["id"]
+ assert upload_response.get_json()["url"]
+ head_mock.assert_called_once_with(url=remote_url)
+ get_mock.assert_called_once_with(remote_url)
+
+ db_session_with_containers.expire_all()
+ upload_file = db_session_with_containers.get(UploadFile, upload_file_id)
+ assert upload_file is not None
+ assert upload_file.tenant_id == app.tenant_id
+ assert upload_file.created_by == account.id
+ assert upload_file.source_url == remote_url
+ link = db_session_with_containers.scalar(
+ select(HumanInputFormUploadFile)
+ .where(
+ HumanInputFormUploadFile.form_id == form.id,
+ HumanInputFormUploadFile.upload_file_id == upload_file_id,
+ )
+ .limit(1)
+ )
+ assert link is not None
diff --git a/api/tests/test_containers_integration_tests/services/test_human_input_file_upload_service.py b/api/tests/test_containers_integration_tests/services/test_human_input_file_upload_service.py
new file mode 100644
index 00000000000..ac9a19c4c48
--- /dev/null
+++ b/api/tests/test_containers_integration_tests/services/test_human_input_file_upload_service.py
@@ -0,0 +1,78 @@
+import uuid
+from datetime import datetime, timedelta
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.orm import Session, sessionmaker
+
+import services.human_input_file_upload_service as service_module
+from extensions.ext_database import db
+from graphon.nodes.human_input.enums import HumanInputFormKind
+from libs.datetime_utils import naive_utc_now
+from models.human_input import (
+ HumanInputForm,
+ HumanInputFormRecipient,
+ HumanInputFormUploadToken,
+ StandaloneWebAppRecipientPayload,
+)
+from services.human_input_file_upload_service import HITL_UPLOAD_TOKEN_PREFIX, HumanInputFileUploadService
+
+
+def _create_waiting_form_recipient(
+ db_session_with_containers: Session,
+) -> tuple[str, str, datetime]:
+ form_id = "00000000-0000-0000-0000-000000000101"
+ recipient_id = "00000000-0000-0000-0000-000000000102"
+ expiration_time = naive_utc_now() + timedelta(hours=1)
+
+ db_session_with_containers.add(
+ HumanInputForm(
+ id=form_id,
+ tenant_id=str(uuid.uuid4()),
+ app_id=str(uuid.uuid4()),
+ workflow_run_id=None,
+ form_kind=HumanInputFormKind.DELIVERY_TEST,
+ node_id="human-node",
+ form_definition="{}",
+ rendered_content="content",
+ expiration_time=expiration_time,
+ )
+ )
+ db_session_with_containers.add(
+ HumanInputFormRecipient(
+ id=recipient_id,
+ form_id=form_id,
+ delivery_id=str(uuid.uuid4()),
+ recipient_type=StandaloneWebAppRecipientPayload().TYPE,
+ recipient_payload=StandaloneWebAppRecipientPayload().model_dump_json(),
+ access_token="form-token-1",
+ )
+ )
+ db_session_with_containers.commit()
+ return form_id, recipient_id, expiration_time
+
+
+def test_issue_upload_token_returns_expiration_with_default_session_expiry(
+ db_session_with_containers: Session,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ form_id, recipient_id, expiration_time = _create_waiting_form_recipient(db_session_with_containers)
+ monkeypatch.setattr(service_module.secrets, "token_urlsafe", lambda _bytes: "random-value")
+
+ service = HumanInputFileUploadService(
+ session_factory=sessionmaker(bind=db.engine),
+ workflow_run_repository=MagicMock(),
+ )
+
+ token = service.issue_upload_token("form-token-1")
+
+ assert token.upload_token == f"{HITL_UPLOAD_TOKEN_PREFIX}random-value"
+ assert token.expires_at == expiration_time
+
+ db_session_with_containers.expire_all()
+ token_model = db_session_with_containers.scalar(select(HumanInputFormUploadToken))
+ assert token_model is not None
+ assert token_model.form_id == form_id
+ assert token_model.recipient_id == recipient_id
+ assert token_model.token == token.upload_token
diff --git a/api/tests/test_containers_integration_tests/services/test_message_service_execution_extra_content.py b/api/tests/test_containers_integration_tests/services/test_message_service_execution_extra_content.py
index 52ebc0131f2..6a9046acd4a 100644
--- a/api/tests/test_containers_integration_tests/services/test_message_service_execution_extra_content.py
+++ b/api/tests/test_containers_integration_tests/services/test_message_service_execution_extra_content.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import pytest
from sqlalchemy.orm import Session
+from models.human_input import HumanInputFormStatus
from services.message_service import MessageService
from tests.test_containers_integration_tests.helpers.execution_extra_content import (
create_human_input_message_fixture,
@@ -23,17 +24,55 @@ def test_pagination_returns_extra_contents(db_session_with_containers: Session):
assert pagination.data
message = pagination.data[0]
- assert message.extra_contents == [
- {
- "type": "human_input",
- "workflow_run_id": fixture.message.workflow_run_id,
- "submitted": True,
- "form_submission_data": {
- "node_id": fixture.form.node_id,
- "node_title": fixture.node_title,
- "rendered_content": fixture.form.rendered_content,
- "action_id": fixture.action_id,
- "action_text": fixture.action_text,
- },
- }
- ]
+ assert len(message.extra_contents) == 1
+ content = message.extra_contents[0]
+ assert content["type"] == "human_input"
+ assert content["workflow_run_id"] == fixture.message.workflow_run_id
+ assert content["submitted"] is True
+
+ form_submission_data = content["form_submission_data"]
+ assert form_submission_data["node_id"] == fixture.form.node_id
+ assert form_submission_data["node_title"] == fixture.node_title
+ assert form_submission_data["rendered_content"] == fixture.form.rendered_content
+ assert form_submission_data["action_id"] == fixture.action_id
+ assert form_submission_data["action_text"] == fixture.action_text
+
+ form_definition = content["form_definition"]
+ assert form_definition["form_id"] == fixture.form.id
+ assert form_definition["node_id"] == fixture.form.node_id
+ assert form_definition["node_title"] == fixture.node_title
+ assert form_definition["form_content"] == fixture.form.rendered_content
+
+
[email protected]("flask_req_ctx_with_containers")
+def test_pagination_returns_waiting_human_input_extra_contents(db_session_with_containers: Session):
+ fixture = create_human_input_message_fixture(db_session_with_containers)
+ fixture.form.status = HumanInputFormStatus.WAITING
+ fixture.form.selected_action_id = None
+ fixture.form.submitted_at = None
+ fixture.form.submitted_data = None
+ db_session_with_containers.commit()
+
+ pagination = MessageService.pagination_by_first_id(
+ app_model=fixture.app,
+ user=fixture.account,
+ conversation_id=fixture.conversation.id,
+ first_id=None,
+ limit=10,
+ )
+
+ assert pagination.data
+ message = pagination.data[0]
+ assert len(message.extra_contents) == 1
+ content = message.extra_contents[0]
+ assert content["type"] == "human_input"
+ assert content["workflow_run_id"] == fixture.message.workflow_run_id
+ assert content["submitted"] is False
+ assert "form_submission_data" not in content
+
+ form_definition = content["form_definition"]
+ assert form_definition["form_id"] == fixture.form.id
+ assert form_definition["node_id"] == fixture.form.node_id
+ assert form_definition["node_title"] == fixture.node_title
+ assert form_definition["form_content"] == fixture.form.rendered_content
+ assert form_definition["display_in_ui"] is True
diff --git a/api/tests/test_containers_integration_tests/services/test_message_service_extra_contents.py b/api/tests/test_containers_integration_tests/services/test_message_service_extra_contents.py
index f2cb667204f..d76a925d0e9 100644
--- a/api/tests/test_containers_integration_tests/services/test_message_service_extra_contents.py
+++ b/api/tests/test_containers_integration_tests/services/test_message_service_extra_contents.py
@@ -4,6 +4,7 @@ from decimal import Decimal
import pytest
+from libs.helper import to_timestamp
from models.enums import ConversationFromSource
from models.model import Message
from services import message_service
@@ -47,17 +48,37 @@ def test_attach_message_extra_contents_assigns_serialized_payload(db_session_wit
message_service.attach_message_extra_contents(messages)
+ form = fixture.form
+
assert messages[0].extra_contents == [
{
"type": "human_input",
"workflow_run_id": fixture.message.workflow_run_id,
"submitted": True,
+ "form_definition": {
+ "form_id": form.id,
+ "node_id": form.node_id,
+ "node_title": "Approval",
+ "form_content": "Rendered block",
+ "inputs": [],
+ "actions": [
+ {
+ "id": "approve",
+ "title": "Approve request",
+ "button_style": "default",
+ }
+ ],
+ "display_in_ui": True,
+ "resolved_default_values": {},
+ "expiration_time": to_timestamp(form.expiration_time),
+ },
"form_submission_data": {
"node_id": fixture.form.node_id,
"node_title": fixture.node_title,
"rendered_content": fixture.form.rendered_content,
"action_id": fixture.action_id,
"action_text": fixture.action_text,
+ "submitted_data": {"name": "Alice"},
},
}
]
diff --git a/api/tests/test_containers_integration_tests/services/workflow/test_workflow_event_snapshot_service.py b/api/tests/test_containers_integration_tests/services/workflow/test_workflow_event_snapshot_service.py
new file mode 100644
index 00000000000..ce8b29c8407
--- /dev/null
+++ b/api/tests/test_containers_integration_tests/services/workflow/test_workflow_event_snapshot_service.py
@@ -0,0 +1,174 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import override
+from uuid import uuid4
+
+from sqlalchemy import Engine, delete
+from sqlalchemy.orm import Session, sessionmaker
+
+from core.app.app_config.entities import WorkflowUIBasedAppConfig
+from core.app.entities.app_invoke_entities import InvokeFrom, WorkflowAppGenerateEntity
+from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext, _WorkflowGenerateEntityWrapper
+from graphon.entities.pause_reason import HumanInputRequired
+from graphon.enums import WorkflowExecutionStatus
+from graphon.nodes.human_input.entities import SelectInputConfig, StringListSource, UserActionConfig
+from graphon.nodes.human_input.enums import HumanInputFormStatus, ValueSourceType
+from graphon.runtime import GraphRuntimeState, VariablePool
+from models.enums import CreatorUserRole
+from models.human_input import HumanInputForm
+from models.model import AppMode
+from models.workflow import WorkflowRun
+from repositories.entities.workflow_pause import WorkflowPauseEntity
+from services.workflow_event_snapshot_service import _build_snapshot_events
+
+
+@dataclass(frozen=True)
+class _FakePauseEntity(WorkflowPauseEntity):
+ pause_id: str
+ workflow_run_id: str
+ paused_at_value: datetime
+ pause_reasons: Sequence[HumanInputRequired]
+
+ @property
+ @override
+ def id(self) -> str:
+ return self.pause_id
+
+ @property
+ @override
+ def workflow_execution_id(self) -> str:
+ return self.workflow_run_id
+
+ @override
+ def get_state(self) -> bytes:
+ raise AssertionError("state is not required for snapshot tests")
+
+ @property
+ @override
+ def resumed_at(self) -> datetime | None:
+ return None
+
+ @property
+ @override
+ def paused_at(self) -> datetime:
+ return self.paused_at_value
+
+ @override
+ def get_pause_reasons(self) -> Sequence[HumanInputRequired]:
+ return self.pause_reasons
+
+
+def _build_resumption_context(workflow_run_id: str) -> WorkflowResumptionContext:
+ app_config = WorkflowUIBasedAppConfig(
+ tenant_id=str(uuid4()),
+ app_id=str(uuid4()),
+ app_mode=AppMode.WORKFLOW,
+ workflow_id=str(uuid4()),
+ )
+ generate_entity = WorkflowAppGenerateEntity(
+ task_id="task-1",
+ app_config=app_config,
+ inputs={},
+ files=[],
+ user_id=str(uuid4()),
+ stream=True,
+ invoke_from=InvokeFrom.EXPLORE,
+ call_depth=0,
+ workflow_execution_id=workflow_run_id,
+ )
+ runtime_state = GraphRuntimeState(variable_pool=VariablePool(), start_at=0.0)
+ runtime_state.variable_pool.add(("start", "options"), ["approve", "reject"])
+ wrapper = _WorkflowGenerateEntityWrapper(entity=generate_entity)
+ return WorkflowResumptionContext(
+ generate_entity=wrapper,
+ serialized_graph_runtime_state=runtime_state.dumps(),
+ )
+
+
+def _build_workflow_run(workflow_run_id: str) -> WorkflowRun:
+ return WorkflowRun(
+ id=workflow_run_id,
+ tenant_id=str(uuid4()),
+ app_id=str(uuid4()),
+ workflow_id=str(uuid4()),
+ type="workflow",
+ triggered_from="app-run",
+ version="v1",
+ graph=None,
+ inputs="{}",
+ status=WorkflowExecutionStatus.PAUSED,
+ outputs="{}",
+ error=None,
+ elapsed_time=0.0,
+ total_tokens=0,
+ total_steps=0,
+ created_by_role=CreatorUserRole.END_USER,
+ created_by=str(uuid4()),
+ created_at=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+
+
+def test_build_snapshot_events_resolves_variable_select_options(db_session_with_containers: Session) -> None:
+ engine = db_session_with_containers.get_bind()
+ assert isinstance(engine, Engine)
+ test_tenant_id = str(uuid4())
+ test_app_id = str(uuid4())
+ workflow_run_id = str(uuid4())
+ form = HumanInputForm(
+ tenant_id=test_tenant_id,
+ app_id=test_app_id,
+ workflow_run_id=workflow_run_id,
+ node_id="node-id",
+ form_definition='{"display_in_ui": true}',
+ rendered_content="Rendered",
+ status=HumanInputFormStatus.WAITING,
+ expiration_time=(datetime.now(UTC) + timedelta(hours=1)).replace(tzinfo=None),
+ )
+ db_session_with_containers.add(form)
+ db_session_with_containers.commit()
+ db_session_with_containers.refresh(form)
+
+ reason = HumanInputRequired(
+ form_id=form.id,
+ form_content="Rendered",
+ inputs=[
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=[],
+ ),
+ )
+ ],
+ actions=[UserActionConfig(id="approve", title="Approve")],
+ node_id="node-id",
+ node_title="Human Input",
+ )
+ pause_entity = _FakePauseEntity(
+ pause_id=str(uuid4()),
+ workflow_run_id=workflow_run_id,
+ paused_at_value=datetime.now(UTC),
+ pause_reasons=[reason],
+ )
+
+ session_maker = sessionmaker(bind=engine, expire_on_commit=False)
+ events = _build_snapshot_events(
+ workflow_run=_build_workflow_run(workflow_run_id),
+ node_snapshots=[],
+ task_id="task-1",
+ message_context=None,
+ pause_entity=pause_entity,
+ resumption_context=_build_resumption_context(workflow_run_id),
+ session_maker=session_maker,
+ )
+
+ human_input_events = [event for event in events if event.get("event") == "human_input_required"]
+ assert len(human_input_events) == 1
+ assert human_input_events[0]["data"]["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
+
+ db_session_with_containers.execute(delete(HumanInputForm).where(HumanInputForm.id == form.id))
+ db_session_with_containers.commit()
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py
index 58274f16888..78e1b0c46fa 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py
@@ -13,7 +13,6 @@ from controllers.web.error import NotFoundError
from graphon.entities.pause_reason import HumanInputRequired
from graphon.enums import WorkflowExecutionStatus
from graphon.nodes.human_input.entities import ParagraphInputConfig, UserActionConfig
-from graphon.nodes.human_input.enums import FormInputType
from libs import login as login_lib
from models.account import Account, AccountStatus, TenantAccountRole
from models.workflow import WorkflowRun
@@ -66,7 +65,7 @@ def test_pause_details_returns_backstage_input_url(app: Flask, monkeypatch: pyte
reason = HumanInputRequired(
form_id="form-1",
form_content="content",
- inputs=[ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="name")],
+ inputs=[ParagraphInputConfig(output_variable_name="name")],
actions=[UserActionConfig(id="approve", title="Approve")],
node_id="node-1",
node_title="Ask Name",
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py b/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
index ff668ac60ad..b2920f93d34 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
@@ -593,7 +593,11 @@ class TestHitlServiceApi:
form_id="form-1",
form_content="Rendered",
inputs=[
- ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="field", default=None),
+ ParagraphInputConfig(
+ type=FormInputType.PARAGRAPH,
+ output_variable_name="field",
+ default=None,
+ ),
],
actions=[UserActionConfig(id="approve", title="Approve")],
display_in_ui=True,
@@ -607,7 +611,7 @@ class TestHitlServiceApi:
paused_nodes=["node-id"],
)
- runtime_state = SimpleNamespace(total_tokens=0, node_run_steps=0)
+ runtime_state = SimpleNamespace(total_tokens=0, node_run_steps=0, variable_pool=VariablePool())
responses = converter.workflow_pause_to_stream_response(
event=queue_event,
task_id="task",
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_human_input_form.py b/api/tests/unit_tests/controllers/service_api/app/test_human_input_form.py
index 5d1c4b4e26a..ce000ab5a25 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_human_input_form.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_human_input_form.py
@@ -12,6 +12,7 @@ import pytest
from flask import Flask
from werkzeug.exceptions import NotFound
+from controllers.common.human_input import HumanInputFormSubmitPayload
from controllers.service_api.app.human_input_form import WorkflowHumanInputFormApi
from models.human_input import RecipientType
from tests.unit_tests.controllers.service_api.conftest import _unwrap
@@ -20,7 +21,7 @@ from tests.unit_tests.controllers.service_api.conftest import _unwrap
class TestWorkflowHumanInputFormApi:
def test_get_success(self, app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
definition = SimpleNamespace(
- model_dump=lambda: {
+ model_dump=lambda **_kwargs: {
"rendered_content": "Rendered form content",
"inputs": [{"output_variable_name": "name"}],
"default_values": {"name": "Alice", "age": 30, "meta": {"k": "v"}},
@@ -36,6 +37,9 @@ class TestWorkflowHumanInputFormApi:
)
service_mock = Mock()
service_mock.get_form_by_token.return_value = form
+ service_mock.resolve_form_inputs.return_value = [
+ SimpleNamespace(model_dump=lambda **_kwargs: {"output_variable_name": "name"})
+ ]
workflow_module = sys.modules["controllers.service_api.app.human_input_form"]
monkeypatch.setattr(workflow_module, "HumanInputService", lambda _engine: service_mock)
monkeypatch.setattr(workflow_module, "db", SimpleNamespace(engine=object()))
@@ -56,8 +60,54 @@ class TestWorkflowHumanInputFormApi:
"expiration_time": int(form.expiration_time.timestamp()),
}
service_mock.get_form_by_token.assert_called_once_with("token-1")
+ service_mock.resolve_form_inputs.assert_called_once_with(form)
service_mock.ensure_form_active.assert_called_once_with(form)
+ def test_get_resolves_runtime_select_values(self, app, monkeypatch: pytest.MonkeyPatch) -> None:
+ definition = SimpleNamespace(
+ model_dump=lambda **_kwargs: {
+ "rendered_content": "Rendered form content",
+ "inputs": [
+ {
+ "output_variable_name": "decision",
+ "option_source": {"type": "variable", "selector": ["start", "options"], "value": []},
+ }
+ ],
+ "default_values": {},
+ "user_actions": [{"id": "approve", "title": "Approve"}],
+ }
+ )
+ form = SimpleNamespace(
+ app_id="app-1",
+ tenant_id="tenant-1",
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ expiration_time=datetime(2099, 1, 1, tzinfo=UTC),
+ get_definition=lambda: definition,
+ )
+ resolved_input = SimpleNamespace(
+ model_dump=lambda **_kwargs: {
+ "output_variable_name": "decision",
+ "option_source": {"type": "variable", "selector": ["start", "options"], "value": ["approve", "reject"]},
+ }
+ )
+ service_mock = Mock()
+ service_mock.get_form_by_token.return_value = form
+ service_mock.resolve_form_inputs.return_value = [resolved_input]
+ workflow_module = sys.modules["controllers.service_api.app.human_input_form"]
+ monkeypatch.setattr(workflow_module, "HumanInputService", lambda _engine: service_mock)
+ monkeypatch.setattr(workflow_module, "db", SimpleNamespace(engine=object()))
+
+ api = WorkflowHumanInputFormApi()
+ handler = _unwrap(api.get)
+ app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")
+
+ with app.test_request_context("/form/human_input/token-1", method="GET"):
+ response = handler(api, app_model=app_model, form_token="token-1")
+
+ payload = json.loads(response.get_data(as_text=True))
+ assert payload["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
+ service_mock.resolve_form_inputs.assert_called_once_with(form)
+
def test_get_form_not_in_app(self, app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
form = SimpleNamespace(
app_id="another-app",
@@ -146,6 +196,71 @@ class TestWorkflowHumanInputFormApi:
submission_end_user_id="end-user-1",
)
+ def test_post_accepts_select_file_and_file_list_inputs(self, app, monkeypatch: pytest.MonkeyPatch) -> None:
+ form = SimpleNamespace(
+ app_id="app-1",
+ tenant_id="tenant-1",
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ )
+ service_mock = Mock()
+ service_mock.get_form_by_token.return_value = form
+ workflow_module = sys.modules["controllers.service_api.app.human_input_form"]
+ monkeypatch.setattr(workflow_module, "HumanInputService", lambda _engine: service_mock)
+ monkeypatch.setattr(workflow_module, "db", SimpleNamespace(engine=object()))
+
+ api = WorkflowHumanInputFormApi()
+ handler = _unwrap(api.post)
+ app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")
+ end_user = SimpleNamespace(id="end-user-1")
+ inputs = {
+ "decision": "approve",
+ "attachment": {
+ "transfer_method": "local_file",
+ "upload_file_id": "4e0d1b87-52f2-49f6-b8c6-95cd9c954b3e",
+ "type": "document",
+ },
+ "attachments": [
+ {
+ "transfer_method": "local_file",
+ "upload_file_id": "1a77f0df-c0e6-461c-987c-e72526f341ee",
+ "type": "document",
+ },
+ {
+ "transfer_method": "remote_url",
+ "url": "https://example.com/report.pdf",
+ "type": "document",
+ },
+ ],
+ }
+
+ with app.test_request_context(
+ "/form/human_input/token-1",
+ method="POST",
+ json={"inputs": inputs, "action": "approve", "user": "external-1"},
+ ):
+ response, status = handler(api, app_model=app_model, end_user=end_user, form_token="token-1")
+
+ assert response == {}
+ assert status == 200
+ service_mock.submit_form_by_token.assert_called_once_with(
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ form_token="token-1",
+ selected_action_id="approve",
+ form_data=inputs,
+ submission_end_user_id="end-user-1",
+ )
+
+ def test_submit_payload_schema_documents_select_file_and_file_list_inputs(self) -> None:
+ schema = HumanInputFormSubmitPayload.model_json_schema()
+
+ inputs_schema = schema["properties"]["inputs"]
+ assert "select input" in inputs_schema["description"]
+ examples = inputs_schema["examples"]
+ assert examples[0]["decision"] == "approve"
+ assert examples[0]["attachment"]["transfer_method"] == "local_file"
+ assert examples[0]["attachment"]["upload_file_id"] == "4e0d1b87-52f2-49f6-b8c6-95cd9c954b3e"
+ assert examples[0]["attachments"][1]["transfer_method"] == "remote_url"
+
@pytest.mark.parametrize(
"recipient_type",
[
diff --git a/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py b/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py
new file mode 100644
index 00000000000..a01a74b5353
--- /dev/null
+++ b/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py
@@ -0,0 +1,217 @@
+"""Unit tests for HITL human input file upload endpoints."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from io import BytesIO
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from flask import Flask
+
+import controllers.web.human_input_file_upload as upload_module
+from controllers.common.errors import NoFileUploadedError
+from controllers.web.human_input_file_upload import (
+ HumanInputFileUploadApi,
+ InvalidUploadTokenForbiddenError,
+ InvalidUploadTokenUnauthorizedError,
+)
+
+
+def app() -> Flask:
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ return app
+
+
+def _upload_context() -> SimpleNamespace:
+ return SimpleNamespace(
+ form_id="form-1",
+ upload_token_id="token-row-1",
+ owner=SimpleNamespace(id="owner-1", current_tenant_id="tenant-1"),
+ )
+
+
+def _upload_file() -> SimpleNamespace:
+ return SimpleNamespace(
+ id="file-1",
+ name="sample.txt",
+ size=7,
+ extension="txt",
+ mime_type="text/plain",
+ created_by="end-user-1",
+ created_at=datetime(2024, 1, 1),
+ tenant_id="tenant-1",
+ source_url="signed-source-url",
+ )
+
+
+def _patch_upload_service(monkeypatch: pytest.MonkeyPatch, service: MagicMock) -> tuple[MagicMock, dict[str, object]]:
+ workflow_run_repository = MagicMock()
+ repo_factory = MagicMock(return_value=workflow_run_repository)
+ captured: dict[str, object] = {}
+
+ def _service_factory(session_factory, workflow_run_repository):
+ captured["session_factory"] = session_factory
+ captured["workflow_run_repository"] = workflow_run_repository
+ return service
+
+ monkeypatch.setattr(
+ upload_module.DifyAPIRepositoryFactory,
+ "create_api_workflow_run_repository",
+ repo_factory,
+ )
+ monkeypatch.setattr(upload_module, "HumanInputFileUploadService", _service_factory)
+ return repo_factory, captured
+
+
+def test_human_input_file_upload_route_uses_unified_path() -> None:
+ urls = {
+ url for _resource, resource_urls, _route_doc, _kwargs in upload_module.web_ns.resources for url in resource_urls
+ }
+
+ assert "/human-input-forms/files" in urls
+ assert "/form/human_input/files/upload" not in urls
+ assert "/form/human_input/files/remote-upload" not in urls
+
+
+def test_local_upload_requires_authorization_before_reading_files(app: Flask) -> None:
+ data = {"file": (BytesIO(b"content"), "sample.txt")}
+
+ with app.test_request_context(
+ "/api/human-input-forms/files",
+ method="POST",
+ data=data,
+ content_type="multipart/form-data",
+ ):
+ with pytest.raises(InvalidUploadTokenUnauthorizedError):
+ HumanInputFileUploadApi().post()
+
+
+def test_local_upload_ignores_source_and_records_form_file_link(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None:
+ service = MagicMock()
+ service.validate_upload_token.return_value = _upload_context()
+ repo_factory, captured = _patch_upload_service(monkeypatch, service)
+
+ file_service = MagicMock()
+ file_service.upload_file.return_value = _upload_file()
+ file_service_cls = MagicMock(return_value=file_service)
+ monkeypatch.setattr(upload_module, "FileService", file_service_cls)
+ monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=object()))
+
+ data = {
+ "file": (BytesIO(b"content"), "sample.txt"),
+ "source": "datasets",
+ }
+ with app.test_request_context(
+ "/api/human-input-forms/files",
+ method="POST",
+ headers={"Authorization": "bearer hitl_upload_token-1"},
+ data=data,
+ content_type="multipart/form-data",
+ ):
+ result, status = HumanInputFileUploadApi().post()
+
+ assert status == 201
+ assert result["id"] == "file-1"
+ file_service.upload_file.assert_called_once()
+ assert file_service.upload_file.call_args.kwargs["source"] is None
+ assert file_service.upload_file.call_args.kwargs["user"].id == "owner-1"
+ repo_factory.assert_called_once()
+ assert captured["workflow_run_repository"] is repo_factory.return_value
+ service.record_upload_file.assert_called_once_with(
+ context=service.validate_upload_token.return_value,
+ file_id="file-1",
+ )
+
+
+def test_local_upload_missing_file_raises_after_valid_token(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None:
+ service = MagicMock()
+ service.validate_upload_token.return_value = _upload_context()
+ _patch_upload_service(monkeypatch, service)
+ monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=object()))
+
+ with app.test_request_context(
+ "/api/human-input-forms/files",
+ method="POST",
+ headers={"Authorization": "bearer hitl_upload_token-1"},
+ content_type="multipart/form-data",
+ ):
+ with pytest.raises(NoFileUploadedError):
+ HumanInputFileUploadApi().post()
+
+ service.validate_upload_token.assert_called_once_with("hitl_upload_token-1")
+
+
+def test_remote_upload_validates_token_before_fetching_remote_url(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None:
+ service = MagicMock()
+ service.validate_upload_token.side_effect = InvalidUploadTokenForbiddenError()
+ _patch_upload_service(monkeypatch, service)
+ monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=object()))
+ ssrf_proxy = MagicMock()
+ monkeypatch.setattr(upload_module, "ssrf_proxy", ssrf_proxy)
+
+ with app.test_request_context(
+ "/api/human-input-forms/files",
+ method="POST",
+ headers={"Authorization": "Bearer hitl_upload_token-1"},
+ data={"url": "https://example.com/file.txt"},
+ content_type="multipart/form-data",
+ ):
+ with pytest.raises(InvalidUploadTokenForbiddenError):
+ HumanInputFileUploadApi().post()
+
+ ssrf_proxy.head.assert_not_called()
+ ssrf_proxy.get.assert_not_called()
+
+
+def test_remote_upload_records_form_file_link(monkeypatch: pytest.MonkeyPatch, app: Flask) -> None:
+ service = MagicMock()
+ service.validate_upload_token.return_value = _upload_context()
+ _patch_upload_service(monkeypatch, service)
+ monkeypatch.setattr(upload_module, "db", SimpleNamespace(engine=object()))
+
+ response = MagicMock()
+ response.status_code = 200
+ response.content = b"remote"
+ response.request.method = "GET"
+ ssrf_proxy = MagicMock()
+ ssrf_proxy.head.return_value = response
+ monkeypatch.setattr(upload_module, "ssrf_proxy", ssrf_proxy)
+ monkeypatch.setattr(
+ upload_module.helpers,
+ "guess_file_info_from_response",
+ lambda _response: SimpleNamespace(filename="sample.txt", extension="txt", mimetype="text/plain", size=6),
+ )
+
+ file_service = MagicMock()
+ file_service.upload_file.return_value = _upload_file()
+ file_service_cls = MagicMock(return_value=file_service)
+ file_service_cls.is_file_size_within_limit.return_value = True
+ monkeypatch.setattr(upload_module, "FileService", file_service_cls)
+ monkeypatch.setattr(
+ upload_module.file_helpers,
+ "get_signed_file_url",
+ lambda upload_file_id: f"signed:{upload_file_id}",
+ )
+
+ with app.test_request_context(
+ "/api/human-input-forms/files",
+ method="POST",
+ headers={"Authorization": "Bearer hitl_upload_token-1"},
+ data={"url": "https://example.com/file.txt"},
+ content_type="multipart/form-data",
+ ):
+ result, status = HumanInputFileUploadApi().post()
+
+ assert status == 201
+ assert result["url"] == "signed:file-1"
+ file_service.upload_file.assert_called_once()
+ assert file_service.upload_file.call_args.kwargs["source_url"] == "https://example.com/file.txt"
+ assert file_service.upload_file.call_args.kwargs["user"].id == "owner-1"
+ service.record_upload_file.assert_called_once_with(
+ context=service.validate_upload_token.return_value,
+ file_id="file-1",
+ )
diff --git a/api/tests/unit_tests/controllers/web/test_human_input_form.py b/api/tests/unit_tests/controllers/web/test_human_input_form.py
index f9d49237b79..0caeae2cee4 100644
--- a/api/tests/unit_tests/controllers/web/test_human_input_form.py
+++ b/api/tests/unit_tests/controllers/web/test_human_input_form.py
@@ -15,10 +15,14 @@ from werkzeug.exceptions import Forbidden
import controllers.web.human_input_form as human_input_module
import controllers.web.site as site_module
from controllers.web.error import WebFormRateLimitExceededError
+from graphon.nodes.human_input.entities import ParagraphInputConfig, SelectInputConfig, StringListSource
+from graphon.nodes.human_input.enums import ValueSourceType
from models.human_input import RecipientType
+from services.feature_service import FeatureModel
from services.human_input_service import FormExpiredError
HumanInputFormApi = human_input_module.HumanInputFormApi
+HumanInputFormUploadTokenApi = human_input_module.HumanInputFormUploadTokenApi
TenantStatus = human_input_module.TenantStatus
@@ -63,7 +67,7 @@ def test_get_form_includes_site(monkeypatch: pytest.MonkeyPatch, app: Flask):
expiration_time = datetime(2099, 1, 1, tzinfo=UTC)
class _FakeDefinition:
- def model_dump(self):
+ def model_dump(self, mode: str | None = None):
return {
"form_content": "Raw content",
"rendered_content": "Rendered {{#$output.name#}}",
@@ -117,6 +121,8 @@ def test_get_form_includes_site(monkeypatch: pytest.MonkeyPatch, app: Flask):
# Patch service to return fake form.
service_mock = MagicMock()
service_mock.get_form_by_token.return_value = form
+ resolved_input = ParagraphInputConfig(output_variable_name="name")
+ service_mock.resolve_form_inputs.return_value = [resolved_input]
monkeypatch.setattr(human_input_module, "HumanInputService", lambda engine: service_mock)
# Patch db session.
@@ -142,7 +148,7 @@ def test_get_form_includes_site(monkeypatch: pytest.MonkeyPatch, app: Flask):
"expiration_time",
}
assert body["form_content"] == "Rendered {{#$output.name#}}"
- assert body["inputs"] == [{"type": "text", "output_variable_name": "name", "default": None}]
+ assert body["inputs"] == [resolved_input.model_dump(mode="json")]
assert body["resolved_default_values"] == {"name": "Alice", "age": "30", "meta": '{"k": "v"}'}
assert body["user_actions"] == [{"id": "approve", "title": "Approve", "button_style": "default"}]
assert body["expiration_time"] == int(expiration_time.timestamp())
@@ -180,13 +186,158 @@ def test_get_form_includes_site(monkeypatch: pytest.MonkeyPatch, app: Flask):
limiter_mock.increment_rate_limit.assert_called_once_with("203.0.113.10")
+def test_get_form_uses_runtime_select_options(monkeypatch: pytest.MonkeyPatch, app: Flask):
+ """GET returns variable-backed select options resolved from runtime state."""
+
+ expiration_time = datetime(2099, 1, 1, tzinfo=UTC)
+ configured_inputs = [
+ {
+ "type": "select",
+ "output_variable_name": "decision",
+ "option_source": {
+ "type": "variable",
+ "selector": ["start", "options"],
+ "value": ["configured"],
+ },
+ }
+ ]
+ runtime_inputs = [
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=["approve", "reject"],
+ ),
+ )
+ ]
+
+ class _FakeDefinition:
+ def model_dump(self, mode: str | None = None):
+ return {
+ "form_content": "Raw content",
+ "rendered_content": "Rendered",
+ "inputs": configured_inputs,
+ "default_values": {},
+ "user_actions": [],
+ }
+
+ class _FakeForm:
+ def __init__(self, expiration: datetime):
+ self.workflow_run_id = "workflow-1"
+ self.app_id = "app-1"
+ self.tenant_id = "tenant-1"
+ self.recipient_type = RecipientType.STANDALONE_WEB_APP
+ self.expiration_time = expiration
+
+ def get_definition(self):
+ return _FakeDefinition()
+
+ limiter_mock = MagicMock()
+ limiter_mock.is_rate_limited.return_value = False
+ monkeypatch.setattr(human_input_module, "_FORM_ACCESS_RATE_LIMITER", limiter_mock)
+ monkeypatch.setattr(human_input_module, "extract_remote_ip", lambda req: "203.0.113.10")
+
+ tenant = SimpleNamespace(
+ id="tenant-1",
+ status=TenantStatus.NORMAL,
+ plan="basic",
+ custom_config_dict={},
+ )
+ app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", tenant=tenant, enable_site=True)
+ site_model = SimpleNamespace(
+ title="My Site",
+ icon_type="emoji",
+ icon="robot",
+ icon_background="#fff",
+ description="desc",
+ default_language="en",
+ chat_color_theme="light",
+ chat_color_theme_inverted=False,
+ copyright=None,
+ privacy_policy=None,
+ custom_disclaimer=None,
+ prompt_public=False,
+ show_workflow_steps=True,
+ use_icon_as_answer_icon=False,
+ )
+
+ form = _FakeForm(expiration_time)
+ service_mock = MagicMock()
+ service_mock.get_form_by_token.return_value = form
+ service_mock.resolve_form_inputs.return_value = runtime_inputs
+ monkeypatch.setattr(human_input_module, "HumanInputService", lambda engine: service_mock)
+ monkeypatch.setattr(human_input_module, "db", _FakeDB(_FakeSession({"App": app_model, "Site": site_model})))
+
+ def mock_get_features(tenant_id: str, exclude_vector_space: bool = False):
+ return FeatureModel(can_replace_logo=True)
+
+ monkeypatch.setattr(site_module.FeatureService, "get_features", mock_get_features)
+
+ with app.test_request_context("/api/form/human_input/token-1", method="GET"):
+ response = HumanInputFormApi().get("token-1")
+
+ body = json.loads(response.get_data(as_text=True))
+ assert body["inputs"] == [input_config.model_dump(mode="json") for input_config in runtime_inputs]
+ service_mock.resolve_form_inputs.assert_called_once_with(form)
+
+
+def test_create_upload_token_returns_token_and_form_expiration(monkeypatch: pytest.MonkeyPatch, app: Flask):
+ """POST returns a HITL upload token for an active form token."""
+
+ expiration_time = datetime(2099, 1, 1, tzinfo=UTC)
+ service_mock = MagicMock()
+ service_mock.issue_upload_token.return_value = SimpleNamespace(
+ upload_token="hitl_upload_token-1",
+ expires_at=expiration_time,
+ )
+ workflow_run_repository = MagicMock()
+ repo_factory = MagicMock(return_value=workflow_run_repository)
+ captured: dict[str, object] = {}
+
+ def _service_factory(session_factory, workflow_run_repository):
+ captured["session_factory"] = session_factory
+ captured["workflow_run_repository"] = workflow_run_repository
+ return service_mock
+
+ monkeypatch.setattr(
+ human_input_module.DifyAPIRepositoryFactory,
+ "create_api_workflow_run_repository",
+ repo_factory,
+ )
+ monkeypatch.setattr(
+ human_input_module,
+ "HumanInputFileUploadService",
+ _service_factory,
+ )
+ monkeypatch.setattr(human_input_module, "db", SimpleNamespace(engine=object()))
+
+ limiter_mock = MagicMock()
+ limiter_mock.is_rate_limited.return_value = False
+ monkeypatch.setattr(human_input_module, "_FORM_UPLOAD_TOKEN_RATE_LIMITER", limiter_mock)
+ monkeypatch.setattr(human_input_module, "extract_remote_ip", lambda req: "203.0.113.10")
+
+ with app.test_request_context("/api/form/human_input/token-1/upload-token", method="POST"):
+ result, status = HumanInputFormUploadTokenApi().post("token-1")
+
+ assert status == 200
+ assert result == {
+ "upload_token": "hitl_upload_token-1",
+ "expires_at": int(expiration_time.timestamp()),
+ }
+ repo_factory.assert_called_once()
+ assert captured["workflow_run_repository"] is workflow_run_repository
+ service_mock.issue_upload_token.assert_called_once_with("token-1")
+ limiter_mock.increment_rate_limit.assert_called_once_with("203.0.113.10")
+
+
def test_get_form_allows_backstage_token(monkeypatch: pytest.MonkeyPatch, app: Flask):
"""GET returns form payload for backstage token."""
expiration_time = datetime(2099, 1, 2, tzinfo=UTC)
class _FakeDefinition:
- def model_dump(self):
+ def model_dump(self, mode: str | None = None):
return {
"form_content": "Raw content",
"rendered_content": "Rendered",
@@ -237,6 +388,7 @@ def test_get_form_allows_backstage_token(monkeypatch: pytest.MonkeyPatch, app: F
service_mock = MagicMock()
service_mock.get_form_by_token.return_value = form
+ service_mock.resolve_form_inputs.return_value = []
monkeypatch.setattr(human_input_module, "HumanInputService", lambda engine: service_mock)
db_stub = _FakeDB(_FakeSession({"WorkflowRun": workflow_run, "App": app_model, "Site": site_model}))
@@ -305,7 +457,7 @@ def test_get_form_raises_forbidden_when_site_missing(monkeypatch: pytest.MonkeyP
expiration_time = datetime(2099, 1, 3, tzinfo=UTC)
class _FakeDefinition:
- def model_dump(self):
+ def model_dump(self, mode: str | None = None):
return {
"form_content": "Raw content",
"rendered_content": "Rendered",
diff --git a/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_human_input.py b/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_human_input.py
index 1bef6f69cdd..9df351fb7aa 100644
--- a/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_human_input.py
+++ b/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_human_input.py
@@ -7,6 +7,7 @@ from core.app.entities.queue_entities import QueueHumanInputFormFilledEvent, Que
from core.workflow.system_variables import build_system_variables
from graphon.entities import WorkflowStartReason
from graphon.runtime import GraphRuntimeState, VariablePool
+from graphon.variables.segments import StringSegment
def _build_converter():
@@ -63,6 +64,37 @@ def test_human_input_form_filled_stream_response_contains_rendered_content():
assert resp.data.action_id == "Approve"
+def test_human_input_form_filled_stream_response_serializes_submitted_data():
+ converter = _build_converter()
+ converter.workflow_start_to_stream_response(
+ task_id="task-1",
+ workflow_run_id="run-1",
+ workflow_id="wf-1",
+ reason=WorkflowStartReason.INITIAL,
+ )
+
+ queue_event = QueueHumanInputFormFilledEvent(
+ node_execution_id="exec-1",
+ node_id="node-1",
+ node_type="human-input",
+ node_title="Human Input",
+ rendered_content="# Title\nvalue",
+ action_id="Approve",
+ action_text="Approve",
+ submitted_data={
+ "decision": StringSegment(value="approve"),
+ "comment": StringSegment(value="looks good"),
+ },
+ )
+
+ resp = converter.human_input_form_filled_to_stream_response(event=queue_event, task_id="task-1")
+
+ assert resp.data.submitted_data == {
+ "decision": "approve",
+ "comment": "looks good",
+ }
+
+
def test_human_input_form_timeout_stream_response_contains_timeout_metadata():
converter = _build_converter()
converter.workflow_start_to_stream_response(
diff --git a/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py b/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py
index 3949c41eae6..77cd81db58e 100644
--- a/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py
+++ b/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py
@@ -9,6 +9,7 @@ from core.app.apps.workflow_app_runner import WorkflowBasedAppRunner
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
from core.app.entities.queue_entities import (
QueueAgentLogEvent,
+ QueueHumanInputFormFilledEvent,
QueueIterationCompletedEvent,
QueueLoopCompletedEvent,
QueueNodeExceptionEvent,
@@ -30,6 +31,7 @@ from graphon.graph_events import (
NodeRunAgentLogEvent,
NodeRunExceptionEvent,
NodeRunFailedEvent,
+ NodeRunHumanInputFormFilledEvent,
NodeRunIterationSucceededEvent,
NodeRunLoopFailedEvent,
NodeRunRetryEvent,
@@ -39,6 +41,7 @@ from graphon.graph_events import (
)
from graphon.node_events import NodeRunResult
from graphon.runtime import GraphRuntimeState, VariablePool
+from graphon.variables.segments import StringSegment
from graphon.variables.variables import StringVariable
@@ -363,6 +366,42 @@ class TestWorkflowBasedAppRunner:
assert any(isinstance(event, QueueIterationCompletedEvent) for event in published)
assert any(isinstance(event, QueueLoopCompletedEvent) for event in published)
+ def test_handle_human_input_form_filled_event_preserves_submitted_data(self):
+ published: list[object] = []
+
+ class _QueueManager:
+ def publish(self, event, publish_from):
+ published.append(event)
+
+ runner = WorkflowBasedAppRunner(queue_manager=_QueueManager(), app_id="app")
+ graph_runtime_state = GraphRuntimeState(
+ variable_pool=VariablePool.from_bootstrap(
+ system_variables=default_system_variables(),
+ user_inputs={},
+ environment_variables=[],
+ ),
+ start_at=0.0,
+ )
+ workflow_entry = SimpleNamespace(graph_engine=SimpleNamespace(graph_runtime_state=graph_runtime_state))
+
+ runner._handle_event(
+ workflow_entry,
+ NodeRunHumanInputFormFilledEvent(
+ id="exec",
+ node_id="node",
+ node_type=BuiltinNodeTypes.HUMAN_INPUT,
+ node_title="Human Input",
+ rendered_content="content",
+ action_id="approve",
+ action_text="Approve",
+ submitted_data={"decision": StringSegment(value="approve")},
+ ),
+ )
+
+ queue_event = published[-1]
+ assert isinstance(queue_event, QueueHumanInputFormFilledEvent)
+ assert queue_event.submitted_data == {"decision": StringSegment(value="approve")}
+
@pytest.mark.parametrize(
("event_factory", "queue_event_cls"),
[
diff --git a/api/tests/unit_tests/core/app/apps/test_workflow_pause_events.py b/api/tests/unit_tests/core/app/apps/test_workflow_pause_events.py
index 72a46a74c96..319e603b351 100644
--- a/api/tests/unit_tests/core/app/apps/test_workflow_pause_events.py
+++ b/api/tests/unit_tests/core/app/apps/test_workflow_pause_events.py
@@ -14,8 +14,14 @@ from core.workflow.system_variables import build_system_variables
from graphon.entities import WorkflowStartReason
from graphon.entities.pause_reason import HumanInputRequired
from graphon.graph_events import GraphRunPausedEvent
-from graphon.nodes.human_input.entities import ParagraphInputConfig, UserActionConfig
-from graphon.nodes.human_input.enums import FormInputType
+from graphon.nodes.human_input.entities import (
+ ParagraphInputConfig,
+ SelectInputConfig,
+ StringListSource,
+ UserActionConfig,
+)
+from graphon.nodes.human_input.enums import ValueSourceType
+from graphon.runtime import GraphRuntimeState, VariablePool
from models.account import Account
from models.human_input import RecipientType
@@ -156,9 +162,7 @@ def test_queue_workflow_paused_event_to_stream_responses(monkeypatch: pytest.Mon
reason = HumanInputRequired(
form_id="form-1",
form_content="Rendered",
- inputs=[
- ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="field", default=None),
- ],
+ inputs=[ParagraphInputConfig(output_variable_name="field")],
actions=[UserActionConfig(id="approve", title="Approve")],
node_id="node-id",
node_title="Human Step",
@@ -169,7 +173,7 @@ def test_queue_workflow_paused_event_to_stream_responses(monkeypatch: pytest.Mon
paused_nodes=["node-id"],
)
- runtime_state = SimpleNamespace(total_tokens=0, node_run_steps=0)
+ runtime_state = GraphRuntimeState(variable_pool=VariablePool(), start_at=0.0)
responses = converter.workflow_pause_to_stream_response(
event=queue_event,
task_id="task",
@@ -193,3 +197,70 @@ def test_queue_workflow_paused_event_to_stream_responses(monkeypatch: pytest.Mon
assert hi_resp.data.display_in_ui is True
assert hi_resp.data.form_token == "backstage-token"
assert hi_resp.data.expiration_time == int(expiration_time.timestamp())
+
+
+def test_queue_workflow_paused_event_resolves_variable_select_options(monkeypatch: pytest.MonkeyPatch):
+ converter = _build_converter()
+ converter.workflow_start_to_stream_response(
+ task_id="task",
+ workflow_run_id="run-id",
+ workflow_id="workflow-id",
+ reason=WorkflowStartReason.INITIAL,
+ )
+
+ expiration_time = datetime(2024, 1, 1, tzinfo=UTC)
+
+ class _FakeSession:
+ def execute(self, _stmt):
+ return [("form-1", expiration_time, '{"display_in_ui": true}')]
+
+ def scalars(self, _stmt):
+ return []
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc, tb):
+ return False
+
+ monkeypatch.setattr(workflow_response_converter, "Session", lambda **_: _FakeSession())
+ monkeypatch.setattr(workflow_response_converter, "db", SimpleNamespace(engine=object()))
+
+ reason = HumanInputRequired(
+ form_id="form-1",
+ form_content="Rendered",
+ inputs=[
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=[],
+ ),
+ )
+ ],
+ actions=[UserActionConfig(id="approve", title="Approve")],
+ node_id="node-id",
+ node_title="Human Step",
+ )
+ queue_event = QueueWorkflowPausedEvent(
+ reasons=[reason],
+ outputs={},
+ paused_nodes=["node-id"],
+ )
+
+ runtime_state = GraphRuntimeState(variable_pool=VariablePool(), start_at=0.0)
+ runtime_state.variable_pool.add(("start", "options"), ["approve", "reject"])
+ responses = converter.workflow_pause_to_stream_response(
+ event=queue_event,
+ task_id="task",
+ graph_runtime_state=runtime_state,
+ )
+
+ assert isinstance(responses[0], HumanInputRequiredResponse)
+ hi_resp = responses[0]
+ assert hi_resp.data.inputs[0].option_source.value == ["approve", "reject"]
+
+ assert isinstance(responses[-1], WorkflowPauseStreamResponse)
+ pause_resp = responses[-1]
+ assert pause_resp.data.reasons[0]["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
diff --git a/api/tests/unit_tests/core/entities/test_entities_execution_extra_content.py b/api/tests/unit_tests/core/entities/test_entities_execution_extra_content.py
index 26421799921..d0849e7b881 100644
--- a/api/tests/unit_tests/core/entities/test_entities_execution_extra_content.py
+++ b/api/tests/unit_tests/core/entities/test_entities_execution_extra_content.py
@@ -5,7 +5,6 @@ from core.entities.execution_extra_content import (
HumanInputFormSubmissionData,
)
from graphon.nodes.human_input.entities import ParagraphInputConfig, UserActionConfig
-from graphon.nodes.human_input.enums import FormInputType
from models.execution_extra_content import ExecutionContentType
@@ -16,7 +15,7 @@ def test_human_input_content_defaults_and_domain_alias() -> None:
node_id="node-1",
node_title="Human Input",
form_content="Please confirm",
- inputs=[ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="answer")],
+ inputs=[ParagraphInputConfig(output_variable_name="answer")],
actions=[UserActionConfig(id="confirm", title="Confirm")],
resolved_default_values={"answer": "yes"},
expiration_time=1_700_000_000,
@@ -27,6 +26,7 @@ def test_human_input_content_defaults_and_domain_alias() -> None:
rendered_content="Please confirm",
action_id="confirm",
action_text="Confirm",
+ submitted_data={"answer": "yes"},
)
# Act
@@ -42,4 +42,5 @@ def test_human_input_content_defaults_and_domain_alias() -> None:
assert content.type == ExecutionContentType.HUMAN_INPUT
assert content.form_definition is form_definition
assert content.form_submission_data is submission_data
+ assert content.form_submission_data.submitted_data == {"answer": "yes"}
assert ExecutionExtraContentDomainModel is HumanInputContent
diff --git a/api/tests/unit_tests/core/repositories/test_human_input_repository.py b/api/tests/unit_tests/core/repositories/test_human_input_repository.py
index 418537675d7..edd8be86184 100644
--- a/api/tests/unit_tests/core/repositories/test_human_input_repository.py
+++ b/api/tests/unit_tests/core/repositories/test_human_input_repository.py
@@ -586,6 +586,73 @@ def test_mark_submitted_updates_and_raises_when_missing(monkeypatch: pytest.Monk
assert record.submitted_data == {"k": "v"}
+def test_mark_submitted_serializes_select_and_file_payloads(monkeypatch: pytest.MonkeyPatch) -> None:
+ fixed_now = datetime(2024, 1, 1, 0, 0, 0)
+ monkeypatch.setattr("core.repositories.human_input_repository.naive_utc_now", lambda: fixed_now)
+
+ form = _DummyForm(
+ id="f-complex",
+ workflow_run_id=None,
+ node_id="node",
+ tenant_id="tenant",
+ app_id="app",
+ form_definition=_make_form_definition_json(include_expiration_time=True),
+ rendered_content="<p>x</p>",
+ expiration_time=fixed_now,
+ )
+ recipient = _DummyRecipient(
+ id="r-complex",
+ form_id=form.id,
+ recipient_type=RecipientType.CONSOLE,
+ access_token="tok",
+ )
+ session = _FakeSession(forms={form.id: form}, recipients={recipient.id: recipient})
+ _patch_session_factory(monkeypatch, session)
+
+ payload = {
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/file.txt",
+ "filename": "file.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ "attachments": [
+ {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/first.txt",
+ "filename": "first.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/second.txt",
+ "filename": "second.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ ],
+ }
+
+ repo = HumanInputFormSubmissionRepository()
+ record = repo.mark_submitted(
+ form_id=form.id,
+ recipient_id=recipient.id,
+ selected_action_id="approve",
+ form_data=payload,
+ submission_user_id="user-1",
+ submission_end_user_id="end-user-1",
+ )
+
+ assert json.loads(form.submitted_data or "") == payload
+ assert record.submitted_data == payload
+
+
def test_mark_timeout_invalid_status_raises(monkeypatch: pytest.MonkeyPatch) -> None:
form = _DummyForm(
id="f",
diff --git a/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.py b/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.py
index c3e6f5d76c3..55dcbdb7a11 100644
--- a/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.py
+++ b/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.py
@@ -81,7 +81,7 @@ class MockNodeMixin:
if isinstance(self, TemplateTransformNode):
kwargs.setdefault("jinja2_template_renderer", _TestJinja2Renderer())
- # Provide default ToolNode dependencies for ToolNode subclasses.
+ # Provide default tool_file_manager for ToolNode subclasses
from graphon.nodes.tool import ToolNode as _ToolNode # local import to avoid cycles
if isinstance(self, _ToolNode):
diff --git a/api/tests/unit_tests/core/workflow/graph_engine/test_parallel_human_input_join_resume.py b/api/tests/unit_tests/core/workflow/graph_engine/test_parallel_human_input_join_resume.py
index fd6263be192..a16a8b481a6 100644
--- a/api/tests/unit_tests/core/workflow/graph_engine/test_parallel_human_input_join_resume.py
+++ b/api/tests/unit_tests/core/workflow/graph_engine/test_parallel_human_input_join_resume.py
@@ -12,6 +12,7 @@ from core.repositories.human_input_repository import (
from core.workflow.node_runtime import DifyFileReferenceFactory, DifyHumanInputNodeRuntime
from core.workflow.system_variables import build_system_variables
from graphon.entities import WorkflowStartReason
+from graphon.file import File, FileTransferMethod, FileType
from graphon.graph import Graph
from graphon.graph_engine import GraphEngine, GraphEngineConfig
from graphon.graph_engine.command_channels import InMemoryChannel
@@ -24,8 +25,15 @@ from graphon.graph_events import (
from graphon.nodes.base.entities import OutputVariableEntity
from graphon.nodes.end.end_node import EndNode
from graphon.nodes.end.entities import EndNodeData
-from graphon.nodes.human_input.entities import HumanInputNodeData, UserActionConfig
-from graphon.nodes.human_input.enums import HumanInputFormStatus
+from graphon.nodes.human_input.entities import (
+ FileInputConfig,
+ FileListInputConfig,
+ HumanInputNodeData,
+ SelectInputConfig,
+ StringListSource,
+ UserActionConfig,
+)
+from graphon.nodes.human_input.enums import HumanInputFormStatus, ValueSourceType
from graphon.nodes.human_input.human_input_node import HumanInputNode
from graphon.nodes.start.entities import StartNodeData
from graphon.nodes.start.start_node import StartNode
@@ -52,6 +60,21 @@ class InMemoryPauseStore:
return GraphRuntimeState.from_snapshot(self._snapshot)
+class _TestFileReferenceFactory:
+ def build_from_mapping(self, *, mapping: Mapping[str, Any]) -> File:
+ return File(
+ file_id=mapping.get("id"),
+ file_type=FileType(mapping["type"]),
+ transfer_method=FileTransferMethod(mapping["transfer_method"]),
+ remote_url=mapping.get("remote_url") or mapping.get("url"),
+ related_id=mapping.get("related_id") or mapping.get("upload_file_id"),
+ filename=mapping.get("filename"),
+ extension=mapping.get("extension"),
+ mime_type=mapping.get("mime_type"),
+ size=mapping.get("size", -1),
+ )
+
+
@dataclass
class StaticForm(HumanInputFormEntity):
form_id: str
@@ -106,6 +129,9 @@ class StaticRepo(HumanInputFormRepository):
def get_form(self, node_id: str) -> HumanInputFormEntity | None:
return self._forms_by_node_id.get(node_id)
+ def set_forms(self, forms_by_node_id: Mapping[str, HumanInputFormEntity]) -> None:
+ self._forms_by_node_id = dict(forms_by_node_id)
+
def create_form(self, params: FormCreateParams) -> HumanInputFormEntity:
raise AssertionError("create_form should not be called in resume scenario")
@@ -148,7 +174,14 @@ def _build_graph(runtime_state: GraphRuntimeState, repo: HumanInputFormRepositor
human_data = HumanInputNodeData(
title="Human Input",
form_content="Human input required",
- inputs=[],
+ inputs=[
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(type=ValueSourceType.CONSTANT, value=["approve", "reject"]),
+ ),
+ FileInputConfig(output_variable_name="attachment"),
+ FileListInputConfig(output_variable_name="attachments", number_limits=2),
+ ],
user_actions=[UserActionConfig(id="approve", title="Approve")],
)
@@ -177,8 +210,12 @@ def _build_graph(runtime_state: GraphRuntimeState, repo: HumanInputFormRepositor
end_data = EndNodeData(
title="End",
outputs=[
- OutputVariableEntity(variable="res_a", value_selector=["human_a", "__action_id"]),
- OutputVariableEntity(variable="res_b", value_selector=["human_b", "__action_id"]),
+ OutputVariableEntity(variable="res_a_action", value_selector=["human_a", "__action_id"]),
+ OutputVariableEntity(variable="res_a_decision", value_selector=["human_a", "decision"]),
+ OutputVariableEntity(variable="res_a_attachment", value_selector=["human_a", "attachment"]),
+ OutputVariableEntity(variable="res_b_action", value_selector=["human_b", "__action_id"]),
+ OutputVariableEntity(variable="res_b_decision", value_selector=["human_b", "decision"]),
+ OutputVariableEntity(variable="res_b_attachments", value_selector=["human_b", "attachments"]),
],
desc=None,
)
@@ -216,13 +253,13 @@ def _run_graph(graph: Graph, runtime_state: GraphRuntimeState) -> list[object]:
return list(engine.run())
-def _form(submitted: bool, action_id: str | None) -> StaticForm:
+def _form(submitted: bool, action_id: str | None, data: Mapping[str, Any] | None = None) -> StaticForm:
return StaticForm(
form_id="form",
rendered="rendered",
is_submitted=submitted,
action_id=action_id,
- data={},
+ data=data,
status_value=HumanInputFormStatus.SUBMITTED if submitted else HumanInputFormStatus.WAITING,
)
@@ -246,7 +283,21 @@ def test_parallel_human_input_join_completes_after_second_resume() -> None:
first_resume_state = pause_store.load()
first_resume_repo = StaticRepo(
{
- "human_a": _form(submitted=True, action_id="approve"),
+ "human_a": _form(
+ submitted=True,
+ action_id="approve",
+ data={
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/resume.pdf",
+ "filename": "resume.pdf",
+ "extension": ".pdf",
+ "mime_type": "application/pdf",
+ },
+ },
+ ),
"human_b": _form(submitted=False, action_id=None),
}
)
@@ -256,19 +307,68 @@ def test_parallel_human_input_join_completes_after_second_resume() -> None:
assert isinstance(first_resume_events[0], GraphRunStartedEvent)
assert first_resume_events[0].reason is WorkflowStartReason.RESUMPTION
assert isinstance(first_resume_events[-1], GraphRunPausedEvent)
- pause_store.save(first_resume_state)
-
- second_resume_state = pause_store.load()
- second_resume_repo = StaticRepo(
+ second_resume_state = first_resume_state
+ first_resume_repo.set_forms(
{
- "human_a": _form(submitted=True, action_id="approve"),
- "human_b": _form(submitted=True, action_id="approve"),
+ "human_a": _form(
+ submitted=True,
+ action_id="approve",
+ data={
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/resume.pdf",
+ "filename": "resume.pdf",
+ "extension": ".pdf",
+ "mime_type": "application/pdf",
+ },
+ },
+ ),
+ "human_b": _form(
+ submitted=True,
+ action_id="approve",
+ data={
+ "decision": "reject",
+ "attachments": [
+ {
+ "type": "image",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/a.png",
+ "filename": "a.png",
+ "extension": ".png",
+ "mime_type": "image/png",
+ },
+ {
+ "type": "image",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/b.png",
+ "filename": "b.png",
+ "extension": ".png",
+ "mime_type": "image/png",
+ },
+ ],
+ },
+ ),
}
)
- second_resume_graph = _build_graph(second_resume_state, second_resume_repo)
- second_resume_events = _run_graph(second_resume_graph, second_resume_state)
+ second_resume_events = _run_graph(first_resume_graph, second_resume_state)
assert isinstance(second_resume_events[0], GraphRunStartedEvent)
assert second_resume_events[0].reason is WorkflowStartReason.RESUMPTION
assert isinstance(second_resume_events[-1], GraphRunSucceededEvent)
assert any(isinstance(event, NodeRunSucceededEvent) and event.node_id == "end" for event in second_resume_events)
+ second_resume_outputs = second_resume_state.outputs
+ assert second_resume_outputs["res_a_action"] == "approve"
+ assert second_resume_outputs["res_a_decision"] == "approve"
+ assert isinstance(second_resume_outputs["res_a_attachment"], File)
+ res_a_attachment_in_second_outputs = second_resume_outputs["res_a_attachment"]
+ assert isinstance(res_a_attachment_in_second_outputs, File)
+ assert res_a_attachment_in_second_outputs.filename == "resume.pdf"
+ assert res_a_attachment_in_second_outputs.type == FileType.DOCUMENT
+ assert res_a_attachment_in_second_outputs.transfer_method == FileTransferMethod.REMOTE_URL
+ assert second_resume_outputs["res_b_action"] == "approve"
+ assert second_resume_outputs["res_b_decision"] == "reject"
+ assert isinstance(second_resume_outputs["res_b_attachments"], list)
+ assert [file.filename for file in second_resume_outputs["res_b_attachments"]] == ["a.png", "b.png"]
+ assert all(file.type == FileType.IMAGE for file in second_resume_outputs["res_b_attachments"])
diff --git a/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.py b/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.py
index a5a8e877f28..1d68610e7f4 100644
--- a/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.py
+++ b/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.py
@@ -33,11 +33,16 @@ from core.workflow.human_input_adapter import (
from core.workflow.node_runtime import DifyFileReferenceFactory, DifyHumanInputNodeRuntime
from core.workflow.system_variables import build_system_variables
from graphon.entities import GraphInitParams
+from graphon.file import File, FileTransferMethod, FileType
from graphon.node_events import PauseRequestedEvent
from graphon.node_events.node import StreamCompletedEvent
from graphon.nodes.human_input.entities import (
+ FileInputConfig,
+ FileListInputConfig,
HumanInputNodeData,
ParagraphInputConfig,
+ SelectInputConfig,
+ StringListSource,
StringSource,
UserActionConfig,
)
@@ -49,7 +54,9 @@ from graphon.nodes.human_input.enums import (
ValueSourceType,
)
from graphon.nodes.human_input.human_input_node import HumanInputNode
+from graphon.nodes.protocols import FileReferenceFactoryProtocol
from graphon.runtime import GraphRuntimeState, VariablePool
+from graphon.variables.segments import ArrayFileSegment, FileSegment, StringSegment
from libs.datetime_utils import naive_utc_now
@@ -136,6 +143,23 @@ class InMemoryHumanInputFormRepository(HumanInputFormRepository):
entity.status_value = HumanInputFormStatus.SUBMITTED
+class _TestFileReferenceFactory(FileReferenceFactoryProtocol):
+ """Build graph-layer file objects without touching Dify persistence in unit tests."""
+
+ def build_from_mapping(self, *, mapping: Mapping[str, Any]) -> File:
+ return File(
+ file_id=mapping.get("id"),
+ file_type=FileType(mapping["type"]),
+ transfer_method=FileTransferMethod(mapping["transfer_method"]),
+ remote_url=mapping.get("remote_url") or mapping.get("url"),
+ related_id=mapping.get("related_id") or mapping.get("upload_file_id"),
+ filename=mapping.get("filename"),
+ extension=mapping.get("extension"),
+ mime_type=mapping.get("mime_type"),
+ size=mapping.get("size", -1),
+ )
+
+
def _build_human_input_node(
*,
node_id: str,
@@ -198,12 +222,11 @@ class TestParagraphInputConfig:
"""Test paragraph input with constant default value."""
default = StringSource(type=ValueSourceType.CONSTANT, value="Enter your response here...")
- form_input = ParagraphInputConfig(
- type=FormInputType.PARAGRAPH, output_variable_name="user_input", default=default
- )
+ form_input = ParagraphInputConfig(output_variable_name="user_input", default=default)
assert form_input.type == FormInputType.PARAGRAPH
assert form_input.output_variable_name == "user_input"
+ assert form_input.default is not None
assert form_input.default.type == ValueSourceType.CONSTANT
assert form_input.default.value == "Enter your response here..."
@@ -211,16 +234,15 @@ class TestParagraphInputConfig:
"""Test paragraph input with variable default value."""
default = StringSource(type=ValueSourceType.VARIABLE, selector=["node_123", "output_var"])
- form_input = ParagraphInputConfig(
- type=FormInputType.PARAGRAPH, output_variable_name="user_input", default=default
- )
+ form_input = ParagraphInputConfig(output_variable_name="user_input", default=default)
+ assert form_input.default is not None
assert form_input.default.type == ValueSourceType.VARIABLE
assert form_input.default.selector == ["node_123", "output_var"]
def test_form_input_without_default(self):
"""Test form input without default value."""
- form_input = ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="description")
+ form_input = ParagraphInputConfig(output_variable_name="description")
assert form_input.type == FormInputType.PARAGRAPH
assert form_input.output_variable_name == "description"
@@ -279,7 +301,6 @@ class TestHumanInputNodeData:
inputs = [
ParagraphInputConfig(
- type=FormInputType.PARAGRAPH,
output_variable_name="content",
default=StringSource(type=ValueSourceType.CONSTANT, value="Enter content..."),
)
@@ -343,8 +364,8 @@ class TestHumanInputNodeData:
def test_duplicate_input_output_variable_name_raises_validation_error(self):
"""Duplicate form input output_variable_name should raise validation error."""
duplicate_inputs = [
- ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="content"),
- ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="content"),
+ ParagraphInputConfig(output_variable_name="content"),
+ ParagraphInputConfig(output_variable_name="content"),
]
with pytest.raises(ValidationError, match="duplicated output_variable_name 'content'"):
@@ -464,12 +485,10 @@ class TestHumanInputNodeVariableResolution:
form_content="Provide your name",
inputs=[
ParagraphInputConfig(
- type=FormInputType.PARAGRAPH,
output_variable_name="user_name",
default=StringSource(type=ValueSourceType.VARIABLE, selector=["start", "name"]),
),
ParagraphInputConfig(
- type=FormInputType.PARAGRAPH,
output_variable_name="user_email",
default=StringSource(type=ValueSourceType.CONSTANT, value="[email protected]"),
),
@@ -726,9 +745,11 @@ class TestValidation:
def test_invalid_form_input_type(self):
"""Test validation with invalid form input type."""
with pytest.raises(ValidationError):
- ParagraphInputConfig(
- type="invalid-type", # Invalid type
- output_variable_name="test",
+ ParagraphInputConfig.model_validate(
+ {
+ "type": "invalid-type",
+ "output_variable_name": "test",
+ }
)
def test_invalid_button_style(self):
@@ -782,11 +803,79 @@ class TestHumanInputNodeRenderedContent:
node_data = HumanInputNodeData(
title="Human Input",
form_content="Name: {{#$output.name#}}",
+ inputs=[ParagraphInputConfig(output_variable_name="name")],
+ user_actions=[UserActionConfig(id="approve", title="Approve")],
+ )
+ config = {"id": "human", "data": node_data.model_dump()}
+
+ form_repository = InMemoryHumanInputFormRepository()
+ runtime = DifyHumanInputNodeRuntime(graph_init_params.run_context)
+ runtime._build_form_repository = MagicMock(return_value=form_repository) # type: ignore[attr-defined]
+ node = _build_human_input_node(
+ node_id=config["id"],
+ node_data=config["data"],
+ graph_init_params=graph_init_params,
+ graph_runtime_state=runtime_state,
+ runtime=runtime,
+ )
+
+ pause_gen = node._run()
+ pause_event = next(pause_gen)
+ assert isinstance(pause_event, PauseRequestedEvent)
+ with pytest.raises(StopIteration):
+ next(pause_gen)
+
+ form_repository.set_submission(action_id="approve", form_data={"name": "Alice"})
+
+ events = list(node._run())
+ last_event = events[-1]
+ assert isinstance(last_event, StreamCompletedEvent)
+ node_run_result = last_event.node_run_result
+ assert node_run_result.outputs["name"] == StringSegment(value="Alice")
+ assert node_run_result.outputs["__action_id"] == StringSegment(value="approve")
+ assert node_run_result.outputs["__rendered_content"] == StringSegment(value="Name: Alice")
+
+ def test_resume_restores_file_outputs_as_runtime_segments(self):
+ variable_pool = VariablePool.from_bootstrap(
+ system_variables=build_system_variables(
+ user_id="user",
+ app_id="app",
+ workflow_id="workflow",
+ workflow_execution_id="run",
+ ),
+ user_inputs={},
+ conversation_variables=[],
+ )
+ runtime_state = GraphRuntimeState(variable_pool=variable_pool, start_at=0.0)
+ graph_init_params = GraphInitParams(
+ workflow_id="workflow",
+ graph_config={"nodes": [], "edges": []},
+ run_context={
+ DIFY_RUN_CONTEXT_KEY: {
+ "tenant_id": "tenant",
+ "app_id": "app",
+ "user_id": "user",
+ "user_from": "account",
+ "invoke_from": "debugger",
+ }
+ },
+ call_depth=0,
+ )
+
+ node_data = HumanInputNodeData(
+ title="Human Input",
+ form_content=(
+ "Decision: {{#$output.decision#}}\n"
+ "Attachment: {{#$output.attachment#}}\n"
+ "Attachments: {{#$output.attachments#}}"
+ ),
inputs=[
- ParagraphInputConfig(
- type=FormInputType.PARAGRAPH,
- output_variable_name="name",
- )
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(type="constant", value=["approve", "reject"]),
+ ),
+ FileInputConfig(output_variable_name="attachment"),
+ FileListInputConfig(output_variable_name="attachments", number_limits=2),
],
user_actions=[UserActionConfig(id="approve", title="Approve")],
)
@@ -809,10 +898,48 @@ class TestHumanInputNodeRenderedContent:
with pytest.raises(StopIteration):
next(pause_gen)
- form_repository.set_submission(action_id="approve", form_data={"name": "Alice"})
+ form_repository.set_submission(
+ action_id="approve",
+ form_data={
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/resume.pdf",
+ "filename": "resume.pdf",
+ "extension": ".pdf",
+ "mime_type": "application/pdf",
+ },
+ "attachments": [
+ {
+ "type": "image",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/a.png",
+ "filename": "a.png",
+ "extension": ".png",
+ "mime_type": "image/png",
+ },
+ {
+ "type": "image",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/b.png",
+ "filename": "b.png",
+ "extension": ".png",
+ "mime_type": "image/png",
+ },
+ ],
+ },
+ )
events = list(node._run())
last_event = events[-1]
assert isinstance(last_event, StreamCompletedEvent)
node_run_result = last_event.node_run_result
- assert node_run_result.outputs["__rendered_content"].to_object() == "Name: Alice"
+ assert node_run_result.outputs["decision"] == StringSegment(value="approve")
+ assert node_run_result.outputs["__rendered_content"] == StringSegment(
+ value="Decision: approve\nAttachment: [file]\nAttachments: [2 files]"
+ )
+ assert isinstance(node_run_result.outputs["attachment"], FileSegment)
+ assert node_run_result.outputs["attachment"].value.filename == "resume.pdf"
+ assert isinstance(node_run_result.outputs["attachments"], ArrayFileSegment)
+ assert [file.filename for file in node_run_result.outputs["attachments"].value] == ["a.png", "b.png"]
diff --git a/api/tests/unit_tests/core/workflow/nodes/human_input/test_human_input_form_filled_event.py b/api/tests/unit_tests/core/workflow/nodes/human_input/test_human_input_form_filled_event.py
index 40522a0d4f0..763e1eecfd7 100644
--- a/api/tests/unit_tests/core/workflow/nodes/human_input/test_human_input_form_filled_event.py
+++ b/api/tests/unit_tests/core/workflow/nodes/human_input/test_human_input_form_filled_event.py
@@ -1,20 +1,34 @@
import datetime
+from collections.abc import Mapping
from types import SimpleNamespace
+from typing import Any
from core.app.entities.app_invoke_entities import DIFY_RUN_CONTEXT_KEY, InvokeFrom, UserFrom
from core.workflow.node_runtime import DifyFileReferenceFactory, DifyHumanInputNodeRuntime
from core.workflow.system_variables import default_system_variables
from graphon.entities import GraphInitParams
from graphon.enums import BuiltinNodeTypes
+from graphon.file import File, FileTransferMethod, FileType
from graphon.graph_events import (
NodeRunHumanInputFormFilledEvent,
NodeRunHumanInputFormTimeoutEvent,
NodeRunStartedEvent,
)
-from graphon.nodes.human_input.entities import HumanInputNodeData
+from graphon.nodes.human_input.entities import (
+ FileInputConfig,
+ FileListInputConfig,
+ HumanInputNodeData,
+ ParagraphInputConfig,
+ SelectInputConfig,
+ StringListSource,
+ UserActionConfig,
+)
from graphon.nodes.human_input.enums import HumanInputFormStatus
from graphon.nodes.human_input.human_input_node import HumanInputNode
+from graphon.nodes.protocols import FileReferenceFactoryProtocol
from graphon.runtime import GraphRuntimeState, VariablePool
+from graphon.variables.segments import ArrayFileSegment, FileSegment, StringSegment
+from graphon.variables.types import SegmentType
from libs.datetime_utils import naive_utc_now
@@ -26,6 +40,21 @@ class _FakeFormRepository:
return self._form
+class _TestFileReferenceFactory(FileReferenceFactoryProtocol):
+ def build_from_mapping(self, *, mapping: Mapping[str, Any]):
+ return File(
+ file_id=mapping.get("id"),
+ file_type=FileType(mapping["type"]),
+ transfer_method=FileTransferMethod(mapping["transfer_method"]),
+ remote_url=mapping.get("remote_url") or mapping.get("url"),
+ related_id=mapping.get("related_id") or mapping.get("upload_file_id"),
+ filename=mapping.get("filename"),
+ extension=mapping.get("extension"),
+ mime_type=mapping.get("mime_type"),
+ size=mapping.get("size", -1),
+ )
+
+
def _create_human_input_node(
*,
config: dict,
@@ -49,7 +78,14 @@ def _create_human_input_node(
)
-def _build_node(form_content: str = "Please enter your name:\n\n{{#$output.name#}}") -> HumanInputNode:
+def _build_node(
+ form_content: str = (
+ "Please enter your name:\n\n{{#$output.name#}}\n"
+ "Decision: {{#$output.decision#}}\n"
+ "Attachment: {{#$output.attachment#}}\n"
+ "Attachments: {{#$output.attachments#}}"
+ ),
+) -> HumanInputNode:
system_variables = default_system_variables()
graph_runtime_state = GraphRuntimeState(
variable_pool=VariablePool.from_bootstrap(
@@ -81,19 +117,15 @@ def _build_node(form_content: str = "Please enter your name:\n\n{{#$output.name#
"title": "Human Input",
"form_content": form_content,
"inputs": [
- {
- "type": "paragraph",
- "output_variable_name": "name",
- "default": {"type": "constant", "value": ""},
- }
- ],
- "user_actions": [
- {
- "id": "Accept",
- "title": "Approve",
- "button_style": "default",
- }
+ ParagraphInputConfig(output_variable_name="name").model_dump(mode="json"),
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(type="constant", value=["approve", "reject"]),
+ ).model_dump(mode="json"),
+ FileInputConfig(output_variable_name="attachment").model_dump(mode="json"),
+ FileListInputConfig(output_variable_name="attachments", number_limits=2).model_dump(mode="json"),
],
+ "user_actions": [UserActionConfig(id="Accept", title="Approve").model_dump(mode="json")],
},
}
@@ -102,7 +134,28 @@ def _build_node(form_content: str = "Please enter your name:\n\n{{#$output.name#
rendered_content=form_content,
submitted=True,
selected_action_id="Accept",
- submitted_data={"name": "Alice"},
+ submitted_data={
+ "name": "Alice",
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/resume.pdf",
+ "filename": "resume.pdf",
+ "extension": ".pdf",
+ "mime_type": "application/pdf",
+ },
+ "attachments": [
+ {
+ "type": "image",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/a.png",
+ "filename": "a.png",
+ "extension": ".png",
+ "mime_type": "image/png",
+ }
+ ],
+ },
status=HumanInputFormStatus.SUBMITTED,
expiration_time=naive_utc_now() + datetime.timedelta(days=1),
)
@@ -147,20 +200,8 @@ def _build_timeout_node() -> HumanInputNode:
"data": {
"title": "Human Input",
"form_content": "Please enter your name:\n\n{{#$output.name#}}",
- "inputs": [
- {
- "type": "paragraph",
- "output_variable_name": "name",
- "default": {"type": "constant", "value": ""},
- }
- ],
- "user_actions": [
- {
- "id": "Accept",
- "title": "Approve",
- "button_style": "default",
- }
- ],
+ "inputs": [ParagraphInputConfig(output_variable_name="name").model_dump(mode="json")],
+ "user_actions": [UserActionConfig(id="Accept", title="Approve").model_dump(mode="json")],
},
}
@@ -193,9 +234,22 @@ def test_human_input_node_emits_form_filled_event_before_succeeded():
filled_event = events[1]
assert filled_event.node_title == "Human Input"
- assert filled_event.rendered_content.endswith("Alice")
+ assert filled_event.rendered_content == (
+ "Please enter your name:\n\nAlice\nDecision: approve\nAttachment: [file]\nAttachments: [1 files]"
+ )
assert filled_event.action_id == "Accept"
assert filled_event.action_text == "Approve"
+ assert filled_event.submitted_data["name"] == StringSegment(value="Alice")
+ assert filled_event.submitted_data["decision"] == StringSegment(value="approve")
+ assert isinstance(filled_event.submitted_data["attachment"], FileSegment)
+ assert filled_event.submitted_data["attachment"].value_type == SegmentType.FILE
+ assert filled_event.submitted_data["attachment"].value.filename == "resume.pdf"
+ assert filled_event.submitted_data["attachment"].value.type == FileType.DOCUMENT
+ assert filled_event.submitted_data["attachment"].value.transfer_method == FileTransferMethod.REMOTE_URL
+ assert isinstance(filled_event.submitted_data["attachments"], ArrayFileSegment)
+ assert filled_event.submitted_data["attachments"].value_type == SegmentType.ARRAY_FILE
+ assert filled_event.submitted_data["attachments"].value[0].filename == "a.png"
+ assert filled_event.submitted_data["attachments"].value[0].type == FileType.IMAGE
def test_human_input_node_emits_timeout_event_before_succeeded():
diff --git a/api/tests/unit_tests/core/workflow/test_form_input_serialization_compat.py b/api/tests/unit_tests/core/workflow/test_form_input_serialization_compat.py
new file mode 100644
index 00000000000..cc83a17dfc3
--- /dev/null
+++ b/api/tests/unit_tests/core/workflow/test_form_input_serialization_compat.py
@@ -0,0 +1,338 @@
+import json
+from typing import Any
+
+from pydantic import TypeAdapter
+
+from core.app.entities.task_entities import HumanInputRequiredResponse
+from core.entities.execution_extra_content import (
+ HumanInputContent,
+ HumanInputFormDefinition,
+)
+from graphon.entities.pause_reason import HumanInputRequired
+from graphon.nodes.human_input.entities import (
+ FormDefinition,
+ FormInputConfig,
+ HumanInputNodeData,
+)
+from graphon.nodes.human_input.enums import ButtonStyle, TimeoutUnit, ValueSourceType
+
+
+def _legacy_form_input_payloads() -> list[dict[str, Any]]:
+ return [
+ {
+ "type": "paragraph",
+ "output_variable_name": "name",
+ "default": {
+ "type": "constant",
+ "selector": [],
+ "value": "Alice",
+ },
+ },
+ {
+ "type": "select",
+ "output_variable_name": "decision",
+ "option_source": {
+ "type": "constant",
+ "selector": [],
+ "value": ["approve", "reject"],
+ },
+ },
+ {
+ "type": "file",
+ "output_variable_name": "attachment",
+ "allowed_file_types": ["document"],
+ "allowed_file_extensions": [],
+ "allowed_file_upload_methods": ["remote_url"],
+ },
+ {
+ "type": "file-list",
+ "output_variable_name": "attachments",
+ "allowed_file_types": ["document"],
+ "allowed_file_extensions": [],
+ "allowed_file_upload_methods": ["remote_url"],
+ "number_limits": 3,
+ },
+ {
+ "type": "paragraph",
+ "output_variable_name": "summary",
+ "default": None,
+ },
+ ]
+
+
+def _legacy_user_action_payloads() -> list[dict[str, Any]]:
+ return [
+ {
+ "id": "approve",
+ "title": "Approve",
+ "button_style": "primary",
+ },
+ {
+ "id": "reject",
+ "title": "Reject",
+ "button_style": "default",
+ },
+ ]
+
+
+def _validate_legacy_json(model_class: type, payload: dict[str, Any]) -> Any:
+ adapter = TypeAdapter(model_class)
+ return adapter.validate_json(json.dumps(payload))
+
+
+def test_form_input_accepts_current_serialized_payload() -> None:
+ payload = {
+ "type": "paragraph",
+ "output_variable_name": "name",
+ "default": {
+ "type": "constant",
+ "selector": [],
+ "value": "Alice",
+ },
+ }
+
+ restored = _validate_legacy_json(FormInputConfig, payload)
+ assert restored.default is not None
+ assert restored.default.type == ValueSourceType.CONSTANT
+
+
+def test_human_input_node_data_accepts_current_serialized_payload() -> None:
+ payload = {
+ "type": "human-input",
+ "title": "Human Input",
+ "form_content": "Hello {{#$output.name#}}",
+ "inputs": _legacy_form_input_payloads(),
+ "user_actions": _legacy_user_action_payloads(),
+ "timeout": 2,
+ "timeout_unit": "day",
+ }
+
+ restored = _validate_legacy_json(HumanInputNodeData, payload)
+ assert restored.inputs[0].output_variable_name == "name"
+ assert restored.timeout_unit == TimeoutUnit.DAY
+
+
+def test_form_definition_accepts_current_serialized_payload() -> None:
+ payload = {
+ "form_content": "Please confirm",
+ "inputs": _legacy_form_input_payloads(),
+ "user_actions": _legacy_user_action_payloads(),
+ "rendered_content": "Please confirm",
+ "expiration_time": "2024-01-01T00:00:00Z",
+ "default_values": {"name": "Alice"},
+ "node_title": "Human Input",
+ "display_in_ui": True,
+ }
+
+ restored = _validate_legacy_json(FormDefinition, payload)
+ assert restored.inputs[2].output_variable_name == "attachment"
+ assert restored.user_actions[0].id == "approve"
+ assert restored.user_actions[0].button_style == ButtonStyle.PRIMARY
+
+
+def test_human_input_required_pause_reason_accepts_current_serialized_payload() -> None:
+ payload = {
+ "TYPE": "human_input_required",
+ "form_id": "form-1",
+ "form_content": "Please confirm",
+ "inputs": _legacy_form_input_payloads(),
+ "actions": _legacy_user_action_payloads(),
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "resolved_default_values": {"name": "Alice"},
+ }
+
+ restored = _validate_legacy_json(HumanInputRequired, payload)
+ assert restored.inputs[1].output_variable_name == "decision"
+ assert restored.actions[0].id == "approve"
+ assert restored.TYPE == "human_input_required"
+
+
+def test_human_input_form_definition_accepts_current_serialized_payload() -> None:
+ payload = {
+ "form_id": "form-1",
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "form_content": "Please confirm",
+ "inputs": _legacy_form_input_payloads(),
+ "actions": _legacy_user_action_payloads(),
+ "display_in_ui": True,
+ "form_token": "token-1",
+ "resolved_default_values": {"name": "Alice"},
+ "expiration_time": 1700000000,
+ }
+
+ restored = _validate_legacy_json(HumanInputFormDefinition, payload)
+ assert restored.inputs[3].output_variable_name == "attachments"
+ assert restored.actions[0].id == "approve"
+
+
+def test_human_input_content_accepts_current_serialized_payload() -> None:
+ payload = {
+ "workflow_run_id": "run-1",
+ "submitted": True,
+ "form_definition": {
+ "form_id": "form-1",
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "form_content": "Please confirm",
+ "inputs": _legacy_form_input_payloads(),
+ "actions": _legacy_user_action_payloads(),
+ "display_in_ui": True,
+ "form_token": "token-1",
+ "resolved_default_values": {"name": "Alice"},
+ "expiration_time": 1700000000,
+ },
+ "form_submission_data": {
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "rendered_content": "Please confirm",
+ "action_id": "approve",
+ "action_text": "Approve",
+ },
+ "type": "human_input",
+ }
+
+ restored = _validate_legacy_json(HumanInputContent, payload)
+ assert restored.form_definition is not None
+ assert restored.form_definition.inputs[0].output_variable_name == "name"
+
+
+def test_human_input_content_accepts_current_serialized_payload_with_form_data() -> None:
+ payload = {
+ "workflow_run_id": "run-1",
+ "submitted": True,
+ "form_definition": {
+ "form_id": "form-1",
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "form_content": "Please confirm",
+ "inputs": [
+ {
+ "type": "select",
+ "output_variable_name": "decision",
+ "option_source": {"type": "constant", "selector": [], "value": ["approve", "reject"]},
+ },
+ {
+ "type": "file",
+ "output_variable_name": "attachment",
+ "allowed_file_types": ["document"],
+ "allowed_file_extensions": [],
+ "allowed_file_upload_methods": ["remote_url"],
+ },
+ {
+ "type": "file-list",
+ "output_variable_name": "attachments",
+ "allowed_file_types": ["document"],
+ "allowed_file_extensions": [],
+ "allowed_file_upload_methods": ["remote_url"],
+ "number_limits": 3,
+ },
+ ],
+ "actions": _legacy_user_action_payloads(),
+ "display_in_ui": True,
+ "form_token": "token-1",
+ "resolved_default_values": {"decision": "approve"},
+ "expiration_time": 1700000000,
+ },
+ "form_submission_data": {
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "rendered_content": "Please confirm",
+ "action_id": "approve",
+ "action_text": "Approve",
+ "submitted_data": {
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/file.txt",
+ "filename": "file.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ "attachments": [
+ {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/first.txt",
+ "filename": "first.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ }
+ ],
+ },
+ },
+ "type": "human_input",
+ }
+
+ restored = HumanInputContent.model_validate_json(json.dumps(payload))
+ assert restored.form_submission_data is not None
+ assert restored.form_submission_data.submitted_data == payload["form_submission_data"]["submitted_data"]
+
+
+def test_human_input_content_accepts_legacy_serialized_payload_with_form_data() -> None:
+ payload = {
+ "workflow_run_id": "run-1",
+ "submitted": True,
+ "form_definition": {
+ "form_id": "form-1",
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "form_content": "Please confirm",
+ "inputs": _legacy_form_input_payloads(),
+ "actions": _legacy_user_action_payloads(),
+ "display_in_ui": True,
+ "form_token": "token-1",
+ "resolved_default_values": {"decision": "approve"},
+ "expiration_time": 1700000000,
+ },
+ "form_submission_data": {
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "rendered_content": "Please confirm",
+ "action_id": "approve",
+ "action_text": "Approve",
+ "form_data": {
+ "decision": "approve",
+ "attachment": {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/file.txt",
+ "filename": "file.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ },
+ },
+ "type": "human_input",
+ }
+
+ restored = HumanInputContent.model_validate_json(json.dumps(payload))
+ assert restored.form_submission_data is not None
+ assert restored.form_submission_data.submitted_data is None
+
+
+def test_human_input_required_response_accepts_current_serialized_payload() -> None:
+ payload = {
+ "event": "human_input_required",
+ "task_id": "task-1",
+ "workflow_run_id": "run-1",
+ "data": {
+ "form_id": "form-1",
+ "node_id": "node-1",
+ "node_title": "Human Input",
+ "form_content": "Please confirm",
+ "inputs": _legacy_form_input_payloads(),
+ "actions": _legacy_user_action_payloads(),
+ "display_in_ui": True,
+ "form_token": "token-1",
+ "resolved_default_values": {"name": "Alice"},
+ "expiration_time": 1700000000,
+ },
+ }
+
+ restored = _validate_legacy_json(HumanInputRequiredResponse, payload)
+ assert restored.data.inputs[1].output_variable_name == "decision"
+ assert restored.data.actions[0].id == "approve"
+ assert restored.event == "human_input_required"
diff --git a/api/tests/unit_tests/core/workflow/test_human_input_policy.py b/api/tests/unit_tests/core/workflow/test_human_input_policy.py
index e6d0366af53..651b69216ae 100644
--- a/api/tests/unit_tests/core/workflow/test_human_input_policy.py
+++ b/api/tests/unit_tests/core/workflow/test_human_input_policy.py
@@ -1,8 +1,14 @@
+import pytest
+
from core.workflow.human_input_policy import (
HumanInputSurface,
get_preferred_form_token,
is_recipient_type_allowed_for_surface,
+ resolve_variable_select_input_options,
)
+from graphon.nodes.human_input.entities import SelectInputConfig, StringListSource
+from graphon.nodes.human_input.enums import ValueSourceType
+from graphon.runtime import VariablePool
from models.human_input import RecipientType
@@ -48,3 +54,40 @@ def test_preferred_form_token_uses_shared_priority_order() -> None:
]
assert get_preferred_form_token(recipients) == "backstage-token"
+
+
+def test_resolve_variable_select_input_options_uses_runtime_values() -> None:
+ variable_pool = VariablePool()
+ variable_pool.add(("start", "options"), ["approve", "reject"])
+ inputs: list[SelectInputConfig] = [
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=[],
+ ),
+ )
+ ]
+
+ resolved = resolve_variable_select_input_options(inputs, variable_pool=variable_pool)
+ assert isinstance(resolved[0], SelectInputConfig)
+ assert resolved[0].option_source.value == ["approve", "reject"]
+
+
+def test_resolve_variable_select_input_options_keeps_original_when_value_not_string_list() -> None:
+ variable_pool = VariablePool()
+ variable_pool.add(("start", "options"), [1, 2, 3])
+ inputs = [
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=[],
+ ),
+ )
+ ]
+
+ with pytest.raises(TypeError):
+ resolve_variable_select_input_options(inputs, variable_pool=variable_pool)
diff --git a/api/tests/unit_tests/core/workflow/test_node_factory.py b/api/tests/unit_tests/core/workflow/test_node_factory.py
index f35624aed15..bd18402c583 100644
--- a/api/tests/unit_tests/core/workflow/test_node_factory.py
+++ b/api/tests/unit_tests/core/workflow/test_node_factory.py
@@ -590,6 +590,7 @@ class TestDifyNodeFactoryCreateNode:
assert kwargs["form_repository"] is form_repository
assert kwargs["file_reference_factory"] is sentinel.file_reference_factory
assert kwargs["runtime"] is factory._human_input_runtime
+ assert kwargs["file_reference_factory"] is sentinel.file_reference_factory
factory._human_input_runtime.build_form_repository.assert_called_once_with()
elif constructor_name == "ToolNode":
assert kwargs["tool_file_manager"] is sentinel.tool_file_manager
@@ -599,6 +600,50 @@ class TestDifyNodeFactoryCreateNode:
assert kwargs["unstructured_api_config"] is sentinel.unstructured_api_config
assert kwargs["http_client"] is sentinel.remote_file_http_client
+ def test_human_input_node_receives_runtime_repository_and_file_reference_factory(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ factory,
+ ) -> None:
+ created_node = object()
+ constructor = _node_constructor(return_value=created_node)
+ form_repository = sentinel.form_repository
+ factory._human_input_runtime = MagicMock()
+ factory._human_input_runtime.build_form_repository.return_value = form_repository
+ monkeypatch.setattr(
+ factory,
+ "_resolve_node_class",
+ MagicMock(return_value=constructor),
+ )
+
+ result = factory.create_node({"id": "human-node", "data": {"type": BuiltinNodeTypes.HUMAN_INPUT}})
+
+ assert result is created_node
+ kwargs = constructor.call_args.kwargs
+ assert kwargs["runtime"] is factory._human_input_runtime
+ assert kwargs["form_repository"] is form_repository
+ assert kwargs["file_reference_factory"] is sentinel.file_reference_factory
+ factory._human_input_runtime.build_form_repository.assert_called_once_with()
+
+ def test_tool_node_receives_tool_file_manager(self, monkeypatch: pytest.MonkeyPatch, factory) -> None:
+ created_node = object()
+ constructor = _node_constructor(return_value=created_node)
+ factory._bound_tool_file_manager_factory = MagicMock(return_value=sentinel.tool_file_manager)
+ monkeypatch.setattr(
+ factory,
+ "_resolve_node_class",
+ MagicMock(return_value=constructor),
+ )
+
+ result = factory.create_node({"id": "tool-node", "data": {"type": BuiltinNodeTypes.TOOL}})
+
+ assert result is created_node
+ kwargs = constructor.call_args.kwargs
+ assert kwargs["tool_file_manager"] is sentinel.tool_file_manager
+ assert kwargs["runtime"] is sentinel.tool_runtime
+ assert "tool_file_manager_factory" not in kwargs
+ factory._bound_tool_file_manager_factory.assert_called_once_with()
+
def test_build_llm_compatible_node_init_kwargs_preserves_structured_output_switch(self, factory):
node_data = LLMNodeData.model_validate(
{
diff --git a/api/tests/unit_tests/core/workflow/test_node_runtime.py b/api/tests/unit_tests/core/workflow/test_node_runtime.py
index 5e83863dc20..244e22a8674 100644
--- a/api/tests/unit_tests/core/workflow/test_node_runtime.py
+++ b/api/tests/unit_tests/core/workflow/test_node_runtime.py
@@ -29,11 +29,12 @@ from core.workflow.node_runtime import (
build_dify_llm_file_saver,
resolve_dify_run_context,
)
-from graphon.file import FileTransferMethod, FileType
+from graphon.file import File, FileTransferMethod, FileType
from graphon.model_runtime.entities.common_entities import I18nObject
from graphon.model_runtime.entities.model_entities import AIModelEntity, FetchFrom, ModelType
-from graphon.nodes.human_input.entities import HumanInputNodeData
+from graphon.nodes.human_input.entities import FileInputConfig, FileListInputConfig, HumanInputNodeData
from graphon.nodes.tool.entities import ToolNodeData, ToolProviderType
+from graphon.variables.segments import ArrayFileSegment, FileSegment
from tests.workflow_test_utils import build_test_run_context
@@ -621,6 +622,70 @@ def test_dify_human_input_runtime_preserves_webapp_delivery_for_web_invocations(
assert params.delivery_methods[1].config.recipients.include_bound_group is True
+def test_dify_human_input_runtime_restore_submitted_data_rehydrates_files() -> None:
+ runtime = DifyHumanInputNodeRuntime(_build_run_context())
+ file_value = File(
+ file_id="file-1",
+ file_type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.LOCAL_FILE,
+ related_id="upload-1",
+ filename="resume.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=128,
+ )
+ file_list_value = [
+ File(
+ file_id="file-2",
+ file_type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.LOCAL_FILE,
+ related_id="upload-2",
+ filename="first.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=64,
+ ),
+ File(
+ file_id="file-3",
+ file_type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.REMOTE_URL,
+ remote_url="https://example.com/second.pdf",
+ filename="second.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=96,
+ ),
+ ]
+ runtime._file_reference_factory.build_from_mapping = MagicMock(side_effect=[file_value, *file_list_value]) # type: ignore[method-assign]
+ node_data = HumanInputNodeData(
+ title="Human Input",
+ inputs=[
+ FileInputConfig(output_variable_name="attachment"),
+ FileListInputConfig(output_variable_name="attachments", number_limits=2),
+ ],
+ )
+
+ restored = runtime.restore_submitted_data(
+ node_data=node_data,
+ submitted_data={
+ "attachment": {"upload_file_id": "upload-1", "type": "document", "transfer_method": "local_file"},
+ "attachments": [
+ {"upload_file_id": "upload-2", "type": "document", "transfer_method": "local_file"},
+ {
+ "url": "https://example.com/second.pdf",
+ "type": "document",
+ "transfer_method": "remote_url",
+ },
+ ],
+ },
+ )
+
+ assert restored["attachment"] is file_value
+ assert restored["attachments"] == file_list_value
+ assert isinstance(FileSegment(value=restored["attachment"]), FileSegment)
+ assert isinstance(ArrayFileSegment(value=restored["attachments"]), ArrayFileSegment)
+
+
def test_build_dify_llm_file_saver_wires_runtime_adapters(monkeypatch: pytest.MonkeyPatch) -> None:
file_saver_cls = MagicMock(return_value=sentinel.file_saver)
monkeypatch.setattr("graphon.nodes.llm.file_saver.FileSaverImpl", file_saver_cls)
diff --git a/api/tests/unit_tests/factories/test_build_from_mapping.py b/api/tests/unit_tests/factories/test_build_from_mapping.py
index 6bc900798da..e2dd0efee32 100644
--- a/api/tests/unit_tests/factories/test_build_from_mapping.py
+++ b/api/tests/unit_tests/factories/test_build_from_mapping.py
@@ -421,3 +421,29 @@ def test_disallowed_extensions(mock_upload_file):
with pytest.raises(ValueError, match="File validation failed"):
build_from_mapping(mapping=mapping, tenant_id=TEST_TENANT_ID, config=restricted_config)
+
+
+def test_custom_file_type_uses_extension_validation_under_strict_mode(mock_upload_file):
+ """Custom form uploads are classified by the configured extension list."""
+ mock_upload_file.return_value.extension = "txt"
+ mock_upload_file.return_value.name = "notes.txt"
+ mock_upload_file.return_value.mime_type = "text/plain"
+
+ custom_config = FileUploadConfig(
+ allowed_file_types=[FileType.CUSTOM],
+ allowed_file_extensions=[".txt"],
+ )
+ mapping = {
+ "transfer_method": "local_file",
+ "upload_file_id": TEST_UPLOAD_FILE_ID,
+ "type": "custom",
+ }
+
+ file = build_from_mapping(
+ mapping=mapping,
+ tenant_id=TEST_TENANT_ID,
+ config=custom_config,
+ strict_type_validation=True,
+ )
+
+ assert file.type == FileType.CUSTOM
diff --git a/api/tests/unit_tests/libs/_human_input/support.py b/api/tests/unit_tests/libs/_human_input/support.py
index 6616cec9b8e..0f593507fdb 100644
--- a/api/tests/unit_tests/libs/_human_input/support.py
+++ b/api/tests/unit_tests/libs/_human_input/support.py
@@ -4,7 +4,7 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any
-from graphon.nodes.human_input.entities import ParagraphInputConfig
+from graphon.nodes.human_input.entities import FormInputConfig
from graphon.nodes.human_input.enums import TimeoutUnit
from libs.datetime_utils import naive_utc_now
@@ -45,7 +45,7 @@ class HumanInputForm:
tenant_id: str
app_id: str | None
form_content: str
- inputs: list[ParagraphInputConfig]
+ inputs: list[FormInputConfig]
user_actions: list[dict[str, Any]]
timeout: int
timeout_unit: TimeoutUnit
@@ -88,7 +88,7 @@ class HumanInputForm:
def to_response_dict(self, *, include_site_info: bool) -> dict[str, Any]:
inputs_response = [
{
- "type": form_input.type.name.lower().replace("_", "-"),
+ "type": form_input.type.value,
"output_variable_name": form_input.output_variable_name,
}
for form_input in self.inputs
diff --git a/api/tests/unit_tests/libs/_human_input/test_form_service.py b/api/tests/unit_tests/libs/_human_input/test_form_service.py
index cb4c2715d0a..decd7c484ba 100644
--- a/api/tests/unit_tests/libs/_human_input/test_form_service.py
+++ b/api/tests/unit_tests/libs/_human_input/test_form_service.py
@@ -11,7 +11,6 @@ from graphon.nodes.human_input.entities import (
UserActionConfig,
)
from graphon.nodes.human_input.enums import (
- FormInputType,
TimeoutUnit,
)
from libs.datetime_utils import naive_utc_now
@@ -50,7 +49,7 @@ class TestFormService:
"tenant_id": "tenant-abc",
"app_id": "app-def",
"form_content": "# Test Form\n\nInput: {{#$output.input#}}",
- "inputs": [ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="input", default=None)],
+ "inputs": [ParagraphInputConfig(output_variable_name="input")],
"user_actions": [UserActionConfig(id="submit", title="Submit")],
"timeout": 1,
"timeout_unit": TimeoutUnit.HOUR,
@@ -304,9 +303,7 @@ class TestFormValidation:
"tenant_id": "tenant-abc",
"app_id": "app-def",
"form_content": "Test form",
- "inputs": [
- ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="required_input", default=None)
- ],
+ "inputs": [ParagraphInputConfig(output_variable_name="required_input")],
"user_actions": [UserActionConfig(id="submit", title="Submit")],
"timeout": 1,
"timeout_unit": TimeoutUnit.HOUR,
diff --git a/api/tests/unit_tests/libs/_human_input/test_models.py b/api/tests/unit_tests/libs/_human_input/test_models.py
index 1413eed51fa..f6e4c9ec181 100644
--- a/api/tests/unit_tests/libs/_human_input/test_models.py
+++ b/api/tests/unit_tests/libs/_human_input/test_models.py
@@ -11,7 +11,6 @@ from graphon.nodes.human_input.entities import (
UserActionConfig,
)
from graphon.nodes.human_input.enums import (
- FormInputType,
TimeoutUnit,
)
from libs.datetime_utils import naive_utc_now
@@ -32,7 +31,7 @@ class TestHumanInputForm:
"tenant_id": "tenant-abc",
"app_id": "app-def",
"form_content": "# Test Form\n\nInput: {{#$output.input#}}",
- "inputs": [ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="input", default=None)],
+ "inputs": [ParagraphInputConfig(output_variable_name="input")],
"user_actions": [UserActionConfig(id="submit", title="Submit")],
"timeout": 2,
"timeout_unit": TimeoutUnit.HOUR,
diff --git a/api/tests/unit_tests/repositories/test_sqlalchemy_execution_extra_content_repository.py b/api/tests/unit_tests/repositories/test_sqlalchemy_execution_extra_content_repository.py
new file mode 100644
index 00000000000..df6805bcdf1
--- /dev/null
+++ b/api/tests/unit_tests/repositories/test_sqlalchemy_execution_extra_content_repository.py
@@ -0,0 +1,101 @@
+from __future__ import annotations
+
+import json
+from datetime import timedelta
+from typing import cast
+
+from sqlalchemy.orm import Session, sessionmaker
+
+from graphon.nodes.human_input.entities import FormDefinition, UserActionConfig
+from graphon.nodes.human_input.enums import HumanInputFormStatus
+from libs.datetime_utils import naive_utc_now
+from models.execution_extra_content import HumanInputContent as HumanInputContentModel
+from models.human_input import HumanInputForm
+from repositories.sqlalchemy_execution_extra_content_repository import SQLAlchemyExecutionExtraContentRepository
+
+
+def test_map_human_input_content_populates_submission_data_from_stored_form_submission() -> None:
+ expiration_time = naive_utc_now() + timedelta(days=1)
+ stored_submission_data = {"decision": "approve", "comment": "Looks good"}
+ form_definition = FormDefinition(
+ form_content="content",
+ inputs=[],
+ user_actions=[UserActionConfig(id="approve", title="Approve")],
+ rendered_content="Rendered Approve",
+ expiration_time=expiration_time,
+ node_title="Approval",
+ display_in_ui=True,
+ )
+ form = HumanInputForm(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workflow_run_id="workflow-run-1",
+ node_id="node-1",
+ form_definition=form_definition.model_dump_json(),
+ rendered_content="Rendered Approve",
+ expiration_time=expiration_time,
+ selected_action_id="approve",
+ submitted_data=json.dumps(stored_submission_data),
+ submitted_at=naive_utc_now(),
+ status=HumanInputFormStatus.SUBMITTED,
+ )
+ form.id = "form-1"
+ model = HumanInputContentModel.new(
+ workflow_run_id="workflow-run-1",
+ form_id=form.id,
+ message_id="message-1",
+ )
+ model.id = "content-1"
+ model.form = form
+ repository = SQLAlchemyExecutionExtraContentRepository(cast(sessionmaker[Session], object()))
+
+ content = repository._map_human_input_content(model, {})
+
+ assert content is not None
+ assert content.form_submission_data is not None
+ assert content.form_submission_data.submitted_data == stored_submission_data
+
+
+def test_map_human_input_content_keeps_waiting_form_without_selected_action() -> None:
+ expiration_time = naive_utc_now() + timedelta(days=1)
+ form_definition = FormDefinition(
+ form_content="content",
+ inputs=[],
+ user_actions=[UserActionConfig(id="approve", title="Approve")],
+ rendered_content="Rendered Approval",
+ expiration_time=expiration_time,
+ node_title="Approval",
+ display_in_ui=True,
+ default_values={"decision": "approve"},
+ )
+ form = HumanInputForm(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workflow_run_id="workflow-run-1",
+ node_id="node-1",
+ form_definition=form_definition.model_dump_json(),
+ rendered_content="Rendered Approval",
+ expiration_time=expiration_time,
+ status=HumanInputFormStatus.WAITING,
+ )
+ form.id = "form-1"
+ model = HumanInputContentModel.new(
+ workflow_run_id="workflow-run-1",
+ form_id=form.id,
+ message_id="message-1",
+ )
+ model.id = "content-1"
+ model.form = form
+ repository = SQLAlchemyExecutionExtraContentRepository(cast(sessionmaker[Session], object()))
+
+ content = repository._map_human_input_content(model, {})
+
+ assert content is not None
+ assert content.submitted is False
+ assert content.form_submission_data is None
+ assert content.form_definition is not None
+ assert content.form_definition.form_id == "form-1"
+ assert content.form_definition.node_id == "node-1"
+ assert content.form_definition.node_title == "Approval"
+ assert content.form_definition.form_content == "Rendered Approval"
+ assert content.form_definition.resolved_default_values == {"decision": "approve"}
diff --git a/api/tests/unit_tests/services/test_human_input_file_upload_service.py b/api/tests/unit_tests/services/test_human_input_file_upload_service.py
new file mode 100644
index 00000000000..c39453557cd
--- /dev/null
+++ b/api/tests/unit_tests/services/test_human_input_file_upload_service.py
@@ -0,0 +1,304 @@
+from __future__ import annotations
+
+from datetime import timedelta
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy import create_engine, select
+from sqlalchemy.orm import sessionmaker
+
+import models.account as account_module
+import services.human_input_file_upload_service as service_module
+from graphon.enums import WorkflowExecutionStatus
+from graphon.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus
+from libs.datetime_utils import naive_utc_now
+from models.account import Account, Tenant, TenantAccountJoin
+from models.base import Base
+from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
+from models.human_input import (
+ HumanInputForm,
+ HumanInputFormRecipient,
+ HumanInputFormUploadFile,
+ HumanInputFormUploadToken,
+)
+from models.model import App, AppMode, EndUser
+from models.workflow import WorkflowRun, WorkflowType
+from services.human_input_file_upload_service import HITL_UPLOAD_TOKEN_PREFIX, HumanInputFileUploadService
+from services.human_input_service import FormSubmittedError
+
+
+def session_maker(monkeypatch: pytest.MonkeyPatch):
+ engine = create_engine("sqlite:///:memory:")
+ monkeypatch.setattr(account_module, "db", SimpleNamespace(engine=engine))
+ Base.metadata.create_all(
+ engine,
+ tables=[
+ Tenant.__table__,
+ Account.__table__,
+ TenantAccountJoin.__table__,
+ App.__table__,
+ EndUser.__table__,
+ WorkflowRun.__table__,
+ HumanInputForm.__table__,
+ HumanInputFormRecipient.__table__,
+ HumanInputFormUploadToken.__table__,
+ HumanInputFormUploadFile.__table__,
+ ],
+ )
+ try:
+ yield sessionmaker(bind=engine, expire_on_commit=False)
+ finally:
+ Base.metadata.drop_all(
+ engine,
+ tables=[
+ HumanInputFormUploadFile.__table__,
+ HumanInputFormUploadToken.__table__,
+ HumanInputFormRecipient.__table__,
+ HumanInputForm.__table__,
+ WorkflowRun.__table__,
+ EndUser.__table__,
+ App.__table__,
+ TenantAccountJoin.__table__,
+ Account.__table__,
+ Tenant.__table__,
+ ],
+ )
+ engine.dispose()
+
+
+def _create_waiting_form(
+ session_maker,
+ *,
+ created_by_role: CreatorUserRole = CreatorUserRole.ACCOUNT,
+ form_kind: HumanInputFormKind = HumanInputFormKind.RUNTIME,
+) -> tuple[str, str, str]:
+ form_id = "00000000-0000-0000-0000-000000000001"
+ recipient_id = "00000000-0000-0000-0000-000000000002"
+ workflow_run_id = None
+ if form_kind == HumanInputFormKind.RUNTIME:
+ workflow_run_id = "00000000-0000-0000-0000-000000000012"
+ tenant_id = "00000000-0000-0000-0000-000000000010"
+ app_id = "00000000-0000-0000-0000-000000000011"
+ now = naive_utc_now()
+ created_by = (
+ "00000000-0000-0000-0000-000000000020"
+ if created_by_role == CreatorUserRole.ACCOUNT
+ else "00000000-0000-0000-0000-000000000021"
+ )
+ with session_maker.begin() as session:
+ tenant = Tenant(name="tenant-1")
+ tenant.id = tenant_id
+ session.add(tenant)
+ if created_by_role == CreatorUserRole.ACCOUNT:
+ account = Account(name="owner", email="[email protected]")
+ account.id = created_by
+ session.add(account)
+ session.add(
+ TenantAccountJoin(
+ tenant_id=tenant_id,
+ account_id=created_by,
+ current=True,
+ )
+ )
+ app_creator = created_by
+ else:
+ end_user = EndUser(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ type="web_app",
+ is_anonymous=False,
+ session_id="session-1",
+ external_user_id="external-1",
+ )
+ end_user.id = created_by
+ session.add(end_user)
+ app_creator = "00000000-0000-0000-0000-000000000020"
+ account = Account(name="owner", email="[email protected]")
+ account.id = app_creator
+ session.add(account)
+ session.add(
+ TenantAccountJoin(
+ tenant_id=tenant_id,
+ account_id=app_creator,
+ current=True,
+ )
+ )
+ app = App(
+ tenant_id=tenant_id,
+ name="app-1",
+ description="",
+ mode=AppMode.WORKFLOW,
+ icon_type="emoji",
+ icon="app",
+ icon_background="#ffffff",
+ enable_site=True,
+ enable_api=True,
+ created_by=app_creator,
+ updated_by=app_creator,
+ )
+ app.id = app_id
+ session.add(app)
+ if workflow_run_id is not None:
+ workflow_run = WorkflowRun(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ workflow_id="00000000-0000-0000-0000-000000000013",
+ type=WorkflowType.WORKFLOW,
+ triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
+ version="1",
+ graph="{}",
+ inputs="{}",
+ status=WorkflowExecutionStatus.RUNNING,
+ created_by_role=created_by_role,
+ created_by=created_by,
+ created_at=now,
+ )
+ workflow_run.id = workflow_run_id
+ session.add(workflow_run)
+ session.add(
+ HumanInputForm(
+ id=form_id,
+ tenant_id=tenant_id,
+ app_id=app_id,
+ workflow_run_id=workflow_run_id,
+ form_kind=form_kind,
+ node_id="node-1",
+ form_definition="{}",
+ rendered_content="content",
+ expiration_time=now + timedelta(hours=1),
+ created_at=now,
+ )
+ )
+ session.add(
+ HumanInputFormRecipient(
+ id=recipient_id,
+ form_id=form_id,
+ delivery_id="00000000-0000-0000-0000-000000000003",
+ recipient_type="standalone_web_app",
+ recipient_payload='{"TYPE": "standalone_web_app"}',
+ access_token="form-token-1",
+ )
+ )
+ return form_id, recipient_id, created_by
+
+
+def _create_service(
+ session_maker,
+ workflow_run_repository: MagicMock | None = None,
+) -> HumanInputFileUploadService:
+ return HumanInputFileUploadService(
+ session_maker,
+ workflow_run_repository=workflow_run_repository or MagicMock(),
+ )
+
+
+def test_issue_upload_token_persists_token_without_technical_end_user(
+ monkeypatch: pytest.MonkeyPatch,
+ session_maker,
+) -> None:
+ form_id, recipient_id, _created_by = _create_waiting_form(session_maker)
+ monkeypatch.setattr(service_module.secrets, "token_urlsafe", lambda _bytes: "random-value")
+
+ token = _create_service(session_maker).issue_upload_token("form-token-1")
+
+ assert token.upload_token == f"{HITL_UPLOAD_TOKEN_PREFIX}random-value"
+ with session_maker() as session:
+ token_model = session.scalar(select(HumanInputFormUploadToken))
+ assert token_model is not None
+ assert token_model.form_id == form_id
+ assert token_model.recipient_id == recipient_id
+ assert token_model.token == token.upload_token
+ assert session.scalar(select(EndUser).where(EndUser.type == "human-input")) is None
+
+
+def test_validate_upload_token_returns_account_owner_and_record_file_link(session_maker) -> None:
+ form_id, recipient_id, created_by = _create_waiting_form(session_maker, created_by_role=CreatorUserRole.ACCOUNT)
+ token = _create_service(session_maker).issue_upload_token("form-token-1")
+ workflow_run_repository = MagicMock()
+ workflow_run_repository.get_workflow_run_by_id.return_value = SimpleNamespace(
+ tenant_id="00000000-0000-0000-0000-000000000010",
+ app_id="00000000-0000-0000-0000-000000000011",
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by=created_by,
+ )
+
+ context = HumanInputFileUploadService(
+ session_maker,
+ workflow_run_repository=workflow_run_repository,
+ ).validate_upload_token(token.upload_token)
+ assert context.form_id == form_id
+ assert context.recipient_id == recipient_id
+ assert isinstance(context.owner, Account)
+ assert context.owner.id == created_by
+ assert context.owner.current_tenant_id == "00000000-0000-0000-0000-000000000010"
+ workflow_run_repository.get_workflow_run_by_id.assert_called_once_with(
+ tenant_id="00000000-0000-0000-0000-000000000010",
+ app_id="00000000-0000-0000-0000-000000000011",
+ run_id="00000000-0000-0000-0000-000000000012",
+ )
+
+ _create_service(session_maker).record_upload_file(
+ context=context,
+ file_id="00000000-0000-0000-0000-000000000099",
+ )
+
+ with session_maker() as session:
+ link = session.scalar(select(HumanInputFormUploadFile))
+ assert link is not None
+ assert link.tenant_id == context.tenant_id
+ assert link.app_id == context.app_id
+ assert link.form_id == form_id
+ assert link.upload_token_id == context.upload_token_id
+
+
+def test_validate_upload_token_returns_end_user_owner(session_maker) -> None:
+ form_id, recipient_id, created_by = _create_waiting_form(session_maker, created_by_role=CreatorUserRole.END_USER)
+ token = _create_service(session_maker).issue_upload_token("form-token-1")
+ workflow_run_repository = MagicMock()
+ workflow_run_repository.get_workflow_run_by_id.return_value = SimpleNamespace(
+ tenant_id="00000000-0000-0000-0000-000000000010",
+ app_id="00000000-0000-0000-0000-000000000011",
+ created_by_role=CreatorUserRole.END_USER,
+ created_by=created_by,
+ )
+
+ context = HumanInputFileUploadService(
+ session_maker,
+ workflow_run_repository=workflow_run_repository,
+ ).validate_upload_token(token.upload_token)
+
+ assert context.form_id == form_id
+ assert context.recipient_id == recipient_id
+ assert isinstance(context.owner, EndUser)
+ assert context.owner.id == created_by
+
+
+def test_validate_upload_token_allows_delivery_test_form(session_maker) -> None:
+ form_id, recipient_id, _created_by = _create_waiting_form(
+ session_maker,
+ form_kind=HumanInputFormKind.DELIVERY_TEST,
+ )
+ token = _create_service(session_maker).issue_upload_token("form-token-1")
+
+ context = _create_service(session_maker).validate_upload_token(token.upload_token)
+
+ assert context.form_id == form_id
+ assert context.recipient_id == recipient_id
+ assert isinstance(context.owner, Account)
+ assert context.owner.id == "00000000-0000-0000-0000-000000000020"
+ assert context.owner.current_tenant_id == "00000000-0000-0000-0000-000000000010"
+
+
+def test_validate_upload_token_rejects_submitted_form(session_maker) -> None:
+ form_id, _recipient_id, _created_by = _create_waiting_form(session_maker)
+ token = _create_service(session_maker).issue_upload_token("form-token-1")
+ with session_maker.begin() as session:
+ form = session.get(HumanInputForm, form_id)
+ assert form is not None
+ form.status = HumanInputFormStatus.SUBMITTED
+ form.submitted_at = naive_utc_now()
+
+ with pytest.raises(FormSubmittedError):
+ _create_service(session_maker).validate_upload_token(token.upload_token)
diff --git a/api/tests/unit_tests/services/test_human_input_service.py b/api/tests/unit_tests/services/test_human_input_service.py
index b6370c03657..a0434f9b436 100644
--- a/api/tests/unit_tests/services/test_human_input_service.py
+++ b/api/tests/unit_tests/services/test_human_input_service.py
@@ -6,18 +6,28 @@ import pytest
from pytest_mock import MockerFixture
import services.human_input_service as human_input_service_module
+from core.app.app_config.entities import WorkflowUIBasedAppConfig
+from core.app.entities.app_invoke_entities import InvokeFrom, WorkflowAppGenerateEntity
+from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext, _WorkflowGenerateEntityWrapper
from core.repositories.human_input_repository import (
HumanInputFormRecord,
HumanInputFormSubmissionRepository,
)
+from graphon.file import File, FileTransferMethod, FileType
from graphon.nodes.human_input.entities import (
+ FileInputConfig,
+ FileListInputConfig,
FormDefinition,
ParagraphInputConfig,
+ SelectInputConfig,
+ StringListSource,
UserActionConfig,
)
-from graphon.nodes.human_input.enums import FormInputType, HumanInputFormKind, HumanInputFormStatus
+from graphon.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus, ValueSourceType
+from graphon.runtime import GraphRuntimeState, VariablePool
from libs.datetime_utils import naive_utc_now
from models.human_input import RecipientType
+from models.model import AppMode
from services.human_input_service import (
Form,
FormExpiredError,
@@ -178,6 +188,70 @@ def test_get_form_definition_by_token_for_console_uses_repository(sample_form_re
assert form.get_definition() == console_record.definition
+def _build_resumption_context_state(*, options: list[str], workflow_run_id: str) -> bytes:
+ app_config = WorkflowUIBasedAppConfig(
+ tenant_id="tenant-id",
+ app_id="app-id",
+ app_mode=AppMode.WORKFLOW,
+ workflow_id="workflow-id",
+ )
+ generate_entity = WorkflowAppGenerateEntity(
+ task_id="task-id",
+ app_config=app_config,
+ inputs={},
+ files=[],
+ user_id="user-id",
+ stream=True,
+ invoke_from=InvokeFrom.EXPLORE,
+ call_depth=0,
+ workflow_execution_id=workflow_run_id,
+ )
+ runtime_state = GraphRuntimeState(variable_pool=VariablePool(), start_at=0.0)
+ runtime_state.variable_pool.add(("start", "options"), options)
+ context = WorkflowResumptionContext(
+ generate_entity=_WorkflowGenerateEntityWrapper(entity=generate_entity),
+ serialized_graph_runtime_state=runtime_state.dumps(),
+ )
+ return context.dumps().encode()
+
+
+def test_resolve_form_inputs_uses_runtime_select_options(sample_form_record, mock_session_factory, mocker):
+ session_factory, _ = mock_session_factory
+ configured_input = SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=["configured"],
+ ),
+ )
+ record = dataclasses.replace(
+ sample_form_record,
+ definition=sample_form_record.definition.model_copy(update={"inputs": [configured_input]}),
+ )
+ pause = MagicMock()
+ pause.resumed_at = None
+ pause.get_state.return_value = _build_resumption_context_state(
+ options=["approve", "reject"],
+ workflow_run_id=record.workflow_run_id or "",
+ )
+ workflow_run_repo = MagicMock()
+ workflow_run_repo.get_workflow_pause.return_value = pause
+ mocker.patch(
+ "services.human_input_service.DifyAPIRepositoryFactory.create_api_workflow_run_repository",
+ return_value=workflow_run_repo,
+ )
+ service = HumanInputService(session_factory)
+
+ resolved_inputs = service.resolve_form_inputs(Form(record))
+
+ assert len(resolved_inputs) == 1
+ resolved_input = resolved_inputs[0]
+ assert isinstance(resolved_input, SelectInputConfig)
+ assert resolved_input.option_source.value == ["approve", "reject"]
+ workflow_run_repo.get_workflow_pause.assert_called_once_with(record.workflow_run_id)
+
+
def test_submit_form_by_token_calls_repository_and_enqueue(
sample_form_record, mock_session_factory, mocker: MockerFixture
):
@@ -280,7 +354,7 @@ def test_submit_form_by_token_missing_inputs(sample_form_record, mock_session_fa
definition_with_input = FormDefinition(
form_content="hello",
- inputs=[ParagraphInputConfig(type=FormInputType.PARAGRAPH, output_variable_name="content")],
+ inputs=[ParagraphInputConfig(output_variable_name="content")],
user_actions=sample_form_record.definition.user_actions,
rendered_content="<p>hello</p>",
expiration_time=sample_form_record.expiration_time,
@@ -301,6 +375,123 @@ def test_submit_form_by_token_missing_inputs(sample_form_record, mock_session_fa
repo.mark_submitted.assert_not_called()
+def test_validate_human_input_submission_accepts_select_file_and_file_list(mock_session_factory):
+ session_factory, _ = mock_session_factory
+ service = HumanInputService(session_factory)
+ definition = FormDefinition.model_validate(
+ {
+ "form_content": "Pick one and upload files",
+ "inputs": [
+ {
+ "type": "select",
+ "output_variable_name": "decision",
+ "option_source": {
+ "type": "constant",
+ "value": ["approve", "reject"],
+ },
+ },
+ {
+ "type": "file",
+ "output_variable_name": "attachment",
+ "allowed_file_types": ["document"],
+ "allowed_file_upload_methods": ["remote_url"],
+ },
+ {
+ "type": "file-list",
+ "output_variable_name": "attachments",
+ "allowed_file_types": ["document"],
+ "allowed_file_upload_methods": ["remote_url"],
+ "number_limits": 3,
+ },
+ ],
+ "user_actions": [{"id": "submit", "title": "Submit"}],
+ "rendered_content": "<p>Pick one and upload files</p>",
+ "expiration_time": naive_utc_now() + timedelta(hours=1),
+ }
+ )
+
+
+ ("input_definition", "submitted_value", "expected_message"),
+ [
+ (
+ {
+ "type": "select",
+ "output_variable_name": "decision",
+ "option_source": {
+ "type": "constant",
+ "value": ["approve", "reject"],
+ },
+ },
+ "unknown",
+ "decision",
+ ),
+ (
+ {
+ "type": "file",
+ "output_variable_name": "attachment",
+ "allowed_file_types": ["document"],
+ "allowed_file_upload_methods": ["remote_url"],
+ },
+ "not-a-file",
+ "attachment",
+ ),
+ (
+ {
+ "type": "file-list",
+ "output_variable_name": "attachments",
+ "allowed_file_types": ["document"],
+ "allowed_file_upload_methods": ["remote_url"],
+ "number_limits": 2,
+ },
+ [
+ {
+ "type": "document",
+ "transfer_method": "remote_url",
+ "remote_url": "https://example.com/ok.txt",
+ "filename": "ok.txt",
+ "extension": ".txt",
+ "mime_type": "text/plain",
+ },
+ "not-a-file",
+ ],
+ "attachments",
+ ),
+ ],
+)
+def test_validate_human_input_submission_rejects_invalid_select_and_file_payloads(
+ sample_form_record,
+ mock_session_factory,
+ input_definition,
+ submitted_value,
+ expected_message,
+):
+ session_factory, _ = mock_session_factory
+ repo = MagicMock(spec=HumanInputFormSubmissionRepository)
+ definition = FormDefinition.model_validate(
+ {
+ "form_content": "Validate form data",
+ "inputs": [input_definition],
+ "user_actions": [{"id": "submit", "title": "Submit"}],
+ "rendered_content": "<p>Validate form data</p>",
+ "expiration_time": naive_utc_now() + timedelta(hours=1),
+ }
+ )
+ repo.get_by_token.return_value = dataclasses.replace(sample_form_record, definition=definition)
+ service = HumanInputService(session_factory, form_repository=repo)
+
+ with pytest.raises(InvalidFormDataError) as exc_info:
+ service.submit_form_by_token(
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ form_token="token",
+ selected_action_id="submit",
+ form_data={input_definition["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):
form = Form(sample_form_record)
assert form.id == "form-id"
@@ -468,3 +659,203 @@ def test_is_globally_expired_zero_timeout(monkeypatch, sample_form_record, mock_
monkeypatch.setattr(human_input_service_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 0)
assert service._is_globally_expired(Form(sample_form_record)) is False
+
+
+def test_submit_form_by_token_normalizes_select_and_files(sample_form_record, mock_session_factory, mocker) -> None:
+ session_factory, _ = mock_session_factory
+ repo = MagicMock(spec=HumanInputFormSubmissionRepository)
+ definition = FormDefinition(
+ form_content="hello",
+ inputs=[
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(type=ValueSourceType.CONSTANT, value=["approve", "reject"]),
+ ),
+ FileInputConfig(output_variable_name="attachment"),
+ FileListInputConfig(output_variable_name="attachments", number_limits=3),
+ ],
+ user_actions=[UserActionConfig(id="submit", title="Submit")],
+ rendered_content="<p>hello</p>",
+ expiration_time=sample_form_record.expiration_time,
+ )
+ form_with_inputs = dataclasses.replace(sample_form_record, definition=definition)
+ repo.get_by_token.return_value = form_with_inputs
+ repo.mark_submitted.return_value = form_with_inputs
+ service = HumanInputService(session_factory, form_repository=repo)
+
+ single_file = File(
+ file_id="file-1",
+ file_type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.LOCAL_FILE,
+ related_id="upload-1",
+ filename="resume.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=128,
+ )
+ list_files = [
+ File(
+ file_id="file-2",
+ file_type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.LOCAL_FILE,
+ related_id="upload-2",
+ filename="a.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=64,
+ ),
+ File(
+ file_id="file-3",
+ file_type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.REMOTE_URL,
+ remote_url="https://example.com/b.pdf",
+ filename="b.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=96,
+ ),
+ ]
+ mocker.patch("services.human_input_service.build_from_mapping", return_value=single_file)
+ mocker.patch("services.human_input_service.build_from_mappings", return_value=list_files)
+ enqueue_spy = mocker.patch.object(service, "enqueue_resume")
+
+ service.submit_form_by_token(
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ form_token="token",
+ selected_action_id="submit",
+ form_data={
+ "decision": "approve",
+ "attachment": {"transfer_method": "local_file", "upload_file_id": "upload-1", "type": "document"},
+ "attachments": [
+ {"transfer_method": "local_file", "upload_file_id": "upload-2", "type": "document"},
+ {"transfer_method": "remote_url", "url": "https://example.com/b.pdf", "type": "document"},
+ ],
+ },
+ )
+
+ submitted_data = repo.mark_submitted.call_args.kwargs["form_data"]
+ assert submitted_data["decision"] == "approve"
+ assert submitted_data["attachment"]["filename"] == "resume.pdf"
+ assert submitted_data["attachment"]["transfer_method"] == "local_file"
+ assert submitted_data["attachments"][0]["filename"] == "a.pdf"
+ assert submitted_data["attachments"][1]["filename"] == "b.pdf"
+ enqueue_spy.assert_called_once_with(sample_form_record.workflow_run_id)
+
+
+def test_submit_form_by_token_invalid_select_value(sample_form_record, mock_session_factory) -> None:
+ session_factory, _ = mock_session_factory
+ repo = MagicMock(spec=HumanInputFormSubmissionRepository)
+ definition = FormDefinition(
+ form_content="hello",
+ inputs=[
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(type=ValueSourceType.CONSTANT, value=["approve", "reject"]),
+ )
+ ],
+ user_actions=[UserActionConfig(id="submit", title="Submit")],
+ rendered_content="<p>hello</p>",
+ expiration_time=sample_form_record.expiration_time,
+ )
+ repo.get_by_token.return_value = dataclasses.replace(sample_form_record, definition=definition)
+ service = HumanInputService(session_factory, form_repository=repo)
+
+ with pytest.raises(InvalidFormDataError, match="Invalid value for select input 'decision'"):
+ service.submit_form_by_token(
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ form_token="token",
+ selected_action_id="submit",
+ form_data={"decision": "hold"},
+ )
+
+
+def test_submit_form_by_token_invalid_file_list_item(sample_form_record, mock_session_factory) -> None:
+ session_factory, _ = mock_session_factory
+ repo = MagicMock(spec=HumanInputFormSubmissionRepository)
+ definition = FormDefinition(
+ form_content="hello",
+ inputs=[FileListInputConfig(output_variable_name="attachments", number_limits=2)],
+ user_actions=[UserActionConfig(id="submit", title="Submit")],
+ rendered_content="<p>hello</p>",
+ expiration_time=sample_form_record.expiration_time,
+ )
+ repo.get_by_token.return_value = dataclasses.replace(sample_form_record, definition=definition)
+ service = HumanInputService(session_factory, form_repository=repo)
+
+ with pytest.raises(
+ InvalidFormDataError,
+ match="Invalid value for file list input 'attachments'",
+ ):
+ service.submit_form_by_token(
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ form_token="token",
+ selected_action_id="submit",
+ form_data={"attachments": ["not-a-file"]},
+ )
+
+
+def test_submit_form_by_token_rejects_cross_tenant_file(sample_form_record, mock_session_factory, mocker) -> None:
+ session_factory, _ = mock_session_factory
+ repo = MagicMock(spec=HumanInputFormSubmissionRepository)
+ definition = FormDefinition(
+ form_content="hello",
+ inputs=[FileInputConfig(output_variable_name="attachment")],
+ user_actions=[UserActionConfig(id="submit", title="Submit")],
+ rendered_content="<p>hello</p>",
+ expiration_time=sample_form_record.expiration_time,
+ )
+ repo.get_by_token.return_value = dataclasses.replace(sample_form_record, definition=definition)
+ service = HumanInputService(session_factory, form_repository=repo)
+ mocker.patch("services.human_input_service.build_from_mapping", side_effect=ValueError("Invalid upload file"))
+
+ with pytest.raises(InvalidFormDataError, match="Invalid value for file input 'attachment'"):
+ service.submit_form_by_token(
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ form_token="token",
+ selected_action_id="submit",
+ form_data={
+ "attachment": {
+ "transfer_method": "local_file",
+ "upload_file_id": "4e0d1b87-52f2-49f6-b8c6-95cd9c954b3e",
+ "type": "document",
+ }
+ },
+ )
+
+ repo.mark_submitted.assert_not_called()
+
+
+def test_submit_form_by_token_rejects_cross_tenant_file_list(sample_form_record, mock_session_factory, mocker) -> None:
+ session_factory, _ = mock_session_factory
+ repo = MagicMock(spec=HumanInputFormSubmissionRepository)
+ definition = FormDefinition(
+ form_content="hello",
+ inputs=[FileListInputConfig(output_variable_name="attachments", number_limits=2)],
+ user_actions=[UserActionConfig(id="submit", title="Submit")],
+ rendered_content="<p>hello</p>",
+ expiration_time=sample_form_record.expiration_time,
+ )
+ repo.get_by_token.return_value = dataclasses.replace(sample_form_record, definition=definition)
+ service = HumanInputService(session_factory, form_repository=repo)
+ mocker.patch("services.human_input_service.build_from_mappings", side_effect=ValueError("Invalid upload file"))
+
+ with pytest.raises(
+ InvalidFormDataError,
+ match="Invalid value for file list input 'attachments'",
+ ):
+ service.submit_form_by_token(
+ recipient_type=RecipientType.STANDALONE_WEB_APP,
+ form_token="token",
+ selected_action_id="submit",
+ form_data={
+ "attachments": [
+ {
+ "transfer_method": "local_file",
+ "upload_file_id": "4e0d1b87-52f2-49f6-b8c6-95cd9c954b3e",
+ "type": "document",
+ }
+ ]
+ },
+ )
+
+ repo.mark_submitted.assert_not_called()
diff --git a/api/tests/unit_tests/services/test_workflow_service.py b/api/tests/unit_tests/services/test_workflow_service.py
index d384c5a83ba..cb494ab8db9 100644
--- a/api/tests/unit_tests/services/test_workflow_service.py
+++ b/api/tests/unit_tests/services/test_workflow_service.py
@@ -2682,6 +2682,7 @@ class TestWorkflowServiceHumanInputOperations:
SimpleNamespace(id="submit", title="card_visa_enterprise_001"),
]
mock_node.node_data.outputs_field_names.return_value = ["field1"]
+ mock_node.node_data.inputs = []
mock_node.render_form_content_before_submission.return_value = "Ticket: {{#$output.field1#}}"
mock_node.render_form_content_with_outputs.return_value = "Ticket: val1"
@@ -2691,7 +2692,10 @@ class TestWorkflowServiceHumanInputOperations:
patch("models.workflow.Workflow.get_node_type_from_node_config", return_value=BuiltinNodeTypes.HUMAN_INPUT),
patch.object(service, "_build_human_input_variable_pool"),
patch("services.workflow_service.HumanInputNode", return_value=mock_node),
- patch("services.workflow_service.validate_human_input_submission"),
+ patch(
+ "services.workflow_service.HumanInputService.validate_and_normalize_submission",
+ return_value={"field1": "val1"},
+ ) as mock_validate,
patch("services.workflow_service.Session"),
patch("services.workflow_service.DraftVariableSaver") as mock_saver_cls,
):
@@ -2699,6 +2703,7 @@ class TestWorkflowServiceHumanInputOperations:
app_model=app_model, account=account, node_id="node-1", form_inputs={"field1": "val1"}, action="submit"
)
assert result["__action_id"] == "submit"
+ mock_validate.assert_called_once()
assert result["__action_value"] == "card_visa_enterprise_001"
assert result["__rendered_content"] == "Ticket: val1"
mock_saver_cls.return_value.save.assert_called_once()
@@ -2714,7 +2719,7 @@ class TestWorkflowServiceHumanInputOperations:
patch.object(service, "_resolve_human_input_delivery_method") as mock_resolve,
patch("services.workflow_service.apply_dify_debug_email_recipient"),
patch.object(service, "_build_human_input_variable_pool"),
- patch.object(service, "_build_human_input_node"),
+ patch.object(service, "_build_human_input_node_for_debugging"),
patch.object(service, "_create_human_input_delivery_test_form", return_value=("form-1", [])),
patch("services.workflow_service.HumanInputDeliveryTestService") as mock_test_srv,
):
@@ -2842,8 +2847,8 @@ class TestWorkflowServiceFreeNodeExecution:
with pytest.raises(Exception, match="unreachable"):
_rebuild_single_file("tenant-1", {}, cast(Any, "invalid_type"))
- def test_build_human_input_node(self, service: WorkflowService) -> None:
- """Cover _build_human_input_node (lines 1065-1088)."""
+ def test_build_human_input_node_for_debugging(self, service: WorkflowService) -> None:
+ """Cover _build_human_input_node_for_debugging."""
workflow = MagicMock()
workflow.id = "wf-1"
workflow.tenant_id = "t-1"
@@ -2863,10 +2868,11 @@ class TestWorkflowServiceFreeNodeExecution:
patch("services.workflow_service.build_dify_run_context") as mock_build_dify_run_context,
patch("services.workflow_service.DifyFileReferenceFactory") as mock_file_reference_factory_cls,
patch("services.workflow_service.DifyHumanInputNodeRuntime") as mock_runtime_cls,
+ patch("services.workflow_service.DifyFileReferenceFactory") as mock_file_reference_factory_cls,
patch("services.workflow_service.HumanInputNode") as mock_node_cls,
):
mock_node_cls.validate_node_data.return_value = sentinel.node_data
- node = service._build_human_input_node(
+ node = service._build_human_input_node_for_debugging(
workflow=workflow, account=account, node_config=node_config, variable_pool=variable_pool
)
assert node == mock_node_cls.return_value
@@ -2878,11 +2884,10 @@ class TestWorkflowServiceFreeNodeExecution:
call_depth=0,
)
mock_runtime_cls.assert_called_once_with(mock_build_dify_run_context.return_value)
+ mock_file_reference_factory_cls.assert_called_once_with(mock_build_dify_run_context.return_value)
mock_adapt_node_data.assert_called_once_with(node_config["data"])
mock_node_cls.validate_node_data.assert_called_once_with(sentinel.adapted_node_data)
- mock_file_reference_factory_cls.assert_called_once_with(
- mock_graph_init_context_cls.return_value.to_graph_init_params.return_value.run_context
- )
+ mock_file_reference_factory_cls.assert_called_once_with(mock_build_dify_run_context.return_value)
mock_node_cls.assert_called_once_with(
node_id="n-1",
data=sentinel.node_data,
diff --git a/api/tests/unit_tests/services/workflow/test_workflow_event_snapshot_service.py b/api/tests/unit_tests/services/workflow/test_workflow_event_snapshot_service.py
index 17e9a077d62..a997ea35832 100644
--- a/api/tests/unit_tests/services/workflow/test_workflow_event_snapshot_service.py
+++ b/api/tests/unit_tests/services/workflow/test_workflow_event_snapshot_service.py
@@ -18,6 +18,8 @@ from core.app.entities.task_entities import StreamEvent
from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext, _WorkflowGenerateEntityWrapper
from graphon.entities.pause_reason import HumanInputRequired
from graphon.enums import WorkflowExecutionStatus, WorkflowNodeExecutionStatus
+from graphon.nodes.human_input.entities import SelectInputConfig, StringListSource
+from graphon.nodes.human_input.enums import ValueSourceType
from graphon.runtime import GraphRuntimeState, VariablePool
from models.enums import CreatorUserRole
from models.model import AppMode
@@ -106,7 +108,7 @@ def _build_snapshot(status: WorkflowNodeExecutionStatus) -> WorkflowNodeExecutio
)
-def _build_resumption_context(task_id: str) -> WorkflowResumptionContext:
+def _build_resumption_context(task_id: str, *, select_options: list[str] | None = None) -> WorkflowResumptionContext:
app_config = WorkflowUIBasedAppConfig(
tenant_id="tenant-1",
app_id="app-1",
@@ -125,6 +127,8 @@ def _build_resumption_context(task_id: str) -> WorkflowResumptionContext:
workflow_execution_id="run-1",
)
runtime_state = GraphRuntimeState(variable_pool=VariablePool(), start_at=0.0)
+ if select_options is not None:
+ runtime_state.variable_pool.add(("start", "options"), select_options)
runtime_state.register_paused_node("node-1")
runtime_state.outputs = {"result": "value"}
wrapper = _WorkflowGenerateEntityWrapper(entity=generate_entity)
@@ -787,6 +791,59 @@ def test_build_snapshot_events_preserves_public_form_token(monkeypatch: pytest.M
assert pause_data["reasons"][0]["expiration_time"] == int(datetime(2024, 1, 1, tzinfo=UTC).timestamp())
+def test_build_snapshot_events_resolves_pause_reason_select_options(monkeypatch: pytest.MonkeyPatch) -> None:
+ workflow_run = _build_workflow_run(WorkflowExecutionStatus.PAUSED)
+ snapshot = _build_snapshot(WorkflowNodeExecutionStatus.PAUSED)
+ resumption_context = _build_resumption_context("task-ctx", select_options=["approve", "reject"])
+ monkeypatch.setattr(
+ service_module, "load_form_tokens_by_form_id", lambda form_ids, session=None, surface=None: {"form-1": "wtok"}
+ )
+ session_maker = _SessionMaker(
+ SimpleNamespace(
+ execute=lambda _stmt: [("form-1", datetime(2024, 1, 1, tzinfo=UTC), '{"display_in_ui": true}')],
+ )
+ )
+ pause_entity = _FakePauseEntity(
+ pause_id="pause-1",
+ workflow_run_id="run-1",
+ paused_at_value=datetime(2024, 1, 1, tzinfo=UTC),
+ pause_reasons=[
+ HumanInputRequired(
+ form_id="form-1",
+ form_content="content",
+ inputs=[
+ SelectInputConfig(
+ output_variable_name="decision",
+ option_source=StringListSource(
+ type=ValueSourceType.VARIABLE,
+ selector=["start", "options"],
+ value=[],
+ ),
+ )
+ ],
+ node_id="node-1",
+ node_title="Human Input",
+ )
+ ],
+ )
+
+ events = _build_snapshot_events(
+ workflow_run=workflow_run,
+ node_snapshots=[snapshot],
+ task_id="task-ctx",
+ message_context=None,
+ pause_entity=pause_entity,
+ resumption_context=resumption_context,
+ session_maker=cast(sessionmaker[Session], session_maker),
+ )
+
+ human_input_event = events[-2]
+ assert human_input_event["data"]["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
+
+ pause_event = events[-1]
+ assert pause_event["data"]["reasons"][0]["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
+
+
def test_build_workflow_event_stream_loads_pause_tokens_without_flask_app_context(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py b/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py
index 170bb24b8af..4b677bca62f 100644
--- a/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py
+++ b/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py
@@ -76,11 +76,11 @@ def test_human_input_delivery_allows_disabled_method(monkeypatch: pytest.MonkeyP
service.get_draft_workflow = MagicMock(return_value=workflow) # type: ignore[method-assign]
service._build_human_input_variable_pool = MagicMock(return_value=MagicMock()) # type: ignore[attr-defined]
node_stub = MagicMock()
- node_stub._render_form_content_before_submission.return_value = "rendered"
- node_stub._resolve_default_values.return_value = {}
- service._build_human_input_node = MagicMock(return_value=node_stub) # type: ignore[attr-defined]
+ node_stub.render_form_content_before_submission.return_value = "rendered"
+ node_stub.resolve_default_values.return_value = {}
+ service._build_human_input_node_for_debugging = MagicMock(return_value=node_stub) # type: ignore[attr-defined]
service._create_human_input_delivery_test_form = MagicMock( # type: ignore[attr-defined]
- return_value=("form-1", {})
+ return_value=("form-1", [])
)
test_service_instance = MagicMock()
@@ -112,11 +112,11 @@ def test_human_input_delivery_dispatches_to_test_service(monkeypatch: pytest.Mon
service.get_draft_workflow = MagicMock(return_value=workflow) # type: ignore[method-assign]
service._build_human_input_variable_pool = MagicMock(return_value=MagicMock()) # type: ignore[attr-defined]
node_stub = MagicMock()
- node_stub._render_form_content_before_submission.return_value = "rendered"
- node_stub._resolve_default_values.return_value = {}
- service._build_human_input_node = MagicMock(return_value=node_stub) # type: ignore[attr-defined]
+ node_stub.render_form_content_before_submission.return_value = "rendered"
+ node_stub.resolve_default_values.return_value = {}
+ service._build_human_input_node_for_debugging = MagicMock(return_value=node_stub) # type: ignore[attr-defined]
service._create_human_input_delivery_test_form = MagicMock( # type: ignore[attr-defined]
- return_value=("form-1", {})
+ return_value=("form-1", [])
)
test_service_instance = MagicMock()
@@ -151,11 +151,11 @@ def test_human_input_delivery_debug_mode_overrides_recipients(monkeypatch: pytes
service.get_draft_workflow = MagicMock(return_value=workflow) # type: ignore[method-assign]
service._build_human_input_variable_pool = MagicMock(return_value=MagicMock()) # type: ignore[attr-defined]
node_stub = MagicMock()
- node_stub._render_form_content_before_submission.return_value = "rendered"
- node_stub._resolve_default_values.return_value = {}
- service._build_human_input_node = MagicMock(return_value=node_stub) # type: ignore[attr-defined]
+ node_stub.render_form_content_before_submission.return_value = "rendered"
+ node_stub.resolve_default_values.return_value = {}
+ service._build_human_input_node_for_debugging = MagicMock(return_value=node_stub) # type: ignore[attr-defined]
service._create_human_input_delivery_test_form = MagicMock( # type: ignore[attr-defined]
- return_value=("form-1", {})
+ return_value=("form-1", [])
)
test_service_instance = MagicMock()
diff --git a/docs/design/human-in-the-loop/hitl-form-file-upload-design.md b/docs/design/human-in-the-loop/hitl-form-file-upload-design.md
new file mode 100644
index 00000000000..86a81d70c95
--- /dev/null
+++ b/docs/design/human-in-the-loop/hitl-form-file-upload-design.md
@@ -0,0 +1,184 @@
+# HITL Standalone Form File Upload Design
+
+## Context
+
+HITL standalone forms can be opened directly through a form link and do not require the
+submitter to sign in through the Web App. After `file` and `file-list` inputs were introduced,
+this standalone entry point also needed file upload support.
+
+This entry point has a different identity model from the existing upload paths:
+
+- Web App upload is backed by Web App authentication and an `EndUser` context.
+- Service API upload is backed by API key authentication and the `user` parameter.
+- HITL standalone form submission is link-based and anonymous from the product perspective.
+ The standalone submitter is not necessarily the workflow or chatflow initiator.
+
+The goal is therefore not to add another general-purpose upload channel. The goal is to
+provide a constrained, short-lived upload capability that is scoped to one HITL form submission.
+
+## Goals
+
+- Support local file upload and remote URL upload from the HITL standalone page.
+- Keep the standalone page independent from the Web App login flow.
+- Avoid creating a technical HITL `EndUser`.
+- Avoid changing the authentication model of existing Web App, Service API, or Console upload endpoints.
+- Keep upload request parameters aligned with the equivalent Web App upload endpoints where possible.
+- Invalidate upload capability once the form is submitted, expired, or timed out.
+- Store uploaded files in a way that remains compatible with the existing workflow resume and file access model.
+
+## Decision
+
+HITL standalone upload uses a dedicated upload token that is bound to a form
+recipient. The token authorizes file upload only while the related form is still valid.
+
+Files uploaded through the HITL standalone page are recorded under the workflow or
+chatflow initiator, not under the anonymous standalone submitter and not under a technical HITL `EndUser`.
+
+This keeps workflow resume aligned with the existing execution model: one initiator owns the
+workflow run context, and file restoration continues to resolve files through that initiator's
+access scope. HITL-specific form/token/file relationships remain available for audit and tracing,
+but they do not become the source of truth for file access control.
+
+## API Shape
+
+HITL standalone upload has three endpoint categories:
+
+| Purpose | HITL endpoint | Aligned Web App endpoint |
+| --- | --- | --- |
+| Issue upload token | `POST /api/form/human_input/{form_token}/upload-token` | No direct equivalent |
+| Upload local file | `POST /api/form/human_input/files/upload` | `POST /api/files/upload` |
+| Upload remote file | `POST /api/form/human_input/files/remote-upload` | `POST /api/remote-files/upload` |
+
+Local upload follows the Web App `POST /api/files/upload` parameter shape:
+
+- `multipart/form-data`
+- Required `file`
+
+Remote upload follows the Web App `POST /api/remote-files/upload` parameter shape:
+
+- `application/json`
+- Required `url`
+
+HITL upload endpoints do not accept the Service API `user` parameter. That parameter
+belongs to the Service API `EndUser` mapping model and does not represent the anonymous
+standalone form submitter.
+
+## Upload Token
+
+The upload token is issued through the form token:
+
+```http
+POST /api/form/human_input/{form_token}/upload-token
+```
+
+Upload requests carry the token through the `Authorization` header:
+
+```http
+Authorization: bearer hitl_upload_{random_value}
+```
+
+The `hitl_upload_` prefix only distinguishes this credential from other bearer token types.
+Security comes from the high-entropy random value, server-side hash storage, and server-side state validation.
+
+The token is bound to at least:
+
+- The HITL form.
+- The form recipient.
+- The tenant.
+- The app.
+
+The token must satisfy these rules:
+
+- It cannot outlive the form expiration.
+- It cannot be used after the form is submitted, expired, or timed out.
+- It is validated through the HITL upload path, not through the existing app token validation chain.
+
+## Why Authorization Header
+
+Putting `upload_token` in the request body would avoid additional CORS header configuration, but it has a bad failure mode for file upload. The server often needs to parse the multipart body before it can read a body token, so invalid requests can still consume upload parsing, temporary file, memory, or disk resources.
+
+Using `Authorization: bearer hitl_upload_{random_value}` keeps authentication before expensive business processing:
+
+- Invalid local upload requests can be rejected before reading the multipart body.
+- Invalid remote upload requests can be rejected before any outbound network access.
+- Bearer credential semantics are explicit and do not mix authentication with business fields.
+- The token is not exposed through query strings, access logs, referrers, or browser history.
+
+The tradeoff is that cross-origin deployments must allow the `Authorization` header and accept browser preflight requests. This is a reasonable configuration cost for an earlier and clearer authentication boundary.
+
+## File Ownership
+
+The standalone submitter is not a reliable product identity. Assigning files to a technical `EndUser` would also conflict with workflow resume: existing file restoration expects files to be readable through the workflow or chatflow initiator's scope.
+
+The selected model is:
+
+- If the original run was started by an `Account`, standalone HITL uploads are stored under that `Account`.
+- If the original run was started by an `EndUser`, standalone HITL uploads are stored under that `EndUser`.
+
+This means `UploadFile.created_by_role` and `UploadFile.created_by` continue to be the source of truth for file access control. HITL association records provide auditability but do not grant file access by themselves.
+
+## Persistence And Audit
+
+The HITL upload model has two responsibilities:
+
+- Upload tokens authorize a form recipient to upload files while the form remains valid.
+- Upload-file association records trace which files were uploaded through which HITL upload token.
+
+These records are intentionally not tied to an `EndUser`. Their purpose is to preserve the HITL form/token/file relationship for audit and cleanup, not to define a separate file owner identity.
+
+## Local Upload Boundary
+
+Local upload should reuse the existing file upload semantics as much as possible:
+
+- Request parameters stay aligned with Web App local upload.
+- Existing file size checks, extension restrictions, and document-type handling remain applicable.
+- Response shape stays aligned with the existing file upload response.
+- Token validation happens before reading the upload body.
+
+## Remote Upload Boundary
+
+Remote upload should reuse the existing remote upload semantics as much as possible:
+
+- Request parameters stay aligned with Web App remote upload.
+- Token validation happens before outbound network access.
+- Remote fetching continues to go through the existing SSRF-safe path.
+- Remote filename, extension, MIME type, and file size inference stay aligned with existing behavior.
+- Response shape stays aligned with the existing remote upload response.
+
+## Alternatives Considered
+
+### Unauthenticated Standalone Upload Endpoint
+
+This is the simplest implementation option and does not require Web App login, `EndUser`, or a new token model. It was not selected because it exposes a public file upload surface that can be abused in SaaS or internet-facing deployments. Adding authentication later would also change the endpoint contract after clients have integrated with it.
+
+### Reuse Web App Login And Upload
+
+This would maximize reuse of existing Web App upload behavior, but it would bind HITL standalone forms to Web App login, app code, Web App enablement, and enterprise SSO semantics. That coupling is undesirable because HITL forms can be reached from independent channels such as email. It also makes product behavior unclear when the Web App is disabled or the app code is reset.
+
+### Create `EndUser` From Form Token
+
+This would satisfy existing upload paths that require an `EndUser` context and would allow form state to limit upload capability. It was not selected because the created identity would be technical rather than a real submitter identity. It would also mix HITL standalone form behavior into the broader `EndUser` model already used by Web App, Service API, triggers, MCP, and other entry points.
+
+More importantly, files owned by this technical `EndUser` would not naturally be readable through the workflow initiator scope during workflow resume.
+
+### Technical `EndUser` With File Access Exception
+
+This would keep the technical `EndUser` as the file owner and add an access-control exception so the workflow initiator can read files uploaded through the same HITL form. It solves the immediate resume problem, but it pushes a HITL-specific rule into the general file access layer. Over time, that makes permission reasoning harder and increases the chance of accidental access expansion.
+
+Assigning files directly to the workflow or chatflow initiator avoids that bypass and keeps file access governed by the existing owner model.
+
+## Design Constraints
+
+- HITL standalone upload does not reuse the Web App login flow.
+- HITL standalone upload does not create a technical HITL `EndUser`.
+- Upload token validity is controlled by form state.
+- File access control continues to use the `UploadFile` owner as the source of truth.
+- HITL association records provide audit and traceability only.
+- Workflow resume continues to restore submitted file values through the existing file restoration path.
+
+## Future Considerations
+
+- If endpoint parameters change, compare them with the corresponding Web App upload endpoint to avoid unnecessary drift.
+- If file ownership changes, verify the workflow resume path and the file access model together.
+- If HITL forms support multiple submissions or reopening, token invalidation semantics must be redefined.
+- If remote upload policy expands, prefer extending the existing remote upload and SSRF-safe behavior instead of creating a HITL-only network path.
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 7675b4dd775..e1a54ec37cf 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -145,11 +145,6 @@
"count": 1
}
},
- "web/app/(humanInputLayout)/form/[token]/form.tsx": {
- "react/set-state-in-effect": {
- "count": 1
- }
- },
"web/app/(shareLayout)/components/splash.tsx": {
"react/set-state-in-effect": {
"count": 1
@@ -857,16 +852,6 @@
"count": 1
}
},
- "web/app/components/base/chat/chat/answer/human-input-content/utils.ts": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/base/chat/chat/answer/index.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/base/chat/chat/answer/workflow-process.tsx": {
"react/set-state-in-effect": {
"count": 1
@@ -903,7 +888,7 @@
},
"web/app/components/base/chat/chat/index.tsx": {
"ts/no-explicit-any": {
- "count": 3
+ "count": 2
},
"ts/no-non-null-asserted-optional-chain": {
"count": 1
@@ -921,7 +906,7 @@
},
"web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx": {
"ts/no-explicit-any": {
- "count": 7
+ "count": 6
}
},
"web/app/components/base/chat/embedded-chatbot/context.ts": {
@@ -1052,9 +1037,6 @@
"web/app/components/base/file-uploader/hooks.ts": {
"react/no-unnecessary-use-prefix": {
"count": 1
- },
- "ts/no-explicit-any": {
- "count": 3
}
},
"web/app/components/base/file-uploader/index.ts": {
@@ -1632,11 +1614,6 @@
"count": 2
}
},
- "web/app/components/base/prompt-editor/index.tsx": {
- "ts/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx": {
"no-restricted-imports": {
"count": 1
@@ -1684,16 +1661,6 @@
"count": 2
}
},
- "web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx": {
- "react-hooks/exhaustive-deps": {
- "count": 1
- }
- },
- "web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx": {
"no-barrel-files/no-barrel-files": {
"count": 3
@@ -4032,22 +3999,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx": {
- "react/unsupported-syntax": {
- "count": 1
- }
- },
- "web/app/components/workflow/nodes/human-input/components/form-content.tsx": {
- "react/no-nested-component-definitions": {
- "count": 1
- },
- "react/set-state-in-effect": {
- "count": 1
- },
- "ts/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/workflow/nodes/human-input/components/timeout.tsx": {
"no-restricted-imports": {
"count": 1
@@ -4058,11 +4009,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx": {
- "react-refresh/only-export-components": {
- "count": 2
- }
- },
"web/app/components/workflow/nodes/human-input/types.ts": {
"erasable-syntax-only/enums": {
"count": 2
@@ -4644,7 +4590,7 @@
},
"web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx": {
"ts/no-explicit-any": {
- "count": 6
+ "count": 5
}
},
"web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx": {
@@ -4657,7 +4603,7 @@
"count": 2
},
"ts/no-explicit-any": {
- "count": 12
+ "count": 11
}
},
"web/app/components/workflow/panel/env-panel/variable-modal.tsx": {
@@ -4683,7 +4629,7 @@
},
"web/app/components/workflow/panel/workflow-preview.tsx": {
"ts/no-explicit-any": {
- "count": 2
+ "count": 1
}
},
"web/app/components/workflow/run/agent-log/index.tsx": {
@@ -5303,9 +5249,6 @@
"no-restricted-imports": {
"count": 1
},
- "regexp/no-unused-capturing-group": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 2
}
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index c36a9ef7fc8..c1bccffa9ce 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -1710,6 +1710,9 @@ export type HumanInputFormSubmissionData = {
node_id: string
node_title: string
rendered_content: string
+ submitted_data?: {
+ [key: string]: JsonValue2
+ } | null
}
export type ExecutionContentType = 'human_input'
@@ -1865,6 +1868,8 @@ export type UserActionConfig = {
export type FormInputConfig = unknown
+export type JsonValue2 = unknown
+
export type OutputErrorStrategy = 'default_value' | 'fail_branch' | 'stop'
export type DeclaredOutputRetryConfig = {
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index 73d37bd958f..ccff2c49f02 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -1848,17 +1848,6 @@ export const zConversationPagination = z.object({
total: z.int(),
})
-/**
- * HumanInputFormSubmissionData
- */
-export const zHumanInputFormSubmissionData = z.object({
- action_id: z.string(),
- action_text: z.string(),
- node_id: z.string(),
- node_title: z.string(),
- rendered_content: z.string(),
-})
-
/**
* ExecutionContentType
*/
@@ -2154,6 +2143,20 @@ export const zAgentSensitiveWordAvoidanceFeatureConfig = z.object({
export const zFormInputConfig = z.unknown()
+export const zJsonValue2 = z.unknown()
+
+/**
+ * HumanInputFormSubmissionData
+ */
+export const zHumanInputFormSubmissionData = z.object({
+ action_id: z.string(),
+ action_text: z.string(),
+ node_id: z.string(),
+ node_title: z.string(),
+ rendered_content: z.string(),
+ submitted_data: z.record(z.string(), zJsonValue2).nullish(),
+})
+
/**
* OutputErrorStrategy
*
diff --git a/packages/contracts/generated/api/web/orpc.gen.ts b/packages/contracts/generated/api/web/orpc.gen.ts
index 4e7c949bdb7..ee46faf3506 100644
--- a/packages/contracts/generated/api/web/orpc.gen.ts
+++ b/packages/contracts/generated/api/web/orpc.gen.ts
@@ -64,6 +64,9 @@ import {
zPostForgotPasswordValidityResponse,
zPostFormHumanInputByFormTokenPath,
zPostFormHumanInputByFormTokenResponse,
+ zPostFormHumanInputByFormTokenUploadTokenPath,
+ zPostFormHumanInputByFormTokenUploadTokenResponse,
+ zPostHumanInputFormsFilesResponse,
zPostLoginBody,
zPostLoginResponse,
zPostLogoutResponse,
@@ -469,6 +472,34 @@ export const forgotPassword = {
validity: validity2,
}
+/**
+ * Issue an upload token for a human input form
+ *
+ * POST /api/form/human_input/<form_token>/upload-token
+ *
+ * Generated contract types may be inaccurate because backend OpenAPI annotations are incomplete. Do not migrate callers until the generated contract is accurate.
+ *
+ * @deprecated
+ */
+export const post13 = oc
+ .route({
+ deprecated: true,
+ description:
+ 'POST /api/form/human_input/<form_token>/upload-token\n\nGenerated contract types may be inaccurate because backend OpenAPI annotations are incomplete. Do not migrate callers until the generated contract is accurate.',
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postFormHumanInputByFormTokenUploadToken',
+ path: '/form/human_input/{form_token}/upload-token',
+ summary: 'Issue an upload token for a human input form',
+ tags: ['web'],
+ })
+ .input(z.object({ params: zPostFormHumanInputByFormTokenUploadTokenPath }))
+ .output(zPostFormHumanInputByFormTokenUploadTokenResponse)
+
+export const uploadToken = {
+ post: post13,
+}
+
/**
* Get human input form definition by token
*
@@ -510,7 +541,7 @@ export const get2 = oc
*
* @deprecated
*/
-export const post13 = oc
+export const post14 = oc
.route({
deprecated: true,
description:
@@ -527,7 +558,8 @@ export const post13 = oc
export const byFormToken = {
get: get2,
- post: post13,
+ post: post14,
+ uploadToken,
}
export const humanInput = {
@@ -538,6 +570,29 @@ export const form = {
humanInput,
}
+/**
+ * Upload one local file or remote URL file for a HITL human input form
+ */
+export const post15 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postHumanInputFormsFiles',
+ path: '/human-input-forms/files',
+ successStatus: 201,
+ summary: 'Upload one local file or remote URL file for a HITL human input form',
+ tags: ['web'],
+ })
+ .output(zPostHumanInputFormsFilesResponse)
+
+export const files2 = {
+ post: post15,
+}
+
+export const humanInputForms = {
+ files: files2,
+}
+
/**
* Check login status
*/
@@ -561,7 +616,7 @@ export const status = {
*
* Authenticate user for web application access
*/
-export const post14 = oc
+export const post16 = oc
.route({
description: 'Authenticate user for web application access',
inputStructure: 'detailed',
@@ -575,14 +630,14 @@ export const post14 = oc
.output(zPostLoginResponse)
export const login = {
- post: post14,
+ post: post16,
status,
}
/**
* Logout user from web application
*/
-export const post15 = oc
+export const post17 = oc
.route({
description: 'Logout user from web application',
inputStructure: 'detailed',
@@ -594,7 +649,7 @@ export const post15 = oc
.output(zPostLogoutResponse)
export const logout = {
- post: post15,
+ post: post17,
}
/**
@@ -604,7 +659,7 @@ export const logout = {
*
* @deprecated
*/
-export const post16 = oc
+export const post18 = oc
.route({
deprecated: true,
description:
@@ -624,7 +679,7 @@ export const post16 = oc
.output(zPostMessagesByMessageIdFeedbacksResponse)
export const feedbacks = {
- post: post16,
+ post: post18,
}
/**
@@ -813,7 +868,7 @@ export const passport = {
*
* @deprecated
*/
-export const post17 = oc
+export const post19 = oc
.route({
deprecated: true,
description:
@@ -829,7 +884,7 @@ export const post17 = oc
.output(zPostRemoteFilesUploadResponse)
export const upload2 = {
- post: post17,
+ post: post19,
}
/**
@@ -921,7 +976,7 @@ export const get11 = oc
*
* @deprecated
*/
-export const post18 = oc
+export const post20 = oc
.route({
deprecated: true,
description:
@@ -937,7 +992,7 @@ export const post18 = oc
export const savedMessages = {
get: get11,
- post: post18,
+ post: post20,
byMessageId: byMessageId2,
}
@@ -1014,7 +1069,7 @@ export const systemFeatures = {
*
* @deprecated
*/
-export const post19 = oc
+export const post21 = oc
.route({
deprecated: true,
description:
@@ -1030,7 +1085,7 @@ export const post19 = oc
.output(zPostTextToAudioResponse)
export const textToAudio = {
- post: post19,
+ post: post21,
}
/**
@@ -1123,7 +1178,7 @@ export const workflow = {
*
* @deprecated
*/
-export const post20 = oc
+export const post22 = oc
.route({
deprecated: true,
description:
@@ -1139,7 +1194,7 @@ export const post20 = oc
.output(zPostWorkflowsRunResponse)
export const run = {
- post: post20,
+ post: post22,
}
/**
@@ -1147,7 +1202,7 @@ export const run = {
*
* Stop a running workflow task.
*/
-export const post21 = oc
+export const post23 = oc
.route({
description: 'Stop a running workflow task.',
inputStructure: 'detailed',
@@ -1161,7 +1216,7 @@ export const post21 = oc
.output(zPostWorkflowsTasksByTaskIdStopResponse)
export const stop3 = {
- post: post21,
+ post: post23,
}
export const byTaskId4 = {
@@ -1186,6 +1241,7 @@ export const contract = {
files,
forgotPassword,
form,
+ humanInputForms,
login,
logout,
messages,
diff --git a/packages/contracts/generated/api/web/types.gen.ts b/packages/contracts/generated/api/web/types.gen.ts
index cc18ffaf597..d55fc42389a 100644
--- a/packages/contracts/generated/api/web/types.gen.ts
+++ b/packages/contracts/generated/api/web/types.gen.ts
@@ -128,6 +128,15 @@ export type ForgotPasswordSendPayload = {
language?: string | null
}
+export type HumanInputFileUploadFormPayload = {
+ url?: string | null
+}
+
+export type HumanInputUploadTokenResponse = {
+ expires_at: number
+ upload_token: string
+}
+
export type LicenseLimitationModel = {
enabled: boolean
limit: number
@@ -853,6 +862,38 @@ export type PostFormHumanInputByFormTokenResponses = {
export type PostFormHumanInputByFormTokenResponse
= PostFormHumanInputByFormTokenResponses[keyof PostFormHumanInputByFormTokenResponses]
+export type PostFormHumanInputByFormTokenUploadTokenData = {
+ body?: never
+ path: {
+ form_token: string
+ }
+ query?: never
+ url: '/form/human_input/{form_token}/upload-token'
+}
+
+export type PostFormHumanInputByFormTokenUploadTokenResponses = {
+ 200: {
+ [key: string]: unknown
+ }
+}
+
+export type PostFormHumanInputByFormTokenUploadTokenResponse
+ = PostFormHumanInputByFormTokenUploadTokenResponses[keyof PostFormHumanInputByFormTokenUploadTokenResponses]
+
+export type PostHumanInputFormsFilesData = {
+ body?: never
+ path?: never
+ query?: never
+ url: '/human-input-forms/files'
+}
+
+export type PostHumanInputFormsFilesResponses = {
+ 201: FileResponse
+}
+
+export type PostHumanInputFormsFilesResponse
+ = PostHumanInputFormsFilesResponses[keyof PostHumanInputFormsFilesResponses]
+
export type PostLoginData = {
body: LoginPayload
path?: never
diff --git a/packages/contracts/generated/api/web/zod.gen.ts b/packages/contracts/generated/api/web/zod.gen.ts
index 9f11a0eaebf..818bceced1e 100644
--- a/packages/contracts/generated/api/web/zod.gen.ts
+++ b/packages/contracts/generated/api/web/zod.gen.ts
@@ -172,6 +172,23 @@ export const zForgotPasswordSendPayload = z.object({
language: z.string().nullish(),
})
+/**
+ * HumanInputFileUploadFormPayload
+ *
+ * Parsed multipart form fields for HITL uploads.
+ */
+export const zHumanInputFileUploadFormPayload = z.object({
+ url: z.url().min(1).max(2083).nullish(),
+})
+
+/**
+ * HumanInputUploadTokenResponse
+ */
+export const zHumanInputUploadTokenResponse = z.object({
+ expires_at: z.int(),
+ upload_token: z.string(),
+})
+
/**
* LicenseLimitationModel
*
@@ -545,6 +562,20 @@ export const zPostFormHumanInputByFormTokenPath = z.object({
*/
export const zPostFormHumanInputByFormTokenResponse = z.record(z.string(), z.unknown())
+export const zPostFormHumanInputByFormTokenUploadTokenPath = z.object({
+ form_token: z.string(),
+})
+
+/**
+ * Success
+ */
+export const zPostFormHumanInputByFormTokenUploadTokenResponse = z.record(z.string(), z.unknown())
+
+/**
+ * File uploaded successfully
+ */
+export const zPostHumanInputFormsFilesResponse = zFileResponse
+
export const zPostLoginBody = zLoginPayload
/**
diff --git a/web/__mocks__/base-ui-select.tsx b/web/__mocks__/base-ui-select.tsx
index a695bebe14c..327d89712dc 100644
--- a/web/__mocks__/base-ui-select.tsx
+++ b/web/__mocks__/base-ui-select.tsx
@@ -26,15 +26,21 @@ export const SelectTrigger = ({
children,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { children?: ReactNode }) => (
- <button type="button" {...props}>
+ <button type="button" role="combobox" {...props}>
{children}
</button>
)
export const SelectValue = ({ placeholder }: { placeholder?: ReactNode }) => <>{placeholder}</>
-export const SelectContent = ({ children }: { children?: ReactNode }) => (
- <div data-testid="select-content">{children}</div>
+export const SelectContent = ({
+ children,
+ popupClassName,
+}: {
+ children?: ReactNode
+ popupClassName?: string
+}) => (
+ <div data-side="bottom" data-testid="select-content" className={popupClassName}>{children}</div>
)
export const SelectItem = ({
diff --git a/web/__tests__/base/file-uploader-flow.test.tsx b/web/__tests__/base/file-uploader-flow.test.tsx
index 81dccedfe51..c77c92ad317 100644
--- a/web/__tests__/base/file-uploader-flow.test.tsx
+++ b/web/__tests__/base/file-uploader-flow.test.tsx
@@ -11,6 +11,7 @@ const mockUploadRemoteFileInfo = vi.fn()
vi.mock('@/next/navigation', () => ({
useParams: () => ({}),
+ usePathname: () => '/',
}))
vi.mock('@/service/common', () => ({
diff --git a/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
new file mode 100644
index 00000000000..ac919ffb051
--- /dev/null
+++ b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
@@ -0,0 +1,357 @@
+import type { FormData } from '../form'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
+import { act, render, renderHook, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
+import FormContent from '../form'
+import { useFormSubmit } from '../use-form-submit'
+
+const mockSubmitForm = vi.hoisted(() => vi.fn())
+const mockUseGetHumanInputForm = vi.hoisted(() => vi.fn())
+const mockContentItemState = vi.hoisted(() => ({
+ staleAttachmentInputChange: undefined as ((name: string, value: unknown) => void) | undefined,
+ uploadedFile: {
+ id: 'file-1',
+ name: 'review.pdf',
+ size: 128,
+ type: 'document',
+ progress: 100,
+ transferMethod: 'local_file',
+ supportFileType: 'document',
+ uploadedId: 'upload-file-1',
+ },
+ uploadingFile: {
+ id: 'file-1',
+ name: 'review.pdf',
+ size: 128,
+ type: 'document',
+ progress: 50,
+ transferMethod: 'local_file',
+ supportFileType: 'document',
+ uploadedId: undefined,
+ },
+}))
+
+vi.mock('@/next/navigation', () => ({
+ useParams: () => ({ token: 'token-123' }),
+}))
+
+vi.mock('@/service/use-share', () => ({
+ useGetHumanInputForm: (...args: unknown[]) => mockUseGetHumanInputForm(...args),
+ useSubmitHumanInputForm: () => ({
+ mutate: mockSubmitForm,
+ isPending: false,
+ }),
+}))
+
+vi.mock('@/hooks/use-document-title', () => ({
+ __esModule: true,
+ default: vi.fn(),
+}))
+
+vi.mock('@/app/components/base/chat/chat/answer/human-input-content/content-item', () => ({
+ __esModule: true,
+ default: ({ content, onInputChange }: { content: string, onInputChange: (name: string, value: unknown) => void }) => {
+ const isSummaryField = content.includes('summary')
+ const isAttachmentField = content.includes('attachments')
+
+ if (isAttachmentField && !mockContentItemState.staleAttachmentInputChange)
+ mockContentItemState.staleAttachmentInputChange = onInputChange
+
+ return (
+ <div data-testid="share-form-content-item">
+ {content}
+ {isSummaryField && (
+ <>
+ <button type="button" onClick={() => onInputChange('summary', '')}>
+ share-clear-summary
+ </button>
+ <button type="button" onClick={() => onInputChange('summary', 'updated summary')}>
+ share-update-summary
+ </button>
+ </>
+ )}
+ {isAttachmentField && (
+ <>
+ <button
+ type="button"
+ onClick={() => mockContentItemState.staleAttachmentInputChange?.('attachments', [mockContentItemState.uploadingFile])}
+ >
+ share-uploading-attachments
+ </button>
+ <button
+ type="button"
+ onClick={() => mockContentItemState.staleAttachmentInputChange?.('attachments', [mockContentItemState.uploadedFile])}
+ >
+ share-update-attachments
+ </button>
+ </>
+ )}
+ </div>
+ )
+ },
+}))
+
+vi.mock('@/app/components/base/chat/chat/answer/human-input-content/expiration-time', () => ({
+ __esModule: true,
+ default: () => <div>expiration-time</div>,
+}))
+
+vi.mock('@/app/components/base/loading', () => ({
+ __esModule: true,
+ default: () => <div>loading</div>,
+}))
+
+vi.mock('@/app/components/base/logo/dify-logo', () => ({
+ __esModule: true,
+ default: () => <div>dify-logo</div>,
+}))
+
+vi.mock('@/app/components/base/app-icon', () => ({
+ __esModule: true,
+ default: () => <div>app-icon</div>,
+}))
+
+describe('Human input share form', () => {
+ const formData: FormData = {
+ site: {
+ site: {
+ title: 'Review App',
+ icon_type: 'emoji',
+ icon: 'R',
+ icon_background: '#fff',
+ icon_url: '',
+ default_language: 'en-US',
+ description: '',
+ copyright: '',
+ privacy_policy: '',
+ custom_disclaimer: '',
+ prompt_public: false,
+ use_icon_as_answer_icon: false,
+ },
+ },
+ form_content: '{{#$output.summary#}} {{#$output.attachments#}}',
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: {
+ type: 'constant',
+ value: 'initial summary',
+ selector: [],
+ },
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'attachments',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ number_limits: 3,
+ },
+ ],
+ resolved_default_values: {},
+ user_actions: [
+ {
+ id: 'approve',
+ title: 'Approve',
+ button_style: UserActionButtonType.Primary,
+ },
+ ],
+ expiration_time: 60,
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockContentItemState.staleAttachmentInputChange = undefined
+ mockUseGetHumanInputForm.mockReturnValue({
+ data: formData,
+ isLoading: false,
+ error: null,
+ })
+ })
+
+ it('should render the loading state while the form is being fetched', () => {
+ mockUseGetHumanInputForm.mockReturnValue({
+ data: undefined,
+ isLoading: true,
+ error: null,
+ })
+
+ render(<FormContent />)
+
+ expect(screen.getByText('loading')).toBeInTheDocument()
+ })
+
+ it('should render status cards for terminal fetch states', () => {
+ const cases = [
+ {
+ error: { code: 'human_input_form_expired' },
+ title: 'share.humanInput.sorry',
+ subtitle: 'share.humanInput.expired',
+ submissionID: true,
+ },
+ {
+ error: { code: 'human_input_form_submitted' },
+ title: 'share.humanInput.sorry',
+ subtitle: 'share.humanInput.completed',
+ submissionID: true,
+ },
+ {
+ error: { code: 'web_form_rate_limit_exceeded' },
+ title: 'share.humanInput.rateLimitExceeded',
+ subtitle: undefined,
+ submissionID: false,
+ },
+ {
+ error: null,
+ title: 'share.humanInput.formNotFound',
+ subtitle: undefined,
+ submissionID: false,
+ },
+ ]
+
+ cases.forEach(({ error, title, subtitle, submissionID }) => {
+ mockUseGetHumanInputForm.mockReturnValue({
+ data: undefined,
+ isLoading: false,
+ error,
+ })
+ const { unmount } = render(<FormContent />)
+
+ expect(screen.getByText(title)).toBeInTheDocument()
+ if (subtitle)
+ expect(screen.getByText(subtitle)).toBeInTheDocument()
+ else
+ expect(screen.queryByText('share.humanInput.expired')).not.toBeInTheDocument()
+
+ if (submissionID)
+ expect(screen.getByText('share.humanInput.submissionID:{"id":"token-123"}')).toBeInTheDocument()
+ else
+ expect(screen.queryByText(/share\.humanInput\.submissionID/)).not.toBeInTheDocument()
+
+ expect(screen.getByText('share.chat.poweredBy')).toBeInTheDocument()
+ expect(screen.getByText('dify-logo')).toBeInTheDocument()
+ unmount()
+ })
+ })
+
+ it('submits typed human input values through the share form mutation', async () => {
+ const user = userEvent.setup()
+
+ render(<FormContent />)
+
+ await user.click(screen.getByRole('button', { name: 'share-update-summary' }))
+ await user.click(screen.getByRole('button', { name: 'share-update-attachments' }))
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+
+ expect(mockSubmitForm).toHaveBeenCalledWith({
+ token: 'token-123',
+ data: {
+ action: 'approve',
+ inputs: {
+ summary: 'updated summary',
+ attachments: [{
+ type: 'document',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ }],
+ },
+ },
+ }, expect.objectContaining({
+ onSuccess: expect.any(Function),
+ }))
+ })
+
+ it('should show the success status after the submit mutation succeeds', async () => {
+ const user = userEvent.setup()
+
+ render(<FormContent />)
+
+ await user.click(screen.getByRole('button', { name: 'share-update-summary' }))
+ await user.click(screen.getByRole('button', { name: 'share-update-attachments' }))
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+
+ const options = mockSubmitForm.mock.calls[0]![1] as { onSuccess: () => void }
+ act(() => {
+ options.onSuccess()
+ })
+
+ expect(screen.getByText('share.humanInput.thanks')).toBeInTheDocument()
+ expect(screen.getByText('share.humanInput.recorded')).toBeInTheDocument()
+ expect(screen.getByText('share.humanInput.submissionID:{"id":"token-123"}')).toBeInTheDocument()
+ })
+
+ it('should submit empty inputs when there are no form values to process', () => {
+ const { result } = renderHook(() => useFormSubmit('token-empty'))
+
+ act(() => {
+ result.current.submit(
+ undefined as unknown as Record<string, HumanInputFieldValue>,
+ 'reject',
+ [],
+ )
+ })
+
+ expect(mockSubmitForm).toHaveBeenCalledWith({
+ token: 'token-empty',
+ data: {
+ action: 'reject',
+ inputs: {},
+ },
+ }, expect.objectContaining({
+ onSuccess: expect.any(Function),
+ }))
+ })
+
+ it('should keep initialized defaults when file upload uses the initial change callback', async () => {
+ const user = userEvent.setup()
+
+ render(<FormContent />)
+
+ await user.click(screen.getByRole('button', { name: 'share-update-attachments' }))
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+
+ expect(mockSubmitForm).toHaveBeenCalledWith({
+ token: 'token-123',
+ data: {
+ action: 'approve',
+ inputs: {
+ summary: 'initial summary',
+ attachments: [{
+ type: 'document',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ }],
+ },
+ },
+ }, expect.objectContaining({
+ onSuccess: expect.any(Function),
+ }))
+ })
+
+ it('should disable action buttons until every required field is filled and files are uploaded', async () => {
+ const user = userEvent.setup()
+
+ render(<FormContent />)
+
+ const approveButton = screen.getByRole('button', { name: 'Approve' })
+ expect(approveButton).toBeDisabled()
+
+ await user.click(screen.getByRole('button', { name: 'share-uploading-attachments' }))
+ expect(approveButton).toBeDisabled()
+
+ await user.click(screen.getByRole('button', { name: 'share-update-attachments' }))
+ expect(approveButton).toBeEnabled()
+
+ await user.click(screen.getByRole('button', { name: 'share-clear-summary' }))
+ expect(approveButton).toBeDisabled()
+
+ await user.click(screen.getByRole('button', { name: 'share-update-summary' }))
+ expect(approveButton).toBeEnabled()
+ })
+})
diff --git a/web/app/(humanInputLayout)/form/[token]/__tests__/page.spec.tsx b/web/app/(humanInputLayout)/form/[token]/__tests__/page.spec.tsx
new file mode 100644
index 00000000000..b4026a1f550
--- /dev/null
+++ b/web/app/(humanInputLayout)/form/[token]/__tests__/page.spec.tsx
@@ -0,0 +1,19 @@
+import { render, screen } from '@testing-library/react'
+import FormPage from '../page'
+
+vi.mock('../form', () => ({
+ __esModule: true,
+ default: () => <div>form-content</div>,
+}))
+
+describe('Human input share form page', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should render the form content inside the page shell', () => {
+ render(<FormPage />)
+
+ expect(screen.getByText('form-content')).toBeInTheDocument()
+ })
+})
diff --git a/web/app/(humanInputLayout)/form/[token]/form-status-card.tsx b/web/app/(humanInputLayout)/form/[token]/form-status-card.tsx
new file mode 100644
index 00000000000..6b7813402d4
--- /dev/null
+++ b/web/app/(humanInputLayout)/form/[token]/form-status-card.tsx
@@ -0,0 +1,51 @@
+import type { ReactNode } from 'react'
+import { cn } from '@langgenius/dify-ui/cn'
+import { useTranslation } from 'react-i18next'
+import DifyLogo from '@/app/components/base/logo/dify-logo'
+
+type FormStatusCardProps = {
+ iconClassName: string
+ title: ReactNode
+ subtitle?: ReactNode
+ submissionID?: string
+}
+
+const FormStatusCard = ({
+ iconClassName,
+ title,
+ subtitle,
+ submissionID,
+}: FormStatusCardProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className={cn('flex size-full flex-col items-center justify-center')}>
+ <div className="max-w-160 min-w-120">
+ <div className="flex h-80 flex-col gap-4 rounded-[20px] border border-divider-subtle bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs">
+ <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
+ <span className={cn('size-8', iconClassName)} />
+ </div>
+ <div className="grow">
+ <div className="title-4xl-semi-bold text-text-primary">{title}</div>
+ {!!subtitle && (
+ <div className="title-4xl-semi-bold text-text-primary">{subtitle}</div>
+ )}
+ </div>
+ {submissionID && (
+ <div className="shrink-0 system-2xs-regular-uppercase text-text-tertiary">
+ {t('humanInput.submissionID', { id: submissionID, ns: 'share' })}
+ </div>
+ )}
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className="flex shrink-0 items-center gap-1.5 px-1">
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default FormStatusCard
diff --git a/web/app/(humanInputLayout)/form/[token]/form.tsx b/web/app/(humanInputLayout)/form/[token]/form.tsx
index 0eb62b1cb28..55491462cee 100644
--- a/web/app/(humanInputLayout)/form/[token]/form.tsx
+++ b/web/app/(humanInputLayout)/form/[token]/form.tsx
@@ -1,34 +1,23 @@
'use client'
-import type { ButtonProps } from '@langgenius/dify-ui/button'
import type { FormInputItem, UserAction } from '@/app/components/workflow/nodes/human-input/types'
import type { SiteInfo } from '@/models/share'
import type { HumanInputFormError } from '@/service/use-share'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
-import {
- RiCheckboxCircleFill,
- RiErrorWarningFill,
- RiInformation2Fill,
-} from '@remixicon/react'
-import { produce } from 'immer'
+import type { HumanInputResolvedValue } from '@/types/workflow'
import * as React from 'react'
-import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import AppIcon from '@/app/components/base/app-icon'
-import ContentItem from '@/app/components/base/chat/chat/answer/human-input-content/content-item'
-import ExpirationTime from '@/app/components/base/chat/chat/answer/human-input-content/expiration-time'
-import { getButtonStyle } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
import Loading from '@/app/components/base/loading'
-import DifyLogo from '@/app/components/base/logo/dify-logo'
import useDocumentTitle from '@/hooks/use-document-title'
import { useParams } from '@/next/navigation'
-import { useGetHumanInputForm, useSubmitHumanInputForm } from '@/service/use-share'
+import { useGetHumanInputForm } from '@/service/use-share'
+import FormStatusCard from './form-status-card'
+import LoadedFormContent from './loaded-form-content'
+import { useFormSubmit } from './use-form-submit'
export type FormData = {
site: { site: SiteInfo }
form_content: string
inputs: FormInputItem[]
- resolved_default_values: Record<string, string>
+ resolved_default_values: Record<string, HumanInputResolvedValue>
user_actions: UserAction[]
expiration_time: number
}
@@ -39,58 +28,13 @@ const FormContent = () => {
const { token } = useParams<{ token: string }>()
useDocumentTitle('')
- const [inputs, setInputs] = useState<Record<string, string>>({})
- const [success, setSuccess] = useState(false)
-
- const { mutate: submitForm, isPending: isSubmitting } = useSubmitHumanInputForm()
-
const { data: formData, isLoading, error } = useGetHumanInputForm(token)
+ const { isSubmitting, submit, success } = useFormSubmit(token)
const expired = (error as HumanInputFormError | null)?.code === 'human_input_form_expired'
const submitted = (error as HumanInputFormError | null)?.code === 'human_input_form_submitted'
const rateLimitExceeded = (error as HumanInputFormError | null)?.code === 'web_form_rate_limit_exceeded'
- const splitByOutputVar = (content: string): string[] => {
- const outputVarRegex = /(\{\{#\$output\.[^#]+#\}\})/g
- const parts = content.split(outputVarRegex)
- return parts.filter(part => part.length > 0)
- }
-
- const contentList = useMemo(() => {
- if (!formData?.form_content)
- return []
- return splitByOutputVar(formData.form_content)
- }, [formData?.form_content])
-
- useEffect(() => {
- if (!formData?.inputs)
- return
- const initialInputs: Record<string, string> = {}
- formData.inputs.forEach((item) => {
- initialInputs[item.output_variable_name] = item.default.type === 'variable' ? formData.resolved_default_values[item.output_variable_name] || '' : item.default.value
- })
- setInputs(initialInputs)
- }, [formData?.inputs, formData?.resolved_default_values])
-
- // use immer
- const handleInputsChange = (name: string, value: string) => {
- const newInputs = produce(inputs, (draft) => {
- draft[name] = value
- })
- setInputs(newInputs)
- }
-
- const submit = (actionID: string) => {
- submitForm(
- { token, data: { inputs, action: actionID } },
- {
- onSuccess: () => {
- setSuccess(true)
- },
- },
- )
- }
-
if (isLoading) {
return (
<Loading type="app" />
@@ -99,190 +43,62 @@ const FormContent = () => {
if (success) {
return (
- <div className={cn('flex size-full flex-col items-center justify-center')}>
- <div className="max-w-[640px] min-w-[480px]">
- <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs">
- <div className="h-[56px] w-[56px] shrink-0 rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
- <RiCheckboxCircleFill className="size-8 text-text-success" />
- </div>
- <div className="grow">
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.thanks', { ns: 'share' })}</div>
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.recorded', { ns: 'share' })}</div>
- </div>
- <div className="shrink-0 system-2xs-regular-uppercase text-text-tertiary">{t('humanInput.submissionID', { id: token, ns: 'share' })}</div>
- </div>
- <div className="flex flex-row-reverse px-2 py-3">
- <div className={cn(
- 'flex shrink-0 items-center gap-1.5 px-1',
- )}
- >
- <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
- <DifyLogo size="small" />
- </div>
- </div>
- </div>
- </div>
+ <FormStatusCard
+ iconClassName="i-ri-checkbox-circle-fill text-text-success"
+ title={t('humanInput.thanks', { ns: 'share' })}
+ subtitle={t('humanInput.recorded', { ns: 'share' })}
+ submissionID={token}
+ />
)
}
if (expired) {
return (
- <div className={cn('flex size-full flex-col items-center justify-center')}>
- <div className="max-w-[640px] min-w-[480px]">
- <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs">
- <div className="flex size-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
- <RiInformation2Fill className="size-8 text-text-accent" />
- </div>
- <div className="grow">
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.sorry', { ns: 'share' })}</div>
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.expired', { ns: 'share' })}</div>
- </div>
- <div className="shrink-0 system-2xs-regular-uppercase text-text-tertiary">{t('humanInput.submissionID', { id: token, ns: 'share' })}</div>
- </div>
- <div className="flex flex-row-reverse px-2 py-3">
- <div className={cn(
- 'flex shrink-0 items-center gap-1.5 px-1',
- )}
- >
- <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
- <DifyLogo size="small" />
- </div>
- </div>
- </div>
- </div>
+ <FormStatusCard
+ iconClassName="i-ri-information-2-fill text-text-accent"
+ title={t('humanInput.sorry', { ns: 'share' })}
+ subtitle={t('humanInput.expired', { ns: 'share' })}
+ submissionID={token}
+ />
)
}
if (submitted) {
return (
- <div className={cn('flex size-full flex-col items-center justify-center')}>
- <div className="max-w-[640px] min-w-[480px]">
- <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs">
- <div className="flex size-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
- <RiInformation2Fill className="size-8 text-text-accent" />
- </div>
- <div className="grow">
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.sorry', { ns: 'share' })}</div>
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.completed', { ns: 'share' })}</div>
- </div>
- <div className="shrink-0 system-2xs-regular-uppercase text-text-tertiary">{t('humanInput.submissionID', { id: token, ns: 'share' })}</div>
- </div>
- <div className="flex flex-row-reverse px-2 py-3">
- <div className={cn(
- 'flex shrink-0 items-center gap-1.5 px-1',
- )}
- >
- <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
- <DifyLogo size="small" />
- </div>
- </div>
- </div>
- </div>
+ <FormStatusCard
+ iconClassName="i-ri-information-2-fill text-text-accent"
+ title={t('humanInput.sorry', { ns: 'share' })}
+ subtitle={t('humanInput.completed', { ns: 'share' })}
+ submissionID={token}
+ />
)
}
if (rateLimitExceeded) {
return (
- <div className={cn('flex size-full flex-col items-center justify-center')}>
- <div className="max-w-[640px] min-w-[480px]">
- <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs">
- <div className="flex size-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
- <RiErrorWarningFill className="size-8 text-text-destructive" />
- </div>
- <div className="grow">
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.rateLimitExceeded', { ns: 'share' })}</div>
- </div>
- </div>
- <div className="flex flex-row-reverse px-2 py-3">
- <div className={cn(
- 'flex shrink-0 items-center gap-1.5 px-1',
- )}
- >
- <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
- <DifyLogo size="small" />
- </div>
- </div>
- </div>
- </div>
+ <FormStatusCard
+ iconClassName="i-ri-error-warning-fill text-text-destructive"
+ title={t('humanInput.rateLimitExceeded', { ns: 'share' })}
+ />
)
}
if (!formData) {
return (
- <div className={cn('flex size-full flex-col items-center justify-center')}>
- <div className="max-w-[640px] min-w-[480px]">
- <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs">
- <div className="flex size-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
- <RiErrorWarningFill className="size-8 text-text-destructive" />
- </div>
- <div className="grow">
- <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.formNotFound', { ns: 'share' })}</div>
- </div>
- </div>
- <div className="flex flex-row-reverse px-2 py-3">
- <div className={cn(
- 'flex shrink-0 items-center gap-1.5 px-1',
- )}
- >
- <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
- <DifyLogo size="small" />
- </div>
- </div>
- </div>
- </div>
+ <FormStatusCard
+ iconClassName="i-ri-error-warning-fill text-text-destructive"
+ title={t('humanInput.formNotFound', { ns: 'share' })}
+ />
)
}
- const site = formData.site.site
-
return (
- <div className={cn('mx-auto flex h-full w-full max-w-[720px] flex-col items-center')}>
- <div className="mt-4 flex w-full shrink-0 items-center gap-3 py-3">
- <AppIcon
- size="large"
- iconType={site.icon_type}
- icon={site.icon}
- background={site.icon_background}
- imageUrl={site.icon_url}
- />
- <div className="grow system-xl-semibold text-text-primary">{site.title}</div>
- </div>
- <div className="h-0 w-full grow overflow-y-auto">
- <div className="border-components-divider-subtle rounded-[20px] border bg-chat-bubble-bg p-4 shadow-lg backdrop-blur-xs">
- {contentList.map((content, index) => (
- <ContentItem
- key={index}
- content={content}
- formInputFields={formData.inputs}
- inputs={inputs}
- onInputChange={handleInputsChange}
- />
- ))}
- <div className="flex flex-wrap gap-1 py-1">
- {formData.user_actions.map((action: UserAction) => (
- <Button
- key={action.id}
- disabled={isSubmitting}
- variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
- onClick={() => submit(action.id)}
- >
- {action.title}
- </Button>
- ))}
- </div>
- <ExpirationTime expirationTime={formData.expiration_time * 1000} />
- </div>
- <div className="flex flex-row-reverse px-2 py-3">
- <div className={cn(
- 'flex shrink-0 items-center gap-1.5 px-1',
- )}
- >
- <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
- <DifyLogo size="small" />
- </div>
- </div>
- </div>
- </div>
+ <LoadedFormContent
+ key={token}
+ formData={formData}
+ isSubmitting={isSubmitting}
+ onSubmit={submit}
+ />
)
}
diff --git a/web/app/(humanInputLayout)/form/[token]/loaded-form-content.tsx b/web/app/(humanInputLayout)/form/[token]/loaded-form-content.tsx
new file mode 100644
index 00000000000..00ab0ac1b79
--- /dev/null
+++ b/web/app/(humanInputLayout)/form/[token]/loaded-form-content.tsx
@@ -0,0 +1,98 @@
+import type { ButtonProps } from '@langgenius/dify-ui/button'
+import type { FormData } from './form'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
+import type { UserAction } from '@/app/components/workflow/nodes/human-input/types'
+import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { produce } from 'immer'
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import AppIcon from '@/app/components/base/app-icon'
+import ContentItem from '@/app/components/base/chat/chat/answer/human-input-content/content-item'
+import ExpirationTime from '@/app/components/base/chat/chat/answer/human-input-content/expiration-time'
+import { getButtonStyle, getRenderedFormInputs, hasInvalidRequiredHumanInput, initializeInputs, splitByOutputVar } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
+import DifyLogo from '@/app/components/base/logo/dify-logo'
+
+type LoadedFormContentProps = {
+ formData: FormData
+ isSubmitting: boolean
+ onSubmit: (inputs: Record<string, HumanInputFieldValue>, actionID: string, formInputs: FormData['inputs']) => void
+}
+
+const LoadedFormContent = ({
+ formData,
+ isSubmitting,
+ onSubmit,
+}: LoadedFormContentProps) => {
+ const { t } = useTranslation()
+ const renderedFormInputs = getRenderedFormInputs(formData.inputs, formData.form_content)
+ const [inputs, setInputs] = useState<Record<string, HumanInputFieldValue>>(() =>
+ initializeInputs(renderedFormInputs, formData.resolved_default_values),
+ )
+
+ const contentList = useMemo(() => {
+ return splitByOutputVar(formData.form_content)
+ }, [formData.form_content])
+
+ const handleInputsChange = (name: string, value: HumanInputFieldValue) => {
+ setInputs(prevInputs => produce(prevInputs, (draft) => {
+ draft[name] = value
+ }))
+ }
+
+ const submit = (actionID: string) => {
+ onSubmit(inputs, actionID, formData.inputs)
+ }
+
+ const isActionDisabled = isSubmitting || hasInvalidRequiredHumanInput(renderedFormInputs, inputs)
+ const site = formData.site.site
+
+ return (
+ <div className={cn('mx-auto flex size-full max-w-180 flex-col items-center')}>
+ <div className="mt-4 flex w-full shrink-0 items-center gap-3 py-3">
+ <AppIcon
+ size="large"
+ iconType={site.icon_type}
+ icon={site.icon}
+ background={site.icon_background}
+ imageUrl={site.icon_url}
+ />
+ <div className="grow system-xl-semibold text-text-primary">{site.title}</div>
+ </div>
+ <div className="h-0 w-full grow overflow-y-auto">
+ <div className="rounded-[20px] border border-divider-subtle bg-chat-bubble-bg p-4 shadow-lg backdrop-blur-xs">
+ {contentList.map((content, index) => (
+ <ContentItem
+ key={index}
+ content={content}
+ formInputFields={formData.inputs}
+ inputs={inputs}
+ onInputChange={handleInputsChange}
+ />
+ ))}
+ <div className="flex flex-wrap gap-1 py-1">
+ {formData.user_actions.map((action: UserAction) => (
+ <Button
+ key={action.id}
+ disabled={isActionDisabled}
+ variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
+ onClick={() => submit(action.id)}
+ >
+ {action.title}
+ </Button>
+ ))}
+ </div>
+ <ExpirationTime expirationTime={formData.expiration_time * 1000} />
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className="flex shrink-0 items-center gap-1.5 px-1">
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default LoadedFormContent
diff --git a/web/app/(humanInputLayout)/form/[token]/page.tsx b/web/app/(humanInputLayout)/form/[token]/page.tsx
index a7e2305b2be..db7952ef1a9 100644
--- a/web/app/(humanInputLayout)/form/[token]/page.tsx
+++ b/web/app/(humanInputLayout)/form/[token]/page.tsx
@@ -4,7 +4,7 @@ import FormContent from './form'
const FormPage = () => {
return (
- <div className="h-full min-w-[300px] bg-chatbot-bg pb-[env(safe-area-inset-bottom)]">
+ <div className="h-full min-w-75 bg-chatbot-bg pb-[env(safe-area-inset-bottom)]">
<FormContent />
</div>
)
diff --git a/web/app/(humanInputLayout)/form/[token]/use-form-submit.ts b/web/app/(humanInputLayout)/form/[token]/use-form-submit.ts
new file mode 100644
index 00000000000..de018b28ed3
--- /dev/null
+++ b/web/app/(humanInputLayout)/form/[token]/use-form-submit.ts
@@ -0,0 +1,33 @@
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import { useCallback, useState } from 'react'
+import { getProcessedHumanInputFormInputs } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
+import { useSubmitHumanInputForm } from '@/service/use-share'
+
+export const useFormSubmit = (token: string) => {
+ const [success, setSuccess] = useState(false)
+ const { mutate: submitForm, isPending: isSubmitting } = useSubmitHumanInputForm()
+
+ const submit = useCallback((inputs: Record<string, HumanInputFieldValue>, actionID: string, formInputs: FormInputItem[]) => {
+ submitForm(
+ {
+ token,
+ data: {
+ inputs: getProcessedHumanInputFormInputs(formInputs, inputs) || {},
+ action: actionID,
+ },
+ },
+ {
+ onSuccess: () => {
+ setSuccess(true)
+ },
+ },
+ )
+ }, [submitForm, token])
+
+ return {
+ isSubmitting,
+ submit,
+ success,
+ }
+}
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
index f1356c9b619..00c96c3e007 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
@@ -1,5 +1,6 @@
/* eslint-disable ts/no-explicit-any */
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import TypeSelector from '../type-select'
vi.mock('@langgenius/dify-ui/select', () => import('@/__mocks__/base-ui-select'))
@@ -9,8 +10,9 @@ vi.mock('@/app/components/workflow/nodes/_base/components/input-var-type-icon',
}))
describe('TypeSelector', () => {
- it('should toggle open state and select a new variable type', () => {
+ it('should select a new variable type when an option is clicked', async () => {
const onSelect = vi.fn()
+ const user = userEvent.setup()
render(
<TypeSelector
@@ -23,9 +25,32 @@ describe('TypeSelector', () => {
/>,
)
- fireEvent.click(screen.getByRole('button'))
- fireEvent.click(screen.getByText('Number'))
+ await user.click(screen.getByRole('combobox'))
+ const [, numberOption] = await screen.findAllByRole('option')
+ await user.click(numberOption!)
expect(onSelect).toHaveBeenCalledWith({ value: 'number', name: 'Number' })
})
+
+ it('should size popup content to match the trigger width', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <TypeSelector
+ value="text-input"
+ onSelect={vi.fn()}
+ items={[
+ { value: 'text-input' as any, name: 'Text' },
+ { value: 'number' as any, name: 'Number' },
+ ]}
+ />,
+ )
+
+ await user.click(screen.getByRole('combobox'))
+
+ const [, numberOption] = await screen.findAllByRole('option')
+ const popup = numberOption!.closest('[data-side]')
+
+ expect(popup).toHaveClass('w-(--anchor-width)')
+ })
})
diff --git a/web/app/components/app/configuration/config-var/config-modal/type-select.tsx b/web/app/components/app/configuration/config-var/config-modal/type-select.tsx
index acd3253f6bb..352b3139ff9 100644
--- a/web/app/components/app/configuration/config-var/config-modal/type-select.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/type-select.tsx
@@ -59,9 +59,10 @@ const TypeSelector: FC<Props> = ({
<div className="flex items-center">
<InputVarTypeIcon type={selectedItem?.value as InputVarType} className="size-4 shrink-0 text-text-secondary" />
<span
- className={`
- ml-1.5 text-components-input-text-filled ${!selectedItem?.name && 'text-components-input-text-placeholder'}
- `}
+ className={cn(
+ 'ml-1.5 truncate text-components-input-text-filled',
+ !selectedItem?.name && 'text-components-input-text-placeholder',
+ )}
>
{selectedItem?.name}
</span>
@@ -73,7 +74,7 @@ const TypeSelector: FC<Props> = ({
</SelectTrigger>
<SelectContent
sideOffset={4}
- popupClassName={cn('w-[432px] rounded-md px-1 py-1 text-base sm:text-sm', popupInnerClassName)}
+ popupClassName={cn('w-(--anchor-width) rounded-md px-1 py-1 text-base sm:text-sm', popupInnerClassName)}
listClassName="max-h-80 p-0"
>
{items.map((item: Item) => (
diff --git a/web/app/components/app/text-generate/item/index.tsx b/web/app/components/app/text-generate/item/index.tsx
index c75350e18d3..0fb085dd879 100644
--- a/web/app/components/app/text-generate/item/index.tsx
+++ b/web/app/components/app/text-generate/item/index.tsx
@@ -1,5 +1,6 @@
'use client'
import type { FC } from 'react'
+import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import type { FeedbackType } from '@/app/components/base/chat/chat/type'
import type { WorkflowProcess } from '@/app/components/base/chat/types'
import type { SiteInfo } from '@/models/share'
@@ -178,7 +179,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({
// eslint-disable-next-line react/set-state-in-effect
setCurrentTab(getDefaultGenerationTab(workflowProcessData))
}, [workflowProcessData])
- const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: { inputs: Record<string, string>, action: string }) => {
+ const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: HumanInputFormSubmitData) => {
if (appSourceType === AppSourceType.installedApp)
await submitHumanInputFormService(formToken, formData)
else
diff --git a/web/app/components/app/text-generate/item/workflow-body.tsx b/web/app/components/app/text-generate/item/workflow-body.tsx
index fb73161d5dc..c15895b5675 100644
--- a/web/app/components/app/text-generate/item/workflow-body.tsx
+++ b/web/app/components/app/text-generate/item/workflow-body.tsx
@@ -1,5 +1,6 @@
'use client'
import type { FC } from 'react'
+import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import type { WorkflowProcess } from '@/app/components/base/chat/types'
import type { SiteInfo } from '@/models/share'
import { cn } from '@langgenius/dify-ui/cn'
@@ -17,7 +18,7 @@ type WorkflowBodyProps = {
depth: number
hideProcessDetail?: boolean
isError: boolean
- onSubmitHumanInputForm: (formToken: string, formData: { inputs: Record<string, string>, action: string }) => Promise<void>
+ onSubmitHumanInputForm: (formToken: string, formData: HumanInputFormSubmitData) => Promise<void>
onSwitchTab: (tab: string) => void
showResultTabs: boolean
siteInfo: SiteInfo | null
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
index e2dee20cadd..35478bae7b6 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
@@ -1076,6 +1076,10 @@ describe('useChatWithHistory', () => {
await waitFor(() => {
expect(result!.current.appPrevChatTree.length).toBeGreaterThan(0)
})
+
+ const answerNode = result!.current.appPrevChatTree[0]?.children?.[0]
+ expect(answerNode?.humanInputFormDataList).toHaveLength(1)
+ expect(answerNode?.workflow_run_id).toBe('wf-run-1')
})
it('should set workflow_run_id for normal messages with submitted human_input', async () => {
@@ -1114,6 +1118,75 @@ describe('useChatWithHistory', () => {
await waitFor(() => {
expect(result!.current.appPrevChatTree.length).toBeGreaterThan(0)
})
+
+ const answerNode = result!.current.appPrevChatTree[0]?.children?.[0]
+ expect(answerNode?.humanInputFilledFormDataList).toHaveLength(1)
+ })
+
+ it('should parse human input payloads regardless of message status', async () => {
+ const listData = createConversationData({
+ data: [createConversationItem({ id: 'conversation-1' })],
+ })
+ const chatListData = {
+ data: [
+ {
+ id: 'msg-status-agnostic',
+ query: 'Needs review',
+ answer: 'Pending follow-up',
+ message_files: [],
+ feedback: null,
+ retriever_resources: [],
+ agent_thoughts: null,
+ parent_message_id: null,
+ inputs: {},
+ status: 'error',
+ extra_contents: [
+ {
+ type: 'human_input',
+ submitted: true,
+ form_definition: {
+ form_id: 'form-1',
+ node_id: 'node-1',
+ node_title: 'Human Input',
+ form_content: '{{#$output.summary#}}',
+ inputs: [],
+ actions: [],
+ form_token: 'token-1',
+ resolved_default_values: {},
+ display_in_ui: true,
+ expiration_time: 0,
+ },
+ workflow_run_id: 'wf-run-status-agnostic',
+ form_submission_data: {
+ node_id: 'node-1',
+ node_title: 'Human Input',
+ rendered_content: 'Submitted summary',
+ action_id: 'submit',
+ action_text: 'Submit',
+ submitted_data: {
+ summary: 'approved',
+ },
+ },
+ },
+ ],
+ },
+ ],
+ }
+ mockFetchConversations.mockResolvedValue(listData)
+ mockFetchChatList.mockResolvedValue(chatListData)
+
+ const { result } = await renderWithClient(() => useChatWithHistory())
+
+ await waitFor(() => {
+ expect(result!.current.appPrevChatTree.length).toBeGreaterThan(0)
+ })
+
+ const answerNode = result!.current.appPrevChatTree[0]?.children?.[0]
+ expect(answerNode?.humanInputFormDataList).toHaveLength(0)
+ expect(answerNode?.humanInputFilledFormDataList).toHaveLength(1)
+ expect(answerNode?.humanInputFilledFormDataList?.[0]?.form_content).toBe('{{#$output.summary#}}')
+ expect(answerNode?.humanInputFilledFormDataList?.[0]?.inputs).toEqual([])
+ expect(answerNode?.workflow_run_id).toBe('wf-run-status-agnostic')
})
it('should return empty appPrevChatTree when there is no currentConversationId', async () => {
@@ -1835,6 +1908,15 @@ describe('useChatWithHistory', () => {
expect(messageWithFiles?.message_files).toHaveLength(1)
expect(messageWithFiles?.children?.[0]?.message_files).toHaveLength(1)
expect(messageWithFiles?.children?.[0]?.agent_thoughts?.[0]?.message_files).toHaveLength(1)
+
+ const normalAnswerNode = messageWithFiles?.children?.[0]
+ const pausedAnswerNode = result!.current.appPrevChatTree.find(item => item.id === 'question-msg-paused-branch')?.children?.[0]
+
+ expect(normalAnswerNode?.humanInputFilledFormDataList).toHaveLength(1)
+ expect(normalAnswerNode?.humanInputFormDataList).toHaveLength(0)
+ expect(pausedAnswerNode?.humanInputFormDataList).toHaveLength(1)
+ expect(pausedAnswerNode?.humanInputFilledFormDataList).toHaveLength(0)
+ expect(pausedAnswerNode?.workflow_run_id).toBe('wf-run-branch')
})
})
diff --git a/web/app/components/base/chat/chat-with-history/hooks.tsx b/web/app/components/base/chat/chat-with-history/hooks.tsx
index 9f89b2e2317..765a32ba69d 100644
--- a/web/app/components/base/chat/chat-with-history/hooks.tsx
+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx
@@ -18,6 +18,7 @@ import { AppSourceType, delConversation, pinConversation, renameConversation, un
import { useInvalidateShareConversations, useShareChatList, useShareConversationName, useShareConversations } from '@/service/use-share'
import { TransferMethod } from '@/types/app'
import { addFileInfos, sortAgentSorts } from '../../../tools/utils'
+import { enrichSubmittedHumanInputFormData } from '../chat/answer/human-input-content/submitted-utils'
import { CONVERSATION_ID_INFO } from '../constants'
import { buildChatItemTree, getProcessedSystemVariablesFromUrlParams, getRawInputsFromUrlParams, getRawUserVariablesFromUrlParams } from '../utils'
@@ -39,21 +40,30 @@ function getFormattedChatList(messages: any[]) {
const humanInputFormDataList: HumanInputFormData[] = []
const humanInputFilledFormDataList: HumanInputFilledFormData[] = []
let workflowRunId = ''
- if (item.status === 'paused') {
- item.extra_contents?.forEach((content: ExtraContent) => {
- if (content.type === 'human_input' && !content.submitted) {
- humanInputFormDataList.push(content.form_definition)
- workflowRunId = content.workflow_run_id
- }
- })
- }
- else if (item.status === 'normal') {
- item.extra_contents?.forEach((content: ExtraContent) => {
- if (content.type === 'human_input' && content.submitted) {
- humanInputFilledFormDataList.push(content.form_submission_data)
- }
- })
- }
+ item.extra_contents?.forEach((content: ExtraContent) => {
+ if (content.type !== 'human_input')
+ return
+
+ const formDefinition = 'form_definition' in content ? content.form_definition : undefined
+ if (!content.submitted) {
+ if (!formDefinition)
+ return
+ humanInputFormDataList.push(formDefinition)
+ workflowRunId = content.workflow_run_id || workflowRunId
+ return
+ }
+
+ if (!('form_submission_data' in content) || !content.form_submission_data)
+ return
+ const currentFormIndex = humanInputFormDataList.findIndex(item => item.node_id === content.form_submission_data.node_id)
+ const requiredFormData = formDefinition || (currentFormIndex > -1
+ ? humanInputFormDataList[currentFormIndex]
+ : undefined)
+ if (currentFormIndex > -1)
+ humanInputFormDataList.splice(currentFormIndex, 1)
+ workflowRunId = content.workflow_run_id || workflowRunId
+ humanInputFilledFormDataList.push(enrichSubmittedHumanInputFormData(content.form_submission_data, requiredFormData))
+ })
newChatList.push({
id: item.id,
content: item.answer,
diff --git a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
index 738ab79bca8..3a63ca0886e 100644
--- a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
@@ -411,7 +411,7 @@ describe('useChat', () => {
// Human input required
callbacks.onHumanInputRequired({ data: { node_id: 'n-human' } })
- callbacks.onHumanInputRequired({ data: { node_id: 'n-human', updated: true } }) // update existing
+ callbacks.onHumanInputRequired({ data: { node_id: 'n-human', updated: true, form_content: '{{#$output.answer#}}', inputs: [] } }) // update existing
// setTimeout for timeout form
callbacks.onHumanInputFormTimeout({ data: { node_id: 'n-human', expiration_time: 123456 } })
@@ -437,6 +437,10 @@ describe('useChat', () => {
const lastResponse = result.current.chatList[1]
expect(lastResponse!.humanInputFormDataList).toHaveLength(0) // Removed when filled
expect(lastResponse!.humanInputFilledFormDataList).toHaveLength(2)
+ expect(lastResponse!.humanInputFilledFormDataList![0]).toEqual(expect.objectContaining({
+ form_content: '{{#$output.answer#}}',
+ inputs: [],
+ }))
expect(sseGet).toHaveBeenCalled() // from workflowPaused
expect(lastResponse!.annotation?.id).toBe('anno-1')
expect(lastResponse!.content).toBe('Replaced content')
diff --git a/web/app/components/base/chat/chat/answer/__tests__/human-input-filled-form-list.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/human-input-filled-form-list.spec.tsx
index 37556550ca1..09cced154ff 100644
--- a/web/app/components/base/chat/chat/answer/__tests__/human-input-filled-form-list.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/__tests__/human-input-filled-form-list.spec.tsx
@@ -1,5 +1,6 @@
import type { HumanInputFilledFormData } from '@/types/workflow'
import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { describe, expect, it } from 'vitest'
import HumanInputFilledFormList from '../human-input-filled-form-list'
@@ -12,13 +13,15 @@ const createFormData = (
): HumanInputFilledFormData => ({
node_id: 'node-1',
node_title: 'Node Title',
+ rendered_content: 'fallback content',
+ action_id: 'approve',
+ action_text: 'Approve',
+ submitted_data: {
+ summary: 'Approved',
+ },
- // 👇 IMPORTANT
- // DO NOT guess properties like `inputs`
- // Only include fields that actually exist in your project type.
- // Leave everything else empty via spread.
...overrides,
-} as HumanInputFilledFormData)
+})
describe('HumanInputFilledFormList', () => {
it('renders nothing when list is empty', () => {
@@ -27,12 +30,15 @@ describe('HumanInputFilledFormList', () => {
expect(screen.queryByText('Node Title')).not.toBeInTheDocument()
})
- it('renders one form item', () => {
+ it('renders one form item', async () => {
+ const user = userEvent.setup()
const data = [createFormData()]
render(<HumanInputFilledFormList humanInputFilledFormDataList={data} />)
expect(screen.getByText('Node Title')).toBeInTheDocument()
+ await user.click(screen.getByTestId('expand-icon'))
+ expect(screen.getByTestId('submitted-field-summary')).toHaveTextContent('Approved')
})
it('renders multiple form items', () => {
diff --git a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
index 816fd333413..bd3de0cec3a 100644
--- a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
@@ -248,6 +248,13 @@ describe('Operation', () => {
expect(screen.getByTestId('log-btn'))!.toBeInTheDocument()
})
+ it('should keep hover-only controls visible when a descendant popup is open', () => {
+ renderOperation({ ...baseProps, showPromptLog: true })
+
+ expect(screen.getByTestId('operation-actions')).toHaveClass('group-has-[[data-popup-open]]:flex')
+ expect(screen.getByTestId('log-btn').parentElement).toHaveClass('group-has-[[data-popup-open]]:block')
+ })
+
it('should not show prompt log for opening statements', () => {
const item = { ...baseItem, isOpeningStatement: true }
renderOperation({ ...baseProps, item, showPromptLog: true })
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx
index b1a6ec51aee..db5da117779 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx
@@ -1,13 +1,35 @@
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
+import { TransferMethod } from '@/types/app'
import ContentItem from '../content-item'
vi.mock('@/app/components/base/markdown', () => ({
Markdown: ({ content }: { content: string }) => <div data-testid="mock-markdown">{content}</div>,
}))
+vi.mock('../field-renderer', () => ({
+ __esModule: true,
+ default: ({
+ field,
+ onChange,
+ }: {
+ field: FormInputItem
+ onChange: (value: unknown) => void
+ }) => (
+ <button
+ type="button"
+ data-testid={`renderer-${field.type}`}
+ aria-label={field.output_variable_name}
+ onClick={() => onChange(field.type === 'paragraph' ? 'updated value' : field.type)}
+ >
+ {field.type}
+ </button>
+ ),
+}))
+
describe('ContentItem', () => {
const mockOnInputChange = vi.fn()
const mockFormInputFields: FormInputItem[] = [
@@ -49,9 +71,9 @@ describe('ContentItem', () => {
/>,
)
- const textarea = screen.getByTestId('content-item-textarea')
+ const textarea = screen.getByTestId('renderer-paragraph')
expect(textarea).toBeInTheDocument()
- expect(textarea).toHaveValue('Initial bio')
+ expect(screen.getByRole('button', { name: 'user_bio' })).toBeInTheDocument()
expect(screen.queryByTestId('mock-markdown')).not.toBeInTheDocument()
})
@@ -66,10 +88,9 @@ describe('ContentItem', () => {
/>,
)
- const textarea = screen.getByTestId('content-item-textarea')
- await user.type(textarea, 'x')
+ await user.click(screen.getByTestId('renderer-paragraph'))
- expect(mockOnInputChange).toHaveBeenCalledWith('user_bio', 'Initial biox')
+ expect(mockOnInputChange).toHaveBeenCalledWith('user_bio', 'updated value')
})
it('should render nothing if field name is valid but not found in formInputFields', () => {
@@ -85,18 +106,20 @@ describe('ContentItem', () => {
expect(container.firstChild).toBeNull()
})
- it('should render nothing if input type is not supported', () => {
- const { container } = render(
+ it('should delegate select fields to the shared renderer', async () => {
+ const user = userEvent.setup()
+
+ render(
<ContentItem
content="{{#$output.user_bio#}}"
formInputFields={[
{
- type: 'text-input',
+ type: 'select',
output_variable_name: 'user_bio',
- default: {
+ option_source: {
type: 'constant',
- value: '',
selector: [],
+ value: [],
},
} as FormInputItem,
]}
@@ -105,7 +128,68 @@ describe('ContentItem', () => {
/>,
)
- expect(container.querySelector('[data-testid="content-item-textarea"]')).not.toBeInTheDocument()
- expect(container.querySelector('.py-3')?.textContent).toBe('')
+ await user.click(screen.getByTestId('renderer-select'))
+
+ expect(mockOnInputChange).toHaveBeenCalledWith('user_bio', 'select')
+ })
+
+ it('should delegate single-file fields to the shared renderer', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <ContentItem
+ content="{{#$output.attachment#}}"
+ formInputFields={[
+ {
+ type: 'file',
+ output_variable_name: 'attachment',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: ['document'],
+ allowed_file_upload_methods: ['local_file'],
+ } as FormInputItem,
+ ]}
+ inputs={{ attachment: null }}
+ onInputChange={mockOnInputChange}
+ />,
+ )
+
+ await user.click(screen.getByTestId('renderer-file'))
+
+ expect(mockOnInputChange).toHaveBeenCalledWith('attachment', 'file')
+ })
+
+ it('should delegate file-list fields to the shared renderer', async () => {
+ const user = userEvent.setup()
+ const existingFiles: FileEntity[] = [{
+ id: 'file-1',
+ name: 'brief.pdf',
+ size: 128,
+ type: 'document',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ }]
+
+ render(
+ <ContentItem
+ content="{{#$output.attachments#}}"
+ formInputFields={[
+ {
+ type: 'file-list',
+ output_variable_name: 'attachments',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: ['document'],
+ allowed_file_upload_methods: ['local_file'],
+ number_limits: 4,
+ } as FormInputItem,
+ ]}
+ inputs={{ attachments: existingFiles }}
+ onInputChange={mockOnInputChange}
+ />,
+ )
+
+ await user.click(screen.getByTestId('renderer-file-list'))
+
+ expect(mockOnInputChange).toHaveBeenCalledWith('attachments', 'file-list')
})
})
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/field-renderer.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/field-renderer.spec.tsx
new file mode 100644
index 00000000000..9dc4fecf715
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/field-renderer.spec.tsx
@@ -0,0 +1,278 @@
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
+import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
+import HumanInputFieldRenderer from '../field-renderer'
+
+function MockTextarea({
+ value,
+ onChange,
+ onValueChange,
+ ...props
+}: {
+ value: string
+ onChange?: (event: { target: { value: string } }) => void
+ onValueChange?: (value: string) => void
+} & React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
+ return (
+ <textarea
+ data-testid="content-item-textarea"
+ value={value}
+ onChange={(event) => {
+ onChange?.({ target: { value: event.target.value } })
+ onValueChange?.(event.target.value)
+ }}
+ {...props}
+ />
+ )
+}
+
+vi.mock('@langgenius/dify-ui/textarea', () => ({
+ Textarea: MockTextarea,
+}))
+
+vi.mock('@langgenius/dify-ui/select', () => ({
+ Select: ({ children, onValueChange }: { children: React.ReactNode, onValueChange: (value: string | null) => void }) => (
+ <div>
+ <button type="button" data-testid="content-item-select-root" onClick={() => onValueChange('alice')}>select alice</button>
+ <button type="button" data-testid="content-item-select-null" onClick={() => onValueChange(null)}>select null</button>
+ {children}
+ </div>
+ ),
+ SelectTrigger: ({ children }: { children: React.ReactNode }) => <button type="button" data-testid="content-item-select">{children}</button>,
+ SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ SelectItem: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ SelectItemText: ({ children }: { children: React.ReactNode }) => <span>{children}</span>,
+ SelectItemIndicator: () => <span>selected</span>,
+}))
+
+vi.mock('@/app/components/base/file-uploader', () => ({
+ FileUploaderInAttachmentWrapper: ({ value, onChange, fileConfig }: {
+ value?: FileEntity[]
+ onChange: (files: FileEntity[]) => void
+ fileConfig: { number_limits?: number }
+ }) => (
+ <>
+ <button
+ type="button"
+ data-testid={`content-item-file-${fileConfig.number_limits ?? 0}`}
+ onClick={() => onChange([{ id: 'file-1', name: 'report.pdf', size: 1, type: 'document', progress: 100, transferMethod: TransferMethod.local_file, supportFileType: 'document' }])}
+ >
+ {(value || []).map(file => file.name).join(',')}
+ </button>
+ <button
+ type="button"
+ data-testid={`content-item-file-clear-${fileConfig.number_limits ?? 0}`}
+ onClick={() => onChange([])}
+ >
+ clear
+ </button>
+ </>
+ ),
+}))
+
+describe('HumanInputFieldRenderer', () => {
+ it('renders paragraph input and emits string changes', async () => {
+ const onChange = vi.fn()
+
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: { type: 'constant', selector: [], value: '' },
+ }}
+ value="hello"
+ onChange={onChange}
+ />,
+ )
+
+ fireEvent.change(screen.getByTestId('content-item-textarea'), {
+ target: { value: 'hello world' },
+ })
+
+ expect(onChange).toHaveBeenLastCalledWith('hello world')
+ })
+
+ it('renders paragraph input with an accessible name', () => {
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: { type: 'constant', selector: [], value: '' },
+ }}
+ value="hello"
+ onChange={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByLabelText('summary')).toHaveValue('hello')
+ })
+
+ it('renders paragraph input with an empty value when the current value is not a string', () => {
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: { type: 'constant', selector: [], value: '' },
+ }}
+ value={null}
+ onChange={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByTestId('content-item-textarea')).toHaveValue('')
+ })
+
+ it('renders select input and emits selected values', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.select,
+ output_variable_name: 'reviewer',
+ option_source: { type: 'constant', selector: [], value: ['alice', 'bob'] },
+ }}
+ value=""
+ onChange={onChange}
+ />,
+ )
+
+ await user.click(screen.getByTestId('content-item-select-root'))
+
+ expect(onChange).toHaveBeenCalledWith('alice')
+ })
+
+ it('ignores null select values', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.select,
+ output_variable_name: 'reviewer',
+ option_source: { type: 'constant', selector: [], value: ['alice', 'bob'] },
+ }}
+ value={null}
+ onChange={onChange}
+ />,
+ )
+
+ expect(screen.getByTestId('content-item-select')).toHaveTextContent('')
+
+ await user.click(screen.getByTestId('content-item-select-null'))
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('renders single-file input and emits one file', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ }}
+ value={null}
+ onChange={onChange}
+ />,
+ )
+
+ await user.click(screen.getByTestId('content-item-file-1'))
+
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ name: 'report.pdf' }))
+ })
+
+ it('renders existing single-file values and emits null when cleared', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ }}
+ value={{ id: 'file-2', name: 'existing.pdf', size: 1, type: 'document', progress: 100, transferMethod: TransferMethod.local_file, supportFileType: 'document' }}
+ onChange={onChange}
+ />,
+ )
+
+ expect(screen.getByTestId('content-item-file-1')).toHaveTextContent('existing.pdf')
+
+ await user.click(screen.getByTestId('content-item-file-clear-1'))
+
+ expect(onChange).toHaveBeenCalledWith(null)
+ })
+
+ it('renders file-list input and emits file arrays with max count', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.multiFiles,
+ output_variable_name: 'attachments',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ number_limits: 3,
+ }}
+ value={[]}
+ onChange={onChange}
+ />,
+ )
+
+ await user.click(screen.getByTestId('content-item-file-3'))
+
+ expect(onChange).toHaveBeenCalledWith([expect.objectContaining({ name: 'report.pdf' })])
+ })
+
+ it('uses the default max count for file-list inputs without an explicit limit', () => {
+ render(
+ <HumanInputFieldRenderer
+ field={{
+ type: InputVarType.multiFiles,
+ output_variable_name: 'attachments',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ }}
+ value={null}
+ onChange={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByTestId('content-item-file-5')).toBeInTheDocument()
+ })
+
+ it('renders nothing for unsupported input types', () => {
+ const { container } = render(
+ <HumanInputFieldRenderer
+ field={{
+ type: 'unsupported',
+ output_variable_name: 'unknown',
+ } as unknown as Parameters<typeof HumanInputFieldRenderer>[0]['field']}
+ value=""
+ onChange={vi.fn()}
+ />,
+ )
+
+ expect(container).toBeEmptyDOMElement()
+ })
+})
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx
index fb6c1259c0a..56953c3c911 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx
@@ -4,13 +4,74 @@ import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
import HumanInputForm from '../human-input-form'
vi.mock('../content-item', () => ({
- default: ({ content, onInputChange }: { content: string, onInputChange: (name: string, value: string) => void }) => (
+ default: ({ content, onInputChange }: { content: string, onInputChange: (name: string, value: unknown) => void }) => (
<div data-testid="mock-content-item">
{content}
<button data-testid="update-input" onClick={() => onInputChange('field1', 'new value')}>Update</button>
+ <button data-testid="update-select" onClick={() => onInputChange('field2', 'approved')}>Update Select</button>
+ <button
+ data-testid="update-single-file"
+ onClick={() => onInputChange('field4', {
+ id: 'file-2',
+ name: 'main.png',
+ size: 256,
+ type: 'image/png',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'image',
+ uploadedId: 'upload-file-2',
+ })}
+ >
+ Update Single File
+ </button>
+ <button
+ data-testid="update-pending-single-file"
+ onClick={() => onInputChange('field4', {
+ id: 'file-2',
+ name: 'main.png',
+ size: 256,
+ type: 'image/png',
+ progress: 50,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'image',
+ })}
+ >
+ Update Pending Single File
+ </button>
+ <button
+ data-testid="update-input-file"
+ onClick={() => onInputChange('field3', [{
+ id: 'file-1',
+ name: 'avatar.png',
+ size: 128,
+ type: 'image/png',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'image',
+ uploadedId: 'upload-file-1',
+ }])}
+ >
+ Update File
+ </button>
+ <button
+ data-testid="update-pending-input-file"
+ onClick={() => onInputChange('field3', [{
+ id: 'file-1',
+ name: 'avatar.png',
+ size: 128,
+ type: 'image/png',
+ progress: 50,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'image',
+ }])}
+ >
+ Update Pending File
+ </button>
</div>
),
}))
@@ -50,12 +111,10 @@ describe('HumanInputForm', () => {
expect(contentItems[1])!.toHaveTextContent('{{#$output.field1#}}')
expect(contentItems[2])!.toHaveTextContent('Part 2')
- const buttons = screen.getAllByRole('button').filter(button => button.textContent !== 'Update')
- expect(buttons).toHaveLength(4)
- expect(buttons[0])!.toHaveTextContent('Submit')
- expect(buttons[1])!.toHaveTextContent('Cancel')
- expect(buttons[2])!.toHaveTextContent('Accent')
- expect(buttons[3])!.toHaveTextContent('Ghost')
+ expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Accent' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Ghost' })).toBeInTheDocument()
})
it('should handle input changes and submit correctly', async () => {
@@ -76,6 +135,175 @@ describe('HumanInputForm', () => {
})
})
+ it('should submit file field values using the backend payload shape', async () => {
+ const user = userEvent.setup()
+ const mockOnSubmit = vi.fn().mockResolvedValue(undefined)
+ const formDataWithFileList: HumanInputFormData = {
+ ...mockFormData,
+ form_content: '{{#$output.field1#}} {{#$output.field3#}}',
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'field1',
+ default: { type: 'constant', value: 'initial', selector: [] },
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'field3',
+ allowed_file_extensions: ['.png'],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ number_limits: 5,
+ },
+ ] as FormInputItem[],
+ }
+
+ render(<HumanInputForm formData={formDataWithFileList} onSubmit={mockOnSubmit} />)
+
+ await user.click(screen.getAllByTestId('update-input')[0]!)
+ await user.click(screen.getAllByTestId('update-input-file')[0]!)
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
+
+ expect(mockOnSubmit).toHaveBeenCalledWith('token_123', {
+ action: 'action_1',
+ inputs: {
+ field1: 'new value',
+ field3: [{
+ type: 'image',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ }],
+ },
+ })
+ })
+
+ it('should disable buttons until select, file, and file list inputs have uploaded values', async () => {
+ const user = userEvent.setup()
+ const mockOnSubmit = vi.fn().mockResolvedValue(undefined)
+ const formDataWithRequiredInteractiveFields: HumanInputFormData = {
+ ...mockFormData,
+ form_content: '{{#$output.field2#}} {{#$output.field3#}} {{#$output.field4#}}',
+ inputs: [
+ {
+ type: InputVarType.select,
+ output_variable_name: 'field2',
+ option_source: {
+ type: 'constant',
+ value: ['approved'],
+ selector: [],
+ },
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'field3',
+ allowed_file_extensions: ['.png'],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ number_limits: 5,
+ },
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'field4',
+ allowed_file_extensions: ['.png'],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ },
+ ] as FormInputItem[],
+ }
+
+ render(<HumanInputForm formData={formDataWithRequiredInteractiveFields} onSubmit={mockOnSubmit} />)
+
+ const submitButton = screen.getByRole('button', { name: 'Submit' })
+ expect(submitButton).toBeDisabled()
+
+ await user.click(screen.getAllByTestId('update-select')[0]!)
+ await user.click(screen.getAllByTestId('update-pending-single-file')[0]!)
+ await user.click(screen.getAllByTestId('update-input-file')[0]!)
+ expect(submitButton).toBeDisabled()
+
+ await user.click(screen.getAllByTestId('update-single-file')[0]!)
+ await user.click(screen.getAllByTestId('update-pending-input-file')[0]!)
+ expect(submitButton).toBeDisabled()
+
+ await user.click(screen.getAllByTestId('update-input-file')[0]!)
+ expect(submitButton).toBeEnabled()
+
+ await user.click(submitButton)
+
+ expect(mockOnSubmit).toHaveBeenCalledWith('token_123', {
+ action: 'action_1',
+ inputs: {
+ field2: 'approved',
+ field3: [{
+ type: 'image',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ }],
+ field4: {
+ type: 'image',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-2',
+ },
+ },
+ })
+ })
+
+ it('should ignore input fields that are not rendered in form content when checking actions', async () => {
+ const user = userEvent.setup()
+ const mockOnSubmit = vi.fn().mockResolvedValue(undefined)
+ const formDataWithStaleInput: HumanInputFormData = {
+ ...mockFormData,
+ form_content: '{{#$output.field2#}}',
+ inputs: [
+ {
+ type: InputVarType.select,
+ output_variable_name: 'field2',
+ option_source: {
+ type: 'constant',
+ value: ['approved'],
+ selector: [],
+ },
+ },
+ {
+ type: InputVarType.select,
+ output_variable_name: 'stale_select',
+ option_source: {
+ type: 'constant',
+ value: ['unused'],
+ selector: [],
+ },
+ },
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'stale_file',
+ allowed_file_extensions: ['.png'],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ },
+ ] as FormInputItem[],
+ }
+
+ render(<HumanInputForm formData={formDataWithStaleInput} onSubmit={mockOnSubmit} />)
+
+ const submitButton = screen.getByRole('button', { name: 'Submit' })
+ expect(submitButton).toBeDisabled()
+
+ await user.click(screen.getByTestId('update-select'))
+ expect(submitButton).toBeEnabled()
+
+ await user.click(submitButton)
+
+ expect(mockOnSubmit).toHaveBeenCalledWith('token_123', {
+ action: 'action_1',
+ inputs: {
+ field2: 'approved',
+ },
+ })
+ })
+
it('should disable buttons during submission', async () => {
const user = userEvent.setup()
let resolveSubmit: (value: void | PromiseLike<void>) => void
@@ -109,19 +337,21 @@ describe('HumanInputForm', () => {
expect(screen.getAllByTestId('mock-content-item')).toHaveLength(3)
})
- it('should handle unsupported input types in initializeInputs', () => {
+ it('should handle mixed supported input types in initializeInputs', () => {
const formDataWithUnsupported = {
...mockFormData,
inputs: [
{
- type: 'text-input',
+ type: InputVarType.select,
output_variable_name: 'field2',
- default: { type: 'variable', value: '', selector: [] },
+ option_source: { type: 'variable', value: [], selector: [] },
} as FormInputItem,
{
- type: 'number',
+ type: InputVarType.singleFile,
output_variable_name: 'field3',
- default: { type: 'constant', value: '0', selector: [] },
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
} as FormInputItem,
],
resolved_default_values: { field2: 'default value' },
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted-content-item.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted-content-item.spec.tsx
new file mode 100644
index 00000000000..14ccf498ea2
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted-content-item.spec.tsx
@@ -0,0 +1,181 @@
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { FileResponse } from '@/types/workflow'
+import { render, screen } from '@testing-library/react'
+import { InputVarType } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
+import SubmittedContentItem from '../submitted-content-item'
+
+const attachmentValue: FileResponse = {
+ related_id: 'file-1',
+ upload_file_id: 'upload-1',
+ filename: 'decision.pdf',
+ extension: 'pdf',
+ size: 128,
+ mime_type: 'application/pdf',
+ transfer_method: TransferMethod.local_file,
+ type: 'document',
+ url: 'https://example.com/decision.pdf',
+ remote_url: '',
+}
+
+const evidenceValues: FileResponse[] = [
+ {
+ related_id: 'file-2',
+ upload_file_id: 'upload-2',
+ filename: 'evidence.png',
+ extension: 'png',
+ size: 256,
+ mime_type: 'image/png',
+ transfer_method: TransferMethod.remote_url,
+ type: 'image',
+ url: 'https://example.com/evidence.png',
+ remote_url: 'https://example.com/evidence.png',
+ },
+ {
+ related_id: 'file-3',
+ upload_file_id: 'upload-3',
+ filename: 'evidence.pdf',
+ extension: 'pdf',
+ size: 512,
+ mime_type: 'application/pdf',
+ transfer_method: TransferMethod.local_file,
+ type: 'document',
+ url: 'https://example.com/evidence.pdf',
+ remote_url: '',
+ },
+]
+
+const fields: FormInputItem[] = [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: { type: 'constant', value: '', selector: [] },
+ },
+ {
+ type: InputVarType.select,
+ output_variable_name: 'decision',
+ option_source: { type: 'constant', value: ['approve', 'reject'], selector: [] },
+ },
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'evidence',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ number_limits: 5,
+ },
+]
+
+describe('SubmittedContentItem', () => {
+ it('renders file-list output placeholders as readonly file lists', () => {
+ render(
+ <SubmittedContentItem
+ content="{{#$output.evidence#}}"
+ formInputFields={fields}
+ values={{ evidence: evidenceValues }}
+ />,
+ )
+
+ expect(screen.getByTestId('submitted-field-evidence')).toBeInTheDocument()
+ expect(screen.getByRole('img', { name: 'Preview' })).toHaveAttribute('src', 'https://example.com/evidence.png')
+ expect(screen.getByText('evidence.pdf')).toBeInTheDocument()
+ })
+
+ it('renders empty text for paragraph and select placeholders with non-string values', () => {
+ const { rerender } = render(
+ <SubmittedContentItem
+ content="{{#$output.summary#}}"
+ formInputFields={fields}
+ values={{ summary: attachmentValue }}
+ />,
+ )
+
+ expect(screen.getByTestId('submitted-field-summary')).toHaveTextContent('')
+
+ rerender(
+ <SubmittedContentItem
+ content="{{#$output.decision#}}"
+ formInputFields={fields}
+ values={{ decision: evidenceValues }}
+ />,
+ )
+
+ expect(screen.getByRole('combobox', { name: 'decision' })).toHaveTextContent('')
+ })
+
+ it('renders nothing when output placeholders do not have a usable submitted value', () => {
+ const { container, rerender } = render(
+ <SubmittedContentItem
+ content="{{#$output.missing#}}"
+ formInputFields={fields}
+ values={{ missing: 'value' }}
+ />,
+ )
+
+ expect(container).toBeEmptyDOMElement()
+
+ rerender(
+ <SubmittedContentItem
+ content="{{#$output.attachment#}}"
+ formInputFields={fields}
+ values={{}}
+ />,
+ )
+
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('skips file placeholders when submitted values have incompatible shapes', () => {
+ const { container, rerender } = render(
+ <SubmittedContentItem
+ content="{{#$output.attachment#}}"
+ formInputFields={fields}
+ values={{ attachment: 'not-a-file' }}
+ />,
+ )
+
+ expect(container).toBeEmptyDOMElement()
+
+ rerender(
+ <SubmittedContentItem
+ content="{{#$output.attachment#}}"
+ formInputFields={fields}
+ values={{ attachment: evidenceValues }}
+ />,
+ )
+
+ expect(container).toBeEmptyDOMElement()
+
+ rerender(
+ <SubmittedContentItem
+ content="{{#$output.evidence#}}"
+ formInputFields={fields}
+ values={{ evidence: attachmentValue }}
+ />,
+ )
+
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('renders nothing for unsupported output field types', () => {
+ const { container } = render(
+ <SubmittedContentItem
+ content="{{#$output.unknown#}}"
+ formInputFields={[{
+ type: 'unsupported',
+ output_variable_name: 'unknown',
+ } as unknown as FormInputItem]}
+ values={{ unknown: 'value' }}
+ />,
+ )
+
+ expect(container).toBeEmptyDOMElement()
+ })
+})
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted-field-values.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted-field-values.spec.tsx
new file mode 100644
index 00000000000..bd131cb7be3
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted-field-values.spec.tsx
@@ -0,0 +1,140 @@
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { FileResponse, HumanInputFormValue } from '@/types/workflow'
+import { render, screen } from '@testing-library/react'
+import { describe, expect, it } from 'vitest'
+import { InputVarType } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
+import SubmittedFieldValues from '../submitted-field-values'
+
+const fields: FormInputItem[] = [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: { type: 'constant', value: '', selector: [] },
+ },
+ {
+ type: InputVarType.select,
+ output_variable_name: 'decision',
+ option_source: { type: 'constant', value: ['approve', 'reject'], selector: [] },
+ },
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'evidence',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ number_limits: 5,
+ },
+]
+
+const attachmentValue: FileResponse = {
+ related_id: 'file-1',
+ upload_file_id: 'upload-1',
+ filename: 'decision.pdf',
+ extension: 'pdf',
+ size: 128,
+ mime_type: 'application/pdf',
+ transfer_method: TransferMethod.local_file,
+ type: 'document',
+ url: 'https://example.com/decision.pdf',
+ remote_url: '',
+}
+
+const evidenceValues: FileResponse[] = [
+ {
+ related_id: 'file-2',
+ upload_file_id: 'upload-2',
+ filename: 'evidence-1.png',
+ extension: 'png',
+ size: 256,
+ mime_type: 'image/png',
+ transfer_method: TransferMethod.remote_url,
+ type: 'image',
+ url: 'https://example.com/evidence-1.png',
+ remote_url: 'https://example.com/evidence-1.png',
+ },
+ {
+ related_id: 'file-3',
+ upload_file_id: 'upload-3',
+ filename: 'evidence-2.pdf',
+ extension: 'pdf',
+ size: 512,
+ mime_type: 'application/pdf',
+ transfer_method: TransferMethod.local_file,
+ type: 'document',
+ url: 'https://example.com/evidence-2.pdf',
+ remote_url: '',
+ },
+]
+
+const values: Record<string, HumanInputFormValue> = {
+ summary: 'Need more context',
+ decision: 'approve',
+ attachment: attachmentValue,
+ evidence: evidenceValues,
+}
+
+describe('SubmittedFieldValues', () => {
+ it('renders text and select values as text', () => {
+ render(<SubmittedFieldValues fields={fields} values={values} />)
+
+ expect(screen.getByTestId('submitted-field-summary')).toHaveTextContent('Need more context')
+ expect(screen.getByTestId('submitted-field-decision')).toHaveTextContent('approve')
+ })
+
+ it('renders file and file-list values as file lists', () => {
+ render(<SubmittedFieldValues fields={fields} values={values} />)
+
+ expect(screen.getByTestId('submitted-field-attachment')).toHaveTextContent('decision.pdf')
+ expect(screen.getByRole('img', { name: 'Preview' })).toHaveAttribute('src', 'https://example.com/evidence-1.png')
+ expect(screen.getByText('evidence-2.pdf')).toBeInTheDocument()
+ expect(screen.getAllByTestId('file-list')).toHaveLength(2)
+ })
+
+ it('skips fields with missing values', () => {
+ render(<SubmittedFieldValues fields={fields} values={{ summary: 'Only one field' }} />)
+
+ expect(screen.getByTestId('submitted-field-summary')).toHaveTextContent('Only one field')
+ expect(screen.queryByTestId('submitted-field-decision')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('submitted-field-attachment')).not.toBeInTheDocument()
+ })
+
+ it('infers value types when field definitions are unavailable', () => {
+ render(
+ <SubmittedFieldValues
+ values={{
+ summary: 'Unstructured summary',
+ attachment: attachmentValue,
+ evidence: evidenceValues,
+ }}
+ />,
+ )
+
+ expect(screen.getByTestId('submitted-field-summary')).toHaveTextContent('Unstructured summary')
+ expect(screen.getByTestId('submitted-field-attachment')).toHaveTextContent('decision.pdf')
+ expect(screen.getByRole('img', { name: 'Preview' })).toHaveAttribute('src', 'https://example.com/evidence-1.png')
+ expect(screen.getByText('evidence-2.pdf')).toBeInTheDocument()
+ })
+
+ it('skips file fields when submitted values have incompatible shapes', () => {
+ render(
+ <SubmittedFieldValues
+ fields={fields}
+ values={{
+ attachment: 'not-a-file',
+ evidence: attachmentValue,
+ }}
+ />,
+ )
+
+ expect(screen.queryByTestId('submitted-field-attachment')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('submitted-field-evidence')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted.spec.tsx
index 69f50547047..4db0014d269 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/submitted.spec.tsx
@@ -1,6 +1,8 @@
import type { HumanInputFilledFormData } from '@/types/workflow'
import { render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
+import { InputVarType } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
import { SubmittedHumanInputContent } from '../submitted'
vi.mock('@/app/components/base/markdown', () => ({
@@ -28,4 +30,99 @@ describe('SubmittedHumanInputContent Integration', () => {
// Trans component for triggered action. The mock usually renders the key.
expect(screen.getByText('nodes.humanInput.userActions.triggered')).toBeInTheDocument()
})
+
+ it('should prefer structured form data over rendered markdown when available', () => {
+ render(
+ <SubmittedHumanInputContent formData={{
+ ...mockFormData,
+ form_content: 'Decision: {{#$output.answer#}}',
+ inputs: [{
+ type: InputVarType.paragraph,
+ output_variable_name: 'answer',
+ default: { type: 'constant', value: '', selector: [] },
+ }],
+ submitted_data: {
+ answer: 'approved',
+ },
+ }}
+ />,
+ )
+
+ expect(screen.getByTestId('submitted-form-content')).toBeInTheDocument()
+ expect(screen.getByTestId('submitted-field-answer')).toHaveTextContent('approved')
+ expect(screen.queryByTestId('submitted-content')).not.toBeInTheDocument()
+ })
+
+ it('should render submitted select and file fields with the original form layout', () => {
+ render(
+ <SubmittedHumanInputContent formData={{
+ ...mockFormData,
+ form_content: '{{#$output.decision#}} {{#$output.attachment#}}',
+ inputs: [
+ {
+ type: InputVarType.select,
+ output_variable_name: 'decision',
+ option_source: { type: 'constant', value: ['approve', 'reject'], selector: [] },
+ },
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ },
+ ],
+ submitted_data: {
+ decision: 'approve',
+ attachment: {
+ related_id: 'file-1',
+ upload_file_id: 'upload-1',
+ filename: 'decision.pdf',
+ extension: 'pdf',
+ size: 128,
+ mime_type: 'application/pdf',
+ transfer_method: TransferMethod.local_file,
+ type: 'document',
+ url: 'https://example.com/decision.pdf',
+ remote_url: '',
+ },
+ },
+ }}
+ />,
+ )
+
+ expect(screen.getByRole('combobox', { name: 'decision' })).toBeDisabled()
+ expect(screen.getByRole('combobox', { name: 'decision' })).toHaveTextContent('approve')
+ expect(screen.getByTestId('submitted-field-attachment')).toHaveTextContent('decision.pdf')
+ })
+
+ it('should fallback to rendered markdown when structured form data is empty', () => {
+ render(
+ <SubmittedHumanInputContent formData={{
+ ...mockFormData,
+ submitted_data: {},
+ }}
+ />,
+ )
+
+ expect(screen.getByTestId('submitted-content')).toBeInTheDocument()
+ expect(screen.getByTestId('mock-markdown')).toHaveTextContent('Rendered **Markdown** content')
+ expect(screen.queryByTestId('submitted-field-values')).not.toBeInTheDocument()
+ })
+
+ it('should render submitted field values when original form layout is unavailable', () => {
+ render(
+ <SubmittedHumanInputContent formData={{
+ ...mockFormData,
+ submitted_data: {
+ answer: 'approved',
+ },
+ }}
+ />,
+ )
+
+ expect(screen.getByTestId('submitted-field-values')).toBeInTheDocument()
+ expect(screen.getByTestId('submitted-field-answer')).toHaveTextContent('approved')
+ expect(screen.queryByTestId('submitted-content')).not.toBeInTheDocument()
+ })
})
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/utils.spec.ts b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/utils.spec.ts
index e63bfc123fa..8539cf1f97d 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/utils.spec.ts
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/utils.spec.ts
@@ -1,29 +1,78 @@
import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import type { Locale } from '@/i18n-config/language'
import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
-import { InputVarType } from '@/app/components/workflow/types'
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
import {
getButtonStyle,
+ getFormContentInputNames,
+ getProcessedHumanInputFormInputs,
getRelativeTime,
+ getRenderedFormInputs,
+ hasInvalidRequiredHumanInput,
+ hasInvalidSelectOrFileInput,
initializeInputs,
isRelativeTimeSameOrAfter,
splitByOutputVar,
} from '../utils'
-const createInput = (overrides: Partial<FormInputItem>): FormInputItem => ({
- label: 'field',
- variable: 'field',
- required: false,
- max_length: 128,
- type: InputVarType.textInput,
+const paragraphInput = (overrides: Partial<Extract<FormInputItem, { type: InputVarType.paragraph }>> = {}): FormInputItem => ({
+ type: InputVarType.paragraph,
+ output_variable_name: 'field',
default: {
- type: 'constant' as const,
+ type: 'constant',
value: '',
- selector: [], // Dummy selector
+ selector: [],
+ },
+ ...overrides,
+})
+
+const selectInput = (overrides: Partial<Extract<FormInputItem, { type: InputVarType.select }>> = {}): FormInputItem => ({
+ type: InputVarType.select,
+ output_variable_name: 'field',
+ option_source: {
+ type: 'constant',
+ value: ['option-a', 'option-b'],
+ selector: [],
},
+ ...overrides,
+})
+
+const fileInput = (overrides: Partial<Extract<FormInputItem, { type: InputVarType.singleFile }>> = {}): FormInputItem => ({
+ type: InputVarType.singleFile,
output_variable_name: 'field',
+ allowed_file_extensions: [],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file],
...overrides,
-} as unknown as FormInputItem)
+})
+
+const fileListInput = (overrides: Partial<Extract<FormInputItem, { type: InputVarType.multiFiles }>> = {}): FormInputItem => ({
+ type: InputVarType.multiFiles,
+ output_variable_name: 'field',
+ allowed_file_extensions: [],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ number_limits: 5,
+ ...overrides,
+})
+
+const uploadedFile = {
+ id: 'file-1',
+ name: 'avatar.png',
+ size: 128,
+ type: 'image',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'image',
+ uploadedId: 'upload-file-1',
+}
+
+const uploadingFile = {
+ ...uploadedFile,
+ uploadedId: undefined,
+ progress: 50,
+}
describe('human-input utils', () => {
describe('getButtonStyle', () => {
@@ -53,16 +102,31 @@ describe('human-input utils', () => {
})
})
+ describe('form content inputs', () => {
+ it('should extract and filter input fields rendered in form content', () => {
+ const formInputs: FormInputItem[] = [
+ selectInput({ output_variable_name: 'visible_select' }),
+ paragraphInput({ output_variable_name: 'visible_paragraph' }),
+ fileInput({ output_variable_name: 'stale_file' }),
+ ]
+ const content = 'Select {{#$output.visible_select#}} and write {{#$output.visible_paragraph#}}'
+
+ expect(getFormContentInputNames(content)).toEqual(['visible_select', 'visible_paragraph'])
+ expect(getRenderedFormInputs(formInputs, content).map(input => input.output_variable_name)).toEqual([
+ 'visible_select',
+ 'visible_paragraph',
+ ])
+ })
+ })
+
describe('initializeInputs', () => {
- it('should initialize text fields with constants and variable defaults', () => {
- const formInputs = [
- createInput({
- type: InputVarType.textInput,
+ it('should initialize paragraph fields with constants and variable defaults', () => {
+ const formInputs: FormInputItem[] = [
+ paragraphInput({
output_variable_name: 'name',
default: { type: 'constant', value: 'John', selector: [] },
}),
- createInput({
- type: InputVarType.paragraph,
+ paragraphInput({
output_variable_name: 'bio',
default: { type: 'variable', value: '', selector: [] },
}),
@@ -74,23 +138,45 @@ describe('human-input utils', () => {
})
})
- it('should set non text-like inputs to undefined', () => {
- const formInputs = [
- createInput({
- type: InputVarType.select,
+ it('should initialize select fields with empty strings', () => {
+ const formInputs: FormInputItem[] = [
+ selectInput({
output_variable_name: 'role',
}),
]
expect(initializeInputs(formInputs)).toEqual({
- role: undefined,
+ role: '',
+ })
+ })
+
+ it('should initialize single file fields with null', () => {
+ const formInputs: FormInputItem[] = [
+ fileInput({
+ output_variable_name: 'avatar',
+ }),
+ ]
+
+ expect(initializeInputs(formInputs)).toEqual({
+ avatar: null,
+ })
+ })
+
+ it('should initialize file list fields with empty arrays', () => {
+ const formInputs: FormInputItem[] = [
+ fileListInput({
+ output_variable_name: 'attachments',
+ }),
+ ]
+
+ expect(initializeInputs(formInputs)).toEqual({
+ attachments: [],
})
})
it('should fallback to empty string when variable default is missing', () => {
- const formInputs = [
- createInput({
- type: InputVarType.textInput,
+ const formInputs: FormInputItem[] = [
+ paragraphInput({
output_variable_name: 'summary',
default: { type: 'variable', value: '', selector: [] },
}),
@@ -100,6 +186,200 @@ describe('human-input utils', () => {
summary: '',
})
})
+
+ it('should fallback to default paragraph values when resolved defaults are not strings', () => {
+ const formInputs: FormInputItem[] = [
+ paragraphInput({
+ output_variable_name: 'summary',
+ default: { type: 'variable', value: '', selector: [] },
+ }),
+ ]
+
+ expect(initializeInputs(formInputs, {
+ summary: {
+ related_id: 'file-1',
+ size: 128,
+ extension: '.pdf',
+ filename: 'brief.pdf',
+ mime_type: 'application/pdf',
+ transfer_method: TransferMethod.local_file,
+ type: 'document',
+ url: 'https://example.com/brief.pdf',
+ upload_file_id: 'upload-file-1',
+ remote_url: '',
+ },
+ })).toEqual({
+ summary: '',
+ })
+ })
+
+ it('should ignore resolved defaults for non-paragraph fields', () => {
+ const formInputs: FormInputItem[] = [
+ selectInput({
+ output_variable_name: 'role',
+ }),
+ fileInput({
+ output_variable_name: 'avatar',
+ }),
+ fileListInput({
+ output_variable_name: 'attachments',
+ }),
+ ]
+
+ expect(initializeInputs(formInputs, {
+ role: 'maintainer',
+ avatar: {
+ related_id: 'file-2',
+ size: 64,
+ extension: '.png',
+ filename: 'avatar.png',
+ mime_type: 'image/png',
+ transfer_method: TransferMethod.local_file,
+ type: 'image',
+ url: 'https://example.com/avatar.png',
+ upload_file_id: 'upload-file-2',
+ remote_url: '',
+ },
+ attachments: [{
+ related_id: 'file-3',
+ size: 16,
+ extension: '.txt',
+ filename: 'notes.txt',
+ mime_type: 'text/plain',
+ transfer_method: TransferMethod.local_file,
+ type: 'document',
+ url: 'https://example.com/notes.txt',
+ upload_file_id: 'upload-file-3',
+ remote_url: '',
+ }],
+ })).toEqual({
+ role: '',
+ avatar: null,
+ attachments: [],
+ })
+ })
+
+ it('should ignore unsupported input types', () => {
+ expect(initializeInputs([
+ {
+ type: 'unsupported',
+ output_variable_name: 'unknown',
+ } as unknown as FormInputItem,
+ ])).toEqual({})
+ })
+ })
+
+ describe('required input checks', () => {
+ it('should ignore fields that are not present in values', () => {
+ const formInputs: FormInputItem[] = [
+ selectInput({ output_variable_name: 'visible_select' }),
+ fileInput({ output_variable_name: 'stale_file' }),
+ paragraphInput({ output_variable_name: 'stale_paragraph' }),
+ ]
+ const values = {
+ visible_select: 'approved',
+ }
+
+ expect(hasInvalidSelectOrFileInput(formInputs, values)).toBe(false)
+ expect(hasInvalidRequiredHumanInput(formInputs, values)).toBe(false)
+ })
+
+ it('should detect empty select values and unuploaded file values', () => {
+ expect(hasInvalidSelectOrFileInput([
+ selectInput({ output_variable_name: 'decision' }),
+ ], {
+ decision: '',
+ })).toBe(true)
+ expect(hasInvalidRequiredHumanInput([
+ paragraphInput({ output_variable_name: 'summary' }),
+ ], {
+ summary: ' ',
+ })).toBe(true)
+ expect(hasInvalidSelectOrFileInput([
+ fileInput({ output_variable_name: 'attachment' }),
+ ], {
+ attachment: uploadingFile,
+ })).toBe(true)
+ expect(hasInvalidRequiredHumanInput([
+ fileListInput({ output_variable_name: 'attachments' }),
+ ], {
+ attachments: [uploadedFile, uploadingFile],
+ })).toBe(true)
+ })
+
+ it('should accept uploaded single and multiple file values', () => {
+ expect(hasInvalidSelectOrFileInput([
+ fileInput({ output_variable_name: 'attachment' }),
+ fileListInput({ output_variable_name: 'attachments' }),
+ ], {
+ attachment: [uploadedFile],
+ attachments: [uploadedFile],
+ })).toBe(false)
+ expect(hasInvalidRequiredHumanInput([
+ fileInput({ output_variable_name: 'attachment' }),
+ fileListInput({ output_variable_name: 'attachments' }),
+ ], {
+ attachment: [uploadedFile],
+ attachments: [uploadedFile],
+ })).toBe(false)
+ })
+
+ it('should treat unsupported input types as valid by default', () => {
+ const unsupportedInput = {
+ type: 'unsupported',
+ output_variable_name: 'unknown',
+ } as unknown as FormInputItem
+
+ expect(hasInvalidSelectOrFileInput([unsupportedInput], {
+ unknown: 'value',
+ })).toBe(false)
+ expect(hasInvalidRequiredHumanInput([unsupportedInput], {
+ unknown: 'value',
+ })).toBe(false)
+ })
+ })
+
+ describe('getProcessedHumanInputFormInputs', () => {
+ it('should return undefined when no values are provided', () => {
+ expect(getProcessedHumanInputFormInputs([], undefined)).toBeUndefined()
+ })
+
+ it('should process file values and fallback invalid file values', () => {
+ expect(getProcessedHumanInputFormInputs([
+ fileInput({ output_variable_name: 'attachment' }),
+ fileInput({ output_variable_name: 'attachmentFromArray' }),
+ fileInput({ output_variable_name: 'emptyAttachment' }),
+ fileListInput({ output_variable_name: 'attachments' }),
+ fileListInput({ output_variable_name: 'emptyAttachments' }),
+ ], {
+ attachment: uploadedFile,
+ attachmentFromArray: [uploadedFile],
+ emptyAttachment: '',
+ attachments: [uploadedFile],
+ emptyAttachments: null,
+ })).toEqual({
+ attachment: {
+ type: 'image',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ },
+ attachmentFromArray: {
+ type: 'image',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ },
+ emptyAttachment: undefined,
+ attachments: [{
+ type: 'image',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ }],
+ emptyAttachments: [],
+ })
+ })
})
describe('time helpers', () => {
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/content-item.tsx b/web/app/components/base/chat/chat/answer/human-input-content/content-item.tsx
index 75dd287c2b4..a1c3e26111e 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/content-item.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/content-item.tsx
@@ -1,8 +1,8 @@
import type { ContentItemProps } from './type'
-import { Textarea } from '@langgenius/dify-ui/textarea'
import * as React from 'react'
import { useMemo } from 'react'
import { Markdown } from '@/app/components/base/markdown'
+import HumanInputFieldRenderer from './field-renderer'
const ContentItem = ({
content,
@@ -40,15 +40,11 @@ const ContentItem = ({
return (
<div className="py-3">
- {formInputField.type === 'paragraph' && (
- <Textarea
- aria-label={fieldName}
- className="h-[104px] sm:text-xs"
- value={inputs[fieldName]!}
- onValueChange={(value) => { onInputChange(fieldName, value) }}
- data-testid="content-item-textarea"
- />
- )}
+ <HumanInputFieldRenderer
+ field={formInputField}
+ value={inputs[fieldName]}
+ onChange={value => onInputChange(fieldName, value)}
+ />
</div>
)
}
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/field-renderer.tsx b/web/app/components/base/chat/chat/answer/human-input-content/field-renderer.tsx
new file mode 100644
index 00000000000..d682fc3e237
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/field-renderer.tsx
@@ -0,0 +1,113 @@
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectItemIndicator,
+ SelectItemText,
+ SelectTrigger,
+} from '@langgenius/dify-ui/select'
+import { Textarea } from '@langgenius/dify-ui/textarea'
+import * as React from 'react'
+import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
+import {
+ isFileFormInput,
+ isFileListFormInput,
+ isParagraphFormInput,
+ isSelectFormInput,
+} from '@/app/components/workflow/nodes/human-input/types'
+
+export type HumanInputFieldValue = string | FileEntity | FileEntity[] | null
+
+type Props = {
+ field: FormInputItem
+ value?: HumanInputFieldValue
+ onChange: (value: HumanInputFieldValue) => void
+}
+
+const HumanInputFieldRenderer = ({
+ field,
+ value,
+ onChange,
+}: Props) => {
+ if (isParagraphFormInput(field)) {
+ return (
+ <Textarea
+ aria-label={field.output_variable_name}
+ className="h-[104px] sm:text-xs"
+ value={typeof value === 'string' ? value : ''}
+ onValueChange={nextValue => onChange(nextValue)}
+ data-testid="content-item-textarea"
+ />
+ )
+ }
+
+ if (isSelectFormInput(field)) {
+ const options = field.option_source.value.map(option => ({
+ name: option,
+ value: option,
+ }))
+
+ return (
+ <Select
+ value={typeof value === 'string' ? value : ''}
+ onValueChange={(nextValue) => {
+ if (nextValue == null)
+ return
+ onChange(nextValue)
+ }}
+ >
+ <SelectTrigger size="large" className="w-full" aria-label={field.output_variable_name}>
+ {typeof value === 'string' ? value : ''}
+ </SelectTrigger>
+ <SelectContent listClassName="max-h-[140px] overflow-y-auto">
+ {options.map(option => (
+ <SelectItem key={option.value} value={option.value}>
+ <SelectItemText>{option.name}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )
+ }
+
+ if (isFileFormInput(field)) {
+ const singleFileValue = value && !Array.isArray(value) && typeof value !== 'string'
+ ? [value]
+ : []
+
+ return (
+ <FileUploaderInAttachmentWrapper
+ value={singleFileValue}
+ onChange={files => onChange(files[0] || null)}
+ fileConfig={{
+ allowed_file_types: field.allowed_file_types,
+ allowed_file_extensions: field.allowed_file_extensions,
+ allowed_file_upload_methods: field.allowed_file_upload_methods,
+ number_limits: 1,
+ }}
+ />
+ )
+ }
+
+ if (isFileListFormInput(field)) {
+ return (
+ <FileUploaderInAttachmentWrapper
+ value={Array.isArray(value) ? value : []}
+ onChange={files => onChange(files)}
+ fileConfig={{
+ allowed_file_types: field.allowed_file_types,
+ allowed_file_extensions: field.allowed_file_extensions,
+ allowed_file_upload_methods: field.allowed_file_upload_methods,
+ number_limits: field.number_limits || 5,
+ }}
+ />
+ )
+ }
+
+ return null
+}
+
+export default React.memo(HumanInputFieldRenderer)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/human-input-form.tsx b/web/app/components/base/chat/chat/answer/human-input-content/human-input-form.tsx
index 18d9d72376a..31b0328a9e2 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/human-input-form.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/human-input-form.tsx
@@ -1,36 +1,43 @@
'use client'
import type { ButtonProps } from '@langgenius/dify-ui/button'
+import type { HumanInputFieldValue } from './field-renderer'
import type { HumanInputFormProps } from './type'
import type { UserAction } from '@/app/components/workflow/nodes/human-input/types'
import { Button } from '@langgenius/dify-ui/button'
import * as React from 'react'
import { useCallback, useState } from 'react'
import ContentItem from './content-item'
-import { getButtonStyle, initializeInputs, splitByOutputVar } from './utils'
+import { getButtonStyle, getProcessedHumanInputFormInputs, getRenderedFormInputs, hasInvalidSelectOrFileInput, initializeInputs, splitByOutputVar } from './utils'
const HumanInputForm = ({
formData,
onSubmit,
}: HumanInputFormProps) => {
const formToken = formData.form_token
- const defaultInputs = initializeInputs(formData.inputs, formData.resolved_default_values || {})
const contentList = splitByOutputVar(formData.form_content)
+ const renderedFormInputs = getRenderedFormInputs(formData.inputs, formData.form_content)
+ const defaultInputs = initializeInputs(renderedFormInputs, formData.resolved_default_values || {})
const [inputs, setInputs] = useState(defaultInputs)
const [isSubmitting, setIsSubmitting] = useState(false)
- const handleInputsChange = useCallback((name: string, value: string) => {
+ const handleInputsChange = useCallback((name: string, value: HumanInputFieldValue) => {
setInputs(prev => ({
...prev,
[name]: value,
}))
}, [])
- const submit = async (formToken: string, actionID: string, inputs: Record<string, string>) => {
+ const submit = async (formToken: string, actionID: string, inputs: Record<string, HumanInputFieldValue>) => {
setIsSubmitting(true)
- await onSubmit?.(formToken, { inputs, action: actionID })
+ await onSubmit?.(formToken, {
+ inputs: getProcessedHumanInputFormInputs(renderedFormInputs, inputs) || {},
+ action: actionID,
+ })
setIsSubmitting(false)
}
+ const isActionDisabled = isSubmitting || hasInvalidSelectOrFileInput(renderedFormInputs, inputs)
+
return (
<>
{contentList.map((content, index) => (
@@ -46,7 +53,7 @@ const HumanInputForm = ({
{formData.actions.map((action: UserAction) => (
<Button
key={action.id}
- disabled={isSubmitting}
+ disabled={isActionDisabled}
variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
onClick={() => submit(formToken, action.id, inputs)}
>
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/submitted-content-item.tsx b/web/app/components/base/chat/chat/answer/human-input-content/submitted-content-item.tsx
new file mode 100644
index 00000000000..df1aaaeb51b
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/submitted-content-item.tsx
@@ -0,0 +1,121 @@
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { HumanInputFormValue } from '@/types/workflow'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectItemIndicator,
+ SelectItemText,
+ SelectTrigger,
+} from '@langgenius/dify-ui/select'
+import * as React from 'react'
+import { FileList } from '@/app/components/base/file-uploader'
+import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
+import { Markdown } from '@/app/components/base/markdown'
+import {
+ isFileFormInput,
+ isFileListFormInput,
+ isParagraphFormInput,
+ isSelectFormInput,
+} from '@/app/components/workflow/nodes/human-input/types'
+
+type SubmittedContentItemProps = {
+ content: string
+ formInputFields: FormInputItem[]
+ values: Record<string, HumanInputFormValue>
+}
+
+const outputVarRegex = /\{\{#\$output\.([^#]+)#\}\}/
+
+const isOutputField = (content: string) => outputVarRegex.test(content)
+
+const extractFieldName = (content: string) => {
+ const match = outputVarRegex.exec(content)
+ return match ? match[1]! : ''
+}
+
+const SubmittedContentItem = ({
+ content,
+ formInputFields,
+ values,
+}: SubmittedContentItemProps) => {
+ if (!isOutputField(content)) {
+ return (
+ <Markdown content={content} />
+ )
+ }
+
+ const fieldName = extractFieldName(content)
+ const field = formInputFields.find(field => field.output_variable_name === fieldName)
+ const value = values[fieldName]
+
+ if (!field || value == null)
+ return null
+
+ if (isParagraphFormInput(field)) {
+ return (
+ <span
+ className="body-md-regular break-words text-text-primary"
+ data-testid={`submitted-field-${fieldName}`}
+ >
+ {typeof value === 'string' ? value : ''}
+ </span>
+ )
+ }
+
+ if (isSelectFormInput(field)) {
+ const selectedValue = typeof value === 'string' ? value : ''
+
+ return (
+ <div className="py-3" data-testid={`submitted-field-${fieldName}`}>
+ <Select value={selectedValue} disabled>
+ <SelectTrigger size="large" className="w-full" aria-label={field.output_variable_name} disabled>
+ {selectedValue}
+ </SelectTrigger>
+ <SelectContent listClassName="max-h-[140px] overflow-y-auto">
+ {field.option_source.value.map(option => (
+ <SelectItem key={option} value={option}>
+ <SelectItemText>{option}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )
+ }
+
+ if (isFileFormInput(field)) {
+ if (typeof value === 'string' || Array.isArray(value))
+ return null
+
+ return (
+ <div className="py-3" data-testid={`submitted-field-${fieldName}`}>
+ <FileList
+ files={getProcessedFilesFromResponse([value])}
+ showDeleteAction={false}
+ showDownloadAction
+ />
+ </div>
+ )
+ }
+
+ if (isFileListFormInput(field)) {
+ if (typeof value === 'string' || !Array.isArray(value))
+ return null
+
+ return (
+ <div className="py-3" data-testid={`submitted-field-${fieldName}`}>
+ <FileList
+ files={getProcessedFilesFromResponse(value)}
+ showDeleteAction={false}
+ showDownloadAction
+ />
+ </div>
+ )
+ }
+
+ return null
+}
+
+export default React.memo(SubmittedContentItem)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/submitted-field-values.tsx b/web/app/components/base/chat/chat/answer/human-input-content/submitted-field-values.tsx
new file mode 100644
index 00000000000..3e059bb6352
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/submitted-field-values.tsx
@@ -0,0 +1,88 @@
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { HumanInputFormValue } from '@/types/workflow'
+import * as React from 'react'
+import { FileList } from '@/app/components/base/file-uploader'
+import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
+import {
+ isFileFormInput,
+ isFileListFormInput,
+} from '@/app/components/workflow/nodes/human-input/types'
+
+type SubmittedFieldValuesProps = {
+ fields?: FormInputItem[]
+ values: Record<string, HumanInputFormValue>
+}
+
+const SubmittedFieldValues = ({
+ fields,
+ values,
+}: SubmittedFieldValuesProps) => {
+ const fieldNames = fields?.map(field => field.output_variable_name) ?? Object.keys(values)
+ const fieldMap = new Map(fields?.map(field => [field.output_variable_name, field]) ?? [])
+
+ return (
+ <div className="flex flex-col gap-3" data-testid="submitted-field-values">
+ {fieldNames.map((fieldName) => {
+ const field = fieldMap.get(fieldName)
+ const value = values[fieldName]
+
+ if (value == null)
+ return null
+
+ let valueKind: 'text' | 'file' | 'file-list' = 'text'
+ if (field && isFileFormInput(field))
+ valueKind = 'file'
+ else if (field && isFileListFormInput(field))
+ valueKind = 'file-list'
+ else if (typeof value === 'string')
+ valueKind = 'text'
+ else if (Array.isArray(value))
+ valueKind = 'file-list'
+ else
+ valueKind = 'file'
+
+ if (valueKind === 'file') {
+ if (typeof value === 'string' || Array.isArray(value))
+ return null
+
+ return (
+ <div key={fieldName} data-testid={`submitted-field-${fieldName}`}>
+ <FileList
+ files={getProcessedFilesFromResponse([value])}
+ showDeleteAction={false}
+ showDownloadAction
+ />
+ </div>
+ )
+ }
+
+ if (valueKind === 'file-list') {
+ if (typeof value === 'string' || !Array.isArray(value))
+ return null
+
+ return (
+ <div key={fieldName} data-testid={`submitted-field-${fieldName}`}>
+ <FileList
+ files={getProcessedFilesFromResponse(value)}
+ showDeleteAction={false}
+ showDownloadAction
+ />
+ </div>
+ )
+ }
+
+ return (
+ <div
+ key={fieldName}
+ className="body-md-regular break-words text-text-primary"
+ data-testid={`submitted-field-${fieldName}`}
+ >
+ {String(value)}
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+export default React.memo(SubmittedFieldValues)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/submitted-form-content.tsx b/web/app/components/base/chat/chat/answer/human-input-content/submitted-form-content.tsx
new file mode 100644
index 00000000000..ac11001d5bb
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/submitted-form-content.tsx
@@ -0,0 +1,34 @@
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { HumanInputFormValue } from '@/types/workflow'
+import * as React from 'react'
+import SubmittedContentItem from './submitted-content-item'
+import { splitByOutputVar } from './utils'
+
+type SubmittedFormContentProps = {
+ formContent: string
+ formInputFields: FormInputItem[]
+ values: Record<string, HumanInputFormValue>
+}
+
+const SubmittedFormContent = ({
+ formContent,
+ formInputFields,
+ values,
+}: SubmittedFormContentProps) => {
+ const contentList = splitByOutputVar(formContent)
+
+ return (
+ <div data-testid="submitted-form-content">
+ {contentList.map((content, index) => (
+ <SubmittedContentItem
+ key={index}
+ content={content}
+ formInputFields={formInputFields}
+ values={values}
+ />
+ ))}
+ </div>
+ )
+}
+
+export default React.memo(SubmittedFormContent)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/submitted-utils.ts b/web/app/components/base/chat/chat/answer/human-input-content/submitted-utils.ts
new file mode 100644
index 00000000000..c11ebd9ab52
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/submitted-utils.ts
@@ -0,0 +1,15 @@
+import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'
+
+export const enrichSubmittedHumanInputFormData = (
+ filledFormData: HumanInputFilledFormData,
+ requiredFormData?: Pick<HumanInputFormData, 'form_content' | 'inputs'>,
+): HumanInputFilledFormData => {
+ if (!requiredFormData)
+ return filledFormData
+
+ return {
+ ...filledFormData,
+ form_content: requiredFormData.form_content,
+ inputs: requiredFormData.inputs,
+ }
+}
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/submitted.tsx b/web/app/components/base/chat/chat/answer/human-input-content/submitted.tsx
index bf598d4c5db..64a14aa5ef4 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/submitted.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/submitted.tsx
@@ -2,11 +2,13 @@ import type { SubmittedHumanInputContentProps } from './type'
import { useMemo } from 'react'
import ExecutedAction from './executed-action'
import SubmittedContent from './submitted-content'
+import SubmittedFieldValues from './submitted-field-values'
+import SubmittedFormContent from './submitted-form-content'
export const SubmittedHumanInputContent = ({
formData,
}: SubmittedHumanInputContentProps) => {
- const { rendered_content, action_id, action_text } = formData
+ const { rendered_content, action_id, action_text, form_content, submitted_data, inputs } = formData
const executedAction = useMemo(() => {
return {
@@ -15,9 +17,21 @@ export const SubmittedHumanInputContent = ({
}
}, [action_id, action_text])
+ const content = form_content && inputs && submitted_data && Object.keys(submitted_data).length > 0
+ ? (
+ <SubmittedFormContent
+ formContent={form_content}
+ formInputFields={inputs}
+ values={submitted_data}
+ />
+ )
+ : submitted_data && Object.keys(submitted_data).length > 0
+ ? <SubmittedFieldValues values={submitted_data} />
+ : <SubmittedContent content={rendered_content} />
+
return (
<>
- <SubmittedContent content={rendered_content} />
+ {content}
{/* Executed Action */}
<ExecutedAction executedAction={executedAction} />
</>
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/type.ts b/web/app/components/base/chat/chat/answer/human-input-content/type.ts
index 7fb4082b4ae..7d01a281a85 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/type.ts
+++ b/web/app/components/base/chat/chat/answer/human-input-content/type.ts
@@ -1,3 +1,4 @@
+import type { HumanInputFieldValue } from './field-renderer'
import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'
@@ -11,7 +12,7 @@ export type UnsubmittedHumanInputContentProps = {
showEmailTip?: boolean
isEmailDebugMode?: boolean
showDebugModeTip?: boolean
- onSubmit?: (formToken: string, data: { inputs: Record<string, string>, action: string }) => Promise<void>
+ onSubmit?: (formToken: string, data: HumanInputFormSubmitData) => Promise<void>
}
export type SubmittedHumanInputContentProps = {
@@ -20,12 +21,17 @@ export type SubmittedHumanInputContentProps = {
export type HumanInputFormProps = {
formData: HumanInputFormData
- onSubmit?: (formToken: string, data: { inputs: Record<string, string>, action: string }) => Promise<void>
+ onSubmit?: (formToken: string, data: HumanInputFormSubmitData) => Promise<void>
+}
+
+export type HumanInputFormSubmitData = {
+ inputs: Record<string, unknown>
+ action: string
}
export type ContentItemProps = {
content: string
formInputFields: FormInputItem[]
- inputs: Record<string, string>
- onInputChange: (name: string, value: string) => void
+ inputs: Record<string, HumanInputFieldValue>
+ onInputChange: (name: string, value: HumanInputFieldValue) => void
}
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/utils.ts b/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
index da81f9f1b96..92584588368 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
+++ b/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
@@ -1,10 +1,20 @@
+import type { HumanInputFieldValue } from './field-renderer'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import type { Locale } from '@/i18n-config'
+import type { HumanInputResolvedValue } from '@/types/workflow'
import dayjs from 'dayjs'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
import relativeTime from 'dayjs/plugin/relativeTime'
import utc from 'dayjs/plugin/utc'
-import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
+import { fileIsUploaded, getProcessedFiles } from '@/app/components/base/file-uploader/utils'
+import {
+ isFileFormInput,
+ isFileListFormInput,
+ isParagraphFormInput,
+ isSelectFormInput,
+ UserActionButtonType,
+} from '@/app/components/workflow/nodes/human-input/types'
import 'dayjs/locale/en'
import 'dayjs/locale/zh-cn'
import 'dayjs/locale/ja'
@@ -31,17 +41,140 @@ export const splitByOutputVar = (content: string): string[] => {
return parts.filter(part => part.length > 0)
}
-export const initializeInputs = (formInputs: FormInputItem[], defaultValues: Record<string, string> = {}) => {
- const initialInputs: Record<string, any> = {}
+export const getFormContentInputNames = (content: string) => {
+ const outputVarRegex = /\{\{#\$output\.([^#]+)#\}\}/g
+ return [...content.matchAll(outputVarRegex)].map(match => match[1]!)
+}
+
+export const getRenderedFormInputs = (formInputs: FormInputItem[], content: string) => {
+ const inputNames = new Set(getFormContentInputNames(content))
+ return formInputs.filter(input => inputNames.has(input.output_variable_name))
+}
+
+export const initializeInputs = (formInputs: FormInputItem[], defaultValues: Record<string, HumanInputResolvedValue> = {}) => {
+ const initialInputs: Record<string, HumanInputFieldValue> = {}
formInputs.forEach((item) => {
- if (item.type === 'text-input' || item.type === 'paragraph')
- initialInputs[item.output_variable_name] = item.default.type === 'variable' ? defaultValues[item.output_variable_name] || '' : item.default.value
- else
- initialInputs[item.output_variable_name] = undefined
+ if (isParagraphFormInput(item)) {
+ const resolvedValue = defaultValues[item.output_variable_name]
+ initialInputs[item.output_variable_name] = item.default.type === 'variable' && typeof resolvedValue === 'string'
+ ? resolvedValue
+ : item.default.value
+ return
+ }
+
+ if (isSelectFormInput(item)) {
+ initialInputs[item.output_variable_name] = ''
+ return
+ }
+
+ if (isFileFormInput(item)) {
+ initialInputs[item.output_variable_name] = null
+ return
+ }
+
+ if (isFileListFormInput(item)) {
+ initialInputs[item.output_variable_name] = []
+ }
})
return initialInputs
}
+const isHumanInputFileUploaded = (value: HumanInputFieldValue | undefined) => {
+ return !!value
+ && !Array.isArray(value)
+ && typeof value !== 'string'
+ && !!fileIsUploaded(value as FileEntity)
+}
+
+const hasUploadedHumanInputFiles = (value: HumanInputFieldValue | undefined) => {
+ return Array.isArray(value)
+ && value.length > 0
+ && value.every(file => !!fileIsUploaded(file))
+}
+
+export const hasInvalidSelectOrFileInput = (
+ formInputs: FormInputItem[],
+ values: Record<string, HumanInputFieldValue>,
+) => {
+ return formInputs.some((input) => {
+ if (!(input.output_variable_name in values))
+ return false
+
+ const value = values[input.output_variable_name]
+
+ if (isSelectFormInput(input))
+ return typeof value !== 'string' || value.length === 0
+
+ if (isFileFormInput(input))
+ return Array.isArray(value) ? !hasUploadedHumanInputFiles(value) : !isHumanInputFileUploaded(value)
+
+ if (isFileListFormInput(input))
+ return !hasUploadedHumanInputFiles(value)
+
+ return false
+ })
+}
+
+export const hasInvalidRequiredHumanInput = (
+ formInputs: FormInputItem[],
+ values: Record<string, HumanInputFieldValue>,
+) => {
+ return formInputs.some((input) => {
+ if (!(input.output_variable_name in values))
+ return false
+
+ const value = values[input.output_variable_name]
+
+ if (isParagraphFormInput(input))
+ return typeof value !== 'string' || value.trim().length === 0
+
+ if (isSelectFormInput(input))
+ return typeof value !== 'string' || value.length === 0
+
+ if (isFileFormInput(input))
+ return Array.isArray(value) ? !hasUploadedHumanInputFiles(value) : !isHumanInputFileUploaded(value)
+
+ if (isFileListFormInput(input))
+ return !hasUploadedHumanInputFiles(value)
+
+ return false
+ })
+}
+
+export const getProcessedHumanInputFormInputs = (
+ formInputs: FormInputItem[],
+ values: Record<string, HumanInputFieldValue> | undefined,
+) => {
+ if (!values)
+ return undefined
+
+ const processedInputs: Record<string, unknown> = { ...values }
+
+ formInputs.forEach((input) => {
+ const value = values[input.output_variable_name]
+
+ if (isFileListFormInput(input)) {
+ processedInputs[input.output_variable_name] = Array.isArray(value)
+ ? getProcessedFiles(value)
+ : []
+ return
+ }
+
+ if (isFileFormInput(input)) {
+ if (Array.isArray(value)) {
+ processedInputs[input.output_variable_name] = getProcessedFiles(value)[0]
+ return
+ }
+
+ processedInputs[input.output_variable_name] = value && typeof value !== 'string'
+ ? getProcessedFiles([value as FileEntity])[0]
+ : undefined
+ }
+ })
+
+ return processedInputs
+}
+
const localeMap: Record<string, string> = {
'en-US': 'en',
'zh-Hans': 'zh-cn',
diff --git a/web/app/components/base/chat/chat/answer/human-input-form-list.tsx b/web/app/components/base/chat/chat/answer/human-input-form-list.tsx
index 47dcd720948..6e9957039d7 100644
--- a/web/app/components/base/chat/chat/answer/human-input-form-list.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-form-list.tsx
@@ -1,3 +1,4 @@
+import type { HumanInputFormSubmitData } from './human-input-content/type'
import type { DeliveryMethod, HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'
import type { Node } from '@/app/components/workflow/types'
import type { HumanInputFormData } from '@/types/workflow'
@@ -8,7 +9,7 @@ import { UnsubmittedHumanInputContent } from './human-input-content/unsubmitted'
type HumanInputFormListProps = {
humanInputFormDataList: HumanInputFormData[]
- onHumanInputFormSubmit?: (formToken: string, formData: { inputs: Record<string, string>, action: string }) => Promise<void>
+ onHumanInputFormSubmit?: (formToken: string, formData: HumanInputFormSubmitData) => Promise<void>
getHumanInputNodeData?: (nodeID: string) => Node<HumanInputNodeType> | undefined
}
diff --git a/web/app/components/base/chat/chat/answer/index.tsx b/web/app/components/base/chat/chat/answer/index.tsx
index c5ce6075792..36c99dd56a4 100644
--- a/web/app/components/base/chat/chat/answer/index.tsx
+++ b/web/app/components/base/chat/chat/answer/index.tsx
@@ -6,6 +6,7 @@ import type {
ChatConfig,
ChatItem,
} from '../../types'
+import type { HumanInputFormSubmitData } from './human-input-content/type'
import type { AppData } from '@/models/share'
import { cn } from '@langgenius/dify-ui/cn'
import { memo, useCallback, useEffect, useRef, useState } from 'react'
@@ -40,7 +41,7 @@ type AnswerProps = {
noChatInput?: boolean
switchSibling?: (siblingMessageId: string) => void
hideAvatar?: boolean
- onHumanInputFormSubmit?: (formToken: string, formData: any) => Promise<void>
+ onHumanInputFormSubmit?: (formToken: string, formData: HumanInputFormSubmitData) => Promise<void>
}
const Answer: FC<AnswerProps> = ({
item,
diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsx
index 8c5eda0aa16..0fac08ede14 100644
--- a/web/app/components/base/chat/chat/answer/operation.tsx
+++ b/web/app/components/base/chat/chat/answer/operation.tsx
@@ -41,6 +41,8 @@ type FeedbackTooltipProps = {
}
const feedbackTooltipClassName = 'max-w-[260px]'
+const answerActiveFlexClassName = 'group-hover:flex group-has-[[data-popup-open]]:flex'
+const answerActiveBlockClassName = 'group-hover:block group-has-[[data-popup-open]]:block'
const FeedbackTooltip = ({ content, children }: FeedbackTooltipProps) => {
return (
@@ -199,7 +201,7 @@ function Operation({
{shouldShowUserFeedbackBar && !humanInputFormDataList?.length && (
<div className={cn(
'ml-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
- hasUserFeedback ? 'flex' : 'hidden group-hover:flex',
+ hasUserFeedback ? 'flex' : `hidden ${answerActiveFlexClassName}`,
)}
>
{hasUserFeedback
@@ -241,7 +243,7 @@ function Operation({
{shouldShowAdminFeedbackBar && !humanInputFormDataList?.length && (
<div className={cn(
'ml-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
- (hasAdminFeedback || hasUserFeedback) ? 'flex' : 'hidden group-hover:flex',
+ (hasAdminFeedback || hasUserFeedback) ? 'flex' : `hidden ${answerActiveFlexClassName}`,
)}
>
{displayUserFeedback?.rating && (
@@ -308,12 +310,12 @@ function Operation({
</div>
)}
{showPromptLog && !isOpeningStatement && (
- <div className="hidden group-hover:block">
+ <div className={cn('hidden', answerActiveBlockClassName)}>
<Log logItem={item} />
</div>
)}
{!isOpeningStatement && (
- <div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs group-hover:flex" data-testid="operation-actions">
+ <div className={cn('ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs', answerActiveFlexClassName)} data-testid="operation-actions">
{(config?.text_to_speech?.enabled && !humanInputFormDataList?.length) && (
<NewAudioButton
id={id}
diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.ts
index 677862a7950..6300dca69a9 100644
--- a/web/app/components/base/chat/chat/hooks.ts
+++ b/web/app/components/base/chat/chat/hooks.ts
@@ -26,6 +26,7 @@ import {
import { useTranslation } from 'react-i18next'
import { v4 as uuidV4 } from 'uuid'
import { AudioPlayerManager } from '@/app/components/base/audio-btn/audio.player.manager'
+import { enrichSubmittedHumanInputFormData } from '@/app/components/base/chat/chat/answer/human-input-content/submitted-utils'
import {
getProcessedFiles,
getProcessedFilesFromResponse,
@@ -538,16 +539,20 @@ export const useChat = (
},
onHumanInputFormFilled: ({ data: humanInputFilledFormData }) => {
updateChatTreeNode(messageId, (responseItem) => {
+ let requiredFormData: NonNullable<ChatItem['humanInputFormDataList']>[number] | undefined
if (responseItem.humanInputFormDataList?.length) {
const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputFilledFormData.node_id)
- if (currentFormIndex > -1)
+ if (currentFormIndex > -1) {
+ requiredFormData = responseItem.humanInputFormDataList[currentFormIndex]
responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
}
+ const enrichedHumanInputFilledFormData = enrichSubmittedHumanInputFormData(humanInputFilledFormData, requiredFormData)
if (!responseItem.humanInputFilledFormDataList) {
- responseItem.humanInputFilledFormDataList = [humanInputFilledFormData]
+ responseItem.humanInputFilledFormDataList = [enrichedHumanInputFilledFormData]
}
else {
- responseItem.humanInputFilledFormDataList.push(humanInputFilledFormData)
+ responseItem.humanInputFilledFormDataList.push(enrichedHumanInputFilledFormData)
}
})
},
@@ -1108,15 +1113,20 @@ export const useChat = (
}
},
onHumanInputFormFilled: ({ data: humanInputFilledFormData }) => {
+ let requiredFormData: NonNullable<ChatItem['humanInputFormDataList']>[number] | undefined
if (responseItem.humanInputFormDataList?.length) {
const currentFormIndex = responseItem.humanInputFormDataList!.findIndex(item => item.node_id === humanInputFilledFormData.node_id)
- responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ if (currentFormIndex > -1) {
+ requiredFormData = responseItem.humanInputFormDataList[currentFormIndex]
+ responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
}
+ const enrichedHumanInputFilledFormData = enrichSubmittedHumanInputFormData(humanInputFilledFormData, requiredFormData)
if (!responseItem.humanInputFilledFormDataList) {
- responseItem.humanInputFilledFormDataList = [humanInputFilledFormData]
+ responseItem.humanInputFilledFormDataList = [enrichedHumanInputFilledFormData]
}
else {
- responseItem.humanInputFilledFormDataList.push(humanInputFilledFormData)
+ responseItem.humanInputFilledFormDataList.push(enrichedHumanInputFilledFormData)
}
updateCurrentQAOnTree({
placeholderQuestionId,
diff --git a/web/app/components/base/chat/chat/index.tsx b/web/app/components/base/chat/chat/index.tsx
index 6a14b76bd4f..f4a32e56072 100644
--- a/web/app/components/base/chat/chat/index.tsx
+++ b/web/app/components/base/chat/chat/index.tsx
@@ -10,6 +10,7 @@ import type {
OnRegenerate,
OnSend,
} from '../types'
+import type { HumanInputFormSubmitData } from './answer/human-input-content/type'
import type { InputForm } from './type'
import type { Emoji } from '@/app/components/tools/types'
import type { AppData } from '@/models/share'
@@ -69,7 +70,7 @@ export type ChatProps = {
sidebarCollapseState?: boolean
hideAvatar?: boolean
sendOnEnter?: boolean
- onHumanInputFormSubmit?: (formToken: string, formData: any) => Promise<void>
+ onHumanInputFormSubmit?: (formToken: string, formData: HumanInputFormSubmitData) => Promise<void>
getHumanInputNodeData?: (nodeID: string) => any
}
diff --git a/web/app/components/base/chat/chat/type.ts b/web/app/components/base/chat/chat/type.ts
index 87aaf1b4b62..5f24c908383 100644
--- a/web/app/components/base/chat/chat/type.ts
+++ b/web/app/components/base/chat/chat/type.ts
@@ -66,18 +66,22 @@ export type CitationItem = {
word_count: number
}
-export type ExtraContent
- = {
- type: 'human_input'
- submitted: false
- form_definition: HumanInputFormData
- workflow_run_id: string
- }
- | {
- type: 'human_input'
- submitted: true
- form_submission_data: HumanInputFilledFormData
- }
+type PendingHumanInputExtraContent = {
+ type: 'human_input'
+ submitted: false
+ form_definition: HumanInputFormData
+ workflow_run_id: string
+}
+
+type SubmittedHumanInputExtraContent = {
+ type: 'human_input'
+ submitted: true
+ form_definition?: HumanInputFormData
+ form_submission_data: HumanInputFilledFormData
+ workflow_run_id?: string
+}
+
+export type ExtraContent = PendingHumanInputExtraContent | SubmittedHumanInputExtraContent
export type IChatItem = {
id: string
diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx
index 865023722e4..1f530f81ffd 100644
--- a/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx
@@ -1,4 +1,5 @@
import type { RefObject } from 'react'
+import type { HumanInputFieldValue } from '../../chat/answer/human-input-content/field-renderer'
import type { ChatConfig, ChatItem, ChatItemInTree } from '../../types'
import type { EmbeddedChatbotContextValue } from '../context'
import type { ConversationItem } from '@/models/share'
@@ -59,7 +60,7 @@ vi.mock('../../chat', () => ({
onSend: (message: string) => void
onRegenerate: (chatItem: ChatItem, editedQuestion?: { message: string, files?: never[] }) => void
switchSibling: (siblingMessageId: string) => void
- onHumanInputFormSubmit: (formToken: string, formData: Record<string, string>) => Promise<void>
+ onHumanInputFormSubmit: (formToken: string, formData: { inputs: Record<string, HumanInputFieldValue>, action: string }) => Promise<void>
onStopResponding: () => void
}) => (
<div>
@@ -78,7 +79,7 @@ vi.mock('../../chat', () => ({
<button onClick={() => switchSibling('sibling-2')}>switch sibling</button>
<button disabled={inputDisabled}>send message</button>
<button onClick={onStopResponding}>stop responding</button>
- <button onClick={() => onHumanInputFormSubmit('form-token', { answer: 'ok' })}>submit human input</button>
+ <button onClick={() => onHumanInputFormSubmit('form-token', { inputs: { answer: 'ok' }, action: 'approve' })}>submit human input</button>
</div>
),
}))
@@ -351,7 +352,7 @@ describe('EmbeddedChatbot chat-wrapper', () => {
fireEvent.click(screen.getByRole('button', { name: 'submit human input' }))
await waitFor(() => {
- expect(submitHumanInputFormService).toHaveBeenCalledWith('form-token', { answer: 'ok' })
+ expect(submitHumanInputFormService).toHaveBeenCalledWith('form-token', { inputs: { answer: 'ok' }, action: 'approve' })
})
expect(submitHumanInputForm).not.toHaveBeenCalled()
})
@@ -391,7 +392,7 @@ describe('EmbeddedChatbot chat-wrapper', () => {
fireEvent.click(screen.getByRole('button', { name: 'submit human input' }))
await waitFor(() => {
- expect(submitHumanInputForm).toHaveBeenCalledWith('form-token', { answer: 'ok' })
+ expect(submitHumanInputForm).toHaveBeenCalledWith('form-token', { inputs: { answer: 'ok' }, action: 'approve' })
})
expect(handleSend).toHaveBeenCalledTimes(2)
const sendOptions = handleSend.mock.calls[0]?.[2] as { onGetSuggestedQuestions: (responseItemId: string) => void }
diff --git a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
index 2f50fe76c6c..63cecc99df7 100644
--- a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
@@ -1,4 +1,5 @@
import type { FileEntity } from '../../file-uploader/types'
+import type { HumanInputFormSubmitData } from '../chat/answer/human-input-content/type'
import type {
ChatConfig,
ChatItem,
@@ -232,7 +233,7 @@ const ChatWrapper = () => {
}
}, [inputsForms.length, isMobile, currentConversationId, collapsed, allInputsHidden])
- const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: any) => {
+ const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: HumanInputFormSubmitData) => {
if (isInstalledApp)
await submitHumanInputFormService(formToken, formData)
else
diff --git a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts b/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
index 72f28603db9..278c3f328b8 100644
--- a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
+++ b/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
@@ -5,9 +5,14 @@ import { act, renderHook } from '@testing-library/react'
import { useFile, useFileSizeLimit } from '../hooks'
const mockNotify = vi.fn()
+const mockNavigationState = vi.hoisted(() => ({
+ params: {} as { token?: string },
+ pathname: '/chat',
+}))
vi.mock('@/next/navigation', () => ({
- useParams: () => ({ token: undefined }),
+ useParams: () => mockNavigationState.params,
+ usePathname: () => mockNavigationState.pathname,
}))
vi.mock('@langgenius/dify-ui/toast', () => ({
@@ -42,6 +47,13 @@ vi.mock('@/service/common', () => ({
uploadRemoteFileInfo: (...args: unknown[]) => mockUploadRemoteFileInfo(...args),
}))
+const mockUploadHumanInputFormLocalFile = vi.fn()
+const mockUploadHumanInputFormRemoteFileInfo = vi.fn()
+vi.mock('@/service/share', () => ({
+ uploadHumanInputFormLocalFile: (...args: unknown[]) => mockUploadHumanInputFormLocalFile(...args),
+ uploadHumanInputFormRemoteFileInfo: (...args: unknown[]) => mockUploadHumanInputFormRemoteFileInfo(...args),
+}))
+
vi.mock('uuid', () => ({
v4: () => 'mock-uuid',
}))
@@ -109,6 +121,8 @@ describe('useFile', () => {
beforeEach(() => {
vi.clearAllMocks()
mockStoreFiles = []
+ mockNavigationState.params = {}
+ mockNavigationState.pathname = '/chat'
mockIsAllowedFileExtension.mockReturnValue(true)
mockGetSupportFileType.mockReturnValue('document')
})
@@ -201,6 +215,31 @@ describe('useFile', () => {
expect(mockFileUpload).toHaveBeenCalled()
})
+ it('should use human input form local upload when re-uploading on form page', () => {
+ mockNavigationState.params = { token: 'form-token' }
+ mockNavigationState.pathname = '/form/form-token'
+ const originalFile = new File(['content'], 'test.txt', { type: 'text/plain' })
+ mockStoreFiles = [{
+ id: 'file-1',
+ name: 'test.txt',
+ type: 'text/plain',
+ size: 100,
+ progress: -1,
+ transferMethod: 'local_file',
+ supportFileType: 'document',
+ originalFile,
+ }] as FileEntity[]
+
+ const { result } = renderHook(() => useFile(defaultFileConfig))
+ result.current.handleReUploadFile('file-1')
+
+ expect(mockUploadHumanInputFormLocalFile).toHaveBeenCalledWith(expect.objectContaining({
+ formToken: 'form-token',
+ file: originalFile,
+ }))
+ expect(mockFileUpload).not.toHaveBeenCalled()
+ })
+
it('should not re-upload when file id is not found', () => {
mockStoreFiles = []
const { result } = renderHook(() => useFile(defaultFileConfig))
@@ -315,6 +354,24 @@ describe('useFile', () => {
expect(mockUploadRemoteFileInfo).toHaveBeenCalledWith('https://example.com/file.txt', false)
})
+ it('should use human input form remote upload on form page', () => {
+ mockNavigationState.params = { token: 'form-token' }
+ mockNavigationState.pathname = '/form/form-token'
+ mockUploadHumanInputFormRemoteFileInfo.mockResolvedValue({
+ id: 'remote-1',
+ mime_type: 'text/plain',
+ size: 100,
+ name: 'remote.txt',
+ url: 'https://example.com/remote.txt',
+ })
+
+ const { result } = renderHook(() => useFile(defaultFileConfig))
+ result.current.handleLoadFileFromLink('https://example.com/file.txt')
+
+ expect(mockUploadHumanInputFormRemoteFileInfo).toHaveBeenCalledWith('form-token', 'https://example.com/file.txt')
+ expect(mockUploadRemoteFileInfo).not.toHaveBeenCalled()
+ })
+
it('should remove file when extension is not allowed', async () => {
mockIsAllowedFileExtension.mockReturnValue(false)
mockUploadRemoteFileInfo.mockResolvedValue({
@@ -702,6 +759,21 @@ describe('useFile', () => {
expect(mockSetFiles).toHaveBeenCalled()
})
+ it('should use human input form local upload on form page', () => {
+ mockNavigationState.params = { token: 'form-token' }
+ mockNavigationState.pathname = '/form/form-token'
+ const file = new File(['content'], 'test.txt', { type: 'text/plain' })
+
+ const { result } = renderHook(() => useFile(defaultFileConfig))
+ result.current.handleLocalFileUpload(file)
+
+ expect(mockUploadHumanInputFormLocalFile).toHaveBeenCalledWith(expect.objectContaining({
+ formToken: 'form-token',
+ file,
+ }))
+ expect(mockFileUpload).not.toHaveBeenCalled()
+ })
+
it('should handle fileUpload error callback', () => {
const file = new File(['content'], 'test.txt', { type: 'text/plain' })
diff --git a/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/index.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/index.spec.tsx
index 895c960ae97..d909deacc60 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/index.spec.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/index.spec.tsx
@@ -164,6 +164,29 @@ describe('FileUploaderInAttachmentWrapper', () => {
expect(linkButton.closest('button')).toBeInTheDocument()
})
+ it('should keep upload button layout stable when remote_url popup opens', () => {
+ render(
+ <FileUploaderInAttachmentWrapper
+ onChange={vi.fn()}
+ fileConfig={createFileConfig()}
+ />,
+ )
+
+ const localButton = screen.getByText(/fileUploader\.uploadFromComputer/).closest('button')
+ const linkButton = screen.getByText(/fileUploader\.pasteFileLink/).closest('button')
+ const uploadGroup = localButton?.parentElement?.parentElement
+
+ expect(uploadGroup?.children).toHaveLength(2)
+
+ fireEvent.click(linkButton!)
+
+ expect(uploadGroup?.children).toHaveLength(2)
+ expect(linkButton).toHaveAttribute('data-popup-open')
+ expect(localButton?.parentElement).toHaveClass('min-w-0', 'flex-1')
+ expect(linkButton?.parentElement).toHaveClass('min-w-0', 'flex-1')
+ expect(linkButton).toHaveClass('w-full', 'min-w-0')
+ })
+
it('should disable upload buttons when file limit is reached', () => {
const files = [
createFile({ id: 'f1' }),
diff --git a/web/app/components/base/file-uploader/file-uploader-in-attachment/index.tsx b/web/app/components/base/file-uploader/file-uploader-in-attachment/index.tsx
index b30e7f5e3de..3360e9c6ec8 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-attachment/index.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-attachment/index.tsx
@@ -55,13 +55,12 @@ const FileUploaderInAttachment = ({
const renderButton = useCallback((option: Option, open?: boolean) => {
return (
<Button
- key={option.value}
variant="tertiary"
- className={cn('relative grow', open && 'bg-components-button-tertiary-bg-hover')}
+ className={cn('relative w-full min-w-0', open && 'bg-components-button-tertiary-bg-hover')}
disabled={!!(fileConfig.number_limits && files.length >= fileConfig.number_limits)}
>
- {option.icon}
- <span className="ml-1">{option.label}</span>
+ <span className="shrink-0">{option.icon}</span>
+ <span className="ml-1 min-w-0 truncate">{option.label}</span>
{
option.value === TransferMethod.local_file && (
<FileInput fileConfig={fileConfig} />
@@ -74,17 +73,23 @@ const FileUploaderInAttachment = ({
return (open: boolean) => renderButton(option, open)
}, [renderButton])
const renderOption = useCallback((option: Option) => {
- if (option.value === TransferMethod.local_file && fileConfig?.allowed_file_upload_methods?.includes(TransferMethod.local_file))
- return renderButton(option)
+ if (option.value === TransferMethod.local_file && fileConfig?.allowed_file_upload_methods?.includes(TransferMethod.local_file)) {
+ return (
+ <div key={option.value} className="min-w-0 flex-1">
+ {renderButton(option)}
+ </div>
+ )
+ }
if (option.value === TransferMethod.remote_url && fileConfig?.allowed_file_upload_methods?.includes(TransferMethod.remote_url)) {
return (
- <FileFromLinkOrLocal
- key={option.value}
- showFromLocal={false}
- trigger={renderTrigger(option)}
- fileConfig={fileConfig}
- />
+ <div key={option.value} className="min-w-0 flex-1">
+ <FileFromLinkOrLocal
+ showFromLocal={false}
+ trigger={renderTrigger(option)}
+ fileConfig={fileConfig}
+ />
+ </div>
)
}
}, [renderButton, renderTrigger, fileConfig])
@@ -92,7 +97,7 @@ const FileUploaderInAttachment = ({
return (
<div>
{!isDisabled && (
- <div className="flex items-center space-x-1">
+ <div className="flex items-center gap-1">
{options.map(renderOption)}
</div>
)}
diff --git a/web/app/components/base/file-uploader/hooks.ts b/web/app/components/base/file-uploader/hooks.ts
index 9aa70e4487f..be8890d41bc 100644
--- a/web/app/components/base/file-uploader/hooks.ts
+++ b/web/app/components/base/file-uploader/hooks.ts
@@ -19,8 +19,12 @@ import {
VIDEO_SIZE_LIMIT,
} from '@/app/components/base/file-uploader/constants'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
-import { useParams } from '@/next/navigation'
+import { useParams, usePathname } from '@/next/navigation'
import { uploadRemoteFileInfo } from '@/service/common'
+import {
+ uploadHumanInputFormLocalFile,
+ uploadHumanInputFormRemoteFileInfo,
+} from '@/service/share'
import { TransferMethod } from '@/types/app'
import { formatFileSize } from '@/utils/format'
import { useFileStore } from './store'
@@ -51,7 +55,10 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
const { t } = useTranslation()
const fileStore = useFileStore()
const params = useParams()
+ const pathname = usePathname()
const { imgSizeLimit, docSizeLimit, audioSizeLimit, videoSizeLimit } = useFileSizeLimit(fileConfig.fileUploadConfig)
+ const formToken = typeof params.token === 'string' ? params.token : undefined
+ const isHumanInputFormPage = !!formToken && /(?:^|\/)form\/[^/]+$/.test(pathname)
const checkSizeLimit = useCallback((fileType: string, fileSize: number) => {
switch (fileType) {
@@ -156,7 +163,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
draft[index]!.progress = 0
})
setFiles(newFiles)
- fileUpload({
+ const uploadParams: Parameters<typeof fileUpload>[0] = {
file: uploadingFile!.originalFile!,
onProgressCallback: (progress) => {
handleUpdateFile({ ...uploadingFile, progress })
@@ -164,14 +171,24 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
onSuccessCallback: (res) => {
handleUpdateFile({ ...uploadingFile, uploadedId: res.id, progress: 100 })
},
- onErrorCallback: (error?: any) => {
+ onErrorCallback: (error?: unknown) => {
const errorMessage = getFileUploadErrorMessage(error, t('fileUploader.uploadFromComputerUploadError', { ns: 'common' }), t)
toast.error(errorMessage)
handleUpdateFile({ ...uploadingFile, progress: -1 })
},
- }, !!params.token)
+ }
+
+ if (isHumanInputFormPage) {
+ uploadHumanInputFormLocalFile({
+ formToken: formToken!,
+ ...uploadParams,
+ })
+ }
+ else {
+ fileUpload(uploadParams, !!params.token)
+ }
}
- }, [fileStore, t, handleUpdateFile, params])
+ }, [fileStore, t, handleUpdateFile, isHumanInputFormPage, formToken, params.token])
const startProgressTimer = useCallback((fileId: string) => {
const timer = setInterval(() => {
@@ -201,7 +218,11 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
handleAddFile(uploadingFile)
startProgressTimer(uploadingFile.id)
- uploadRemoteFileInfo(url, !!params.token).then((res) => {
+ const remoteUpload = isHumanInputFormPage
+ ? uploadHumanInputFormRemoteFileInfo(formToken!, url)
+ : uploadRemoteFileInfo(url, !!params.token)
+
+ remoteUpload.then((res) => {
const newFile = {
...uploadingFile,
type: res.mime_type,
@@ -223,7 +244,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
toast.error(t('fileUploader.pasteFileLinkInvalid', { ns: 'common' }))
handleRemoveFile(uploadingFile.id)
})
- }, [checkSizeLimit, handleAddFile, handleUpdateFile, t, handleRemoveFile, fileConfig?.allowed_file_types, fileConfig.allowed_file_extensions, startProgressTimer, params.token])
+ }, [checkSizeLimit, handleAddFile, handleUpdateFile, t, handleRemoveFile, fileConfig?.allowed_file_types, fileConfig.allowed_file_extensions, startProgressTimer, isHumanInputFormPage, formToken, params.token])
const handleLoadFileFromLinkSuccess = useCallback(noop, [])
@@ -269,7 +290,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
base64Url: isImage ? reader.result as string : '',
}
handleAddFile(uploadingFile)
- fileUpload({
+ const uploadParams: Parameters<typeof fileUpload>[0] = {
file: uploadingFile.originalFile,
onProgressCallback: (progress) => {
handleUpdateFile({ ...uploadingFile, progress })
@@ -277,12 +298,22 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
onSuccessCallback: (res) => {
handleUpdateFile({ ...uploadingFile, uploadedId: res.id, progress: 100 })
},
- onErrorCallback: (error?: any) => {
- const errorMessage = getFileUploadErrorMessage(error, t('fileUploader.uploadFromComputerUploadError', { ns: 'common' }), t as any)
+ onErrorCallback: (error?: unknown) => {
+ const errorMessage = getFileUploadErrorMessage(error, t('fileUploader.uploadFromComputerUploadError', { ns: 'common' }), t)
toast.error(errorMessage)
handleUpdateFile({ ...uploadingFile, progress: -1 })
},
- }, !!params.token)
+ }
+
+ if (isHumanInputFormPage) {
+ uploadHumanInputFormLocalFile({
+ formToken: formToken!,
+ ...uploadParams,
+ })
+ }
+ else {
+ fileUpload(uploadParams, !!params.token)
+ }
},
false,
)
@@ -294,7 +325,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
false,
)
reader.readAsDataURL(file)
- }, [noNeedToCheckEnable, checkSizeLimit, t, handleAddFile, handleUpdateFile, params.token, fileConfig?.allowed_file_types, fileConfig?.allowed_file_extensions, fileConfig?.enabled])
+ }, [noNeedToCheckEnable, checkSizeLimit, t, handleAddFile, handleUpdateFile, isHumanInputFormPage, formToken, params.token, fileConfig?.allowed_file_types, fileConfig?.allowed_file_extensions, fileConfig?.enabled])
const handleClipboardPasteFile = useCallback((e: ClipboardEvent<HTMLTextAreaElement>) => {
const file = e.clipboardData?.files[0]
diff --git a/web/app/components/base/form/components/field/__tests__/file-uploader.spec.tsx b/web/app/components/base/form/components/field/__tests__/file-uploader.spec.tsx
index 67716a00c88..3f20afa738f 100644
--- a/web/app/components/base/form/components/field/__tests__/file-uploader.spec.tsx
+++ b/web/app/components/base/form/components/field/__tests__/file-uploader.spec.tsx
@@ -29,6 +29,7 @@ vi.mock('../../..', () => ({
vi.mock('@/next/navigation', () => ({
useParams: () => ({ token: 'test-token' }),
+ usePathname: () => '/',
}))
describe('FileUploaderField', () => {
diff --git a/web/app/components/base/form/form-scenarios/base/__tests__/field.spec.tsx b/web/app/components/base/form/form-scenarios/base/__tests__/field.spec.tsx
index 81190dc277e..ee8065fc50d 100644
--- a/web/app/components/base/form/form-scenarios/base/__tests__/field.spec.tsx
+++ b/web/app/components/base/form/form-scenarios/base/__tests__/field.spec.tsx
@@ -8,6 +8,7 @@ import { BaseFieldType } from '../types'
vi.mock('@/next/navigation', () => ({
useParams: () => ({}),
+ usePathname: () => '/',
}))
const createConfig = (overrides: Partial<BaseConfiguration> = {}): BaseConfiguration => ({
diff --git a/web/app/components/base/prompt-editor/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/__tests__/index.spec.tsx
index 31e25ab19e1..9c0b3cec39f 100644
--- a/web/app/components/base/prompt-editor/__tests__/index.spec.tsx
+++ b/web/app/components/base/prompt-editor/__tests__/index.spec.tsx
@@ -36,6 +36,7 @@ const mocks = vi.hoisted(() => {
})),
parseEditorState: vi.fn(() => ({ state: 'parsed' })),
setEditorState: vi.fn(),
+ setEditable: vi.fn(),
focus: vi.fn(),
update: vi.fn((fn: () => void) => fn()),
},
@@ -71,6 +72,7 @@ vi.mock('lexical', async (importOriginal) => {
})),
getAllTextNodes: () => [],
}),
+ $nodesOfType: () => [],
TextNode: class TextNode {
__text: string
constructor(text = '') {
@@ -92,9 +94,8 @@ vi.mock('@lexical/react/LexicalComposer', () => ({
try {
initialConfig.onError(new Error('test error'))
}
- catch (e) {
- // ignore error
- console.error(e)
+ catch {
+ // Ignore the intentional throw from the mocked error boundary path.
}
}
if (initialConfig?.nodes) {
@@ -328,6 +329,20 @@ describe('PromptEditor', () => {
expect(screen.getByTestId('lexical-composer')).toBeInTheDocument()
})
+ it('should sync editable changes to the lexical editor instance', async () => {
+ const { rerender } = render(<PromptEditor editable={true} />)
+
+ await waitFor(() => {
+ expect(mocks.editor.setEditable).toHaveBeenCalledWith(true)
+ })
+
+ rerender(<PromptEditor editable={false} />)
+
+ await waitFor(() => {
+ expect(mocks.editor.setEditable).toHaveBeenLastCalledWith(false)
+ })
+ })
+
it('should render with isSupportFileVar=true', () => {
render(<PromptEditor isSupportFileVar={true} />)
expect(screen.getByTestId('lexical-composer')).toBeInTheDocument()
diff --git a/web/app/components/base/prompt-editor/index.tsx b/web/app/components/base/prompt-editor/index.tsx
index 29d0d717157..e381d61a3d8 100644
--- a/web/app/components/base/prompt-editor/index.tsx
+++ b/web/app/components/base/prompt-editor/index.tsx
@@ -3,10 +3,9 @@
import type { InitialConfigType } from '@lexical/react/LexicalComposer'
import type {
EditorState,
- LexicalCommand,
} from 'lexical'
import type { FC } from 'react'
-import type { Hotkey } from './plugins/shortcuts-popup-plugin'
+import type { Hotkey, ShortcutPopupInsertHandler } from './plugins/shortcuts-popup-plugin'
import type {
ContextBlockType,
CurrentBlockType,
@@ -97,6 +96,16 @@ const ValueSyncPlugin: FC<{ value?: string }> = ({ value }) => {
return null
}
+const EditableSyncPlugin: FC<{ editable: boolean }> = ({ editable }) => {
+ const [editor] = useLexicalComposerContext()
+
+ useEffect(() => {
+ editor.setEditable(editable)
+ }, [editor, editable])
+
+ return null
+}
+
export type PromptEditorProps = {
instanceId?: string
compact?: boolean
@@ -122,7 +131,7 @@ export type PromptEditorProps = {
errorMessageBlock?: ErrorMessageBlockType
lastRunBlock?: LastRunBlockType
isSupportFileVar?: boolean
- shortcutPopups?: Array<{ hotkey: Hotkey, Popup: React.ComponentType<{ onClose: () => void, onInsert: (command: LexicalCommand<unknown>, params: any[]) => void }> }>
+ shortcutPopups?: Array<{ hotkey: Hotkey, Popup: React.ComponentType<{ onClose: () => void, onInsert: ShortcutPopupInsertHandler }> }>
}
const PromptEditor: FC<PromptEditorProps> = ({
@@ -194,13 +203,13 @@ const PromptEditor: FC<PromptEditorProps> = ({
eventEmitter?.emit({
type: UPDATE_DATASETS_EVENT_EMITTER,
payload: contextBlock?.datasets,
- } as any)
+ })
}, [eventEmitter, contextBlock?.datasets])
useEffect(() => {
eventEmitter?.emit({
type: UPDATE_HISTORY_EVENT_EMITTER,
payload: historyBlock?.history,
- } as any)
+ })
}, [eventEmitter, historyBlock?.history])
const [floatingAnchorElem, setFloatingAnchorElem] = useState<HTMLDivElement | null>(null)
@@ -243,6 +252,7 @@ const PromptEditor: FC<PromptEditorProps> = ({
onEditorChange={handleEditorChange}
/>
<ValueSyncPlugin value={value} />
+ <EditableSyncPlugin editable={editable} />
</div>
</LexicalComposer>
)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component-ui.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component-ui.spec.tsx
index ca279a1d4d8..2fa310d0581 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component-ui.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component-ui.spec.tsx
@@ -1,15 +1,17 @@
import type { ComponentProps } from 'react'
import type { WorkflowNodesMap } from '../../workflow-variable-block/node'
-import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { FormInputItem, ParagraphFormInput } from '@/app/components/workflow/nodes/human-input/types'
import type { ValueSelector } from '@/app/components/workflow/types'
import { LexicalComposer } from '@lexical/react/LexicalComposer'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { useEffect, useState } from 'react'
+import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
import HITLInputComponentUI from '../component-ui'
import { HITLInputNode } from '../node'
-const createFormInput = (overrides?: Partial<FormInputItem>): FormInputItem => ({
+const createParagraphFormInput = (overrides?: Partial<ParagraphFormInput>): ParagraphFormInput => ({
type: InputVarType.paragraph,
output_variable_name: 'customer_name',
default: {
@@ -93,7 +95,7 @@ describe('HITLInputComponentUI', () => {
const selector = ['node-2', 'answer'] as ValueSelector
const { getByText } = renderComponent({
- formInput: createFormInput({
+ formInput: createParagraphFormInput({
default: {
type: 'variable',
selector,
@@ -112,6 +114,124 @@ describe('HITLInputComponentUI', () => {
expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.operation.remove' })).not.toBeInTheDocument()
})
+
+ it('should close the edit modal when readonly becomes true', async () => {
+ let setReadonlyValue: ((readonly: boolean) => void) | undefined
+ const Harness = () => {
+ const [readonly, setReadonly] = useState(false)
+ const [namespace] = useState(() => `hitl-input-test-${crypto.randomUUID()}`)
+
+ useEffect(() => {
+ setReadonlyValue = setReadonly
+ return () => {
+ setReadonlyValue = undefined
+ }
+ }, [])
+
+ return (
+ <LexicalComposer
+ initialConfig={{
+ namespace,
+ onError: (error: Error) => {
+ throw error
+ },
+ nodes: [HITLInputNode],
+ }}
+ >
+ <HITLInputComponentUI
+ nodeId="node-1"
+ varName="customer_name"
+ workflowNodesMap={createWorkflowNodesMap()}
+ onChange={vi.fn()}
+ onRename={vi.fn()}
+ onRemove={vi.fn()}
+ readonly={readonly}
+ />
+ </LexicalComposer>
+ )
+ }
+
+ render(<Harness />)
+
+ fireEvent.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
+
+ expect(await screen.findByRole('textbox')).toBeInTheDocument()
+
+ act(() => {
+ setReadonlyValue?.(true)
+ })
+
+ await waitFor(() => {
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
+ })
+ })
+
+ it('should render select option summary for constant options', () => {
+ const { getByText } = renderComponent({
+ formInput: {
+ type: InputVarType.select,
+ output_variable_name: 'customer_name',
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: ['alpha', 'beta'],
+ },
+ } satisfies FormInputItem,
+ })
+
+ expect(getByText('alpha, beta')).toBeInTheDocument()
+ })
+
+ it('should render input type label after the summary content', () => {
+ const { getByText } = renderComponent({
+ formInput: {
+ type: InputVarType.select,
+ output_variable_name: 'customer_name',
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: ['alpha', 'beta'],
+ },
+ } satisfies FormInputItem,
+ })
+
+ const summary = getByText('alpha, beta')
+ const typeLabel = getByText('appDebug.variableConfig.select')
+
+ expect(summary.compareDocumentPosition(typeLabel) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ })
+
+ it('should render file-list placeholder instead of selected file details', () => {
+ const { getAllByText, queryByText } = renderComponent({
+ formInput: {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'customer_name',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ number_limits: 4,
+ } satisfies FormInputItem,
+ })
+
+ expect(getAllByText('appDebug.variableConfig.multi-files')).toHaveLength(2)
+ expect(queryByText(/document/)).not.toBeInTheDocument()
+ expect(queryByText(/4/)).not.toBeInTheDocument()
+ })
+
+ it('should render single-file placeholder instead of selected file details', () => {
+ const { getAllByText, queryByText } = renderComponent({
+ formInput: {
+ type: InputVarType.singleFile,
+ output_variable_name: 'customer_name',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ } satisfies FormInputItem,
+ })
+
+ expect(getAllByText('appDebug.variableConfig.single-file')).toHaveLength(2)
+ expect(queryByText(/document/)).not.toBeInTheDocument()
+ })
})
describe('Remove action', () => {
@@ -145,10 +265,33 @@ describe('HITLInputComponentUI', () => {
expect(queryByRole('textbox')).not.toBeInTheDocument()
})
+
+ it('should prevent renaming to an existing variable name', async () => {
+ const {
+ findByRole,
+ onChange,
+ onRename,
+ } = renderComponent({
+ unavailableVariableNames: ['existing_name'],
+ })
+
+ fireEvent.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
+
+ const textbox = await findByRole('textbox')
+ fireEvent.change(textbox, { target: { value: 'existing_name' } })
+
+ expect(screen.getByText('workflow.nodes.humanInput.insertInputField.variableNameDuplicated')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.operation.save' })).toBeDisabled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(onChange).not.toHaveBeenCalled()
+ expect(onRename).not.toHaveBeenCalled()
+ })
})
describe('Default formInput', () => {
- it('should pass default payload to InputField when formInput is undefined', async () => {
+ it('should open an empty default editor when formInput is undefined', async () => {
const { findByRole } = renderComponent({
formInput: undefined,
})
@@ -156,16 +299,16 @@ describe('HITLInputComponentUI', () => {
fireEvent.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
const textbox = await findByRole('textbox')
+ const saveButton = await screen.findByRole('button', { name: 'common.operation.save' })
- fireEvent.click(await screen.findByRole('button', { name: 'common.operation.save' }))
-
- expect(textbox).toHaveValue('customer_name')
+ expect(textbox).toHaveValue('')
+ expect(saveButton).toBeDisabled()
})
it('should render variable selector when workflowNodesMap fallback is used', () => {
const { getByText } = renderComponent({
workflowNodesMap: undefined as unknown as WorkflowNodesMap,
- formInput: createFormInput({
+ formInput: createParagraphFormInput({
default: {
type: 'variable',
selector: ['node-2', 'answer'] as ValueSelector,
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component.spec.tsx
index ee82595d1c3..dc97ee05a50 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/component.spec.tsx
@@ -1,5 +1,5 @@
import type { RefObject } from 'react'
-import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { FormInputItem, ParagraphFormInput } from '@/app/components/workflow/nodes/human-input/types'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { InputVarType } from '@/app/components/workflow/types'
@@ -15,15 +15,17 @@ vi.mock('../../../hooks', () => ({
vi.mock('../component-ui', () => ({
default: ({ formInput, onChange }: { formInput?: FormInputItem, onChange: (payload: FormInputItem) => void }) => {
- const basePayload: FormInputItem = formInput ?? {
- type: InputVarType.paragraph,
- output_variable_name: 'user_name',
- default: {
- type: 'constant',
- selector: [],
- value: 'hello',
- },
- }
+ const basePayload: ParagraphFormInput = (formInput && formInput.type === InputVarType.paragraph
+ ? formInput
+ : {
+ type: InputVarType.paragraph,
+ output_variable_name: 'user_name',
+ default: {
+ type: 'constant',
+ selector: [],
+ value: 'hello',
+ },
+ }) satisfies ParagraphFormInput
return (
<div>
<button
@@ -63,7 +65,7 @@ const createHookReturn = (): [RefObject<HTMLDivElement | null>, boolean] => {
return [{ current: null }, false]
}
-const createInput = (overrides?: Partial<FormInputItem>): FormInputItem => ({
+const createInput = (overrides?: Partial<ParagraphFormInput>): ParagraphFormInput => ({
type: InputVarType.paragraph,
output_variable_name: 'user_name',
default: {
@@ -127,6 +129,31 @@ describe('HITLInputComponent', () => {
expect(onChange.mock.calls[0]![0][0].output_variable_name).toBe('renamed_name')
})
+ it('should ignore rename when the target variable name already exists', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <HITLInputComponent
+ nodeKey="node-key-duplicate"
+ nodeId="node-duplicate"
+ varName="user_name"
+ formInputs={[
+ createInput(),
+ createInput({ output_variable_name: 'renamed_name' }),
+ ]}
+ onChange={onChange}
+ onRename={vi.fn()}
+ onRemove={vi.fn()}
+ workflowNodesMap={{}}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'emit-rename' }))
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
it('should update existing payload when variable name stays the same', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/index.spec.tsx
index 62b867d155b..79b806b889c 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/index.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/index.spec.tsx
@@ -1,11 +1,13 @@
+import type { LexicalEditor } from 'lexical'
import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import { LexicalComposer } from '@lexical/react/LexicalComposer'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { act, render, waitFor } from '@testing-library/react'
import {
+ $nodesOfType,
COMMAND_PRIORITY_EDITOR,
} from 'lexical'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import {
BlockEnum,
InputVarType,
@@ -13,6 +15,7 @@ import {
import { CustomTextNode } from '../../custom-text/node'
import {
getNodeCount,
+ readEditorStateValue,
readRootTextContent,
renderLexicalEditor,
selectRootEnd,
@@ -76,6 +79,12 @@ const createInsertPayload = () => ({
onFormInputItemRemove: vi.fn(),
})
+const readHITLReadonlyValues = (editor: LexicalEditor): boolean[] => {
+ return readEditorStateValue(editor, () => {
+ return $nodesOfType(HITLInputNode).map(node => node.getReadonly())
+ })
+}
+
const renderHITLInputBlock = (props?: {
onInsert?: () => void
onDelete?: () => void
@@ -169,6 +178,65 @@ describe('HITLInputBlock', () => {
expect(getNodeCount(editor, HITLInputNode)).toBe(1)
})
+ it('should update existing and newly inserted nodes when readonly changes', async () => {
+ let setReadonlyValue: ((readonly: boolean) => void) | undefined
+ const ReadonlyHarness = () => {
+ const [readonly, setReadonly] = useState(false)
+
+ useEffect(() => {
+ setReadonlyValue = setReadonly
+ return () => {
+ setReadonlyValue = undefined
+ }
+ }, [])
+
+ return (
+ <HITLInputBlock
+ nodeId="node-1"
+ formInputs={[createFormInput()]}
+ onFormInputItemRename={vi.fn()}
+ onFormInputItemRemove={vi.fn()}
+ workflowNodesMap={createWorkflowNodesMap('First Node')}
+ readonly={readonly}
+ />
+ )
+ }
+
+ const { getEditor } = renderLexicalEditor({
+ namespace: 'hitl-input-block-readonly-update-test',
+ nodes: [CustomTextNode, HITLInputNode],
+ children: <ReadonlyHarness />,
+ })
+
+ const editor = await waitForEditorReady(getEditor)
+
+ selectRootEnd(editor)
+ act(() => {
+ editor.dispatchCommand(INSERT_HITL_INPUT_BLOCK_COMMAND, createInsertPayload())
+ })
+
+ await waitFor(() => {
+ expect(readHITLReadonlyValues(editor)).toEqual([false])
+ })
+
+ act(() => {
+ setReadonlyValue?.(true)
+ })
+
+ await waitFor(() => {
+ expect(readHITLReadonlyValues(editor)).toEqual([true])
+ })
+
+ selectRootEnd(editor)
+ act(() => {
+ editor.dispatchCommand(INSERT_HITL_INPUT_BLOCK_COMMAND, createInsertPayload())
+ })
+
+ await waitFor(() => {
+ expect(readHITLReadonlyValues(editor)).toEqual([true, true])
+ })
+ })
+
it('should call onDelete when delete command is dispatched', async () => {
const onDelete = vi.fn()
const { getEditor } = renderHITLInputBlock({ onDelete })
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
index ad6ef42a0fa..4af00aa704e 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
@@ -1,15 +1,20 @@
-import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { FormInputItem, ParagraphFormInput } from '@/app/components/workflow/nodes/human-input/types'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { InputVarType } from '@/app/components/workflow/types'
+import { InputVarType, SupportUploadFileTypes, VarType } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
import InputField from '../input-field'
type VarReferencePickerProps = {
onChange: (value: string[]) => void
+ filterVar?: (payload: { type: VarType }) => boolean
}
+let lastVarReferencePickerProps: VarReferencePickerProps | undefined
+
vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
default: (props: VarReferencePickerProps) => {
+ lastVarReferencePickerProps = props
return (
<button type="button" onClick={() => props.onChange(['node-a', 'var-a'])}>
pick-variable
@@ -18,7 +23,58 @@ vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference
},
}))
-const createPayload = (overrides?: Partial<FormInputItem>): FormInputItem => ({
+vi.mock('@/app/components/app/configuration/config-var/config-modal/type-select', () => ({
+ __esModule: true,
+ default: ({ onSelect }: { onSelect: (item: { value: InputVarType }) => void }) => (
+ <div>
+ <button type="button" onClick={() => onSelect({ value: InputVarType.paragraph })}>
+ select-paragraph
+ </button>
+ <button type="button" onClick={() => onSelect({ value: InputVarType.select })}>
+ select-select
+ </button>
+ <button type="button" onClick={() => onSelect({ value: InputVarType.singleFile })}>
+ select-file
+ </button>
+ <button type="button" onClick={() => onSelect({ value: InputVarType.multiFiles })}>
+ select-file-list
+ </button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/app/configuration/config-var/config-select', () => ({
+ __esModule: true,
+ default: ({ onChange }: { onChange: (options: string[]) => void }) => (
+ <button type="button" onClick={() => onChange(['alpha', 'beta'])}>
+ config-select
+ </button>
+ ),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/components/file-upload-setting', () => ({
+ __esModule: true,
+ default: ({ onChange }: { onChange: (payload: {
+ allowed_file_extensions: string[]
+ allowed_file_types: SupportUploadFileTypes[]
+ allowed_file_upload_methods: TransferMethod[]
+ max_length?: number
+ }) => void }) => (
+ <button
+ type="button"
+ onClick={() => onChange({
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ max_length: 4,
+ })}
+ >
+ file-upload-setting
+ </button>
+ ),
+}))
+
+const createPayload = (overrides?: Partial<ParagraphFormInput>): ParagraphFormInput => ({
type: InputVarType.paragraph,
output_variable_name: 'valid_name',
default: {
@@ -32,6 +88,7 @@ const createPayload = (overrides?: Partial<FormInputItem>): FormInputItem => ({
describe('InputField', () => {
beforeEach(() => {
vi.clearAllMocks()
+ lastVarReferencePickerProps = undefined
})
it('should disable save and show validation error when variable name is invalid', async () => {
@@ -59,6 +116,31 @@ describe('InputField', () => {
expect(onChange).not.toHaveBeenCalled()
})
+ it('should disable save and show validation error when variable name already exists', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-duplicate-name"
+ isEdit={false}
+ payload={createPayload()}
+ unavailableVariableNames={['existing_name']}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ const inputs = screen.getAllByRole('textbox')
+ await user.clear(inputs[0]!)
+ await user.type(inputs[0]!, 'existing_name')
+
+ expect(screen.getByText('workflow.nodes.humanInput.insertInputField.variableNameDuplicated')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i })).toBeDisabled()
+ await user.keyboard('{Control>}{Enter}{/Control}')
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
it('should call onChange when saving a valid payload in edit mode', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
@@ -274,4 +356,278 @@ describe('InputField', () => {
value: '',
})
})
+
+ it('should switch to select payload when field type changes', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-7"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).toEqual({
+ type: InputVarType.select,
+ output_variable_name: 'valid_name',
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: [],
+ },
+ })
+ expect(screen.queryByText(/workflow\.nodes\.humanInput\.insertInputField\.prePopulateField/i)).not.toBeInTheDocument()
+ })
+
+ it('should keep paragraph pre-populate editor available after switching back to paragraph', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <InputField
+ nodeId="node-8"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText(/workflow\.nodes\.humanInput\.insertInputField\.prePopulateField/i)).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'select-file' }))
+ expect(screen.queryByText(/workflow\.nodes\.humanInput\.insertInputField\.prePopulateField/i)).not.toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'select-paragraph' }))
+ expect(screen.getByText(/workflow\.nodes\.humanInput\.insertInputField\.prePopulateField/i)).toBeInTheDocument()
+ })
+
+ it('should save constant select options', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-9"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(screen.getByRole('button', { name: 'config-select' }))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).toEqual({
+ type: InputVarType.select,
+ output_variable_name: 'valid_name',
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: ['alpha', 'beta'],
+ },
+ })
+ })
+
+ it('should preserve constant and variable select sources when toggling', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-10"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(screen.getByRole('button', { name: 'config-select' }))
+ await user.click(screen.getByText(/workflow\.nodes\.humanInput\.insertInputField\.useVarInstead/i))
+ await user.click(screen.getByText('pick-variable'))
+ await user.click(screen.getByText(/workflow\.nodes\.humanInput\.insertInputField\.useConstantInstead/i))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).toEqual({
+ type: InputVarType.select,
+ output_variable_name: 'valid_name',
+ option_source: {
+ type: 'constant',
+ selector: ['node-a', 'var-a'],
+ value: ['alpha', 'beta'],
+ },
+ })
+ })
+
+ it('should only allow array[string] variables for select option source', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <InputField
+ nodeId="node-11"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(screen.getByText(/workflow\.nodes\.humanInput\.insertInputField\.useVarInstead/i))
+
+ expect(lastVarReferencePickerProps?.filterVar?.({ type: VarType.arrayString })).toBe(true)
+ expect(lastVarReferencePickerProps?.filterVar?.({ type: VarType.string })).toBe(false)
+ expect(lastVarReferencePickerProps?.filterVar?.({ type: VarType.arrayFile })).toBe(false)
+ })
+
+ it('should clear paragraph default state when switching to select', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-12"
+ isEdit={false}
+ payload={createPayload({
+ default: {
+ type: 'constant',
+ selector: [],
+ value: 'paragraph-default',
+ },
+ })}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).not.toHaveProperty('default')
+ })
+
+ it('should save single file upload settings', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-13"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-file' }))
+ await user.click(screen.getByRole('button', { name: 'file-upload-setting' }))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).toEqual({
+ type: InputVarType.singleFile,
+ output_variable_name: 'valid_name',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: ['document'],
+ allowed_file_upload_methods: ['local_file'],
+ })
+ })
+
+ it('should clear paragraph default state when switching to single file', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-13-1"
+ isEdit={false}
+ payload={createPayload({
+ default: {
+ type: 'constant',
+ selector: [],
+ value: 'paragraph-default',
+ },
+ })}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-file' }))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).not.toHaveProperty('default')
+ })
+
+ it('should save file-list upload settings and max upload count', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-14"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-file-list' }))
+ await user.click(screen.getByRole('button', { name: 'file-upload-setting' }))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).toEqual({
+ type: InputVarType.multiFiles,
+ output_variable_name: 'valid_name',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: ['document'],
+ allowed_file_upload_methods: ['local_file'],
+ number_limits: 4,
+ })
+ })
+
+ it('should clear paragraph default state when switching to file-list', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+
+ render(
+ <InputField
+ nodeId="node-14-1"
+ isEdit={false}
+ payload={createPayload({
+ default: {
+ type: 'constant',
+ selector: [],
+ value: 'paragraph-default',
+ },
+ })}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'select-file-list' }))
+ await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i }))
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0]![0]).not.toHaveProperty('default')
+ })
})
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/node.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/node.spec.tsx
index f4ab8ff90af..e80277e1914 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/node.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/node.spec.tsx
@@ -98,6 +98,8 @@ describe('HITLInputNode', () => {
expect(node.getConversationVariables()).toEqual(props.conversationVariables)
expect(node.getRagVariables()).toEqual(props.ragVariables)
expect(node.getReadonly()).toBe(true)
+ node.setReadonly(false)
+ expect(node.getReadonly()).toBe(false)
expect(node.getTextContent()).toBe('{{#$output.user_name#}}')
})
})
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
index 322e2e0d756..089dcf9a72d 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
@@ -9,16 +9,24 @@ import { useBoolean } from 'ahooks'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { InputVarType } from '@/app/components/workflow/types'
+import {
+ createDefaultParagraphFormInput,
+ isFileFormInput,
+ isParagraphFormInput,
+ isSelectFormInput,
+} from '@/app/components/workflow/nodes/human-input/types'
import ActionButton from '../../../action-button'
import { VariableX } from '../../../icons/src/vender/workflow'
import InputField from './input-field'
import VariableBlock from './variable-block'
+const i18nPrefix = 'nodes.humanInput.insertInputField'
+
type HITLInputComponentUIProps = {
nodeId: string
varName: string
formInput?: FormInputItem
+ unavailableVariableNames?: string[]
onChange: (input: FormInputItem) => void
onRename: (payload: FormInputItem, oldName: string) => void
onRemove: (varName: string) => void
@@ -36,15 +44,8 @@ type HITLInputComponentUIProps = {
const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
nodeId,
varName,
- formInput = {
- type: InputVarType.paragraph,
- output_variable_name: varName,
- default: {
- type: 'constant',
- selector: [],
- value: '',
- },
- },
+ formInput,
+ unavailableVariableNames = [],
onChange,
onRename,
onRemove,
@@ -56,11 +57,20 @@ const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
readonly,
}) => {
const { t } = useTranslation()
+ const resolvedFormInput = formInput || createDefaultParagraphFormInput(varName)
+ const paragraphDefault = isParagraphFormInput(resolvedFormInput)
+ ? resolvedFormInput.default
+ : null
const [isShowEditModal, {
setTrue: showEditModal,
setFalse: hideEditModal,
}] = useBoolean(false)
+ useEffect(() => {
+ if (readonly)
+ hideEditModal()
+ }, [hideEditModal, readonly])
+
// Lexical delegate the click make it unable to add click by the method of react
const editBtnRef = useRef<HTMLDivElement>(null)
useEffect(() => {
@@ -72,8 +82,7 @@ const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
if (editBtn)
editBtn.removeEventListener('click', showEditModal)
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [])
+ }, [showEditModal])
const removeBtnRef = useRef<HTMLDivElement>(null)
useEffect(() => {
@@ -89,16 +98,47 @@ const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
}, [onRemove, varName])
const handleChange = useCallback((newPayload: FormInputItem) => {
+ if (newPayload.output_variable_name !== varName && unavailableVariableNames.includes(newPayload.output_variable_name))
+ return
+
if (varName === newPayload.output_variable_name)
onChange(newPayload)
else
onRename(newPayload, varName)
hideEditModal()
- }, [hideEditModal, onChange, onRename, varName])
+ }, [hideEditModal, onChange, onRename, unavailableVariableNames, varName])
const isDefaultValueVariable = useMemo(() => {
- return formInput.default?.type === 'variable'
- }, [formInput.default?.type])
+ return paragraphDefault?.type === 'variable'
+ }, [paragraphDefault])
+ const inputTypeLabel = useMemo(() => {
+ if (isParagraphFormInput(resolvedFormInput))
+ return t('variableConfig.paragraph', { ns: 'appDebug' })
+ if (isSelectFormInput(resolvedFormInput))
+ return t('variableConfig.select', { ns: 'appDebug' })
+ if (isFileFormInput(resolvedFormInput))
+ return t('variableConfig.single-file', { ns: 'appDebug' })
+ return t('variableConfig.multi-files', { ns: 'appDebug' })
+ }, [resolvedFormInput, t])
+ const variableSelector = useMemo(() => {
+ if (isDefaultValueVariable)
+ return paragraphDefault?.selector || []
+ if (isSelectFormInput(resolvedFormInput) && resolvedFormInput.option_source.type === 'variable')
+ return resolvedFormInput.option_source.selector
+ return null
+ }, [isDefaultValueVariable, paragraphDefault?.selector, resolvedFormInput])
+ const summaryText = useMemo(() => {
+ if (isParagraphFormInput(resolvedFormInput))
+ return paragraphDefault?.value || inputTypeLabel
+
+ if (isSelectFormInput(resolvedFormInput)) {
+ if (resolvedFormInput.option_source.type === 'variable')
+ return t(`${i18nPrefix}.variable`, { ns: 'workflow' })
+ return resolvedFormInput.option_source.value.join(', ') || inputTypeLabel
+ }
+
+ return inputTypeLabel
+ }, [inputTypeLabel, paragraphDefault?.value, resolvedFormInput, t])
return (
<div
@@ -112,22 +152,27 @@ const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
</div>
</div>
- <div className="flex w-full items-center gap-x-0.5 pr-5">
+ <div className="flex w-full items-center gap-x-2 pr-5">
<div className="min-w-0 grow">
- {/* Default Value Info */}
- {isDefaultValueVariable && (
- <VariableBlock
- variables={formInput.default?.selector}
- workflowNodesMap={workflowNodesMap}
- getVarType={getVarType}
- environmentVariables={environmentVariables}
- conversationVariables={conversationVariables}
- ragVariables={ragVariables}
- />
- )}
- {!isDefaultValueVariable && (
- <div className="max-w-full truncate system-xs-medium text-components-input-text-filled">{formInput.default?.value}</div>
- )}
+ {variableSelector
+ ? (
+ <VariableBlock
+ variables={variableSelector}
+ workflowNodesMap={workflowNodesMap}
+ getVarType={getVarType}
+ environmentVariables={environmentVariables}
+ conversationVariables={conversationVariables}
+ ragVariables={ragVariables}
+ />
+ )
+ : (
+ <div className="max-w-full truncate system-xs-medium text-components-input-text-filled">
+ {summaryText}
+ </div>
+ )}
+ </div>
+ <div className="shrink-0 system-2xs-medium text-text-tertiary uppercase">
+ {inputTypeLabel}
</div>
{/* Actions */}
@@ -168,6 +213,7 @@ const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
nodeId={nodeId}
isEdit
payload={formInput}
+ unavailableVariableNames={unavailableVariableNames}
onChange={handleChange}
onCancel={hideEditModal}
/>
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component.tsx
index e13ac2aee36..48f16b188cd 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component.tsx
@@ -45,8 +45,14 @@ const HITLInputComponent: FC<HITLInputComponentProps> = ({
}) => {
const [ref] = useSelectOrDelete(nodeKey, DELETE_HITL_INPUT_BLOCK_COMMAND)
const payload = formInputs.find(item => item.output_variable_name === varName)
+ const unavailableVariableNames = formInputs
+ .map(item => item.output_variable_name)
+ .filter(name => name !== varName)
const handleChange = useCallback((newPayload: FormInputItem) => {
+ if (newPayload.output_variable_name !== varName && unavailableVariableNames.includes(newPayload.output_variable_name))
+ return
+
if (!payload) {
onChange([...formInputs, newPayload])
return
@@ -58,7 +64,7 @@ const HITLInputComponent: FC<HITLInputComponentProps> = ({
return
}
onChange(formInputs.map(item => item.output_variable_name === varName ? newPayload : item))
- }, [formInputs, onChange, payload, varName])
+ }, [formInputs, onChange, payload, unavailableVariableNames, varName])
return (
<div
@@ -69,6 +75,7 @@ const HITLInputComponent: FC<HITLInputComponentProps> = ({
nodeId={nodeId}
varName={varName}
formInput={payload}
+ unavailableVariableNames={unavailableVariableNames}
onChange={handleChange}
onRename={onRename}
onRemove={onRemove}
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx
index a63d694e2b0..d6431f81d6e 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx
@@ -1,5 +1,6 @@
import type { TextNode } from 'lexical'
import type { HITLInputBlockType } from '../../types'
+import type { Var } from '@/app/components/workflow/types'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { mergeRegister } from '@lexical/utils'
import { $applyNodeReplacement } from 'lexical'
@@ -8,6 +9,7 @@ import {
useCallback,
useEffect,
useMemo,
+ useRef,
} from 'react'
import { HITL_INPUT_REG } from '@/config'
import { decoratorTransform } from '../../utils'
@@ -31,13 +33,39 @@ const HITLInputReplacementBlock = ({
const environmentVariables = useMemo(() => variables?.find(o => o.nodeId === 'env')?.vars || [], [variables])
const conversationVariables = useMemo(() => variables?.find(o => o.nodeId === 'conversation')?.vars || [], [variables])
- const ragVariables = useMemo(() => variables?.reduce<any[]>((acc, curr) => {
+ const ragVariables = useMemo(() => variables?.reduce<Var[]>((acc, curr) => {
if (curr.nodeId === 'rag')
acc.push(...curr.vars)
else
acc.push(...curr.vars.filter(v => v.isRagVariable))
return acc
}, []), [variables])
+ const latestConfigRef = useRef({
+ nodeId,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ workflowNodesMap,
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+ readonly,
+ })
+ latestConfigRef.current = {
+ nodeId,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ workflowNodesMap,
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+ readonly,
+ }
useEffect(() => {
if (!editor.hasNodes([HITLInputNode]))
@@ -46,6 +74,20 @@ const HITLInputReplacementBlock = ({
const createHITLInputBlockNode = useCallback((textNode: TextNode): HITLInputNode => {
const varName = textNode.getTextContent().split('.')[1]!.replace(/#\}\}$/, '')
+ const {
+ nodeId,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ workflowNodesMap,
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+ readonly,
+ } = latestConfigRef.current
+
return $applyNodeReplacement($createHITLInputNode(
varName,
nodeId,
@@ -60,7 +102,7 @@ const HITLInputReplacementBlock = ({
ragVariables,
readonly,
))
- }, [nodeId, formInputs, onFormInputsChange, onFormInputItemRename, onFormInputItemRemove, workflowNodesMap, getVarType, environmentVariables, conversationVariables, ragVariables, readonly])
+ }, [])
const getMatch = useCallback((text: string) => {
const matchArr = REGEX.exec(text)
@@ -81,7 +123,7 @@ const HITLInputReplacementBlock = ({
return mergeRegister(
editor.registerNodeTransform(CustomTextNode, textNode => decoratorTransform(textNode, getMatch, createHITLInputBlockNode)),
)
- }, [])
+ }, [editor, getMatch, createHITLInputBlockNode])
return null
}
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx
index 1b2af39ebe8..73cbbc3ef5e 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx
@@ -6,6 +6,7 @@ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext
import { mergeRegister } from '@lexical/utils'
import {
$insertNodes,
+ $nodesOfType,
COMMAND_PRIORITY_EDITOR,
createCommand,
} from 'lexical'
@@ -43,6 +44,14 @@ const HITLInputBlock = memo(({
})
}, [editor, workflowNodesMap, workflowAvailableVariables])
+ useEffect(() => {
+ editor.update(() => {
+ $nodesOfType(HITLInputNode).forEach((node) => {
+ node.setReadonly(readonly)
+ })
+ })
+ }, [editor, readonly])
+
useEffect(() => {
if (!editor.hasNodes([HITLInputNode]))
throw new Error('HITLInputBlockPlugin: HITLInputBlock not registered on editor')
@@ -95,7 +104,7 @@ const HITLInputBlock = memo(({
COMMAND_PRIORITY_EDITOR,
),
)
- }, [editor, onInsert, onDelete])
+ }, [editor, onInsert, onDelete, workflowNodesMap, getVarType, readonly])
return null
})
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
index f42ee37e621..cb1766b3111 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
@@ -1,15 +1,30 @@
-import type { FormInputItem, FormInputItemDefault } from '@/app/components/workflow/nodes/human-input/types'
-import type { ValueSelector } from '@/app/components/workflow/types'
+import type { Item as TypeSelectItem } from '@/app/components/app/configuration/config-var/config-modal/type-select'
+import type { FormInputItem, FormInputItemDefault, ParagraphFormInput } from '@/app/components/workflow/nodes/human-input/types'
+import type { UploadFileSetting, ValueSelector } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { formatForDisplay } from '@tanstack/react-hotkeys'
import { produce } from 'immer'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import TypeSelector from '@/app/components/app/configuration/config-var/config-modal/type-select'
+import ConfigSelect from '@/app/components/app/configuration/config-var/config-select'
import Input from '@/app/components/base/input'
-import { InputVarType } from '@/app/components/workflow/types'
+import FileUploadSetting from '@/app/components/workflow/nodes/_base/components/file-upload-setting'
+import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
+import {
+ createDefaultFormInputByType,
+ createDefaultParagraphFormInput,
+ isFileFormInput,
+ isFileListFormInput,
+ isParagraphFormInput,
+ isSelectFormInput,
+} from '@/app/components/workflow/nodes/human-input/types'
+import { InputVarType, VarType } from '@/app/components/workflow/types'
import PrePopulate from './pre-populate'
+import TypeSwitch from './type-switch'
const i18nPrefix = 'nodes.humanInput.insertInputField'
@@ -17,42 +32,79 @@ type InputFieldProps = {
nodeId: string
isEdit: boolean
payload?: FormInputItem
+ unavailableVariableNames?: string[]
onChange: (newPayload: FormInputItem) => void
onCancel: () => void
}
-const defaultPayload: FormInputItem = {
- type: InputVarType.paragraph,
- output_variable_name: '',
- default: { type: 'constant', selector: [], value: '' },
-}
const InputField: React.FC<InputFieldProps> = ({
nodeId,
isEdit,
payload,
+ unavailableVariableNames = [],
onChange,
onCancel,
}) => {
const { t } = useTranslation()
- const [tempPayload, setTempPayload] = useState(payload || defaultPayload)
- const nameValid = useMemo(() => {
+ const [tempPayload, setTempPayload] = useState<FormInputItem>(() => payload || createDefaultParagraphFormInput())
+ const fieldTypeItems = useMemo<TypeSelectItem[]>(() => {
+ return [
+ {
+ name: t('variableConfig.paragraph', { ns: 'appDebug' }),
+ value: InputVarType.paragraph,
+ },
+ {
+ name: t('variableConfig.select', { ns: 'appDebug' }),
+ value: InputVarType.select,
+ },
+ {
+ name: t('variableConfig.single-file', { ns: 'appDebug' }),
+ value: InputVarType.singleFile,
+ },
+ {
+ name: t('variableConfig.multi-files', { ns: 'appDebug' }),
+ value: InputVarType.multiFiles,
+ },
+ ]
+ }, [t])
+ const paragraphPayload = useMemo<ParagraphFormInput>(() => {
+ if (isParagraphFormInput(tempPayload)) {
+ return {
+ ...tempPayload,
+ default: tempPayload.default || createDefaultParagraphFormInput().default,
+ }
+ }
+
+ return createDefaultParagraphFormInput(tempPayload.output_variable_name)
+ }, [tempPayload])
+ const unavailableVariableNameSet = useMemo(() => {
+ return new Set(unavailableVariableNames.map(name => name.trim()).filter(Boolean))
+ }, [unavailableVariableNames])
+ const variableNameError = useMemo(() => {
const name = tempPayload.output_variable_name.trim()
if (!name)
- return false
+ return null
if (name.includes(' '))
- return false
- return /^[a-z_]\w{0,29}$/.test(name)
- }, [tempPayload.output_variable_name])
+ return 'variableNameInvalid'
+ if (!/^[a-z_]\w{0,29}$/.test(name))
+ return 'variableNameInvalid'
+ if (unavailableVariableNameSet.has(name))
+ return 'variableNameDuplicated'
+ return null
+ }, [tempPayload.output_variable_name, unavailableVariableNameSet])
+ const nameValid = useMemo(() => {
+ return !!tempPayload.output_variable_name.trim() && !variableNameError
+ }, [tempPayload.output_variable_name, variableNameError])
const handleSave = useCallback(() => {
if (!nameValid)
return
onChange(tempPayload)
}, [nameValid, onChange, tempPayload])
- const defaultValueConfig = tempPayload.default
+ const handleTypeChange = useCallback((item: TypeSelectItem) => {
+ setTempPayload(prev => createDefaultFormInputByType(item.value as FormInputItem['type'], prev.output_variable_name))
+ }, [])
const handleDefaultValueChange = useCallback((key: keyof FormInputItemDefault) => {
return (value: ValueSelector | string) => {
- const nextValue = produce(tempPayload, (draft) => {
- if (!draft.default)
- draft.default = { type: 'constant', selector: [], value: '' }
+ const nextValue = produce(paragraphPayload, (draft) => {
if (key === 'selector') {
draft.default.type = 'variable'
draft.default.selector = value as ValueSelector
@@ -67,7 +119,78 @@ const InputField: React.FC<InputFieldProps> = ({
})
setTempPayload(nextValue)
}
- }, [tempPayload])
+ }, [paragraphPayload])
+ const handleSelectOptionsChange = useCallback((options: string[]) => {
+ setTempPayload((prev) => {
+ if (!isSelectFormInput(prev))
+ return prev
+
+ return {
+ ...prev,
+ option_source: {
+ ...prev.option_source,
+ type: 'constant',
+ value: options,
+ },
+ }
+ })
+ }, [])
+ const handleSelectOptionSourceTypeChange = useCallback((isVariable: boolean) => {
+ setTempPayload((prev) => {
+ if (!isSelectFormInput(prev))
+ return prev
+
+ return {
+ ...prev,
+ option_source: {
+ ...prev.option_source,
+ type: isVariable ? 'variable' : 'constant',
+ },
+ }
+ })
+ }, [])
+ const handleSelectOptionSourceSelectorChange = useCallback((selector: ValueSelector | string) => {
+ setTempPayload((prev) => {
+ if (!isSelectFormInput(prev))
+ return prev
+
+ return {
+ ...prev,
+ option_source: {
+ ...prev.option_source,
+ type: 'variable',
+ selector: selector as ValueSelector,
+ },
+ }
+ })
+ }, [])
+ const handleFilePayloadChange = useCallback((payload: UploadFileSetting) => {
+ setTempPayload((prev) => {
+ if (!isFileFormInput(prev))
+ return prev
+
+ return {
+ ...prev,
+ allowed_file_extensions: payload.allowed_file_extensions || [],
+ allowed_file_types: payload.allowed_file_types,
+ allowed_file_upload_methods: payload.allowed_file_upload_methods,
+ }
+ })
+ }, [])
+ const handleFileListPayloadChange = useCallback((payload: UploadFileSetting) => {
+ setTempPayload((prev) => {
+ if (!isFileListFormInput(prev))
+ return prev
+
+ return {
+ ...prev,
+ allowed_file_extensions: payload.allowed_file_extensions || [],
+ allowed_file_types: payload.allowed_file_types,
+ allowed_file_upload_methods: payload.allowed_file_upload_methods,
+ number_limits: payload.max_length,
+ }
+ })
+ }, [])
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -83,74 +206,151 @@ const InputField: React.FC<InputFieldProps> = ({
}, [handleSave])
return (
- <div className="w-[372px]
- rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-3 shadow-lg backdrop-blur-[5px]"
- >
- <div className="system-md-semibold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'workflow' })}</div>
- <div className="mt-3">
- <div className="system-xs-medium text-text-secondary">
- {t(`${i18nPrefix}.saveResponseAs`, { ns: 'workflow' })}
- <span className="relative system-xs-regular text-text-destructive-secondary">*</span>
+ <div className="flex max-h-[540px] w-[372px] flex-col rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-[5px]">
+ <div className="min-h-0 flex-1 overflow-y-auto p-3 pb-0">
+ <div className="system-md-semibold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'workflow' })}</div>
+ <div className="mt-3">
+ <div className="system-xs-medium text-text-secondary">
+ {t(`${i18nPrefix}.fieldType`, { ns: 'workflow' })}
+ </div>
+ <div className="mt-1.5">
+ <TypeSelector
+ value={tempPayload.type}
+ items={fieldTypeItems}
+ onSelect={handleTypeChange}
+ />
+ </div>
+ </div>
+ <div className="mt-3">
+ <div className="system-xs-medium text-text-secondary">
+ {t(`${i18nPrefix}.saveResponseAs`, { ns: 'workflow' })}
+ <span className="relative system-xs-regular text-text-destructive-secondary">*</span>
+ </div>
+ <Input
+ className="mt-1.5"
+ placeholder={t(`${i18nPrefix}.saveResponseAsPlaceholder`, { ns: 'workflow' })}
+ value={tempPayload.output_variable_name}
+ onChange={(e) => {
+ setTempPayload(prev => ({ ...prev, output_variable_name: e.target.value }))
+ }}
+ autoFocus
+ />
+ {tempPayload.output_variable_name && variableNameError && (
+ <div className="mt-1 px-1 system-xs-regular text-text-destructive-secondary">
+ {t(`${i18nPrefix}.${variableNameError}`, { ns: 'workflow' })}
+ </div>
+ )}
</div>
- <Input
- className="mt-1.5"
- placeholder={t(`${i18nPrefix}.saveResponseAsPlaceholder`, { ns: 'workflow' })}
- value={tempPayload.output_variable_name}
- onChange={(e) => {
- setTempPayload(prev => ({ ...prev, output_variable_name: e.target.value }))
- }}
- autoFocus
- />
- {tempPayload.output_variable_name && !nameValid && (
- <div className="mt-1 px-1 system-xs-regular text-text-destructive-secondary">
- {t(`${i18nPrefix}.variableNameInvalid`, { ns: 'workflow' })}
+ {isParagraphFormInput(tempPayload) && (
+ <div className="mt-4">
+ <div className="mb-1.5 system-xs-medium text-text-secondary">
+ {t(`${i18nPrefix}.prePopulateField`, { ns: 'workflow' })}
+ </div>
+ <PrePopulate
+ isVariable={paragraphPayload.default.type === 'variable'}
+ onIsVariableChange={(isVariable) => {
+ handleDefaultValueChange('type')(isVariable ? 'variable' : 'constant')
+ }}
+ nodeId={nodeId}
+ valueSelector={paragraphPayload.default.selector}
+ onValueSelectorChange={handleDefaultValueChange('selector')}
+ value={paragraphPayload.default.value}
+ onValueChange={handleDefaultValueChange('value')}
+ />
+ </div>
+ )}
+ {isSelectFormInput(tempPayload) && (
+ <div className="mt-4">
+ <div className="mb-1.5 system-xs-medium text-text-secondary">
+ {t(`${i18nPrefix}.options`, { ns: 'workflow' })}
+ </div>
+ {tempPayload.option_source.type === 'variable'
+ ? (
+ <div className="relative min-h-[80px] rounded-lg border border-transparent bg-components-input-bg-normal px-3 pt-2 pb-8">
+ <VarReferencePicker
+ nodeId={nodeId}
+ value={tempPayload.option_source.selector}
+ onChange={handleSelectOptionSourceSelectorChange}
+ readonly={false}
+ isJustShowValue
+ filterVar={varPayload => varPayload.type === VarType.arrayString}
+ />
+ <TypeSwitch
+ className="absolute bottom-1 left-1.5"
+ isVariable
+ onIsVariableChange={handleSelectOptionSourceTypeChange}
+ />
+ </div>
+ )
+ : (
+ <div className={cn('rounded-lg border border-transparent bg-components-input-bg-normal p-2')}>
+ <ConfigSelect
+ options={tempPayload.option_source.value}
+ onChange={handleSelectOptionsChange}
+ />
+ <TypeSwitch
+ className="mt-2"
+ isVariable={false}
+ onIsVariableChange={handleSelectOptionSourceTypeChange}
+ />
+ </div>
+ )}
+ </div>
+ )}
+ {isFileFormInput(tempPayload) && (
+ <div className="mt-4">
+ <FileUploadSetting
+ payload={{
+ ...tempPayload,
+ max_length: 1,
+ }}
+ isMultiple={false}
+ onChange={handleFilePayloadChange}
+ />
+ </div>
+ )}
+ {isFileListFormInput(tempPayload) && (
+ <div className="mt-4">
+ <FileUploadSetting
+ payload={{
+ ...tempPayload,
+ max_length: tempPayload.number_limits || 5,
+ }}
+ isMultiple
+ onChange={handleFileListPayloadChange}
+ />
</div>
)}
</div>
- <div className="mt-4">
- <div className="mb-1.5 system-xs-medium text-text-secondary">
- {t(`${i18nPrefix}.prePopulateField`, { ns: 'workflow' })}
+ <div className="shrink-0 p-3">
+ <div className="flex justify-end space-x-2">
+ <Button onClick={onCancel}>{t('operation.cancel', { ns: 'common' })}</Button>
+ {isEdit
+ ? (
+ <Button
+ variant="primary"
+ onClick={handleSave}
+ disabled={!nameValid}
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ )
+ : (
+ <Button
+ className="flex"
+ variant="primary"
+ disabled={!nameValid}
+ onClick={handleSave}
+ >
+ <span className="mr-1">{t(`${i18nPrefix}.insert`, { ns: 'workflow' })}</span>
+ <KbdGroup>
+ {['Mod', 'Enter'].map(key => (
+ <Kbd key={key} color="white">{formatForDisplay(key)}</Kbd>
+ ))}
+ </KbdGroup>
+ </Button>
+ )}
</div>
- <PrePopulate
- isVariable={defaultValueConfig?.type === 'variable'}
- onIsVariableChange={(isVariable) => {
- handleDefaultValueChange('type')(isVariable ? 'variable' : 'constant')
- }}
- nodeId={nodeId}
- valueSelector={defaultValueConfig?.selector}
- onValueSelectorChange={handleDefaultValueChange('selector')}
- value={defaultValueConfig?.value}
- onValueChange={handleDefaultValueChange('value')}
- />
- </div>
- <div className="mt-4 flex justify-end space-x-2">
- <Button onClick={onCancel}>{t('operation.cancel', { ns: 'common' })}</Button>
- {isEdit
- ? (
- <Button
- variant="primary"
- onClick={handleSave}
- disabled={!nameValid}
- >
- {t('operation.save', { ns: 'common' })}
- </Button>
- )
- : (
- <Button
- className="flex"
- variant="primary"
- disabled={!nameValid}
- onClick={handleSave}
- >
- <span className="mr-1">{t(`${i18nPrefix}.insert`, { ns: 'workflow' })}</span>
- <KbdGroup>
- {['Mod', 'Enter'].map(key => (
- <Kbd key={key} color="white">{formatForDisplay(key)}</Kbd>
- ))}
- </KbdGroup>
- </Button>
- )}
-
</div>
</div>
)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/node.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/node.tsx
index 592ecf1f6c5..ff26d8d62da 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/node.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/node.tsx
@@ -109,6 +109,11 @@ export class HITLInputNode extends DecoratorNode<React.JSX.Element> {
return self.__readonly || false
}
+ setReadonly(readonly?: boolean): void {
+ const self = this.getWritable()
+ self.__readonly = readonly
+ }
+
static override clone(node: HITLInputNode): HITLInputNode {
return new HITLInputNode(
node.__variableName,
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
index 4b42e234f25..209e5d4c7ef 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
@@ -29,7 +29,6 @@ type PlaceholderProps = {
value: ValueSelector
onChange: (valueSelector: ValueSelector | string) => void
readonly: boolean
- zIndex: number
filterVar: (varPayload: Var) => boolean
isJustShowValue?: boolean
}
@@ -86,7 +85,6 @@ const PrePopulate: FC<Props> = ({
value: valueSelector || [],
onChange: onValueSelectorChange!,
readonly: false,
- zIndex: 1000000, // bigger than shortcut plugin popup
filterVar: (varPayload: Var) => {
return [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
},
diff --git a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx
index 114d1d78026..e40d597ac41 100644
--- a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx
@@ -149,6 +149,30 @@ describe('ShortcutsPopupPlugin', () => {
})
})
+ it('does not close on mousedown inside a Base UI portal overlay', async () => {
+ render(<MinimalEditor />)
+ const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
+ ce.focus()
+
+ fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
+
+ const portal = document.createElement('div')
+ portal.setAttribute('data-base-ui-portal', '')
+ const portalChild = document.createElement('button')
+ portalChild.textContent = 'portal-child'
+ portal.appendChild(portalChild)
+ document.body.appendChild(portal)
+
+ fireEvent.mouseDown(portalChild)
+
+ await waitFor(() => {
+ expect(screen.getByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
+ })
+
+ portal.remove()
+ })
+
// ─── Container / portal ───
it('portals into provided container when container is set', async () => {
render(<MinimalEditor withContainer />)
@@ -162,7 +186,10 @@ describe('ShortcutsPopupPlugin', () => {
render(<MinimalEditor withContainer={false} />)
focusAndTriggerHotkey('/')
const portalContent = await screen.findByText(SHORTCUTS_EMPTY_CONTENT)
+ const floatingDiv = screen.getByTestId('shortcuts-popup')
expect(document.body).toContainElement(portalContent)
+ expect(floatingDiv).toHaveStyle({ zIndex: '50' })
+ expect(floatingDiv).toHaveStyle({ overflow: 'visible' })
})
// ─── matchHotkey: string hotkey ───
@@ -407,8 +434,8 @@ describe('ShortcutsPopupPlugin', () => {
it('applies custom className to floating popup', async () => {
render(<MinimalEditor className="custom-popup-class" />)
focusAndTriggerHotkey('/')
- const content = await screen.findByText(SHORTCUTS_EMPTY_CONTENT)
- const floatingDiv = content.closest('div')
+ await screen.findByText(SHORTCUTS_EMPTY_CONTENT)
+ const floatingDiv = screen.getByTestId('shortcuts-popup')
expect(floatingDiv).toHaveClass('custom-popup-class')
})
diff --git a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
index ec03b2fc3da..c36f97a6d53 100644
--- a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
+++ b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
@@ -158,10 +158,9 @@ export default function ShortcutsPopupPlugin({
size({
apply({ availableWidth, availableHeight, elements }) {
Object.assign(elements.floating.style, {
- maxWidth: `${Math.min(400, availableWidth)}px`,
- maxHeight: `${Math.max(0, availableHeight)}px`,
- overflowX: 'hidden',
- overflowY: 'auto',
+ '--shortcut-popup-max-width': `${Math.min(400, availableWidth)}px`,
+ '--shortcut-popup-max-height': `${Math.max(0, availableHeight)}px`,
+ 'overflow': 'visible',
})
},
padding: 8,
@@ -275,6 +274,9 @@ export default function ShortcutsPopupPlugin({
/* v8 ignore next 2 -- outside-click listener can race with ref cleanup during close/unmount; null-ref path is a safety guard. @preserve */
if (!portalRef.current)
return
+ const target = e.target as HTMLElement | null
+ if (target?.closest('[data-base-ui-portal]'))
+ return
if (!portalRef.current.contains(e.target as Node))
closePortal()
}
@@ -292,21 +294,25 @@ export default function ShortcutsPopupPlugin({
return createPortal(
<div
+ data-testid="shortcuts-popup"
ref={(node) => {
portalRef.current = node
refs.setFloating(node)
}}
className={cn(
- useContainer ? '' : 'z-999999',
'absolute rounded-xl bg-components-panel-bg-blur shadow-lg',
className,
)}
style={{
...floatingStyles,
+ zIndex: useContainer ? undefined : 50,
+ overflow: 'visible',
visibility: isPositioned ? 'visible' : 'hidden',
}}
>
- {typeof children === 'function' ? children(closePortal, handleInsert) : (children ?? SHORTCUTS_EMPTY_CONTENT)}
+ <div className="max-h-(--shortcut-popup-max-height) max-w-(--shortcut-popup-max-width) overflow-x-hidden overflow-y-auto rounded-xl">
+ {typeof children === 'function' ? children(closePortal, handleInsert) : (children ?? SHORTCUTS_EMPTY_CONTENT)}
+ </div>
</div>,
containerEl,
)
diff --git a/web/app/components/base/prompt-editor/prompt-editor-content.tsx b/web/app/components/base/prompt-editor/prompt-editor-content.tsx
index 2c64a3c04e5..16dff0a6eeb 100644
--- a/web/app/components/base/prompt-editor/prompt-editor-content.tsx
+++ b/web/app/components/base/prompt-editor/prompt-editor-content.tsx
@@ -1,9 +1,6 @@
-import type {
- EditorState,
- LexicalCommand,
-} from 'lexical'
+import type { EditorState } from 'lexical'
import type { FC } from 'react'
-import type { Hotkey } from './plugins/shortcuts-popup-plugin'
+import type { Hotkey, ShortcutPopupInsertHandler } from './plugins/shortcuts-popup-plugin'
import type {
ContextBlockType,
CurrentBlockType,
@@ -71,7 +68,7 @@ import {
type ShortcutPopup = {
hotkey: Hotkey
- Popup: React.ComponentType<{ onClose: () => void, onInsert: (command: LexicalCommand<unknown>, params: unknown[]) => void }>
+ Popup: React.ComponentType<{ onClose: () => void, onInsert: ShortcutPopupInsertHandler }>
}
type PromptEditorContentProps = {
diff --git a/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts b/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts
index 63c0f43de06..88d7769e1d0 100644
--- a/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts
+++ b/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts
@@ -139,6 +139,8 @@ describe('workflow-stream-handlers helpers', () => {
expect(workflowProcessData.humanInputFilledFormDataList).toEqual([
expect.objectContaining({
action_text: 'Submit',
+ form_content: 'content',
+ inputs: [],
}),
])
expect(workflowProcessData.tracing[0]).toEqual(expect.objectContaining({
diff --git a/web/app/components/share/text-generation/result/workflow-stream-handlers.ts b/web/app/components/share/text-generation/result/workflow-stream-handlers.ts
index f7db4c6b248..31b2fa283fd 100644
--- a/web/app/components/share/text-generation/result/workflow-stream-handlers.ts
+++ b/web/app/components/share/text-generation/result/workflow-stream-handlers.ts
@@ -3,6 +3,7 @@ import type { WorkflowProcess } from '@/app/components/base/chat/types'
import type { IOtherOptions } from '@/service/base'
import type { HumanInputFormTimeoutData, NodeTracing, WorkflowFinishedResponse } from '@/types/workflow'
import { produce } from 'immer'
+import { enrichSubmittedHumanInputFormData } from '@/app/components/base/chat/chat/answer/human-input-content/submitted-utils'
import { getFilesInLogs } from '@/app/components/base/file-uploader/utils'
import { NodeRunningStatus, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { sseGet } from '@/service/base'
@@ -204,16 +205,20 @@ const updateHumanInputFilled = (
data: NonNullable<WorkflowProcess['humanInputFilledFormDataList']>[number],
) => {
return updateWorkflowProcess(current, (draft) => {
+ let requiredFormData: NonNullable<WorkflowProcess['humanInputFormDataList']>[number] | undefined
if (draft.humanInputFormDataList?.length) {
const currentFormIndex = draft.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
- if (currentFormIndex > -1)
+ if (currentFormIndex > -1) {
+ requiredFormData = draft.humanInputFormDataList[currentFormIndex]
draft.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
}
+ const enrichedData = enrichSubmittedHumanInputFormData(data, requiredFormData)
if (!draft.humanInputFilledFormDataList)
- draft.humanInputFilledFormDataList = [data]
+ draft.humanInputFilledFormDataList = [enrichedData]
else
- draft.humanInputFilledFormDataList.push(data)
+ draft.humanInputFilledFormDataList.push(enrichedData)
})
}
diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts
index 010fad6afae..ec7c4f17deb 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts
+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts
@@ -4,7 +4,7 @@ import type { LLMNodeType } from '@/app/components/workflow/nodes/llm/types'
import type { Node, PromptItem } from '@/app/components/workflow/types'
import { describe, expect, it } from 'vitest'
import { DeliveryMethodType } from '@/app/components/workflow/nodes/human-input/types'
-import { BlockEnum, EditionType, PromptRole } from '@/app/components/workflow/types'
+import { BlockEnum, EditionType, InputVarType, PromptRole } from '@/app/components/workflow/types'
import { AppModeEnum } from '@/types/app'
import { getNodeUsedVars, updateNodeVars } from '../utils'
@@ -62,7 +62,26 @@ describe('variable utils', () => {
title: 'Human Input',
desc: '',
form_content: '',
- inputs: [],
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: {
+ type: 'variable',
+ selector: ['conversation', 'memory'],
+ value: '',
+ },
+ },
+ {
+ type: InputVarType.select,
+ output_variable_name: 'decision',
+ option_source: {
+ type: 'variable',
+ selector: ['env', 'OPTIONS'],
+ value: [],
+ },
+ },
+ ],
user_actions: [],
timeout: 1,
timeout_unit: 'day',
@@ -84,6 +103,8 @@ describe('variable utils', () => {
expect(getNodeUsedVars(node)).toEqual(
expect.arrayContaining([
['env', 'API_KEY'],
+ ['conversation', 'memory'],
+ ['env', 'OPTIONS'],
]),
)
})
@@ -129,7 +150,26 @@ describe('variable utils', () => {
title: 'Human Input',
desc: '',
form_content: '',
- inputs: [],
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: {
+ type: 'variable',
+ selector: ['env', 'API_KEY'],
+ value: '',
+ },
+ },
+ {
+ type: InputVarType.select,
+ output_variable_name: 'decision',
+ option_source: {
+ type: 'variable',
+ selector: ['env', 'API_KEY'],
+ value: [],
+ },
+ },
+ ],
user_actions: [],
timeout: 1,
timeout_unit: 'day',
@@ -154,6 +194,16 @@ describe('variable utils', () => {
subject: 'Subject {{#conversation.memory#}}',
body: 'Body {{#env.RENAMED_KEY#}}',
})
+ expect((updatedNode.data as HumanInputNodeType).inputs[0]).toMatchObject({
+ default: {
+ selector: ['env', 'RENAMED_KEY'],
+ },
+ })
+ expect((updatedNode.data as HumanInputNodeType).inputs[1]).toMatchObject({
+ option_source: {
+ selector: ['env', 'RENAMED_KEY'],
+ },
+ })
})
})
})
diff --git a/web/app/components/workflow/nodes/_base/components/variable/utils.ts b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
index 3754058b509..80a33eecc6d 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/utils.ts
+++ b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
@@ -1530,7 +1530,14 @@ export const getNodeUsedVars = (node: Node): ValueSelector[] => {
return []
return [method.config.body]
})
- res = matchNotSystemVars([formContent, ...mailTemplates])
+ const inputSelectors = payload.inputs.flatMap((input) => {
+ if (input.type === InputVarType.paragraph && input.default.type === 'variable')
+ return [input.default.selector]
+ if (input.type === InputVarType.select && input.option_source.type === 'variable')
+ return [input.option_source.selector]
+ return []
+ })
+ res = [...matchNotSystemVars([formContent, ...mailTemplates]), ...inputSelectors]
break
}
}
@@ -2032,6 +2039,15 @@ export const updateNodeVars = (
},
}
})
+ payload.inputs = payload.inputs.map((input) => {
+ if (input.type === InputVarType.paragraph && input.default.type === 'variable' && input.default.selector.join('.') === oldVarSelector.join('.')) {
+ input.default.selector = newVarSelector
+ }
+ if (input.type === InputVarType.select && input.option_source.type === 'variable' && input.option_source.selector.join('.') === oldVarSelector.join('.')) {
+ input.option_source.selector = newVarSelector
+ }
+ return input
+ })
break
}
}
diff --git a/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx b/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx
index 8d41a454682..2a150d4c548 100644
--- a/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx
@@ -444,6 +444,88 @@ describe('DSL Import with Human Input Node', () => {
expect(result.isValid).toBe(false)
})
+ it('should validate that enabled email delivery methods have complete configuration', () => {
+ const t = (key: string) => key
+ const payload = {
+ ...humanInputDefault.defaultValue,
+ delivery_methods: [
+ {
+ id: 'dm-email',
+ type: DeliveryMethodType.Email,
+ enabled: true,
+ },
+ ],
+ user_actions: [
+ { id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary },
+ ],
+ } as HumanInputNodeType
+
+ const result = humanInputDefault.checkValid(payload, t)
+
+ expect(result.isValid).toBe(false)
+ expect(result.errorMessage).toBe('nodes.humanInput.errorMsg.emailConfigIncomplete')
+ })
+
+ it('should validate email delivery config fields before user actions', () => {
+ const t = (key: string) => key
+ const payload = {
+ ...humanInputDefault.defaultValue,
+ delivery_methods: [
+ {
+ id: 'dm-email',
+ type: DeliveryMethodType.Email,
+ enabled: true,
+ config: {
+ recipients: { whole_workspace: false, items: [] },
+ subject: 'Review request',
+ body: 'Please review {{#url#}}',
+ debug_mode: false,
+ },
+ },
+ ],
+ user_actions: [
+ { id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary },
+ ],
+ } as HumanInputNodeType
+
+ const result = humanInputDefault.checkValid(payload, t)
+
+ expect(result.isValid).toBe(false)
+ expect(result.errorMessage).toBe('nodes.humanInput.errorMsg.emailConfigIncomplete')
+ })
+
+ it('should validate enabled email subject and body content', () => {
+ const t = (key: string) => key
+ const createPayload = (body: string, subject = 'Review request') => ({
+ ...humanInputDefault.defaultValue,
+ delivery_methods: [
+ {
+ id: 'dm-email',
+ type: DeliveryMethodType.Email,
+ enabled: true,
+ config: {
+ recipients: { whole_workspace: true, items: [] },
+ subject,
+ body,
+ debug_mode: false,
+ },
+ },
+ ],
+ user_actions: [
+ { id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary },
+ ],
+ }) as HumanInputNodeType
+
+ expect(humanInputDefault.checkValid(createPayload('{{#url#}}', ' '), t)).toEqual({
+ isValid: false,
+ errorMessage: 'nodes.humanInput.errorMsg.emailConfigIncomplete',
+ })
+ expect(humanInputDefault.checkValid(createPayload('Please review'), t)).toEqual({
+ isValid: false,
+ errorMessage: 'nodes.humanInput.errorMsg.emailConfigIncomplete',
+ })
+ })
+
it('should validate that user actions are required', () => {
const t = (key: string) => key
const payload = {
@@ -477,6 +559,30 @@ describe('DSL Import with Human Input Node', () => {
expect(result.isValid).toBe(false)
})
+ it('should validate that user action ids and titles are not empty', () => {
+ const t = (key: string) => key
+ const createPayload = (userActions: HumanInputNodeType['user_actions']) => ({
+ ...humanInputDefault.defaultValue,
+ delivery_methods: [
+ { id: 'dm-1', type: DeliveryMethodType.WebApp, enabled: true },
+ ],
+ user_actions: userActions,
+ }) as HumanInputNodeType
+
+ expect(humanInputDefault.checkValid(createPayload([
+ { id: ' ', title: 'Approve', button_style: UserActionButtonType.Primary },
+ ]), t)).toEqual({
+ isValid: false,
+ errorMessage: 'nodes.humanInput.errorMsg.emptyActionId',
+ })
+ expect(humanInputDefault.checkValid(createPayload([
+ { id: 'approve', title: ' ', button_style: UserActionButtonType.Primary },
+ ]), t)).toEqual({
+ isValid: false,
+ errorMessage: 'nodes.humanInput.errorMsg.emptyActionTitle',
+ })
+ })
+
it('should pass validation with correct configuration', () => {
const t = (key: string) => key
const payload = {
@@ -503,8 +609,10 @@ describe('DSL Import with Human Input Node', () => {
const payload = {
...humanInputDefault.defaultValue,
inputs: [
- { type: 'text-input', output_variable_name: 'review_result', default: { selector: [], type: 'constant' as const, value: '' } },
- { type: 'text-input', output_variable_name: 'comment', default: { selector: [], type: 'constant' as const, value: '' } },
+ { type: 'paragraph', output_variable_name: 'review_result', default: { selector: [], type: 'constant' as const, value: '' } },
+ { type: 'file', output_variable_name: 'attachment', allowed_file_extensions: [], allowed_file_types: [], allowed_file_upload_methods: [] },
+ { type: 'file-list', output_variable_name: 'attachments', allowed_file_extensions: [], allowed_file_types: [], allowed_file_upload_methods: [], number_limits: 3 },
+ { type: 'select', output_variable_name: 'comment', option_source: { type: 'constant', selector: [], value: ['A', 'B'] } },
],
} as HumanInputNodeType
@@ -512,6 +620,8 @@ describe('DSL Import with Human Input Node', () => {
expect(outputVars).toEqual([
{ variable: 'review_result', type: 'string' },
+ { variable: 'attachment', type: 'file' },
+ { variable: 'attachments', type: 'array[file]' },
{ variable: 'comment', type: 'string' },
])
})
diff --git a/web/app/components/workflow/nodes/human-input/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/human-input/__tests__/node.spec.tsx
index 915f9136bea..fcffb286e59 100644
--- a/web/app/components/workflow/nodes/human-input/__tests__/node.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/__tests__/node.spec.tsx
@@ -23,7 +23,7 @@ const createData = (overrides: Partial<HumanInputNodeType> = {}): HumanInputNode
}],
form_content: 'Please review this request',
inputs: [{
- type: InputVarType.textInput,
+ type: InputVarType.paragraph,
output_variable_name: 'review_result',
default: {
selector: [],
diff --git a/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx
index 03247710a71..b5230296576 100644
--- a/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx
@@ -98,7 +98,7 @@ vi.mock('../components/form-content', () => ({
<button
type="button"
onClick={() => props.onFormInputsChange([{
- type: InputVarType.textInput,
+ type: InputVarType.paragraph,
output_variable_name: 'email',
default: {
selector: [],
@@ -225,7 +225,7 @@ const createData = (overrides: Partial<HumanInputNodeType> = {}): HumanInputNode
}],
form_content: 'Please review this request',
inputs: [{
- type: InputVarType.textInput,
+ type: InputVarType.paragraph,
output_variable_name: 'review_result',
default: {
selector: [],
@@ -286,6 +286,9 @@ describe('human-input/panel', () => {
availableVars: [{
variable: ['start', 'email'],
type: VarType.string,
+ }, {
+ variable: ['code', 'result'],
+ type: VarType.arrayString,
}, {
variable: ['start', 'files'],
type: VarType.file,
@@ -315,6 +318,12 @@ describe('human-input/panel', () => {
expect(screen.getByText('__action_id:string:Action ID user triggered')).toBeInTheDocument()
expect(screen.getByText('__action_value:string:Selected action value')).toBeInTheDocument()
expect(screen.getByText('__rendered_content:string:Rendered content')).toBeInTheDocument()
+ expect(mockDeliveryMethod).toHaveBeenCalledWith(expect.objectContaining({
+ nodesOutputVars: [
+ expect.objectContaining({ type: VarType.string }),
+ expect.objectContaining({ type: VarType.arrayString }),
+ ],
+ }))
await user.click(screen.getByRole('button', { name: 'delivery-method:editable' }))
await user.click(screen.getByRole('button', { name: /workflow\.nodes\.humanInput\.formContent\.preview/ }))
@@ -378,4 +387,33 @@ describe('human-input/panel', () => {
expect(screen.getByRole('button', { name: 'timeout:readonly' })).toBeInTheDocument()
expect(screen.queryByText('form-preview')).not.toBeInTheDocument()
})
+
+ it('renders file outputs with file-aware types', () => {
+ mockUseConfig.mockReturnValue(createConfigResult({
+ inputs: createData({
+ inputs: [
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'attachments',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ number_limits: 3,
+ },
+ ],
+ }),
+ }))
+
+ renderPanel()
+
+ expect(screen.getByText('attachment:file:Form input value')).toBeInTheDocument()
+ expect(screen.getByText('attachments:array[file]:Form input value')).toBeInTheDocument()
+ })
})
diff --git a/web/app/components/workflow/nodes/human-input/__tests__/types.spec.ts b/web/app/components/workflow/nodes/human-input/__tests__/types.spec.ts
new file mode 100644
index 00000000000..a60769b529a
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/__tests__/types.spec.ts
@@ -0,0 +1,73 @@
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
+import {
+ createDefaultFormInputByType,
+ createDefaultParagraphFormInput,
+ isFileFormInput,
+ isFileListFormInput,
+ isParagraphFormInput,
+ isSelectFormInput,
+} from '../types'
+
+describe('human-input/types', () => {
+ describe('type guards', () => {
+ it('should identify each form input kind', () => {
+ const paragraph = createDefaultFormInputByType(InputVarType.paragraph, 'comment')
+ const select = createDefaultFormInputByType(InputVarType.select, 'decision')
+ const singleFile = createDefaultFormInputByType(InputVarType.singleFile, 'attachment')
+ const multiFiles = createDefaultFormInputByType(InputVarType.multiFiles, 'attachments')
+
+ expect(isParagraphFormInput(paragraph)).toBe(true)
+ expect(isParagraphFormInput(select)).toBe(false)
+ expect(isSelectFormInput(select)).toBe(true)
+ expect(isSelectFormInput(singleFile)).toBe(false)
+ expect(isFileFormInput(singleFile)).toBe(true)
+ expect(isFileFormInput(multiFiles)).toBe(false)
+ expect(isFileListFormInput(multiFiles)).toBe(true)
+ expect(isFileListFormInput(paragraph)).toBe(false)
+ })
+ })
+
+ describe('default factories', () => {
+ it('should create a paragraph input with an empty constant default', () => {
+ expect(createDefaultParagraphFormInput('review')).toEqual({
+ type: InputVarType.paragraph,
+ output_variable_name: 'review',
+ default: {
+ type: 'constant',
+ selector: [],
+ value: '',
+ },
+ })
+ })
+
+ it('should create defaults for every supported input type', () => {
+ expect(createDefaultFormInputByType(InputVarType.select, 'choice')).toEqual({
+ type: InputVarType.select,
+ output_variable_name: 'choice',
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: [],
+ },
+ })
+
+ expect(createDefaultFormInputByType(InputVarType.singleFile, 'file')).toEqual({
+ type: InputVarType.singleFile,
+ output_variable_name: 'file',
+ allowed_file_extensions: [],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ })
+
+ expect(createDefaultFormInputByType(InputVarType.multiFiles, 'files')).toEqual({
+ type: InputVarType.multiFiles,
+ output_variable_name: 'files',
+ allowed_file_extensions: [],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ number_limits: 5,
+ })
+ })
+ })
+})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/add-input-field.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/add-input-field.spec.tsx
new file mode 100644
index 00000000000..2dd829fe411
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/add-input-field.spec.tsx
@@ -0,0 +1,75 @@
+import type { FormInputItem } from '../../types'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { InputVarType } from '@/app/components/workflow/types'
+import AddInputField from '../add-input-field'
+
+const mockInputField = vi.hoisted(() => vi.fn())
+
+vi.mock('@/app/components/base/prompt-editor/plugins/hitl-input-block/input-field', () => ({
+ __esModule: true,
+ default: (props: {
+ nodeId: string
+ isEdit: boolean
+ unavailableVariableNames?: string[]
+ onChange: (newPayload: FormInputItem) => void
+ onCancel: () => void
+ }) => {
+ mockInputField(props)
+ return (
+ <div>
+ <button
+ type="button"
+ onClick={() => props.onChange({
+ type: InputVarType.paragraph,
+ output_variable_name: 'comment',
+ default: {
+ type: 'constant',
+ selector: [],
+ value: '',
+ },
+ })}
+ >
+ save
+ </button>
+ <button type="button" onClick={props.onCancel}>cancel</button>
+ </div>
+ )
+ },
+}))
+
+describe('human-input/components/add-input-field', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should render InputField in create mode and forward callbacks', () => {
+ const handleSave = vi.fn()
+ const handleCancel = vi.fn()
+
+ render(
+ <AddInputField
+ nodeId="human-node"
+ unavailableVariableNames={['comment']}
+ onSave={handleSave}
+ onCancel={handleCancel}
+ />,
+ )
+
+ expect(mockInputField).toHaveBeenCalledWith(expect.objectContaining({
+ nodeId: 'human-node',
+ isEdit: false,
+ unavailableVariableNames: ['comment'],
+ onChange: handleSave,
+ onCancel: handleCancel,
+ }))
+
+ fireEvent.click(screen.getByRole('button', { name: 'save' }))
+ expect(handleSave).toHaveBeenCalledWith(expect.objectContaining({
+ type: InputVarType.paragraph,
+ output_variable_name: 'comment',
+ }))
+
+ fireEvent.click(screen.getByRole('button', { name: 'cancel' }))
+ expect(handleCancel).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx
index 89b26897616..436793edd4b 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx
@@ -64,10 +64,14 @@ vi.mock('../variable-in-markdown', () => ({
rehypeNotes: vi.fn(),
rehypeVariable: vi.fn(),
Variable: ({ path }: { path: string }) => <div data-testid="variable-path">{path}</div>,
- Note: ({ defaultInput, nodeName }: {
- defaultInput: { selector: string[] }
+ Note: ({ input, nodeName }: {
+ input: { type: string, default?: { selector: string[] }, option_source?: { selector: string[] } }
nodeName: (nodeId: string) => string
- }) => <div data-testid="note">{nodeName(defaultInput.selector[0]!)}</div>,
+ }) => (
+ <div data-testid="note">
+ {input.default?.selector?.length ? nodeName(input.default.selector[0]!) : input.option_source?.selector?.join('.') || input.type}
+ </div>
+ ),
}))
describe('FormContentPreview', () => {
@@ -131,4 +135,25 @@ describe('FormContentPreview', () => {
expect(onClose).toHaveBeenCalledTimes(1)
})
+
+ it('should pass non-paragraph inputs through the preview note renderer', () => {
+ render(
+ <FormContentPreview
+ content="content"
+ formInputs={[{
+ type: 'select' as never,
+ output_variable_name: 'field_1',
+ option_source: {
+ type: 'variable',
+ selector: ['node-1', 'items'],
+ value: [],
+ },
+ }]}
+ userActions={[]}
+ onClose={onClose}
+ />,
+ )
+
+ expect(screen.getByTestId('note')).toHaveTextContent('node-1.items')
+ })
})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx
index f546ca00dfe..1b7fd400637 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import * as React from 'react'
import FormContent from '../form-content'
const mockUseTranslation = vi.hoisted(() => vi.fn())
@@ -54,12 +55,13 @@ vi.mock('@/app/components/base/prompt-editor', () => ({
}) => {
mockPromptEditor(props)
const popup = props.shortcutPopups?.[0]
+ const Popup = popup?.Popup
return (
<div>
<button type="button" onClick={props.onFocus}>focus-editor</button>
<button type="button" onClick={props.onBlur}>blur-editor</button>
<button type="button" onClick={() => props.onChange('updated value')}>change-editor</button>
- {popup && popup.Popup({ onClose: vi.fn(), onInsert: mockOnInsert })}
+ {Popup && <Popup onClose={vi.fn()} onInsert={mockOnInsert} />}
</div>
)
},
@@ -67,7 +69,8 @@ vi.mock('@/app/components/base/prompt-editor', () => ({
vi.mock('../add-input-field', () => ({
__esModule: true,
- default: (props: {
+ default: function MockAddInputField(props: {
+ unavailableVariableNames?: string[]
onSave: (payload: {
type: string
output_variable_name: string
@@ -78,10 +81,17 @@ vi.mock('../add-input-field', () => ({
}
}) => void
onCancel: () => void
- }) => {
+ }) {
+ const [draftName, setDraftName] = React.useState('')
+
mockAddInputField(props)
return (
<div>
+ <input
+ aria-label="field-name"
+ value={draftName}
+ onChange={event => setDraftName(event.target.value)}
+ />
<button
type="button"
onClick={() => props.onSave({
@@ -235,6 +245,41 @@ describe('FormContent', () => {
expect(container.firstChild).toHaveClass('pointer-events-none')
})
+ it('should not insert a new input when the variable name already exists', () => {
+ render(
+ <FormContent
+ nodeId="node-2"
+ value="Initial content"
+ onChange={onChange}
+ formInputs={[{
+ type: 'paragraph',
+ output_variable_name: 'approval',
+ default: {
+ type: 'constant',
+ selector: [],
+ value: '',
+ },
+ } as never]}
+ onFormInputsChange={onFormInputsChange}
+ onFormInputItemRename={onFormInputItemRename}
+ onFormInputItemRemove={onFormInputItemRemove}
+ editorKey={1}
+ isExpand={false}
+ availableVars={[]}
+ availableNodes={[]}
+ />,
+ )
+
+ expect(mockAddInputField).toHaveBeenCalledWith(expect.objectContaining({
+ unavailableVariableNames: ['approval'],
+ }))
+
+ fireEvent.click(screen.getByText('save-input'))
+
+ expect(mockOnInsert).not.toHaveBeenCalled()
+ expect(onFormInputsChange).not.toHaveBeenCalled()
+ })
+
it('should render the mac hotkey hint when focused on macOS', () => {
mockFormatForDisplay.mockReturnValue('⌘')
@@ -259,4 +304,29 @@ describe('FormContent', () => {
expect(screen.getByText('⌘')).toBeInTheDocument()
expect(screen.getByText('/')).toBeInTheDocument()
})
+
+ it('should preserve add-input draft state across parent rerenders', () => {
+ const props = {
+ nodeId: 'node-2',
+ value: 'Initial content',
+ onChange,
+ formInputs: [],
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ editorKey: 1,
+ isExpand: false,
+ availableVars: [],
+ availableNodes: [],
+ }
+ const { rerender } = render(<FormContent {...props} />)
+
+ fireEvent.change(screen.getByRole('textbox', { name: 'field-name' }), {
+ target: { value: 'approval_name' },
+ })
+
+ rerender(<FormContent {...props} />)
+
+ expect(screen.getByRole('textbox', { name: 'field-name' })).toHaveValue('approval_name')
+ })
})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.spec.tsx
index 13ec9b346d5..0c477a9160a 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.spec.tsx
@@ -1,4 +1,5 @@
-import type { ReactNode } from 'react'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import type { HumanInputFormData } from '@/types/workflow'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -12,25 +13,54 @@ vi.mock('react-i18next', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode
- disabled?: boolean
- onClick?: () => void
- }) => (
- <button type="button" disabled={disabled} onClick={onClick}>
- {children}
- </button>
- ),
-}))
-
vi.mock('@/app/components/base/chat/chat/answer/human-input-content/content-item', () => ({
__esModule: true,
- default: ({ content }: { content: string }) => <div>{content}</div>,
+ default: ({
+ content,
+ formInputFields,
+ inputs,
+ onInputChange,
+ }: {
+ content: string
+ formInputFields: FormInputItem[]
+ inputs: Record<string, HumanInputFieldValue>
+ onInputChange: (name: string, value: HumanInputFieldValue) => void
+ }) => {
+ const fieldName = /\{\{#\$output\.([^#]+)#\}\}/.exec(content)?.[1]
+ if (!fieldName)
+ return <div>{content}</div>
+
+ const field = formInputFields.find(field => field.output_variable_name === fieldName)
+ if (!field)
+ return null
+
+ if (field.type === 'select') {
+ return (
+ <select
+ aria-label={fieldName}
+ value={typeof inputs[fieldName] === 'string' ? inputs[fieldName] : ''}
+ onChange={event => onInputChange(fieldName, event.target.value)}
+ >
+ <option value="">Select</option>
+ {field.option_source.value.map(option => (
+ <option key={option} value={option}>{option}</option>
+ ))}
+ </select>
+ )
+ }
+
+ if (field.type === 'paragraph') {
+ return (
+ <textarea
+ aria-label={fieldName}
+ value={typeof inputs[fieldName] === 'string' ? inputs[fieldName] : ''}
+ onChange={event => onInputChange(fieldName, event.target.value)}
+ />
+ )
+ }
+
+ return <div>{fieldName}</div>
+ },
}))
const createFormData = (overrides: Partial<HumanInputFormData> = {}): HumanInputFormData => ({
@@ -60,6 +90,10 @@ const createFormData = (overrides: Partial<HumanInputFormData> = {}): HumanInput
})
describe('SingleRunForm', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
it('renders the back action as a named button and forwards clicks', async () => {
const user = userEvent.setup()
const handleBack = vi.fn()
@@ -99,4 +133,99 @@ describe('SingleRunForm', () => {
})
})
})
+
+ it('submits updated paragraph input values', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn().mockResolvedValue(undefined)
+
+ render(
+ <SingleRunForm
+ nodeName="Review"
+ data={createFormData()}
+ onSubmit={onSubmit}
+ />,
+ )
+
+ await user.clear(screen.getByRole('textbox', { name: 'review' }))
+ await user.type(screen.getByRole('textbox', { name: 'review' }), 'updated review')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+
+ await waitFor(() => {
+ expect(onSubmit).toHaveBeenCalledWith({
+ inputs: { review: 'updated review' },
+ action: 'approve',
+ })
+ })
+ })
+
+ it('uses resolved default values for variable paragraph inputs', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn().mockResolvedValue(undefined)
+
+ render(
+ <SingleRunForm
+ nodeName="Review"
+ data={createFormData({
+ inputs: [{
+ type: InputVarType.paragraph,
+ output_variable_name: 'review',
+ default: {
+ selector: ['source', 'answer'],
+ type: 'variable',
+ value: 'fallback review',
+ },
+ }],
+ resolved_default_values: {
+ review: 'resolved review',
+ },
+ })}
+ onSubmit={onSubmit}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+
+ await waitFor(() => {
+ expect(onSubmit).toHaveBeenCalledWith({
+ inputs: { review: 'resolved review' },
+ action: 'approve',
+ })
+ })
+ })
+
+ it('disables submit actions until a select input has a value', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn().mockResolvedValue(undefined)
+
+ render(
+ <SingleRunForm
+ nodeName="Review"
+ data={createFormData({
+ form_content: 'Choose {{#$output.choice#}}',
+ inputs: [{
+ type: InputVarType.select,
+ output_variable_name: 'choice',
+ option_source: {
+ selector: [],
+ type: 'constant',
+ value: ['approve', 'reject'],
+ },
+ }],
+ })}
+ onSubmit={onSubmit}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'Approve' })).toBeDisabled()
+
+ await user.selectOptions(screen.getByRole('combobox', { name: 'choice' }), 'approve')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+
+ await waitFor(() => {
+ expect(onSubmit).toHaveBeenCalledWith({
+ inputs: { choice: 'approve' },
+ action: 'approve',
+ })
+ })
+ })
})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/variable-in-markdown.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/variable-in-markdown.spec.tsx
index 1847ceaa9b0..212fc8713d2 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/variable-in-markdown.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/variable-in-markdown.spec.tsx
@@ -1,4 +1,7 @@
import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { InputVarType } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
import { Note, rehypeNotes, rehypeVariable, Variable } from '../variable-in-markdown'
describe('variable-in-markdown', () => {
@@ -86,10 +89,14 @@ describe('variable-in-markdown', () => {
it('should render note values and replace node ids with labels for variable defaults', () => {
const { rerender } = render(
<Note
- defaultInput={{
- type: 'variable',
- selector: ['node-1', 'output'],
- value: '',
+ input={{
+ type: InputVarType.paragraph,
+ output_variable_name: 'approval',
+ default: {
+ type: 'variable',
+ selector: ['node-1', 'output'],
+ value: '',
+ },
}}
nodeName={nodeId => nodeId === 'node-1' ? 'Start Node' : nodeId}
/>,
@@ -99,10 +106,14 @@ describe('variable-in-markdown', () => {
rerender(
<Note
- defaultInput={{
- type: 'constant',
- value: 'Plain value',
- selector: [],
+ input={{
+ type: InputVarType.paragraph,
+ output_variable_name: 'approval',
+ default: {
+ type: 'constant',
+ value: 'Plain value',
+ selector: [],
+ },
}}
nodeName={nodeId => nodeId}
/>,
@@ -110,5 +121,88 @@ describe('variable-in-markdown', () => {
expect(screen.getByText('Plain value')).toBeInTheDocument()
})
+
+ it('should render a select preview control for select inputs', () => {
+ render(
+ <Note
+ input={{
+ type: InputVarType.select,
+ output_variable_name: 'approval',
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: ['Approved', 'Rejected'],
+ },
+ }}
+ nodeName={nodeId => nodeId}
+ />,
+ )
+
+ expect(screen.getByTestId('human-input-note-select-preview')).toBeInTheDocument()
+ expect(screen.getByText('Approved')).toBeInTheDocument()
+ })
+
+ it('should render dynamic select inputs as variable information without a select control', () => {
+ render(
+ <Note
+ input={{
+ type: InputVarType.select,
+ output_variable_name: 'approval',
+ option_source: {
+ type: 'variable',
+ selector: ['node-1', 'options'],
+ value: [],
+ },
+ }}
+ nodeName={nodeId => nodeId === 'node-1' ? 'Start Node' : nodeId}
+ />,
+ )
+
+ expect(screen.queryByTestId('human-input-note-select-preview')).not.toBeInTheDocument()
+ expect(screen.queryByRole('combobox', { name: 'human-input-note-select' })).not.toBeInTheDocument()
+ expect(screen.getByText('{{Start Node/options}}')).toBeInTheDocument()
+ })
+
+ it('should open the select preview and show option items', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <Note
+ input={{
+ type: InputVarType.select,
+ output_variable_name: 'approval',
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: ['Approved', 'Rejected'],
+ },
+ }}
+ nodeName={nodeId => nodeId}
+ />,
+ )
+
+ await user.click(screen.getByRole('combobox', { name: 'human-input-note-select' }))
+
+ expect(await screen.findByRole('option', { name: 'Rejected' })).toBeInTheDocument()
+ })
+
+ it('should render upload placeholders for file inputs', () => {
+ render(
+ <Note
+ input={{
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ }}
+ nodeName={nodeId => nodeId}
+ />,
+ )
+
+ expect(screen.getByTestId('human-input-note-file-preview')).toBeInTheDocument()
+ expect(screen.getByText('common.fileUploader.uploadFromComputer')).toBeInTheDocument()
+ expect(screen.getByText('common.fileUploader.pasteFileLink')).toBeInTheDocument()
+ })
})
})
diff --git a/web/app/components/workflow/nodes/human-input/components/add-input-field.tsx b/web/app/components/workflow/nodes/human-input/components/add-input-field.tsx
index 35049f683b2..b8fe4ebf9ad 100644
--- a/web/app/components/workflow/nodes/human-input/components/add-input-field.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/add-input-field.tsx
@@ -6,12 +6,14 @@ import InputField from '@/app/components/base/prompt-editor/plugins/hitl-input-b
type Props = {
nodeId: string
+ unavailableVariableNames?: string[]
onSave: (newPayload: FormInputItem) => void
onCancel: () => void
}
const AddInputField: FC<Props> = ({
nodeId,
+ unavailableVariableNames,
onSave,
onCancel,
}) => {
@@ -19,6 +21,7 @@ const AddInputField: FC<Props> = ({
<InputField
nodeId={nodeId}
isEdit={false}
+ unavailableVariableNames={unavailableVariableNames}
onChange={onSave}
onCancel={onCancel}
/>
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-item.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-item.spec.tsx
index 8ad330e3f2c..bbe0bf1921f 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-item.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-item.spec.tsx
@@ -77,7 +77,7 @@ const createEmailConfig = (overrides: Partial<EmailConfig> = {}): EmailConfig =>
})
const formInputs: FormInputItem[] = [{
- type: InputVarType.textInput,
+ type: InputVarType.paragraph,
output_variable_name: 'name',
default: {
selector: ['start', 'name'],
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx
index 638a309c065..ea1514fc965 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx
@@ -1,16 +1,26 @@
+/* eslint-disable react/no-context-provider -- use-context-selector contexts require .Provider in tests. */
import type { ReactNode } from 'react'
-import type { EmailConfig, FormInputItem } from '../../../types'
+import type { EmailConfig, FormInputItem, ParagraphFormInput, SelectFormInput } from '../../../types'
+import type { CodeNodeType } from '@/app/components/workflow/nodes/code/types'
import type { App, AppSSO } from '@/types/app'
+import { toast } from '@langgenius/dify-ui/toast'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useStore as useAppStore } from '@/app/components/app/store'
import { HooksStoreContext } from '@/app/components/workflow/hooks-store/provider'
import { createHooksStore } from '@/app/components/workflow/hooks-store/store'
+import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
import { AppContext, initialLangGeniusVersionInfo, initialWorkspaceInfo, userProfilePlaceholder } from '@/context/app-context'
import EmailSenderModal from '../test-email-sender'
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: {
+ error: vi.fn(),
+ },
+}))
+
type RecordedRequest = {
url: string
method: string
@@ -145,8 +155,8 @@ const createConfig = (overrides: Partial<EmailConfig> = {}): EmailConfig => ({
...overrides,
})
-const createFormInput = (overrides: Partial<FormInputItem> = {}): FormInputItem => ({
- type: InputVarType.textInput,
+const createFormInput = (overrides: Partial<ParagraphFormInput> = {}): FormInputItem => ({
+ type: InputVarType.paragraph,
output_variable_name: 'user_name',
default: {
type: 'variable',
@@ -156,6 +166,16 @@ const createFormInput = (overrides: Partial<FormInputItem> = {}): FormInputItem
...overrides,
})
+const createDynamicSelectInput = (): SelectFormInput => ({
+ type: InputVarType.select,
+ output_variable_name: 'decision',
+ option_source: {
+ type: 'variable',
+ selector: ['code', 'result'],
+ value: [],
+ },
+})
+
describe('human-input/delivery-method/test-email-sender', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -233,7 +253,7 @@ describe('human-input/delivery-method/test-email-sender', () => {
delivery_method_id: 'delivery-1',
inputs: {
'#start.user_name#': 'Ada',
- '#start.score#': '42',
+ '#start.score#': 42,
},
},
}))
@@ -243,6 +263,81 @@ describe('human-input/delivery-method/test-email-sender', () => {
expect(handleOpenChange).toHaveBeenCalledWith(false)
})
+ it('should submit variables referenced by dynamic select option sources', async () => {
+ const user = userEvent.setup()
+ const { requests } = setupFetch()
+
+ renderWithProviders(
+ <EmailSenderModal
+ nodeId="human-node"
+ deliveryId="delivery-1"
+ open
+ onOpenChange={vi.fn()}
+ jumpToEmailConfigModal={vi.fn()}
+ config={createConfig({
+ body: '{{#url#}}',
+ })}
+ formInputs={[createDynamicSelectInput()]}
+ availableNodes={[
+ {
+ id: 'code',
+ type: 'custom',
+ position: { x: 0, y: 0 },
+ data: {
+ title: 'Code',
+ desc: '',
+ type: BlockEnum.Code,
+ variables: [],
+ code_language: CodeLanguage.python3,
+ code: '',
+ outputs: {
+ result: {
+ type: VarType.arrayString,
+ children: null,
+ },
+ },
+ } as CodeNodeType,
+ },
+ ]}
+ nodesOutputVars={[
+ {
+ nodeId: 'code',
+ title: 'Code',
+ vars: [
+ {
+ variable: 'result',
+ type: VarType.arrayString,
+ },
+ ],
+ },
+ ]}
+ />,
+ )
+
+ const sendButton = screen.getByRole('button', { name: 'workflow.nodes.humanInput.deliveryMethod.emailSender.send' })
+ expect(sendButton).toBeDisabled()
+
+ expect(screen.queryByPlaceholderText('result')).not.toBeInTheDocument()
+
+ fireEvent.change(screen.getByTestId('monaco-editor'), {
+ target: { value: '["approve","reject"]' },
+ })
+ expect(sendButton).toBeEnabled()
+
+ await user.click(sendButton)
+
+ await waitFor(() => expect(requests).toContainEqual(expect.objectContaining({
+ url: 'http://localhost:5001/console/api/apps/app-1/workflows/draft/human-input/nodes/human-node/delivery-test',
+ method: 'POST',
+ body: {
+ delivery_method_id: 'delivery-1',
+ inputs: {
+ '#code.result#': ['approve', 'reject'],
+ },
+ },
+ })))
+ })
+
it('should render fallback variable inputs and allow cancelling', async () => {
const user = userEvent.setup()
setupFetch()
@@ -295,4 +390,118 @@ describe('human-input/delivery-method/test-email-sender', () => {
expect(screen.getByText('[email protected]')).toBeInTheDocument()
expect(screen.getByText('nodes.humanInput.deliveryMethod.emailSender.tip')).toBeInTheDocument()
})
+
+ it('should show a validation toast when generated JSON input is invalid', async () => {
+ const user = userEvent.setup()
+ const { requests } = setupFetch()
+
+ renderWithProviders(
+ <EmailSenderModal
+ nodeId="human-node"
+ deliveryId="delivery-1"
+ open
+ onOpenChange={vi.fn()}
+ jumpToEmailConfigModal={vi.fn()}
+ config={createConfig({
+ body: 'Please review {{#code.payload#}}',
+ })}
+ availableNodes={[
+ {
+ id: 'code',
+ type: 'custom',
+ position: { x: 0, y: 0 },
+ data: {
+ title: 'Code',
+ desc: '',
+ type: BlockEnum.Code,
+ variables: [],
+ code_language: CodeLanguage.python3,
+ code: '',
+ outputs: {
+ payload: {
+ type: VarType.object,
+ children: null,
+ },
+ },
+ } as CodeNodeType,
+ },
+ ]}
+ nodesOutputVars={[
+ {
+ nodeId: 'code',
+ title: 'Code',
+ vars: [
+ {
+ variable: 'payload',
+ type: VarType.object,
+ },
+ ],
+ },
+ ]}
+ />,
+ )
+
+ fireEvent.change(screen.getByTestId('monaco-editor'), {
+ target: { value: '{invalid' },
+ })
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.humanInput.deliveryMethod.emailSender.send' }))
+
+ expect(toast.error).toHaveBeenCalledWith('workflow.errorMsg.invalidJson:{"field":"payload"}')
+ expect(requests).not.toContainEqual(expect.objectContaining({
+ url: 'http://localhost:5001/console/api/apps/app-1/workflows/draft/human-input/nodes/human-node/delivery-test',
+ method: 'POST',
+ }))
+ })
+
+ it('should show debug success copy after sending in debug mode', async () => {
+ const user = userEvent.setup()
+ setupFetch()
+
+ renderWithProviders(
+ <EmailSenderModal
+ nodeId="human-node"
+ deliveryId="delivery-1"
+ open
+ onOpenChange={vi.fn()}
+ jumpToEmailConfigModal={vi.fn()}
+ config={createConfig({
+ body: 'Plain body',
+ debug_mode: true,
+ })}
+ />,
+ )
+
+ expect(screen.getByText('workflow.nodes.humanInput.deliveryMethod.emailSender.debugModeTip')).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.humanInput.deliveryMethod.emailSender.send' }))
+
+ await waitFor(() => expect(screen.getByText('nodes.humanInput.deliveryMethod.emailSender.debugDone')).toBeInTheDocument())
+ })
+
+ it('should show specific-recipient success copy after sending', async () => {
+ const user = userEvent.setup()
+ setupFetch()
+
+ renderWithProviders(
+ <EmailSenderModal
+ nodeId="human-node"
+ deliveryId="delivery-1"
+ open
+ onOpenChange={vi.fn()}
+ jumpToEmailConfigModal={vi.fn()}
+ config={createConfig({
+ body: 'Plain body',
+ recipients: {
+ whole_workspace: false,
+ items: [{ type: 'external', email: '[email protected]' }],
+ },
+ })}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.humanInput.deliveryMethod.emailSender.send' }))
+
+ await waitFor(() => expect(screen.getByText('workflow.nodes.humanInput.deliveryMethod.emailSender.wholeTeamDone3')).toBeInTheDocument())
+ expect(screen.getByText('[email protected]')).toBeInTheDocument()
+ })
})
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx
index 360d3b0c146..30c6db59230 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx
@@ -136,6 +136,40 @@ describe('human-input/delivery-method/recipient/email-input', () => {
expect(handleSelect).toHaveBeenCalledTimes(1)
})
+ it('should keep typing focused and stop keyboard events from reaching workflow listeners', () => {
+ const handleParentKeyDown = vi.fn()
+ const handleWindowKeyDown = vi.fn()
+ window.addEventListener('keydown', handleWindowKeyDown)
+
+ try {
+ render(
+ <div onKeyDown={handleParentKeyDown}>
+ <EmailInput
+ value={[]}
+ list={members}
+ onDelete={vi.fn()}
+ onSelect={vi.fn()}
+ onAdd={vi.fn()}
+ />
+ </div>,
+ )
+
+ const input = screen.getByRole('textbox')
+ input.focus()
+
+ fireEvent.change(input, { target: { value: 'a' } })
+ fireEvent.keyDown(input, { key: 'a', code: 'KeyA' })
+
+ expect(document.activeElement).toBe(input)
+ expect(handleParentKeyDown).not.toHaveBeenCalled()
+ expect(handleWindowKeyDown).not.toHaveBeenCalled()
+ }
+ finally {
+ window.removeEventListener('keydown', handleWindowKeyDown)
+ }
+ })
+
it('should delete the last recipient with backspace, flag missing members as errors, and stop focusing when disabled', () => {
const handleDelete = vi.fn()
const { container, rerender } = render(
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsx
index d2dfef27951..8d54e3babae 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/member-selector.spec.tsx
@@ -11,9 +11,22 @@ vi.mock('../member-list', () => ({
searchValue: string
list: Member[]
email: string
+ onSearchChange: (value: string) => void
+ onSelect: (memberId: string) => void
}) => {
mockMemberList(props)
- return <div data-testid="member-list" />
+ return (
+ <div data-testid="member-list">
+ <input
+ aria-label="member search"
+ value={props.searchValue}
+ onChange={e => props.onSearchChange(e.target.value)}
+ />
+ <button type="button" onClick={() => props.onSelect('member-1')}>
+ select member
+ </button>
+ </div>
+ )
},
}))
@@ -66,4 +79,32 @@ describe('human-input/delivery-method/recipient/member-selector', () => {
await user.click(trigger)
expect(screen.queryByTestId('member-list')).not.toBeInTheDocument()
})
+
+ it('should update search value and close the list after selecting a member', async () => {
+ const user = userEvent.setup()
+ const handleSelect = vi.fn()
+
+ render(
+ <MemberSelector
+ value={[]}
+ onSelect={handleSelect}
+ list={members}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', {
+ name: 'workflow.nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.trigger',
+ }))
+ await user.type(screen.getByRole('textbox', { name: 'member search' }), 'member one')
+
+ expect(mockMemberList).toHaveBeenLastCalledWith(expect.objectContaining({
+ searchValue: 'member one',
+ }))
+
+ await user.click(screen.getByRole('button', { name: 'select member' }))
+
+ expect(handleSelect).toHaveBeenCalledWith('member-1')
+ expect(screen.queryByTestId('member-list')).not.toBeInTheDocument()
+ })
})
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
index 189a2ce1d9d..017b5228859 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
@@ -104,6 +104,8 @@ const EmailInput = ({
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ e.stopPropagation()
+
if (e.key === 'Enter' || e.key === 'Tab' || e.key === ' ' || e.key === ',') {
e.preventDefault()
handleEmailAdd()
@@ -155,6 +157,7 @@ const EmailInput = ({
sideOffset={4}
alignOffset={-40}
popupClassName="border-none bg-transparent p-0 shadow-none backdrop-blur-none"
+ popupProps={{ initialFocus: false, finalFocus: false }}
positionerProps={{ anchor: inputRef }}
>
<MemberList
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx
index 8b54d64bd85..bf9702ef7ef 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx
@@ -2,12 +2,12 @@ import type { EmailConfig, FormInputItem } from '../../types'
import type {
Node,
NodeOutPutVar,
- ValueSelector,
Var,
} from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { toast } from '@langgenius/dify-ui/toast'
import { RiArrowRightSFill } from '@remixicon/react'
import { noop, unionBy } from 'es-toolkit/compat'
import { memo, useCallback, useMemo, useState } from 'react'
@@ -16,6 +16,7 @@ import { useStore as useAppStore } from '@/app/components/app/store'
import Divider from '@/app/components/base/divider'
import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'
import FormItem from '@/app/components/workflow/nodes/_base/components/before-run-form/form-item'
+import { formatValue } from '@/app/components/workflow/nodes/_base/components/before-run-form/helpers'
import {
getNodeInfoById,
isConversationVar,
@@ -26,7 +27,7 @@ import { InputVarType, VarType } from '@/app/components/workflow/types'
import { useAppContext } from '@/context/app-context'
import { useMembers } from '@/service/use-common'
import { useTestEmailSender } from '@/service/use-workflow'
-import { isOutput } from '../../utils'
+import { getHumanInputFormDependencySelectors, isOutput } from '../../utils'
import EmailInput from './recipient/email-input'
const i18nPrefix = 'nodes.humanInput'
@@ -70,6 +71,45 @@ const getOriginVar = (valueSelector: string[], list: NodeOutPutVar[]) => {
return undefined
}
+const varTypeToInputVarType = (type: VarType) => {
+ if (type === VarType.number)
+ return InputVarType.number
+ if (type === VarType.boolean)
+ return InputVarType.checkbox
+ if ([VarType.object, VarType.array, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject].includes(type))
+ return InputVarType.json
+ if (type === VarType.file)
+ return InputVarType.singleFile
+ if (type === VarType.arrayFile)
+ return InputVarType.multiFiles
+
+ return InputVarType.textInput
+}
+
+const formatEmailSenderInputs = (
+ variables: Array<{ variable: string, type: InputVarType, label: unknown }>,
+ values: Record<string, unknown>,
+) => {
+ const formattedValues: Record<string, unknown> = {}
+ let parseErrorJsonField = ''
+
+ variables.forEach((variable) => {
+ try {
+ formattedValues[variable.variable] = formatValue(values[variable.variable], variable.type)
+ }
+ catch {
+ parseErrorJsonField = typeof variable.label === 'object' && variable.label !== null && 'variable' in variable.label
+ ? String(variable.label.variable)
+ : variable.variable
+ }
+ })
+
+ return {
+ formattedValues,
+ parseErrorJsonField,
+ }
+}
+
const EmailSenderModal = ({
nodeId,
deliveryId,
@@ -96,14 +136,9 @@ const EmailSenderModal = ({
const accounts = members?.accounts || []
const generatedInputs = useMemo(() => {
- const defaultValueSelectors = (formInputs || []).reduce((acc, input) => {
- if (input.default.type === 'variable') {
- acc.push(input.default.selector)
- }
- return acc
- }, [] as ValueSelector[])
+ const formInputDependencySelectors = getHumanInputFormDependencySelectors(formInputs || [])
const valueSelectors = doGetInputVars((formContent || '') + (config?.body || ''))
- const variables = unionBy([...valueSelectors, ...defaultValueSelectors], item => item.join('.')).map((item) => {
+ const variables = unionBy([...valueSelectors, ...formInputDependencySelectors], item => item.join('.')).map((item) => {
const varInfo = getNodeInfoById(availableNodes, item[0]!)?.data
return {
@@ -132,7 +167,7 @@ const EmailSenderModal = ({
return {
label: item.label || item.variable,
variable: item.variable,
- type: originalVar.type === VarType.number ? InputVarType.number : InputVarType.textInput,
+ type: varTypeToInputVarType(originalVar.type),
required: true,
}
})
@@ -166,20 +201,25 @@ const EmailSenderModal = ({
const handleConfirm = useCallback(async () => {
if (!confirmChecked)
return
+ const { formattedValues, parseErrorJsonField } = formatEmailSenderInputs(generatedInputs, inputs)
+ if (parseErrorJsonField) {
+ toast.error(t('errorMsg.invalidJson', { ns: 'workflow', field: parseErrorJsonField }))
+ return
+ }
setSendingEmail(true)
try {
await testEmailSender({
appID: appDetail?.id || '',
nodeID: nodeId,
deliveryID: deliveryId,
- inputs,
+ inputs: formattedValues,
})
setDone(true)
}
finally {
setSendingEmail(false)
}
- }, [confirmChecked, testEmailSender, appDetail?.id, nodeId, deliveryId, inputs])
+ }, [confirmChecked, generatedInputs, inputs, testEmailSender, appDetail?.id, nodeId, deliveryId, t])
if (done) {
return (
diff --git a/web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx b/web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx
index 73e88507897..abfe653f737 100644
--- a/web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx
@@ -38,6 +38,21 @@ const FormContentPreview: FC<FormContentPreviewProps> = ({
return node?.data.title || nodeId
}, [nodes])
+ const renderInputPreview = React.useCallback(({ node }: { node?: { properties?: Record<string, unknown> } }) => {
+ const name = String(node?.properties?.dataName ?? '')
+ const input = formInputs.find(i => i.output_variable_name === name)
+ if (!input) {
+ return (
+ <div>
+ Can't find note:
+ {name}
+ </div>
+ )
+ }
+
+ return <Note input={input} nodeName={nodeName} />
+ }, [formInputs, nodeName])
+
return (
<div
className="fixed top-[112px] z-10 max-h-[calc(100vh-116px)] w-[600px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg py-3 shadow-xl"
@@ -64,22 +79,7 @@ const FormContentPreview: FC<FormContentPreviewProps> = ({
}
return <Variable path={newPath} />
},
- section: ({ node }) => (() => {
- const name = String(node?.properties?.dataName ?? '')
- const input = formInputs.find(i => i.output_variable_name === name)
- if (!input) {
- return (
- <div>
- Can't find note:
- {name}
- </div>
- )
- }
- const defaultInput = input.default
- return (
- <Note defaultInput={defaultInput!} nodeName={nodeName} />
- )
- })(),
+ section: renderInputPreview,
}}
/>
<div className="mt-3 flex flex-wrap gap-1 py-1">
diff --git a/web/app/components/workflow/nodes/human-input/components/form-content.tsx b/web/app/components/workflow/nodes/human-input/components/form-content.tsx
index 8ee2a07fe87..7bfbe1492a4 100644
--- a/web/app/components/workflow/nodes/human-input/components/form-content.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/form-content.tsx
@@ -1,14 +1,15 @@
'use client'
-import type { LexicalCommand } from 'lexical'
import type { FC } from 'react'
import type { FormInputItem } from '../types'
+import type { ShortcutPopupInsertHandler } from '@/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin'
+import type { WorkflowNodesMap } from '@/app/components/base/prompt-editor/types'
import type { Node, NodeOutPutVar } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { Kbd } from '@langgenius/dify-ui/kbd'
import { formatForDisplay } from '@tanstack/react-hotkeys'
import { useBoolean } from 'ahooks'
import * as React from 'react'
-import { useEffect, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import PromptEditor from '@/app/components/base/prompt-editor'
import { INSERT_HITL_INPUT_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/hitl-input-block'
@@ -49,11 +50,20 @@ const FormContent: FC<FormContentProps> = ({
const getVarType = useWorkflowVariableType()
- const [needToAddFormInput, setNeedToAddFormInput] = useState(false)
- const [newFormInputs, setNewFormInputs] = useState<FormInputItem[]>([])
- const handleInsertHITLNode = (onInsert: (command: LexicalCommand<unknown>, params: any) => void) => {
+ const pendingFormInputsRef = useRef<{
+ value: string
+ formInputs: FormInputItem[]
+ } | null>(null)
+ const handleInsertHITLNode = useCallback((onInsert: ShortcutPopupInsertHandler) => {
return (payload: FormInputItem) => {
+ if (formInputs.some(input => input.output_variable_name === payload.output_variable_name))
+ return
+
const newFormInputs = [...(formInputs || []), payload]
+ pendingFormInputsRef.current = {
+ value,
+ formInputs: newFormInputs,
+ }
onInsert(INSERT_HITL_INPUT_BLOCK_COMMAND, {
variableName: payload.output_variable_name,
nodeId,
@@ -62,30 +72,37 @@ const FormContent: FC<FormContentProps> = ({
onFormInputItemRename,
onFormInputItemRemove,
})
- setNewFormInputs(newFormInputs)
- setNeedToAddFormInput(true)
}
- }
+ }, [
+ formInputs,
+ nodeId,
+ onFormInputsChange,
+ onFormInputItemRemove,
+ onFormInputItemRename,
+ value,
+ ])
// avoid update formInputs would overwrite the value just inserted
useEffect(() => {
- if (needToAddFormInput) {
- onFormInputsChange(newFormInputs)
- setNeedToAddFormInput(false)
- }
- }, [value])
+ const pendingFormInputs = pendingFormInputsRef.current
+ if (!pendingFormInputs || pendingFormInputs.value === value)
+ return
+
+ onFormInputsChange(pendingFormInputs.formInputs)
+ pendingFormInputsRef.current = null
+ }, [onFormInputsChange, value])
const [isFocus, {
setTrue: setFocus,
setFalse: setBlur,
}] = useBoolean(false)
- const workflowNodesMap = availableNodes.reduce((acc: any, node) => {
+ const workflowNodesMap = availableNodes.reduce<WorkflowNodesMap>((acc, node) => {
acc[node.id] = {
title: node.data.title,
type: node.data.type,
- width: node.width,
- height: node.height,
+ width: node.width ?? undefined,
+ height: node.height ?? undefined,
position: node.position,
}
if (node.data.type === BlockEnum.Start) {
@@ -96,6 +113,48 @@ const FormContent: FC<FormContentProps> = ({
}
return acc
}, {})
+ const unavailableVariableNames = useMemo(() => {
+ return formInputs.map(input => input.output_variable_name)
+ }, [formInputs])
+ const addInputFieldConfigRef = useRef({
+ nodeId,
+ unavailableVariableNames,
+ handleInsertHITLNode,
+ })
+ addInputFieldConfigRef.current = {
+ nodeId,
+ unavailableVariableNames,
+ handleInsertHITLNode,
+ }
+ const shortcutPopups = useMemo(() => {
+ if (readonly)
+ return []
+
+ return [{
+ hotkey: ['mod', '/'],
+ // Keep this component type stable while the popup is open; it reads fresh props from a ref.
+ // eslint-disable-next-line react/no-nested-component-definitions
+ Popup: ({ onClose, onInsert }: {
+ onClose: () => void
+ onInsert: ShortcutPopupInsertHandler
+ }) => {
+ const {
+ nodeId,
+ unavailableVariableNames,
+ handleInsertHITLNode,
+ } = addInputFieldConfigRef.current
+
+ return (
+ <AddInputField
+ nodeId={nodeId}
+ unavailableVariableNames={unavailableVariableNames}
+ onSave={handleInsertHITLNode(onInsert)}
+ onCancel={onClose}
+ />
+ )
+ },
+ }]
+ }, [readonly])
return (
<div
@@ -130,22 +189,11 @@ const FormContent: FC<FormContentProps> = ({
workflowVariableBlock={{
show: true,
variables: availableVars || [],
- getVarType: getVarType as any,
+ getVarType,
workflowNodesMap,
}}
editable={!readonly}
- shortcutPopups={readonly
- ? []
- : [{
- hotkey: ['mod', '/'],
- Popup: ({ onClose, onInsert }) => (
- <AddInputField
- nodeId={nodeId}
- onSave={handleInsertHITLNode(onInsert!)}
- onCancel={onClose}
- />
- ),
- }]}
+ shortcutPopups={shortcutPopups}
/>
</div>
{isFocus && (
diff --git a/web/app/components/workflow/nodes/human-input/components/single-run-form.tsx b/web/app/components/workflow/nodes/human-input/components/single-run-form.tsx
index 7dda8486171..c0d27bfb6d4 100644
--- a/web/app/components/workflow/nodes/human-input/components/single-run-form.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/single-run-form.tsx
@@ -1,5 +1,6 @@
'use client'
import type { ButtonProps } from '@langgenius/dify-ui/button'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import type { UserAction } from '@/app/components/workflow/nodes/human-input/types'
import type { HumanInputFormData } from '@/types/workflow'
import { Button } from '@langgenius/dify-ui/button'
@@ -9,14 +10,14 @@ import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import ContentItem from '@/app/components/base/chat/chat/answer/human-input-content/content-item'
-import { getButtonStyle, initializeInputs, splitByOutputVar } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
+import { getButtonStyle, getRenderedFormInputs, hasInvalidSelectOrFileInput, initializeInputs, splitByOutputVar } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
type Props = {
nodeName: string
data: HumanInputFormData
showBackButton?: boolean
handleBack?: () => void
- onSubmit?: ({ inputs, action }: { inputs: Record<string, string>, action: string }) => Promise<void>
+ onSubmit?: ({ inputs, action }: { inputs: Record<string, HumanInputFieldValue>, action: string }) => Promise<void>
}
const FormContent = ({
@@ -27,18 +28,21 @@ const FormContent = ({
onSubmit,
}: Props) => {
const { t } = useTranslation()
- const defaultInputs = initializeInputs(data.inputs, data.resolved_default_values || {})
const contentList = splitByOutputVar(data.form_content)
+ const renderedFormInputs = getRenderedFormInputs(data.inputs, data.form_content)
+ const defaultInputs = initializeInputs(renderedFormInputs, data.resolved_default_values || {})
const [inputs, setInputs] = useState(defaultInputs)
const [isSubmitting, setIsSubmitting] = useState(false)
- const handleInputsChange = (name: string, value: string) => {
+ const handleInputsChange = (name: string, value: HumanInputFieldValue) => {
setInputs(prev => ({
...prev,
[name]: value,
}))
}
+ const hasEmptySelectOrFileInput = hasInvalidSelectOrFileInput(renderedFormInputs, inputs)
+
const submit = async (actionID: string) => {
setIsSubmitting(true)
await onSubmit?.({ inputs, action: actionID })
@@ -75,7 +79,7 @@ const FormContent = ({
{data.actions.map((action: UserAction) => (
<Button
key={action.id}
- disabled={isSubmitting}
+ disabled={isSubmitting || hasEmptySelectOrFileInput}
variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
onClick={() => submit(action.id)}
>
diff --git a/web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx b/web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx
index d0d20ed5b53..23e211b912f 100644
--- a/web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx
@@ -1,5 +1,11 @@
-import type * as React from 'react'
-import type { FormInputItemDefault } from '../types'
+/* eslint-disable react-refresh/only-export-components */
+import type { FormInputItem } from '../types'
+import { cn } from '@langgenius/dify-ui/cn'
+import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger } from '@langgenius/dify-ui/select'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import { TransferMethod } from '@/types/app'
+import { isFileFormInput, isFileListFormInput, isSelectFormInput } from '../types'
const variableRegex = /\{\{#(.+?)#\}\}/g
const noteRegex = /\{\{#\$(.+?)#\}\}/g
@@ -87,6 +93,17 @@ const formatVariablePath = (path: string) => {
.replace('#}}', '}}')
}
+const sourceToVariablePath = (
+ source: { selector: string[] },
+ nodeName: (nodeId: string) => string,
+) => {
+ if (!source.selector.length)
+ return ''
+
+ const path = `{{#${source.selector.join('.')}#}}`
+ return replaceNodeIdsWithNames(path, nodeName)
+}
+
export function rehypeVariable() {
return (tree: MarkdownNode) => {
visitTextNodes(tree, (value) => {
@@ -132,13 +149,98 @@ export const Variable: React.FC<{ path: string }> = ({ path }) => {
)
}
-export const Note: React.FC<{ defaultInput: FormInputItemDefault, nodeName: (nodeId: string) => string }> = ({ defaultInput, nodeName }) => {
- const isVariable = defaultInput.type === 'variable'
- const path = `{{#${defaultInput.selector.join('.')}#}}`
- const newPath = path ? replaceNodeIdsWithNames(path, nodeName) : path
+const SelectPreview: React.FC<{ label: string, options: string[] }> = ({ label, options }) => {
+ const [value, setValue] = React.useState(options[0] || label)
+
+ return (
+ <div data-testid="human-input-note-select-preview" className="my-3">
+ <Select value={value} onValueChange={nextValue => nextValue && setValue(nextValue)}>
+ <SelectTrigger size="large" className="w-full rounded-[10px]" aria-label="human-input-note-select">
+ {value}
+ </SelectTrigger>
+ <SelectContent listClassName="max-h-[140px] overflow-y-auto">
+ {options.map(option => (
+ <SelectItem key={option} value={option}>
+ <SelectItemText>{option}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )
+}
+
+const FileUploadPreview: React.FC<{ methods: TransferMethod[], t: (key: string, options?: Record<string, unknown>) => string }> = ({ methods, t }) => {
+ const normalizedMethods = methods.length
+ ? methods
+ : [TransferMethod.local_file, TransferMethod.remote_url]
+ const actions = [
+ normalizedMethods.includes(TransferMethod.local_file) && {
+ iconClassName: 'i-ri-upload-cloud-2-line',
+ label: t('fileUploader.uploadFromComputer', { ns: 'common' }),
+ },
+ normalizedMethods.includes(TransferMethod.remote_url) && {
+ iconClassName: 'i-ri-link',
+ label: t('fileUploader.pasteFileLink', { ns: 'common' }),
+ },
+ ].filter(Boolean) as Array<{ iconClassName: string, label: string }>
+
+ return (
+ <div
+ data-testid="human-input-note-file-preview"
+ className={cn(
+ 'my-3 grid gap-2',
+ actions.length > 1 ? 'grid-cols-2' : 'grid-cols-1',
+ )}
+ >
+ {actions.map(action => (
+ <div
+ key={action.label}
+ className="flex h-10 items-center justify-center rounded-xl bg-components-input-bg-normal px-3"
+ >
+ <span className={cn('mr-2 size-5 shrink-0 text-text-tertiary', action.iconClassName)} />
+ <span className="truncate system-sm-medium text-text-tertiary">
+ {action.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ )
+}
+
+export const Note: React.FC<{ input: FormInputItem, nodeName: (nodeId: string) => string }> = ({ input, nodeName }) => {
+ const { t } = useTranslation()
+ if (isSelectFormInput(input)) {
+ const isVariable = input.option_source.type === 'variable'
+ if (isVariable) {
+ const variablePath = sourceToVariablePath(input.option_source, nodeName)
+ return (
+ <div className="my-3 rounded-[10px] bg-components-input-bg-normal px-2.5 py-2">
+ {variablePath
+ ? <Variable path={variablePath} />
+ : <span>{t('nodes.humanInput.insertInputField.variable', { ns: 'workflow' })}</span>}
+ </div>
+ )
+ }
+
+ const label = input.option_source.value[0] || t('variableConfig.select', { ns: 'appDebug' })
+ return <SelectPreview label={label} options={input.option_source.value} />
+ }
+
+ if (isFileFormInput(input)) {
+ return <FileUploadPreview methods={input.allowed_file_upload_methods} t={t} />
+ }
+
+ if (isFileListFormInput(input)) {
+ return <FileUploadPreview methods={input.allowed_file_upload_methods} t={t} />
+ }
+
+ const isVariable = input.default.type === 'variable'
+ const newPath = sourceToVariablePath(input.default, nodeName)
return (
<div className="my-3 rounded-[10px] bg-components-input-bg-normal px-2.5 py-2">
- {isVariable ? <Variable path={newPath} /> : <span>{defaultInput.value}</span>}
+ {isVariable ? <Variable path={newPath} /> : <span>{input.default.value}</span>}
</div>
)
}
diff --git a/web/app/components/workflow/nodes/human-input/default.ts b/web/app/components/workflow/nodes/human-input/default.ts
index 7e3d8d581e7..15b228bd732 100644
--- a/web/app/components/workflow/nodes/human-input/default.ts
+++ b/web/app/components/workflow/nodes/human-input/default.ts
@@ -1,8 +1,9 @@
import type { NodeDefault, Var } from '../../types'
-import type { HumanInputNodeType } from './types'
+import type { DeliveryMethod, EmailConfig, FormInputItem, HumanInputNodeType } from './types'
import { BlockClassificationEnum } from '@/app/components/workflow/block-selector/types'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
import { genNodeMetaData } from '@/app/components/workflow/utils'
+import { DeliveryMethodType } from './types'
const i18nPrefix = 'nodes.humanInput.errorMsg'
@@ -12,15 +13,46 @@ const metaData = genNodeMetaData({
type: BlockEnum.HumanInput,
})
-const buildOutputVars = (variables: string[]): Var[] => {
- return variables.map((variable) => {
+const getFormInputVarType = (input: FormInputItem): VarType => {
+ if (input.type === 'file')
+ return VarType.file
+
+ if (input.type === 'file-list')
+ return VarType.arrayFile
+
+ return VarType.string
+}
+
+const buildOutputVars = (inputs: FormInputItem[]): Var[] => {
+ return inputs.map((input) => {
return {
- variable,
- type: VarType.string,
+ variable: input.output_variable_name,
+ type: getFormInputVarType(input),
}
})
}
+const isEmailConfigComplete = (config?: EmailConfig): boolean => {
+ if (!config)
+ return false
+
+ if (!config.subject?.trim() || !config.body?.trim())
+ return false
+
+ if (!/\{\{#url#\}\}/.test(config.body.trim()))
+ return false
+
+ return !!config.recipients?.whole_workspace || !!config.recipients?.items?.length
+}
+
+const hasIncompleteEnabledEmailConfig = (deliveryMethods: DeliveryMethod[]): boolean => {
+ return deliveryMethods.some((method) => {
+ return method.enabled
+ && method.type === DeliveryMethodType.Email
+ && !isEmailConfigComplete(method.config)
+ })
+}
+
const nodeDefault: NodeDefault<HumanInputNodeType> = {
metaData,
defaultValue: {
@@ -39,6 +71,9 @@ const nodeDefault: NodeDefault<HumanInputNodeType> = {
if (!errorMessages && payload.delivery_methods.length > 0 && !payload.delivery_methods.some(method => method.enabled))
errorMessages = t(`${i18nPrefix}.noDeliveryMethodEnabled`, { ns: 'workflow' })
+ if (!errorMessages && hasIncompleteEnabledEmailConfig(payload.delivery_methods))
+ errorMessages = t(`${i18nPrefix}.emailConfigIncomplete`, { ns: 'workflow' })
+
if (!errorMessages && !payload.user_actions.length)
errorMessages = t(`${i18nPrefix}.noUserActions`, { ns: 'workflow' })
@@ -67,8 +102,7 @@ const nodeDefault: NodeDefault<HumanInputNodeType> = {
}
},
getOutputVars(payload, _allPluginInfoList, _ragVars) {
- const variables = payload.inputs.map(input => input.output_variable_name)
- return buildOutputVars(variables)
+ return buildOutputVars(payload.inputs)
},
}
diff --git a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.spec.ts b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.spec.ts
index c809e515954..f31c24ae613 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.spec.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.spec.ts
@@ -1,4 +1,4 @@
-import type { FormInputItem, HumanInputNodeType } from '../../types'
+import type { HumanInputNodeType, ParagraphFormInput } from '../../types'
import { act, renderHook } from '@testing-library/react'
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
import useFormContent from '../use-form-content'
@@ -15,8 +15,8 @@ vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({
default: (...args: unknown[]) => mockUseNodeCrud(...args),
}))
-const createFormInput = (overrides: Partial<FormInputItem> = {}): FormInputItem => ({
- type: InputVarType.textInput,
+const createFormInput = (overrides: Partial<ParagraphFormInput> = {}): ParagraphFormInput => ({
+ type: InputVarType.paragraph,
output_variable_name: 'old_name',
default: {
selector: [],
@@ -96,6 +96,26 @@ describe('human-input/use-form-content', () => {
expect(result.current.editorKey).toBe(1)
})
+ it('should not rename an input to an existing variable name', () => {
+ currentInputs = createPayload({
+ inputs: [
+ createFormInput(),
+ createFormInput({ output_variable_name: 'existing_name' }),
+ ],
+ })
+ const { result } = renderHook(() => useFormContent('human-input-node', currentInputs))
+
+ act(() => {
+ result.current.handleFormInputItemRename(createFormInput({
+ output_variable_name: 'existing_name',
+ }), 'old_name')
+ })
+
+ expect(mockSetInputs).not.toHaveBeenCalled()
+ expect(mockHandleOutVarRenameChange).not.toHaveBeenCalled()
+ expect(result.current.editorKey).toBe(0)
+ })
+
it('should remove an input placeholder and its form input metadata', () => {
const { result } = renderHook(() => useFormContent('human-input-node', currentInputs))
diff --git a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
index fa93c7d87ff..b984ee2b2fb 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
@@ -1,9 +1,10 @@
import type { HumanInputNodeType } from '../../types'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { InputVar } from '@/app/components/workflow/types'
import type { HumanInputFormData } from '@/types/workflow'
import { act, renderHook } from '@testing-library/react'
-import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
-import { AppModeEnum } from '@/types/app'
+import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { AppModeEnum, TransferMethod } from '@/types/app'
import useSingleRunFormParams from '../use-single-run-form-params'
const mockUseTranslation = vi.hoisted(() => vi.fn())
@@ -37,7 +38,7 @@ const createPayload = (overrides: Partial<HumanInputNodeType> = {}): HumanInputN
delivery_methods: [],
form_content: 'Summary: {{#start.topic#}}',
inputs: [{
- type: InputVarType.textInput,
+ type: InputVarType.paragraph,
output_variable_name: 'summary',
default: {
type: 'variable',
@@ -114,6 +115,28 @@ describe('human-input/hooks/use-single-run-form-params', () => {
mockSubmitHumanInputNodeStepRunForm.mockResolvedValue({})
})
+ const uploadedFile: FileEntity = {
+ id: 'file-1',
+ name: 'decision.pdf',
+ size: 128,
+ type: 'application/pdf',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ uploadedId: 'upload-file-1',
+ }
+
+ const remoteFile: FileEntity = {
+ id: 'file-2',
+ name: 'reference.pdf',
+ size: 256,
+ type: 'application/pdf',
+ progress: 100,
+ transferMethod: TransferMethod.remote_url,
+ supportFileType: 'document',
+ url: 'https://example.com/reference.pdf',
+ }
+
it('should build a single before-run form, filter output vars, and expose dependent vars', () => {
const { result } = renderHook(() => useSingleRunFormParams({
id: 'node-1',
@@ -147,7 +170,93 @@ describe('human-input/hooks/use-single-run-form-params', () => {
])
})
+ it('should include variables referenced by dynamic select option sources', () => {
+ currentInputs = createPayload({
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'summary',
+ default: {
+ type: 'variable',
+ selector: ['start', 'topic'],
+ value: '',
+ },
+ },
+ {
+ type: InputVarType.select,
+ output_variable_name: 'choice',
+ option_source: {
+ type: 'variable',
+ selector: ['start', 'choices'],
+ value: [],
+ },
+ },
+ ],
+ })
+ getInputVars.mockReturnValue([
+ createInputVar(),
+ createInputVar({
+ label: 'Choices',
+ variable: '#start.choices#',
+ value_selector: ['start', 'choices'],
+ }),
+ ])
+
+ const { result } = renderHook(() => useSingleRunFormParams({
+ id: 'node-1',
+ payload: currentInputs,
+ runInputData: {},
+ getInputVars,
+ setRunInputData: mockSetRunInputData,
+ }))
+
+ expect(getInputVars).toHaveBeenCalledWith([
+ '{{#start.topic#}}',
+ '{{#start.choices#}}',
+ 'Summary: {{#start.topic#}}',
+ ])
+ expect(result.current.forms[0]!.inputs).toEqual([
+ expect.objectContaining({ variable: '#start.topic#' }),
+ expect.objectContaining({ variable: '#start.choices#' }),
+ ])
+ expect(result.current.getDependentVars()).toEqual([
+ ['start', 'topic'],
+ ['start', 'choices'],
+ ])
+ })
+
it('should fetch and submit generated forms in workflow mode while keeping required inputs', async () => {
+ const formDataWithFiles = {
+ ...mockFormData,
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'answer',
+ default: {
+ type: 'constant',
+ selector: [],
+ value: '',
+ },
+ },
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'references',
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ number_limits: 3,
+ },
+ ],
+ } satisfies HumanInputFormData
+ mockFetchHumanInputNodeStepRunForm.mockResolvedValue(formDataWithFiles)
+
const { result } = renderHook(() => useSingleRunFormParams({
id: 'node-1',
payload: currentInputs,
@@ -170,11 +279,11 @@ describe('human-input/hooks/use-single-run-form-params', () => {
inputs: { topic: 'AI' },
},
)
- expect(result.current.formData).toEqual(mockFormData)
+ expect(result.current.formData).toEqual(formDataWithFiles)
await act(async () => {
await result.current.handleSubmitHumanInputForm({
- inputs: { answer: 'approved' },
+ inputs: { answer: 'approved', attachment: uploadedFile, references: [uploadedFile, remoteFile] },
form_inputs: { ignored: 'value' },
action: 'approve',
})
@@ -184,7 +293,29 @@ describe('human-input/hooks/use-single-run-form-params', () => {
'/apps/app-1/workflows/draft/human-input/nodes/node-1/form',
{
inputs: { topic: 'AI' },
- form_inputs: { answer: 'approved' },
+ form_inputs: {
+ answer: 'approved',
+ attachment: {
+ type: 'document',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ },
+ references: [
+ {
+ type: 'document',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ },
+ {
+ type: 'document',
+ transfer_method: TransferMethod.remote_url,
+ url: 'https://example.com/reference.pdf',
+ upload_file_id: '',
+ },
+ ],
+ },
action: 'approve',
},
)
diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-form-content.ts b/web/app/components/workflow/nodes/human-input/hooks/use-form-content.ts
index c1a75914373..476c814c16b 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/use-form-content.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/use-form-content.ts
@@ -29,6 +29,13 @@ const useFormContent = (id: string, payload: HumanInputNodeType) => {
const handleFormInputItemRename = useCallback((payload: FormInputItem, oldName: string) => {
const inputs = inputsRef.current
+ if (
+ oldName !== payload.output_variable_name
+ && inputs.inputs.some(item => item.output_variable_name === payload.output_variable_name)
+ ) {
+ return
+ }
+
const newInputs = produce(inputs, (draft) => {
draft.form_content = draft.form_content.replaceAll(`{{#$output.${oldName}#}}`, `{{#$output.${payload.output_variable_name}#}}`)
draft.inputs = draft.inputs.map(item => item.output_variable_name === oldName ? payload : item)
diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
index de7084390b3..db7f95de36a 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
@@ -1,14 +1,16 @@
import type { HumanInputNodeType } from '../types'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
import type { InputVar } from '@/app/components/workflow/types'
import type { HumanInputFormData } from '@/types/workflow'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore as useAppStore } from '@/app/components/app/store'
+import { getProcessedHumanInputFormInputs } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
import { fetchHumanInputNodeStepRunForm, submitHumanInputNodeStepRunForm } from '@/service/workflow'
import { AppModeEnum } from '@/types/app'
import useNodeCrud from '../../_base/hooks/use-node-crud'
-import { isOutput } from '../utils'
+import { getHumanInputFormDependencySelectors, isOutput } from '../utils'
const i18nPrefix = 'nodes.humanInput'
@@ -19,6 +21,7 @@ type Params = {
getInputVars: (textList: string[]) => InputVar[]
setRunInputData: (data: Record<string, string>) => void
}
+
const useSingleRunFormParams = ({
id,
payload,
@@ -32,13 +35,9 @@ const useSingleRunFormParams = ({
const [formData, setFormData] = useState<HumanInputFormData | null>(null)
const [requiredInputs, setRequiredInputs] = useState<Record<string, string>>({})
const generatedInputs = useMemo(() => {
- const defaultInputs = inputs.inputs.reduce((acc, input) => {
- if (input.default.type === 'variable') {
- acc.push(`{{#${input.default.selector.join('.')}#}}`)
- }
- return acc
- }, [] as string[])
- const allInputs = getInputVars([...defaultInputs, inputs.form_content || '']).filter(item => !isOutput(item.value_selector || []))
+ const formInputDependencyInputs = getHumanInputFormDependencySelectors(inputs.inputs)
+ .map(selector => `{{#${selector.join('.')}#}}`)
+ const allInputs = getInputVars([...formInputDependencyInputs, inputs.form_content || '']).filter(item => !isOutput(item.value_selector || []))
return allInputs
}, [getInputVars, inputs.form_content, inputs.inputs])
@@ -92,17 +91,19 @@ const useSingleRunFormParams = ({
return data
}, [fetchURL])
- const handleSubmitHumanInputForm = useCallback(async (formData: {
- inputs: Record<string, string> | undefined
- form_inputs: Record<string, string> | undefined
+ const handleSubmitHumanInputForm = useCallback(async (submission: {
+ inputs: Record<string, HumanInputFieldValue> | undefined
+ form_inputs: Record<string, HumanInputFieldValue> | undefined
action: string
}) => {
+ const formInputs = formData?.inputs?.length ? formData.inputs : inputs.inputs
+
await submitHumanInputNodeStepRunForm(fetchURL, {
inputs: requiredInputs,
- form_inputs: formData.inputs,
- action: formData.action,
+ form_inputs: getProcessedHumanInputFormInputs(formInputs, submission.inputs),
+ action: submission.action,
})
- }, [fetchURL, requiredInputs])
+ }, [fetchURL, formData?.inputs, inputs.inputs, requiredInputs])
const handleShowGeneratedForm = async (formValue: Record<string, string>) => {
setShowGeneratedForm(true)
diff --git a/web/app/components/workflow/nodes/human-input/panel.tsx b/web/app/components/workflow/nodes/human-input/panel.tsx
index 3c5c8e261ab..d157dc1558a 100644
--- a/web/app/components/workflow/nodes/human-input/panel.tsx
+++ b/web/app/components/workflow/nodes/human-input/panel.tsx
@@ -1,5 +1,5 @@
import type { FC } from 'react'
-import type { HumanInputNodeType } from './types'
+import type { FormInputItem, HumanInputNodeType } from './types'
import type { NodePanelProps, Var } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -34,6 +34,16 @@ import { UserActionButtonType } from './types'
const i18nPrefix = 'nodes.humanInput'
+const getOutputVarType = (input: FormInputItem): VarType => {
+ if (input.type === 'file')
+ return VarType.file
+
+ if (input.type === 'file-list')
+ return VarType.arrayFile
+
+ return VarType.string
+}
+
const Panel: FC<NodePanelProps<HumanInputNodeType>> = ({
id,
data,
@@ -59,7 +69,7 @@ const Panel: FC<NodePanelProps<HumanInputNodeType>> = ({
const { availableVars, availableNodesWithParent } = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: (varPayload: Var) => {
- return [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
+ return [VarType.string, VarType.number, VarType.secret, VarType.arrayString].includes(varPayload.type)
},
})
@@ -226,7 +236,7 @@ const Panel: FC<NodePanelProps<HumanInputNodeType>> = ({
<VarItem
key={input.output_variable_name}
name={input.output_variable_name}
- type={VarType.string}
+ type={getOutputVarType(input)}
description="Form input value"
/>
))
diff --git a/web/app/components/workflow/nodes/human-input/types.ts b/web/app/components/workflow/nodes/human-input/types.ts
index 128cfd8b98d..c066e0ada1a 100644
--- a/web/app/components/workflow/nodes/human-input/types.ts
+++ b/web/app/components/workflow/nodes/human-input/types.ts
@@ -1,8 +1,13 @@
import type {
CommonNodeType,
- InputVarType,
+ UploadFileSetting,
ValueSelector,
} from '@/app/components/workflow/types'
+import {
+ InputVarType,
+ SupportUploadFileTypes,
+} from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
export type HumanInputNodeType = CommonNodeType & {
delivery_methods: DeliveryMethod[]
@@ -59,14 +64,137 @@ export type UserAction = {
button_style: UserActionButtonType
}
-export type FormInputItemDefault = {
+type StringDefault = {
selector: ValueSelector
type: 'variable' | 'constant'
value: string
}
-export type FormInputItem = {
- type: InputVarType
+type StringListSource = {
+ selector: ValueSelector
+ type: 'variable' | 'constant'
+ value: string[]
+}
+
+// Preserve the old export during the transition to the new schema names.
+export type FormInputItemDefault = StringDefault
+
+type BaseFormInputItem = {
output_variable_name: string
- default: FormInputItemDefault
+}
+
+export type ParagraphFormInput = BaseFormInputItem & {
+ type: InputVarType.paragraph
+ default: StringDefault
+}
+
+export type SelectFormInput = BaseFormInputItem & {
+ type: InputVarType.select
+ option_source: StringListSource
+}
+
+type SharedFileFormInput = Pick<
+ UploadFileSetting,
+ 'allowed_file_extensions' | 'allowed_file_types' | 'allowed_file_upload_methods'
+>
+
+export type FileFormInput = BaseFormInputItem & SharedFileFormInput & {
+ type: InputVarType.singleFile
+}
+
+export type FileListFormInput = BaseFormInputItem & SharedFileFormInput & {
+ type: InputVarType.multiFiles
+ number_limits?: UploadFileSetting['number_limits']
+}
+
+export type FormInputItem
+ = | ParagraphFormInput
+ | SelectFormInput
+ | FileFormInput
+ | FileListFormInput
+
+export const isParagraphFormInput = (
+ input: FormInputItem,
+): input is ParagraphFormInput => {
+ return input.type === InputVarType.paragraph
+}
+
+export const isSelectFormInput = (
+ input: FormInputItem,
+): input is SelectFormInput => {
+ return input.type === InputVarType.select
+}
+
+export const isFileFormInput = (
+ input: FormInputItem,
+): input is FileFormInput => {
+ return input.type === InputVarType.singleFile
+}
+
+export const isFileListFormInput = (
+ input: FormInputItem,
+): input is FileListFormInput => {
+ return input.type === InputVarType.multiFiles
+}
+
+export const createDefaultParagraphFormInput = (
+ output_variable_name = '',
+): ParagraphFormInput => ({
+ type: InputVarType.paragraph,
+ output_variable_name,
+ default: {
+ type: 'constant',
+ selector: [],
+ value: '',
+ },
+})
+
+const createDefaultSelectFormInput = (
+ output_variable_name = '',
+): SelectFormInput => ({
+ type: InputVarType.select,
+ output_variable_name,
+ option_source: {
+ type: 'constant',
+ selector: [],
+ value: [],
+ },
+})
+
+const createDefaultFileFormInput = (
+ output_variable_name = '',
+): FileFormInput => ({
+ type: InputVarType.singleFile,
+ output_variable_name,
+ allowed_file_extensions: [],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+})
+
+const createDefaultFileListFormInput = (
+ output_variable_name = '',
+): FileListFormInput => ({
+ type: InputVarType.multiFiles,
+ output_variable_name,
+ allowed_file_extensions: [],
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ number_limits: 5,
+})
+
+export const createDefaultFormInputByType = (
+ type: FormInputItem['type'],
+ output_variable_name = '',
+): FormInputItem => {
+ switch (type) {
+ case InputVarType.select:
+ return createDefaultSelectFormInput(output_variable_name)
+ case InputVarType.singleFile:
+ return createDefaultFileFormInput(output_variable_name)
+ case InputVarType.multiFiles:
+ return createDefaultFileListFormInput(output_variable_name)
+ case InputVarType.paragraph:
+ default:
+ return createDefaultParagraphFormInput(output_variable_name)
+ }
}
diff --git a/web/app/components/workflow/nodes/human-input/utils.ts b/web/app/components/workflow/nodes/human-input/utils.ts
index 59358fab1eb..6b032430bf7 100644
--- a/web/app/components/workflow/nodes/human-input/utils.ts
+++ b/web/app/components/workflow/nodes/human-input/utils.ts
@@ -1,3 +1,19 @@
+import type { FormInputItem } from './types'
+import type { ValueSelector } from '@/app/components/workflow/types'
+import { isParagraphFormInput, isSelectFormInput } from './types'
+
export const isOutput = (valueSelector: string[]) => {
return valueSelector[0] === '$output'
}
+
+export const getHumanInputFormDependencySelectors = (inputs: FormInputItem[]): ValueSelector[] => {
+ return inputs.flatMap((input) => {
+ if (isParagraphFormInput(input) && input.default.type === 'variable' && input.default.selector.length > 0)
+ return [input.default.selector]
+
+ if (isSelectFormInput(input) && input.option_source.type === 'variable' && input.option_source.selector.length > 0)
+ return [input.option_source.selector]
+
+ return []
+ })
+}
diff --git a/web/app/components/workflow/panel/__tests__/human-input-filled-form-list.spec.tsx b/web/app/components/workflow/panel/__tests__/human-input-filled-form-list.spec.tsx
index e3d0557180f..4a77e71705b 100644
--- a/web/app/components/workflow/panel/__tests__/human-input-filled-form-list.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/human-input-filled-form-list.spec.tsx
@@ -9,6 +9,9 @@ const createFilledForm = (overrides: Partial<HumanInputFilledFormData> = {}): Hu
rendered_content: 'Approved by Alice',
action_id: 'approve',
action_text: 'Approve',
+ submitted_data: {
+ summary: 'Approved by Alice',
+ },
...overrides,
})
@@ -33,11 +36,13 @@ describe('HumanInputFilledFormList', () => {
expect(screen.getByText('Approval'))!.toBeInTheDocument()
expect(screen.getByText('Review'))!.toBeInTheDocument()
- expect(screen.getAllByTestId('submitted-content')).toHaveLength(2)
+ expect(screen.getAllByTestId('submitted-field-values')).toHaveLength(2)
expect(screen.getAllByTestId('executed-action')).toHaveLength(2)
+ expect(screen.getAllByTestId('submitted-field-summary')).toHaveLength(2)
+ expect(screen.getAllByTestId('submitted-field-summary')[0]).toHaveTextContent('Approved by Alice')
await user.click(screen.getAllByTestId('expand-icon')[0]!)
- expect(screen.getAllByTestId('submitted-content')).toHaveLength(1)
+ expect(screen.getAllByTestId('submitted-field-values')).toHaveLength(1)
})
})
diff --git a/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx b/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
index 63ee0ceb37b..a3d629d1708 100644
--- a/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
@@ -1,4 +1,5 @@
import type { Shape } from '../../store/workflow'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'
import { toast } from '@langgenius/dify-ui/toast'
import { fireEvent, screen, waitFor } from '@testing-library/react'
@@ -84,11 +85,11 @@ vi.mock('@/app/components/workflow/panel/human-input-form-list', () => ({
onHumanInputFormSubmit,
}: {
humanInputFormDataList: unknown[]
- onHumanInputFormSubmit?: (token: string, formData: Record<string, string>) => Promise<void>
+ onHumanInputFormSubmit?: (token: string, formData: { inputs: Record<string, HumanInputFieldValue>, action: string }) => Promise<void>
}) => (
<div>
<div data-testid="human-form-list">{humanInputFormDataList.length}</div>
- <button type="button" onClick={() => onHumanInputFormSubmit?.('form-token', { answer: 'ok' })}>
+ <button type="button" onClick={() => onHumanInputFormSubmit?.('form-token', { inputs: { answer: 'ok' }, action: 'approve' })}>
submit-human-form
</button>
</div>
@@ -236,7 +237,7 @@ describe('WorkflowPreview', () => {
expect(screen.getByTestId('filled-form-list')).toHaveTextContent('1')
await user.click(screen.getByRole('button', { name: 'submit-human-form' }))
- expect(mockSubmitHumanInputForm).toHaveBeenCalledWith('form-token', { answer: 'ok' })
+ expect(mockSubmitHumanInputForm).toHaveBeenCalledWith('form-token', { inputs: { answer: 'ok' }, action: 'approve' })
})
it('should copy successful string output and show a success toast', async () => {
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx
index 20a47d545c1..2167e7c411b 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx
@@ -1,4 +1,5 @@
import type { ChatWrapperRefType } from '../index'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useStore as useAppStore } from '@/app/components/app/store'
@@ -37,7 +38,7 @@ vi.mock('@/app/components/base/chat/chat', () => ({
onSend?: (message: string, files: unknown[]) => void
onRegenerate?: (chatItem: { id: string, parentMessageId?: string, content?: string, message_files?: unknown[] }) => void
switchSibling?: (siblingMessageId: string) => void
- onHumanInputFormSubmit?: (formToken: string, formData: Record<string, string>) => Promise<void>
+ onHumanInputFormSubmit?: (formToken: string, formData: { inputs: Record<string, HumanInputFieldValue>, action: string }) => Promise<void>
onFeatureBarClick?: (state: boolean) => void
}) => (
<div data-testid="chat-shell">
@@ -55,7 +56,7 @@ vi.mock('@/app/components/base/chat/chat', () => ({
regenerate-chat
</button>
<button type="button" onClick={() => switchSibling?.('sibling-2')}>switch-sibling</button>
- <button type="button" onClick={() => onHumanInputFormSubmit?.('token-1', { answer: 'ok' })}>submit-human-input</button>
+ <button type="button" onClick={() => onHumanInputFormSubmit?.('token-1', { inputs: { answer: 'ok' }, action: 'approve' })}>submit-human-input</button>
<button type="button" onClick={() => onFeatureBarClick?.(true)}>open-feature-panel</button>
{chatNode}
</div>
@@ -296,7 +297,7 @@ describe('ChatWrapper', () => {
await user.click(screen.getByRole('button', { name: 'submit-human-input' }))
await waitFor(() => {
- expect(handleSubmitHumanInputForm).toHaveBeenCalledWith('token-1', { answer: 'ok' })
+ expect(handleSubmitHumanInputForm).toHaveBeenCalledWith('token-1', { inputs: { answer: 'ok' }, action: 'approve' })
})
const subscription = mockUseSubscription.mock.calls[0]?.[0] as (payload: { type: string }) => void
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx
index b7ab773836e..13d9108c636 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx
@@ -1,4 +1,5 @@
import type { ChatWrapperRefType } from '../index'
+import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import type { ConversationVariable } from '@/app/components/workflow/types'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -78,7 +79,7 @@ vi.mock('@/app/components/base/chat/chat', () => ({
onSend?: (message: string, files: unknown[]) => void
onRegenerate?: (chatItem: { id: string, parentMessageId?: string, content?: string, message_files?: unknown[] }) => void
switchSibling?: (siblingMessageId: string) => void
- onHumanInputFormSubmit?: (formToken: string, formData: Record<string, string>) => Promise<void>
+ onHumanInputFormSubmit?: (formToken: string, formData: { inputs: Record<string, HumanInputFieldValue>, action: string }) => Promise<void>
onFeatureBarClick?: (state: boolean) => void
}) => {
mockChatRender({
@@ -101,7 +102,7 @@ vi.mock('@/app/components/base/chat/chat', () => ({
regenerate-chat
</button>
<button type="button" onClick={() => switchSibling?.('sibling-2')}>switch-sibling</button>
- <button type="button" onClick={() => onHumanInputFormSubmit?.('token-1', { answer: 'ok' })}>submit-human-input</button>
+ <button type="button" onClick={() => onHumanInputFormSubmit?.('token-1', { inputs: { answer: 'ok' }, action: 'approve' })}>submit-human-input</button>
<button type="button" onClick={() => onFeatureBarClick?.(true)}>open-feature-panel</button>
{chatNode}
</div>
@@ -593,7 +594,7 @@ describe('debug-and-preview components', () => {
await user.click(screen.getByRole('button', { name: 'submit-human-input' }))
await waitFor(() => {
- expect(handleSubmitHumanInputForm).toHaveBeenCalledWith('token-1', { answer: 'ok' })
+ expect(handleSubmitHumanInputForm).toHaveBeenCalledWith('token-1', { inputs: { answer: 'ok' }, action: 'approve' })
})
const stopResponding = mockUseChat.mock.calls[0]?.[3] as (taskId: string) => void
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts
index 9a2b8a8df7f..223a4d769c0 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts
@@ -126,10 +126,10 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat({}))
await act(async () => {
- await result.current.handleSubmitHumanInputForm('token-123', { field: 'value' })
+ await result.current.handleSubmitHumanInputForm('token-123', { inputs: { field: 'value' }, action: 'approve' })
})
- expect(mockSubmitHumanInputForm).toHaveBeenCalledWith('token-123', { field: 'value' })
+ expect(mockSubmitHumanInputForm).toHaveBeenCalledWith('token-123', { inputs: { field: 'value' }, action: 'approve' })
expect(submitHumanInputForm).toBeDefined()
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts
index 5a608dcc5b1..603db4df80a 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts
@@ -782,7 +782,7 @@ describe('useChat – handleResume', () => {
act(() => {
capturedResumeOptions.onHumanInputFormFilled({
- data: { node_id: 'rn-human', form_data: { a: 1 } },
+ data: { node_id: 'rn-human', submitted_data: { a: 1 } },
})
})
@@ -796,7 +796,7 @@ describe('useChat – handleResume', () => {
act(() => {
capturedResumeOptions.onHumanInputFormFilled({
- data: { node_id: 'rn-human', form_data: { b: 2 } },
+ data: { node_id: 'rn-human', submitted_data: { b: 2 } },
})
})
@@ -937,7 +937,7 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData
act(() => {
capturedResumeOptions.onHumanInputFormFilled({
- data: { node_id: 'hn-bare', form_data: { x: 1 } },
+ data: { node_id: 'hn-bare', submitted_data: { x: 1 } },
})
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
index cd2eaa0e007..a4bd20ef9d0 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
@@ -228,10 +228,10 @@ describe('useChat – handleSubmitHumanInputForm', () => {
const { result } = renderHook(() => useChat({}))
await act(async () => {
- await result.current.handleSubmitHumanInputForm('token-123', { field: 'value' })
+ await result.current.handleSubmitHumanInputForm('token-123', { inputs: { field: 'value' }, action: 'approve' })
})
- expect(mockSubmitHumanInputForm).toHaveBeenCalledWith('token-123', { field: 'value' })
+ expect(mockSubmitHumanInputForm).toHaveBeenCalledWith('token-123', { inputs: { field: 'value' }, action: 'approve' })
})
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts
index f8f3a02c5c9..a67165fba64 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts
@@ -784,7 +784,7 @@ describe('useChat – handleSend SSE callbacks', () => {
act(() => {
capturedCallbacks.onHumanInputRequired({
- data: { node_id: 'human-node', form_token: 'token-1' },
+ data: { node_id: 'human-node', form_token: 'token-1', form_content: '{{#$output.answer#}}', inputs: [] },
})
})
@@ -801,7 +801,7 @@ describe('useChat – handleSend SSE callbacks', () => {
act(() => {
capturedCallbacks.onHumanInputRequired({
- data: { node_id: 'human-node', form_token: 'token-1' },
+ data: { node_id: 'human-node', form_token: 'token-1', form_content: '{{#$output.answer#}}', inputs: [] },
})
})
@@ -862,13 +862,13 @@ describe('useChat – handleSend SSE callbacks', () => {
act(() => {
capturedCallbacks.onHumanInputRequired({
- data: { node_id: 'human-node', form_token: 'token-1' },
+ data: { node_id: 'human-node', form_token: 'token-1', form_content: '{{#$output.answer#}}', inputs: [] },
})
})
act(() => {
capturedCallbacks.onHumanInputFormFilled({
- data: { node_id: 'human-node', form_data: { answer: 'yes' } },
+ data: { node_id: 'human-node', submitted_data: { answer: 'yes' } },
})
})
@@ -876,7 +876,11 @@ describe('useChat – handleSend SSE callbacks', () => {
expect(answer!.humanInputFormDataList).toHaveLength(0)
expect(answer!.humanInputFilledFormDataList).toHaveLength(1)
expect(answer!.humanInputFilledFormDataList![0]!.node_id).toBe('human-node')
- expect((answer!.humanInputFilledFormDataList![0] as any).form_data).toEqual({ answer: 'yes' })
+ expect(answer!.humanInputFilledFormDataList![0]!.submitted_data).toEqual({ answer: 'yes' })
+ expect(answer!.humanInputFilledFormDataList![0]).toEqual(expect.objectContaining({
+ form_content: '{{#$output.answer#}}',
+ inputs: [],
+ }))
})
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx
index 33ae66eebce..0829f605421 100644
--- a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx
@@ -1,5 +1,6 @@
import type { StartNodeType } from '../../nodes/start/types'
import type { ChatWrapperRefType } from './index'
+import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import type { ChatItem, OnSend } from '@/app/components/base/chat/types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { memo, useCallback, useEffect, useImperativeHandle, useMemo } from 'react'
@@ -129,8 +130,7 @@ const ChatWrapper = (
})
}, [handleSwitchSibling, appDetail])
- const doHumanInputFormSubmit = useCallback(async (formToken: string, formData: any) => {
- // Handle human input form submission
+ const doHumanInputFormSubmit = useCallback(async (formToken: string, formData: HumanInputFormSubmitData) => {
await handleSubmitHumanInputForm(formToken, formData)
}, [handleSubmitHumanInputForm])
diff --git a/web/app/components/workflow/panel/debug-and-preview/hooks.ts b/web/app/components/workflow/panel/debug-and-preview/hooks.ts
index a94e4c1edd0..24f643ec870 100644
--- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts
@@ -1,3 +1,4 @@
+import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import type { InputForm } from '@/app/components/base/chat/chat/type'
import type {
ChatItem,
@@ -18,6 +19,7 @@ import {
} from 'react'
import { useTranslation } from 'react-i18next'
import { useStoreApi } from 'reactflow'
+import { enrichSubmittedHumanInputFormData } from '@/app/components/base/chat/chat/answer/human-input-content/submitted-utils'
import {
getProcessedInputs,
processOpeningStatement,
@@ -618,15 +620,20 @@ export const useChat = (
}
},
onHumanInputFormFilled: ({ data }) => {
+ let requiredFormData: NonNullable<ChatItem['humanInputFormDataList']>[number] | undefined
if (responseItem.humanInputFormDataList?.length) {
const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
- responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ if (currentFormIndex > -1) {
+ requiredFormData = responseItem.humanInputFormDataList[currentFormIndex]
+ responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
}
+ const enrichedData = enrichSubmittedHumanInputFormData(data, requiredFormData)
if (!responseItem.humanInputFilledFormDataList) {
- responseItem.humanInputFilledFormDataList = [data]
+ responseItem.humanInputFilledFormDataList = [enrichedData]
}
else {
- responseItem.humanInputFilledFormDataList.push(data)
+ responseItem.humanInputFilledFormDataList.push(enrichedData)
}
updateCurrentQAOnTree({
placeholderQuestionId,
@@ -660,7 +667,7 @@ export const useChat = (
)
}, [threadMessages, chatTree.length, updateCurrentQAOnTree, handleResponding, formSettings?.inputsForm, handleRun, t, workflowStore, fetchInspectVars, invalidAllLastRun, config?.suggested_questions_after_answer?.enabled])
- const handleSubmitHumanInputForm = async (formToken: string, formData: any) => {
+ const handleSubmitHumanInputForm = async (formToken: string, formData: HumanInputFormSubmitData) => {
await submitHumanInputForm(formToken, formData)
}
@@ -885,16 +892,20 @@ export const useChat = (
},
onHumanInputFormFilled: ({ data: humanInputFilledFormData }) => {
updateChatTreeNode(messageId, (responseItem) => {
+ let requiredFormData: NonNullable<ChatItem['humanInputFormDataList']>[number] | undefined
if (responseItem.humanInputFormDataList?.length) {
const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputFilledFormData.node_id)
- if (currentFormIndex > -1)
+ if (currentFormIndex > -1) {
+ requiredFormData = responseItem.humanInputFormDataList[currentFormIndex]
responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
}
+ const enrichedHumanInputFilledFormData = enrichSubmittedHumanInputFormData(humanInputFilledFormData, requiredFormData)
if (!responseItem.humanInputFilledFormDataList) {
- responseItem.humanInputFilledFormDataList = [humanInputFilledFormData]
+ responseItem.humanInputFilledFormDataList = [enrichedHumanInputFilledFormData]
}
else {
- responseItem.humanInputFilledFormDataList.push(humanInputFilledFormData)
+ responseItem.humanInputFilledFormDataList.push(enrichedHumanInputFilledFormData)
}
})
},
diff --git a/web/app/components/workflow/panel/workflow-preview.tsx b/web/app/components/workflow/panel/workflow-preview.tsx
index 298c5345638..2c9300f8476 100644
--- a/web/app/components/workflow/panel/workflow-preview.tsx
+++ b/web/app/components/workflow/panel/workflow-preview.tsx
@@ -1,3 +1,4 @@
+import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { toast } from '@langgenius/dify-ui/toast'
@@ -97,7 +98,7 @@ const WorkflowPreview = () => {
}
}, [resize, stopResizing])
- const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: any) => {
+ const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: HumanInputFormSubmitData) => {
await submitHumanInputForm(formToken, formData)
}, [])
diff --git a/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsx b/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsx
index bba17a7c32c..e955a0e465a 100644
--- a/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsx
+++ b/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsx
@@ -38,6 +38,7 @@ vi.mock('@/app/components/workflow/nodes/llm/components/json-schema-config-modal
vi.mock('@/next/navigation', () => ({
useParams: () => ({ token: '' }),
+ usePathname: () => '/',
}))
describe('value-content sections', () => {
diff --git a/web/i18n/en-US/workflow.json b/web/i18n/en-US/workflow.json
index 4083f6b3cbb..4ff5babd929 100644
--- a/web/i18n/en-US/workflow.json
+++ b/web/i18n/en-US/workflow.json
@@ -614,6 +614,7 @@
"nodes.humanInput.deliveryMethod.upgradeTipHide": "Dismiss",
"nodes.humanInput.editor.previewTip": "In preview mode, action buttons are not functional.",
"nodes.humanInput.errorMsg.duplicateActionId": "Duplicate action ID found in user actions",
+ "nodes.humanInput.errorMsg.emailConfigIncomplete": "Please complete the Email delivery method configuration",
"nodes.humanInput.errorMsg.emptyActionId": "Action ID cannot be empty",
"nodes.humanInput.errorMsg.emptyActionTitle": "Action title cannot be empty",
"nodes.humanInput.errorMsg.noDeliveryMethod": "Please select at least one delivery method",
@@ -624,7 +625,10 @@
"nodes.humanInput.formContent.preview": "Preview",
"nodes.humanInput.formContent.title": "Form Content",
"nodes.humanInput.formContent.tooltip": "What users will see after opening the form. Supports Markdown formatting.",
+ "nodes.humanInput.insertInputField.fieldType": "Field Type",
"nodes.humanInput.insertInputField.insert": "Insert",
+ "nodes.humanInput.insertInputField.maxUploads": "Max uploads",
+ "nodes.humanInput.insertInputField.options": "Options",
"nodes.humanInput.insertInputField.prePopulateField": "Pre-populate Field",
"nodes.humanInput.insertInputField.prePopulateFieldPlaceholder": "Add <staticContent/> or <variable/> users will see this content initially, or leave empty.",
"nodes.humanInput.insertInputField.saveResponseAs": "Save Response As",
@@ -634,6 +638,7 @@
"nodes.humanInput.insertInputField.useConstantInstead": "Use Constant Instead",
"nodes.humanInput.insertInputField.useVarInstead": "Use Variable Instead",
"nodes.humanInput.insertInputField.variable": "variable",
+ "nodes.humanInput.insertInputField.variableNameDuplicated": "Variable name already exists",
"nodes.humanInput.insertInputField.variableNameInvalid": "Variable name can only contain letters, numbers, and underscores, and cannot start with a number",
"nodes.humanInput.log.backstageInputURL": "Backstage input URL:",
"nodes.humanInput.log.reason": "Reason:",
diff --git a/web/i18n/zh-Hans/workflow.json b/web/i18n/zh-Hans/workflow.json
index c24c4b2ece9..9d8da449d83 100644
--- a/web/i18n/zh-Hans/workflow.json
+++ b/web/i18n/zh-Hans/workflow.json
@@ -614,6 +614,7 @@
"nodes.humanInput.deliveryMethod.upgradeTipHide": "关闭",
"nodes.humanInput.editor.previewTip": "在预览模式下,操作按钮无法使用。",
"nodes.humanInput.errorMsg.duplicateActionId": "用户操作中存在重复的操作 ID",
+ "nodes.humanInput.errorMsg.emailConfigIncomplete": "请完成 Email 提交方式配置",
"nodes.humanInput.errorMsg.emptyActionId": "操作 ID 不能为空",
"nodes.humanInput.errorMsg.emptyActionTitle": "操作标题不能为空",
"nodes.humanInput.errorMsg.noDeliveryMethod": "请至少选择一种提交方式",
@@ -624,7 +625,10 @@
"nodes.humanInput.formContent.preview": "预览",
"nodes.humanInput.formContent.title": "表单内容",
"nodes.humanInput.formContent.tooltip": "用户打开表单后看到的内容。支持 Markdown 格式。",
+ "nodes.humanInput.insertInputField.fieldType": "字段类型",
"nodes.humanInput.insertInputField.insert": "插入",
+ "nodes.humanInput.insertInputField.maxUploads": "最大上传数",
+ "nodes.humanInput.insertInputField.options": "选项",
"nodes.humanInput.insertInputField.prePopulateField": "预填充字段",
"nodes.humanInput.insertInputField.prePopulateFieldPlaceholder": "添加 <staticContent/> 或 <variable/> 用户将最初看到此内容,或留空。",
"nodes.humanInput.insertInputField.saveResponseAs": "保存响应为",
@@ -634,6 +638,7 @@
"nodes.humanInput.insertInputField.useConstantInstead": "使用常量代替",
"nodes.humanInput.insertInputField.useVarInstead": "使用变量代替",
"nodes.humanInput.insertInputField.variable": "变量",
+ "nodes.humanInput.insertInputField.variableNameDuplicated": "变量名已存在",
"nodes.humanInput.insertInputField.variableNameInvalid": "只能包含字母、数字和下划线,且不能以数字开头",
"nodes.humanInput.log.backstageInputURL": "表单输入 URL:",
"nodes.humanInput.log.reason": "原因:",
diff --git a/web/service/__tests__/share-human-input-upload.spec.ts b/web/service/__tests__/share-human-input-upload.spec.ts
new file mode 100644
index 00000000000..18478410614
--- /dev/null
+++ b/web/service/__tests__/share-human-input-upload.spec.ts
@@ -0,0 +1,116 @@
+const mockPostPublic = vi.hoisted(() => vi.fn())
+const mockUpload = vi.hoisted(() => vi.fn())
+
+vi.mock('../base', () => ({
+ del: vi.fn(),
+ get: vi.fn(),
+ patch: vi.fn(),
+ post: vi.fn(),
+ delPublic: vi.fn(),
+ getPublic: vi.fn(),
+ patchPublic: vi.fn(),
+ postPublic: (...args: unknown[]) => mockPostPublic(...args),
+ ssePost: vi.fn(),
+ upload: (...args: unknown[]) => mockUpload(...args),
+}))
+
+vi.mock('../webapp-auth', () => ({
+ getWebAppAccessToken: vi.fn(),
+}))
+
+describe('human input form upload services', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-05-06T00:00:00Z'))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('should fetch upload token before local file upload', async () => {
+ const { uploadHumanInputFormLocalFile } = await import('../share')
+ const file = new File(['content'], 'test.txt', { type: 'text/plain' })
+ const onProgressCallback = vi.fn()
+ const onSuccessCallback = vi.fn()
+ const onErrorCallback = vi.fn()
+
+ mockPostPublic.mockResolvedValueOnce({
+ upload_token: 'hitl-upload-token',
+ expires_at: Math.floor(Date.now() / 1000) + 60,
+ })
+ mockUpload.mockResolvedValueOnce({
+ id: 'file-1',
+ name: 'test.txt',
+ size: 7,
+ extension: 'txt',
+ mime_type: 'text/plain',
+ created_by: 'actor-1',
+ created_at: Math.floor(Date.now() / 1000),
+ preview_url: null,
+ source_url: 'https://example.com/file-preview',
+ })
+
+ await uploadHumanInputFormLocalFile({
+ formToken: 'local-form-token',
+ file,
+ onProgressCallback,
+ onSuccessCallback,
+ onErrorCallback,
+ })
+
+ expect(mockPostPublic).toHaveBeenCalledWith('/form/human_input/local-form-token/upload-token')
+ expect(mockUpload).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.any(FormData),
+ headers: {
+ Authorization: 'bearer hitl-upload-token',
+ },
+ }),
+ true,
+ '/human-input-forms/files',
+ )
+ expect(onSuccessCallback).toHaveBeenCalledWith(expect.objectContaining({ id: 'file-1' }))
+ expect(onErrorCallback).not.toHaveBeenCalled()
+ })
+
+ it('should fetch upload token before remote file upload', async () => {
+ const { uploadHumanInputFormRemoteFileInfo } = await import('../share')
+
+ mockPostPublic
+ .mockResolvedValueOnce({
+ upload_token: 'hitl-remote-token',
+ expires_at: Math.floor(Date.now() / 1000) + 60,
+ })
+ mockUpload.mockResolvedValueOnce({
+ id: 'remote-file-1',
+ name: 'remote.txt',
+ size: 10,
+ extension: 'txt',
+ mime_type: 'text/plain',
+ created_by: 'actor-1',
+ created_at: Math.floor(Date.now() / 1000),
+ url: 'https://example.com/remote.txt',
+ })
+
+ const response = await uploadHumanInputFormRemoteFileInfo('remote-form-token', 'https://example.com/file.txt')
+
+ expect(mockPostPublic).toHaveBeenCalledTimes(1)
+ expect(mockPostPublic).toHaveBeenNthCalledWith(1, '/form/human_input/remote-form-token/upload-token')
+ expect(mockUpload).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.any(FormData),
+ headers: {
+ Authorization: 'bearer hitl-remote-token',
+ },
+ }),
+ true,
+ '/human-input-forms/files',
+ )
+ const uploadCall = mockUpload.mock.calls[0]
+ const formData = uploadCall?.[0]?.data as FormData
+ expect(formData.get('url')).toBe('https://example.com/file.txt')
+ expect(response).toEqual(expect.objectContaining({ id: 'remote-file-1' }))
+ })
+})
diff --git a/web/service/fetch.ts b/web/service/fetch.ts
index 34bd07160a3..bca302ca4b4 100644
--- a/web/service/fetch.ts
+++ b/web/service/fetch.ts
@@ -60,7 +60,7 @@ const createResponseFromHTTPError = (error: HTTPError): Response => {
const afterResponseErrorCode = (otherOptions: IOtherOptions): AfterResponseHook => {
return async ({ response }) => {
- if (!/^([23])\d{2}$/.test(String(response.status))) {
+ if (!/^[23]\d{2}$/.test(String(response.status))) {
let errorData: ResponseError | null = null
try {
const data: unknown = await response.clone().json()
@@ -101,11 +101,13 @@ const resolveShareCode = () => {
}
const beforeRequestPublicWithCode: BeforeRequestHook = ({ request }) => {
- const accessToken = getWebAppAccessToken()
- if (accessToken)
- request.headers.set('Authorization', `Bearer ${accessToken}`)
- else
- request.headers.delete('Authorization')
+ if (!request.headers.has('Authorization')) {
+ const accessToken = getWebAppAccessToken()
+ if (accessToken)
+ request.headers.set('Authorization', `Bearer ${accessToken}`)
+ else
+ request.headers.delete('Authorization')
+ }
const shareCode = resolveShareCode()
if (!shareCode)
return
diff --git a/web/service/share.ts b/web/service/share.ts
index de0adb2be26..732e32eff1a 100644
--- a/web/service/share.ts
+++ b/web/service/share.ts
@@ -26,6 +26,7 @@ import {
patchPublic as patch,
postPublic as post,
ssePost,
+ upload,
} from './base'
import { getWebAppAccessToken } from './webapp-auth'
@@ -274,8 +275,117 @@ export const getHumanInputForm = (token: string) => {
return get<HumanInputFormData>(`/form/human_input/${token}`)
}
+type HumanInputFormUploadTokenResponse = {
+ upload_token: string
+ expires_at: number
+}
+
+type HumanInputFormLocalFileUploadResponse = {
+ created_at: number
+ created_by: string
+ extension: string
+ id: string
+ mime_type: string
+ name: string
+ preview_url: string | null
+ size: number
+ source_url: string
+}
+
+type HumanInputFormRemoteFileUploadResponse = {
+ created_at: number
+ created_by: string
+ extension: string
+ id: string
+ mime_type: string
+ name: string
+ size: number
+ url: string
+}
+
+type HumanInputFormLocalFileUploadParams = {
+ formToken: string
+ file: File
+ onProgressCallback: (progress: number) => void
+ onSuccessCallback: (res: HumanInputFormLocalFileUploadResponse) => void
+ onErrorCallback: (error?: unknown) => void
+}
+
+const humanInputFormUploadTokenCache = new Map<string, HumanInputFormUploadTokenResponse>()
+const UPLOAD_TOKEN_REFRESH_BUFFER_SECONDS = 30
+
+const getHumanInputFormUploadToken = async (formToken: string) => {
+ const cachedToken = humanInputFormUploadTokenCache.get(formToken)
+ const now = Math.floor(Date.now() / 1000)
+
+ if (cachedToken && cachedToken.expires_at > now + UPLOAD_TOKEN_REFRESH_BUFFER_SECONDS)
+ return cachedToken.upload_token
+
+ const tokenResponse = await post<HumanInputFormUploadTokenResponse>(`/form/human_input/${formToken}/upload-token`)
+ humanInputFormUploadTokenCache.set(formToken, tokenResponse)
+ return tokenResponse.upload_token
+}
+
+const uploadHumanInputFormFile = async (
+ formToken: string,
+ formData: FormData,
+ onProgress?: (e: ProgressEvent) => void,
+) => {
+ const uploadToken = await getHumanInputFormUploadToken(formToken)
+
+ return upload({
+ xhr: new XMLHttpRequest(),
+ data: formData,
+ headers: {
+ Authorization: `bearer ${uploadToken}`,
+ },
+ onprogress: onProgress,
+ }, true, '/human-input-forms/files')
+}
+
+export const uploadHumanInputFormLocalFile = async ({
+ formToken,
+ file,
+ onProgressCallback,
+ onSuccessCallback,
+ onErrorCallback,
+}: HumanInputFormLocalFileUploadParams) => {
+ const formData = new FormData()
+ formData.append('file', file)
+
+ const onProgress = (e: ProgressEvent) => {
+ if (e.lengthComputable) {
+ const percent = Math.floor(e.loaded / e.total * 100)
+ onProgressCallback(percent)
+ }
+ }
+
+ try {
+ const response = await uploadHumanInputFormFile(
+ formToken,
+ formData,
+ onProgress,
+ ) as HumanInputFormLocalFileUploadResponse
+
+ onSuccessCallback(response)
+ }
+ catch (error) {
+ onErrorCallback(error)
+ }
+}
+
+export const uploadHumanInputFormRemoteFileInfo = async (
+ formToken: string,
+ url: string,
+): Promise<HumanInputFormRemoteFileUploadResponse> => {
+ const formData = new FormData()
+ formData.append('url', url)
+
+ return uploadHumanInputFormFile(formToken, formData) as Promise<HumanInputFormRemoteFileUploadResponse>
+}
+
export const submitHumanInputForm = (token: string, data: {
- inputs: Record<string, string>
+ inputs: Record<string, unknown>
action: string
}) => {
return post(`/form/human_input/${token}`, { body: data })
diff --git a/web/service/use-share.ts b/web/service/use-share.ts
index e164276699c..0facd3a8c43 100644
--- a/web/service/use-share.ts
+++ b/web/service/use-share.ts
@@ -197,7 +197,7 @@ export const useGetHumanInputForm = (token: string, options: ShareQueryOptions =
type SubmitHumanInputFormParams = {
token: string
data: {
- inputs: Record<string, string>
+ inputs: Record<string, unknown>
action: string
}
}
diff --git a/web/service/workflow.ts b/web/service/workflow.ts
index 3ecbf826374..0bf76ed8073 100644
--- a/web/service/workflow.ts
+++ b/web/service/workflow.ts
@@ -131,7 +131,7 @@ export const updateFeatures = ({ appId, features }: {
}
export const submitHumanInputForm = (token: string, data: {
- inputs: Record<string, string>
+ inputs: Record<string, unknown>
action: string
}) => {
return post(`/form/human_input/${token}`, { body: data })
@@ -140,7 +140,7 @@ export const submitHumanInputForm = (token: string, data: {
export const fetchHumanInputNodeStepRunForm = (
url: string,
data: {
- inputs: Record<string, string>
+ inputs: Record<string, unknown>
},
) => {
return post<HumanInputFormData>(`${url}/preview`, { body: data })
@@ -149,8 +149,8 @@ export const fetchHumanInputNodeStepRunForm = (
export const submitHumanInputNodeStepRunForm = (
url: string,
data: {
- inputs: Record<string, string> | undefined
- form_inputs: Record<string, string> | undefined
+ inputs: Record<string, unknown> | undefined
+ form_inputs: Record<string, unknown> | undefined
action: string
},
) => {
diff --git a/web/types/workflow.ts b/web/types/workflow.ts
index 95d8e47fdbf..66297ba5c2d 100644
--- a/web/types/workflow.ts
+++ b/web/types/workflow.ts
@@ -331,7 +331,7 @@ export type HumanInputFormData = {
inputs: FormInputItem[]
actions: UserAction[]
form_token: string
- resolved_default_values: Record<string, string>
+ resolved_default_values: Record<string, HumanInputResolvedValue>
display_in_ui: boolean
expiration_time: number
}
@@ -343,12 +343,19 @@ export type HumanInputRequiredResponse = {
data: HumanInputFormData
}
+export type HumanInputFormValue = string | FileResponse | FileResponse[]
+
+export type HumanInputResolvedValue = string | FileResponse | FileResponse[]
+
export type HumanInputFilledFormData = {
node_id: string
node_title: string
rendered_content: string
action_id: string
action_text: string
+ form_content?: string
+ inputs?: FormInputItem[]
+ submitted_data?: Record<string, HumanInputFormValue>
}
export type HumanInputFormFilledResponse = {