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.

fix: honor file input defaults across app execution (#44780)

非法操作430d9aff99fe
diff --git a/api/.importlinter b/api/.importlinter
index 7da95e59cf6..bec3ef4daf6 100644
--- a/api/.importlinter
+++ b/api/.importlinter
@@ -29,6 +29,10 @@ layers =
# error makes this list shrink whenever a legacy dependency is removed.
unmatched_ignore_imports_alerting = error
ignore_imports =
+ # Legacy generators delegate configured file defaults to the application owner during core migration.
+ core.app.apps.base_app_generator -> services.app.file_input_defaults
+ core.app.apps.advanced_chat.app_generator -> services.app.file_input_defaults
+ core.app.apps.workflow.app_generator -> services.app.file_input_defaults
core.app.app_config.easy_ui_based_app.dataset.manager -> services.knowledge.dataset_service
core.app.apps.advanced_chat.app_generator -> controllers.console.app.workflow
core.app.apps.advanced_chat.app_generator -> services.conversation_service
diff --git a/api/core/app/apps/advanced_chat/app_generator.py b/api/core/app/apps/advanced_chat/app_generator.py
index 1b3f52f6bf5..1b7f2170585 100644
--- a/api/core/app/apps/advanced_chat/app_generator.py
+++ b/api/core/app/apps/advanced_chat/app_generator.py
@@ -56,6 +56,7 @@ from graphon.variable_loader import DUMMY_VARIABLE_LOADER, VariableLoader
from libs.flask_utils import preserve_flask_contexts
from models import Account, App, Conversation, EndUser, Message, Workflow, WorkflowNodeExecutionTriggeredFrom
from models.enums import WorkflowRunTriggeredFrom
+from services.app.file_input_defaults import grant_file_default_access
from services.conversation_service import ConversationService
from services.errors.conversation import ConversationNotExistsError
from services.workflow_draft_variable_service import (
@@ -544,6 +545,7 @@ class AdvancedChatAppGenerator(MessageBasedAppGenerator):
user=user,
invoke_from=invoke_from,
):
+ grant_file_default_access(application_generate_entity.app_config.variables)
is_first_conversation = conversation is None
if conversation is not None and message is not None:
diff --git a/api/core/app/apps/base_app_generator.py b/api/core/app/apps/base_app_generator.py
index 249dd72bfc4..4a23bb71af4 100644
--- a/api/core/app/apps/base_app_generator.py
+++ b/api/core/app/apps/base_app_generator.py
@@ -13,7 +13,11 @@ from core.app.apps.draft_variable_saver import (
NoopDraftVariableSaver,
)
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
-from core.app.file_access import DatabaseFileAccessController, FileAccessScope, bind_file_access_scope
+from core.app.file_access import (
+ DatabaseFileAccessController,
+ FileAccessScope,
+ bind_file_access_scope,
+)
from extensions.ext_database import db
from factories import file_factory
from graphon.enums import NodeType
@@ -21,6 +25,7 @@ from graphon.file import File, FileUploadConfig
from graphon.variables.input_entities import VariableEntityType
from libs.orjson import orjson_dumps
from models import Account, EndUser, Workflow, WorkflowRun
+from services.app.file_input_defaults import apply_file_input_defaults
from services.workflow_draft_variable_service import DraftVariableSaver as DraftVariableSaverImpl
if TYPE_CHECKING:
@@ -134,7 +139,7 @@ class BaseAppGenerator:
tenant_id: str,
strict_type_validation: bool = False,
) -> Mapping[str, Any]:
- user_inputs = user_inputs or {}
+ user_inputs = apply_file_input_defaults(user_inputs, variables)
# Filter input variables from form configuration, handle required fields, default values, and option values
user_inputs = {
var.variable: self._validate_inputs(value=user_inputs.get(var.variable), variable_entity=var)
diff --git a/api/core/app/apps/workflow/app_generator.py b/api/core/app/apps/workflow/app_generator.py
index daf053c8b4d..4a34825bde6 100644
--- a/api/core/app/apps/workflow/app_generator.py
+++ b/api/core/app/apps/workflow/app_generator.py
@@ -56,6 +56,7 @@ from models.enums import WorkflowRunTriggeredFrom
from models.model import App, EndUser
from models.workflow import Workflow, WorkflowNodeExecutionTriggeredFrom
from repositories.entities.workflow_execution import WorkflowExecutionIdentity
+from services.app.file_input_defaults import grant_file_default_access
from services.workflow_draft_variable_service import DraftVarLoader, WorkflowDraftVariableService
if TYPE_CHECKING:
@@ -366,6 +367,7 @@ class WorkflowAppGenerator(BaseAppGenerator):
user=user,
invoke_from=invoke_from,
):
+ grant_file_default_access(application_generate_entity.app_config.variables)
# init queue manager
queue_manager = WorkflowAppQueueManager(
task_id=application_generate_entity.task_id,
diff --git a/api/services/app/file_input_defaults.py b/api/services/app/file_input_defaults.py
new file mode 100644
index 00000000000..470119290c2
--- /dev/null
+++ b/api/services/app/file_input_defaults.py
@@ -0,0 +1,60 @@
+"""Prepare configured file defaults and grant execution-local access to them."""
+
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+from core.app.file_access import grant_upload_file_access
+from factories.file_factory.common import resolve_mapping_file_id
+from graphon.file import FileTransferMethod
+from graphon.variables.input_entities import VariableEntity, VariableEntityType
+
+
+def _normalize_file_default(value: Any) -> Any:
+ if isinstance(value, list):
+ return [_normalize_file_default(item) for item in value]
+ if isinstance(value, dict) and "transferMethod" in value:
+ # The editor persists FileEntity values, whereas the file factory accepts API mappings.
+ return {
+ "type": value.get("supportFileType"),
+ "transfer_method": value.get("transferMethod"),
+ "url": value.get("url") or "",
+ "upload_file_id": value.get("uploadedId") or "",
+ }
+ return value
+
+
+def grant_file_default_access(variables: Sequence[VariableEntity]) -> None:
+ """Grant only files configured by the app author, within the current execution's tenant."""
+ file_ids: set[str] = set()
+ for variable in variables:
+ if variable.type not in {VariableEntityType.FILE, VariableEntityType.FILE_LIST}:
+ continue
+ default = _normalize_file_default(variable.default)
+ mappings = default if isinstance(default, list) else [default]
+ for mapping in mappings:
+ if not isinstance(mapping, dict) or mapping.get("transfer_method") not in {
+ FileTransferMethod.LOCAL_FILE,
+ FileTransferMethod.REMOTE_URL,
+ }:
+ continue
+ file_id = resolve_mapping_file_id(mapping, "upload_file_id")
+ if file_id:
+ file_ids.add(file_id)
+ grant_upload_file_access(file_ids)
+
+
+def apply_file_input_defaults(
+ user_inputs: Mapping[str, Any] | None, variables: Sequence[VariableEntity]
+) -> dict[str, Any]:
+ """Copy inputs (None means omitted), grant defaults, and fill missing file values."""
+ inputs = dict(user_inputs or {})
+ grant_file_default_access(variables)
+ # Fill omitted file inputs before required validation; explicit values win.
+ for variable in variables:
+ if (
+ variable.type in {VariableEntityType.FILE, VariableEntityType.FILE_LIST}
+ and inputs.get(variable.variable) is None
+ and variable.default
+ ):
+ inputs[variable.variable] = _normalize_file_default(variable.default)
+ return inputs
diff --git a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py
index 61e032d8706..20bccd869f4 100644
--- a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py
@@ -33,8 +33,10 @@ from core.app.apps.advanced_chat.generate_task_pipeline import (
from core.app.apps.exc import GenerateTaskStoppedError
from core.app.apps.workflow import app_generator as wf_app_gen_module
from core.app.entities.app_invoke_entities import AdvancedChatAppGenerateEntity, InvokeFrom
+from core.app.file_access import DatabaseFileAccessController
from core.app.task_pipeline import message_cycle_manager
from core.app.task_pipeline.message_cycle_manager import MessageCycleManager
+from core.app.workflow.file_runtime import DifyWorkflowFileRuntime
from core.ops.ops_trace_manager import TraceQueueManager
from core.workflow import node_factory as node_factory_module
from core.workflow.node_factory import DifyNodeFactory
@@ -59,6 +61,7 @@ from graphon.nodes.base.node import Node
from graphon.nodes.end.entities import EndNodeData
from graphon.nodes.start.entities import StartNodeData
from graphon.runtime import RuntimeState, VariablePool
+from graphon.variables.input_entities import VariableEntity
from libs.datetime_utils import naive_utc_now
from models import Account as _advanced_chat_app_generator_Account
from models import Workflow as _advanced_chat_app_generator_Workflow
@@ -72,6 +75,7 @@ from models.workflow import WorkflowType
from services.errors.conversation import ConversationNotExistsError
from services.workflow_run_agg import WorkflowRunAgg
from tests.helpers.unit.config_override import apply_config_overrides
+from tests.helpers.unit.model_factories import make_upload_file
from tests.workflow_test_utils import build_test_graph_init_params
@@ -629,6 +633,19 @@ class TestAdvancedChatAppGeneratorInternals:
generator = AdvancedChatAppGenerator(execution_driver=WorkflowRunAgg.run)
generator._dialogue_count = 0
app_config = self._build_app_config()
+ default_file = make_upload_file(tenant_id=app_config.tenant_id)
+ app_config.variables = [
+ VariableEntity.model_validate(
+ {
+ "type": "file",
+ "variable": "file",
+ "label": "File",
+ "default": {"transfer_method": "local_file", "upload_file_id": default_file.id},
+ }
+ )
+ ]
+ file_runtime = DifyWorkflowFileRuntime(file_access_controller=DatabaseFileAccessController())
+ monkeypatch.setattr(file_runtime, "_secret_key", lambda: b"test-key")
application_generate_entity = AdvancedChatAppGenerateEntity.model_construct(
task_id="task",
@@ -648,7 +665,7 @@ class TestAdvancedChatAppGeneratorInternals:
workflow = _app_generator_make_workflow(workflow_id="wf-2")
conversation = _make_conversation(conversation_id="conv-2")
message = _make_message(message_id="msg-2", conversation_id=conversation.id)
- sqlite_session.add_all([app, workflow, conversation, message])
+ sqlite_session.add_all([app, workflow, conversation, message, default_file])
sqlite_session.commit()
commit_count = 0
@@ -673,7 +690,6 @@ class TestAdvancedChatAppGeneratorInternals:
"core.app.apps.advanced_chat.app_generator.current_app",
SimpleNamespace(_get_current_object=lambda: SimpleNamespace(name="flask")),
)
- monkeypatch.setattr("core.app.apps.advanced_chat.app_generator.contextvars.copy_context", lambda: "ctx")
class _Thread:
def __init__(self, *, target, kwargs):
@@ -696,11 +712,14 @@ class TestAdvancedChatAppGeneratorInternals:
SimpleNamespace(engine=sqlite_engine, session=sqlite_session),
)
monkeypatch.setattr(generator, "_get_draft_var_saver_factory", lambda *args, **kwargs: "draft-factory")
- monkeypatch.setattr(
- generator,
- "_handle_advanced_chat_response",
- lambda **kwargs: {"raw": True},
- )
+
+ def handle_response(**kwargs):
+ assert file_runtime.resolve_upload_file_uri(upload_file_id=default_file.id).startswith(
+ f"/files/{default_file.id}/file-preview?"
+ )
+ return {"raw": True}
+
+ monkeypatch.setattr(generator, "_handle_advanced_chat_response", handle_response)
monkeypatch.setattr(
"core.app.apps.advanced_chat.app_generator.AdvancedChatAppGenerateResponseConverter.convert",
lambda response, invoke_from: response,
@@ -708,7 +727,7 @@ class TestAdvancedChatAppGeneratorInternals:
response = generator._generate(
workflow=workflow,
- user=_app_generator_make_account(account_id="user"),
+ user=_make_end_user(end_user_id="user"),
invoke_from=InvokeFrom.WEB_APP,
application_generate_entity=application_generate_entity,
session=sqlite_session,
@@ -726,6 +745,11 @@ class TestAdvancedChatAppGeneratorInternals:
assert thread_data["joined"] is True
assert thread_data["join_timeout"] == 300
assert commit_count == 0
+ assert (
+ thread_data["kwargs"]["context"]
+ .run(file_runtime.resolve_upload_file_uri, upload_file_id=default_file.id)
+ .startswith(f"/files/{default_file.id}/file-preview?")
+ )
def test_generate_worker_raises_when_workflow_not_found(
self, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session, sqlite_engine: _app_generator_Engine
diff --git a/api/tests/unit_tests/core/app/apps/test_base_app_generator.py b/api/tests/unit_tests/core/app/apps/test_base_app_generator.py
index b1f0f9c1d88..9327cf5d759 100644
--- a/api/tests/unit_tests/core/app/apps/test_base_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/test_base_app_generator.py
@@ -1,4 +1,6 @@
import logging
+from copy import deepcopy
+from datetime import UTC, datetime
from unittest.mock import Mock
import pytest
@@ -6,10 +8,16 @@ from sqlalchemy import inspect
from sqlalchemy.orm import Session
from core.app.apps.base_app_generator import BaseAppGenerator
+from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
+from core.app.file_access import FileAccessScope, bind_file_access_scope, get_current_file_access_scope
+from core.workflow.file_reference import resolve_file_record_id
+from extensions.storage.storage_type import StorageType
from graphon.enums import BuiltinNodeTypes, WorkflowExecutionStatus
+from graphon.file import File
from graphon.variables.input_entities import VariableEntity, VariableEntityType
-from models import CreatorUserRole, Workflow, WorkflowRun, WorkflowRunTriggeredFrom
+from models import CreatorUserRole, UploadFile, Workflow, WorkflowRun, WorkflowRunTriggeredFrom
from models.workflow import WorkflowType as ModelWorkflowType
+from tests.helpers.unit.config_override import apply_config_overrides
def _workflow_run(*, graph: str | None) -> WorkflowRun:
@@ -593,7 +601,6 @@ class TestBaseAppGeneratorExtras:
assert converted[1] == "event: ping\n\n"
def test_get_draft_var_saver_factory_debugger(self):
- from core.app.entities.app_invoke_entities import InvokeFrom
from models import Account
base_app_generator = BaseAppGenerator()
@@ -614,3 +621,193 @@ class TestBaseAppGeneratorExtras:
)
assert saver is not None
+
+
+DEFAULT_FILE_TENANT_ID = "tenant-1"
+DEFAULT_FILE_END_USER_ID = "end-user-1"
+
+
+def default_upload_file(sqlite_session: Session) -> UploadFile:
+ file = UploadFile(
+ tenant_id=DEFAULT_FILE_TENANT_ID,
+ storage_type=StorageType.LOCAL,
+ key="default-file.gif",
+ name="default.gif",
+ size=5798,
+ extension="gif",
+ mime_type="image/gif",
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by="author-1",
+ created_at=datetime(2026, 1, 1, tzinfo=UTC),
+ used=False,
+ )
+ sqlite_session.add(file)
+ sqlite_session.commit()
+ return file
+
+
+def _file_input_variable(file: UploadFile, *, multiple: bool = False, required: bool = True) -> VariableEntity:
+ default = {
+ "id": "editor-id",
+ "uploadedId": file.id,
+ "transferMethod": "local_file",
+ "supportFileType": "image",
+ "type": "image/gif",
+ "name": "untrusted-name.gif",
+ "size": 1,
+ "base64Url": "https://expired.example/preview",
+ }
+ return VariableEntity(
+ variable="file",
+ label="File",
+ type=VariableEntityType.FILE_LIST if multiple else VariableEntityType.FILE,
+ required=required,
+ default=[default] if multiple else default,
+ allowed_file_types=["image"],
+ allowed_file_upload_methods=["local_file", "remote_url"],
+ max_length=2,
+ )
+
+
+def _prepare_file_inputs(
+ variable: VariableEntity, inputs: dict[str, object], invoke_from: InvokeFrom = InvokeFrom.SERVICE_API
+):
+ return BaseAppGenerator()._prepare_user_inputs(
+ user_inputs=inputs,
+ variables=[variable],
+ tenant_id=DEFAULT_FILE_TENANT_ID,
+ strict_type_validation=invoke_from == InvokeFrom.SERVICE_API,
+ )["file"]
+
+
+def _file_access_scope(invoke_from: InvokeFrom = InvokeFrom.SERVICE_API):
+ return bind_file_access_scope(
+ FileAccessScope(
+ tenant_id=DEFAULT_FILE_TENANT_ID,
+ user_id=DEFAULT_FILE_END_USER_ID,
+ user_from=UserFrom.END_USER,
+ invoke_from=invoke_from,
+ )
+ )
+
+
[email protected]("required", [True, False])
[email protected]("multiple", [True, False])
[email protected]("invoke_from", [InvokeFrom.WEB_APP, InvokeFrom.SERVICE_API])
+def test_omitted_file_uses_author_default(
+ default_upload_file: UploadFile, required: bool, multiple: bool, invoke_from: InvokeFrom
+):
+ variable = _file_input_variable(default_upload_file, multiple=multiple, required=required)
+ original_default = deepcopy(variable.default)
+ with _file_access_scope(invoke_from):
+ result = _prepare_file_inputs(variable, {}, invoke_from)
+ file = result[0] if multiple else result
+ assert isinstance(file, File)
+ assert resolve_file_record_id(file.reference) == default_upload_file.id
+ assert (file.filename, file.size) == (default_upload_file.name, default_upload_file.size)
+ assert variable.default == original_default
+ assert get_current_file_access_scope() is None
+
+
[email protected]("multiple", [False, True])
+def test_webapp_can_submit_configured_default_explicitly(default_upload_file: UploadFile, multiple: bool):
+ value = {"type": "image", "transfer_method": "local_file", "upload_file_id": default_upload_file.id}
+ with _file_access_scope(InvokeFrom.WEB_APP):
+ result = _prepare_file_inputs(
+ _file_input_variable(default_upload_file, multiple=multiple), {"file": [value] if multiple else value}
+ )
+ file = result[0] if multiple else result
+ assert resolve_file_record_id(file.reference) == default_upload_file.id
+
+
+def test_explicit_user_file_overrides_default(default_upload_file: UploadFile, sqlite_session: Session):
+ variable = _file_input_variable(default_upload_file)
+ variable.default["uploadedId"] = "00000000-0000-0000-0000-000000000000"
+ default_upload_file.created_by_role = CreatorUserRole.END_USER
+ default_upload_file.created_by = DEFAULT_FILE_END_USER_ID
+ sqlite_session.commit()
+ with _file_access_scope():
+ result = _prepare_file_inputs(
+ variable,
+ {"file": {"type": "image", "transfer_method": "local_file", "upload_file_id": default_upload_file.id}},
+ )
+ assert resolve_file_record_id(result.reference) == default_upload_file.id
+
+
[email protected]("role", [CreatorUserRole.ACCOUNT, CreatorUserRole.END_USER])
+def test_caller_cannot_grant_unconfigured_file(
+ default_upload_file: UploadFile, sqlite_session: Session, role: CreatorUserRole
+):
+ variable = _file_input_variable(default_upload_file)
+ variable.default["uploadedId"] = "00000000-0000-0000-0000-000000000000"
+ default_upload_file.created_by_role = role
+ sqlite_session.commit()
+ with _file_access_scope(), pytest.raises(ValueError, match="Invalid upload file"):
+ _prepare_file_inputs(
+ variable,
+ {"file": {"type": "image", "transfer_method": "local_file", "upload_file_id": default_upload_file.id}},
+ )
+
+
+def test_default_cannot_grant_cross_tenant_file(default_upload_file: UploadFile, sqlite_session: Session):
+ default_upload_file.tenant_id = "other-tenant"
+ sqlite_session.commit()
+ with _file_access_scope(), pytest.raises(ValueError, match="Invalid upload file"):
+ _prepare_file_inputs(_file_input_variable(default_upload_file), {})
+
+
+def test_single_file_default_obeys_strict_file_type_validation(default_upload_file: UploadFile):
+ variable = _file_input_variable(default_upload_file)
+ variable.default["supportFileType"] = "document"
+ with _file_access_scope(), pytest.raises(ValueError, match="Detected file type does not match"):
+ _prepare_file_inputs(variable, {})
+
+
[email protected]("multiple", [False, True])
+def test_default_obeys_allowed_file_types(default_upload_file: UploadFile, multiple: bool):
+ variable = _file_input_variable(default_upload_file, multiple=multiple)
+ variable.allowed_file_types = ["document"]
+ with _file_access_scope(), pytest.raises(ValueError, match="File validation failed"):
+ _prepare_file_inputs(variable, {})
+
+
+def test_explicit_empty_file_list_stays_empty(default_upload_file: UploadFile):
+ with _file_access_scope():
+ assert (
+ _prepare_file_inputs(_file_input_variable(default_upload_file, multiple=True, required=False), {"file": []})
+ == []
+ )
+
+
+def test_explicitly_cleared_optional_file_stays_empty(default_upload_file: UploadFile):
+ with _file_access_scope():
+ assert _prepare_file_inputs(_file_input_variable(default_upload_file, required=False), {"file": ""}) is None
+
+
+def test_empty_file_list_default_does_not_satisfy_required_input(default_upload_file: UploadFile):
+ variable = _file_input_variable(default_upload_file, multiple=True)
+ variable.default = []
+ with _file_access_scope(), pytest.raises(ValueError, match="file is required"):
+ _prepare_file_inputs(variable, {})
+ variable.required = False
+ with _file_access_scope():
+ assert _prepare_file_inputs(variable, {}) == []
+
+
[email protected]("multiple", [False, True])
+def test_missing_file_without_default_is_still_required(default_upload_file: UploadFile, multiple: bool):
+ variable = _file_input_variable(default_upload_file, multiple=multiple)
+ variable.default = None
+ with _file_access_scope(), pytest.raises(ValueError, match="file is required"):
+ _prepare_file_inputs(variable, {})
+
+
+def test_api_shaped_and_remote_upload_defaults(default_upload_file: UploadFile, monkeypatch: pytest.MonkeyPatch):
+ apply_config_overrides(monkeypatch, FILES_URL="https://files.example.com")
+ variable = _file_input_variable(default_upload_file)
+ variable.default = {"type": "image", "transfer_method": "remote_url", "upload_file_id": default_upload_file.id}
+ with _file_access_scope():
+ result = _prepare_file_inputs(variable, {})
+ assert resolve_file_record_id(result.reference) == default_upload_file.id
+ assert result.transfer_method == "remote_url"
diff --git a/api/tests/unit_tests/core/app/apps/workflow/test_app_generator.py b/api/tests/unit_tests/core/app/apps/workflow/test_app_generator.py
index 16fc32e9b47..a6f0085a80f 100644
--- a/api/tests/unit_tests/core/app/apps/workflow/test_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/workflow/test_app_generator.py
@@ -22,11 +22,13 @@ from core.app.apps.workflow.app_queue_manager import WorkflowAppQueueManager
from core.app.apps.workflow_app_runner import WorkflowBasedAppRunner
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom, WorkflowAppGenerateEntity
from core.app.entities.queue_entities import QueueWorkflowSucceededEvent
+from core.app.file_access import DatabaseFileAccessController
from core.app.layers.pause_state_persist_layer import (
PauseStateLayerConfig,
WorkflowResumptionContext,
_WorkflowGenerateEntityWrapper,
)
+from core.app.workflow.file_runtime import DifyWorkflowFileRuntime
from core.ops.ops_trace_manager import OpsTraceManager, TraceQueueManager
from core.repositories import SQLAlchemyWorkflowExecutionRepository, SQLAlchemyWorkflowNodeExecutionRepository
from core.repositories.factory import WorkflowExecutionRepository, WorkflowNodeExecutionRepository
@@ -37,6 +39,7 @@ from core.workflow.system_variables import SystemVariableKey, get_system_text
from graphon.enums import WorkflowExecutionStatus
from graphon.runtime import RuntimeState, VariablePool
from graphon.variable_loader import DUMMY_VARIABLE_LOADER
+from graphon.variables.input_entities import VariableEntity
from models.enums import CreatorUserRole, EndUserType, WorkflowRunTriggeredFrom
from models.model import App, AppMode, EndUser
from models.snippet import CustomizedSnippet
@@ -44,7 +47,7 @@ from models.workflow import Workflow, WorkflowKind, WorkflowNodeExecutionTrigger
from repositories.entities.workflow_execution import WorkflowExecutionIdentity
from services.file_request_service import FileRequestService
from services.workflow_run_agg import WorkflowRunAgg
-from tests.helpers.unit.model_factories import make_account, make_workflow
+from tests.helpers.unit.model_factories import make_account, make_upload_file, make_workflow
"""SQLite-backed tests for workflow app generation and worker reload behavior."""
@@ -497,13 +500,39 @@ class TestWorkflowAppGeneratorCases:
assert draft_factory_tenant_ids == [app.tenant_id]
@staticmethod
- def test_resume_path_runs_worker_with_runtime_state(
+ @pytest.mark.parametrize("resuming", [False, True])
+ @pytest.mark.parametrize("invoke_from", [InvokeFrom.WEB_APP, InvokeFrom.SERVICE_API])
+ def test_execution_grants_default_files_to_worker_and_response(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
sqlite_session_factory: sessionmaker[Session],
+ resuming: bool,
+ invoke_from: InvokeFrom,
) -> None:
generator = WorkflowAppGenerator(execution_driver=WorkflowRunAgg.run)
app, workflow, end_user = _persist_generator_rows(sqlite_session)
+ default_file, unrelated_file = [
+ make_upload_file(
+ tenant_id=app.tenant_id,
+ key=name,
+ name=name,
+ extension="gif",
+ mime_type="image/gif",
+ )
+ for name in ("default.gif", "unrelated.gif")
+ ]
+ variable = VariableEntity.model_validate(
+ {
+ "type": "file",
+ "variable": "file",
+ "label": "File",
+ "required": True,
+ "default": {"transferMethod": "local_file", "uploadedId": default_file.id, "supportFileType": "image"},
+ }
+ )
+ graph = workflow.graph_dict
+ graph["nodes"][0]["data"]["variables"] = [variable.model_dump(mode="json")]
+ workflow.graph = json.dumps(graph)
workflow_run = WorkflowRun(
id="run",
tenant_id=workflow.tenant_id,
@@ -518,9 +547,22 @@ class TestWorkflowAppGeneratorCases:
created_by_role=CreatorUserRole.END_USER,
created_by=end_user.id,
)
- sqlite_session.add(workflow_run)
+ sqlite_session.add_all([workflow_run, default_file, unrelated_file])
sqlite_session.commit()
- runtime_state = _runtime_state()
+ if resuming:
+ graph["nodes"][0]["data"]["variables"][0]["default"]["uploadedId"] = unrelated_file.id
+ workflow.graph = json.dumps(graph)
+ sqlite_session.commit()
+ runtime_state = _runtime_state() if resuming else None
+ file_runtime = DifyWorkflowFileRuntime(file_access_controller=DatabaseFileAccessController())
+ monkeypatch.setattr(file_runtime, "_secret_key", lambda: b"test-key")
+
+ def assert_default_file_access() -> None:
+ assert file_runtime.resolve_upload_file_uri(upload_file_id=default_file.id).startswith(
+ f"/files/{default_file.id}/file-preview?"
+ )
+ with pytest.raises(ValueError, match="not found"):
+ file_runtime.resolve_upload_file_uri(upload_file_id=unrelated_file.id)
queue_manager = MagicMock()
monkeypatch.setattr(
@@ -528,7 +570,11 @@ class TestWorkflowAppGeneratorCases:
MagicMock(return_value=queue_manager),
)
- monkeypatch.setattr(generator, "_handle_response", MagicMock(return_value="raw-response"))
+ def handle_response(**_kwargs):
+ assert_default_file_access()
+ return "raw-response"
+
+ monkeypatch.setattr(generator, "_handle_response", handle_response)
monkeypatch.setattr(
"core.app.apps.workflow.app_generator.WorkflowAppGenerateResponseConverter.convert",
MagicMock(side_effect=lambda response, invoke_from: response),
@@ -545,6 +591,7 @@ class TestWorkflowAppGeneratorCases:
assert kwargs["workflow"].id == workflow.id
assert kwargs["system_user_id"] == end_user.session_id
assert kwargs["queue_manager"] is queue_manager
+ assert_default_file_access()
return runner_instance
monkeypatch.setattr(
@@ -575,21 +622,23 @@ class TestWorkflowAppGeneratorCases:
state_owner_user_id="owner",
)
- application_generate_entity = _generate_entity(app, workflow, end_user)
+ application_generate_entity = _generate_entity(app, workflow, end_user, invoke_from=invoke_from)
+ application_generate_entity.app_config.variables = [variable]
workflow_execution_repository, workflow_node_execution_repository = _repositories(
sqlite_session_factory, app, end_user
)
- result = generator.resume(
- app_model=app,
- workflow=workflow,
- user=end_user,
- application_generate_entity=application_generate_entity,
- graph_runtime_state=runtime_state,
- workflow_execution_repository=workflow_execution_repository,
- workflow_node_execution_repository=workflow_node_execution_repository,
- pause_state_config=pause_config,
- )
+ kwargs = {
+ "app_model": app,
+ "workflow": workflow,
+ "user": end_user,
+ "application_generate_entity": application_generate_entity,
+ "graph_runtime_state": runtime_state,
+ "workflow_execution_repository": workflow_execution_repository,
+ "workflow_node_execution_repository": workflow_node_execution_repository,
+ "pause_state_config": pause_config,
+ }
+ result = generator.resume(**kwargs) if resuming else generator._generate(**kwargs, invoke_from=invoke_from)
assert result == "raw-response"
assert worker_lifecycle["joined"] is True
diff --git a/api/tests/unit_tests/services/app/test_file_input_defaults.py b/api/tests/unit_tests/services/app/test_file_input_defaults.py
new file mode 100644
index 00000000000..e80644ddaee
--- /dev/null
+++ b/api/tests/unit_tests/services/app/test_file_input_defaults.py
@@ -0,0 +1,60 @@
+from copy import deepcopy
+
+import pytest
+
+from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
+from core.app.file_access import FileAccessScope, bind_file_access_scope, get_current_file_access_scope
+from graphon.variables.input_entities import VariableEntity, VariableEntityType
+from services.app.file_input_defaults import apply_file_input_defaults
+
+
[email protected]("cleared", [False, True])
+def test_defaults_are_prepared_without_changing_inputs_or_configuration(cleared: bool) -> None:
+ editor_file = {
+ "transferMethod": "local_file",
+ "uploadedId": "00000000-0000-0000-0000-000000000001",
+ "supportFileType": "document",
+ }
+ api_file = {
+ "transfer_method": "remote_url",
+ "upload_file_id": "00000000-0000-0000-0000-000000000002",
+ "type": "document",
+ "url": "https://example.com/default.txt",
+ }
+ variables = [
+ VariableEntity(variable="file", label="File", type=VariableEntityType.FILE, default=editor_file),
+ VariableEntity(variable="files", label="Files", type=VariableEntityType.FILE_LIST, default=[api_file]),
+ ]
+ inputs: dict[str, object] = {"file": "", "files": []} if cleared else {"file": None}
+ original_inputs = deepcopy(inputs)
+ original_variables = deepcopy(variables)
+ scope = FileAccessScope(
+ tenant_id="tenant-1",
+ user_id="end-user-1",
+ user_from=UserFrom.END_USER,
+ invoke_from=InvokeFrom.SERVICE_API,
+ )
+
+ with bind_file_access_scope(scope):
+ result = apply_file_input_defaults(inputs, variables)
+
+ if cleared:
+ assert result == {"file": "", "files": []}
+ else:
+ assert result == {
+ "file": {
+ "type": "document",
+ "transfer_method": "local_file",
+ "url": "",
+ "upload_file_id": editor_file["uploadedId"],
+ },
+ "files": [api_file],
+ }
+ current_scope = get_current_file_access_scope()
+ assert current_scope is not None
+ assert current_scope.granted_upload_file_ids == {editor_file["uploadedId"], api_file["upload_file_id"]}
+
+ assert result is not inputs
+ assert inputs == original_inputs
+ assert variables == original_variables
+ assert get_current_file_access_scope() is None
diff --git a/web/app/components/base/chat/__tests__/file-input-defaults.spec.tsx b/web/app/components/base/chat/__tests__/file-input-defaults.spec.tsx
new file mode 100644
index 00000000000..b998791dcb2
--- /dev/null
+++ b/web/app/components/base/chat/__tests__/file-input-defaults.spec.tsx
@@ -0,0 +1,212 @@
+import type { InputForm } from '../chat/type'
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { noop } from 'es-toolkit/function'
+import { useEffect, useRef, useState } from 'react'
+import { InputVarType } from '@/app/components/workflow/types'
+import { AppSourceType } from '@/service/share'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createChatConfigFixture, createChatFileFixture } from '@/test/fixtures/chat'
+import { ChatWithHistoryContext, useChatWithHistoryContext } from '../chat-with-history/context'
+import HistoryInputsForm from '../chat-with-history/inputs-form'
+import { useChat } from '../chat/hooks'
+import { getProcessedInputs } from '../chat/utils'
+import { EmbeddedChatbotContext, useEmbeddedChatbotContext } from '../embedded-chatbot/context'
+import EmbeddedInputsForm from '../embedded-chatbot/inputs-form'
+
+vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/' }))
+vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
+ default: () => null,
+}))
+
+const singleFile = createChatFileFixture({ name: 'default.txt' })
+const listFile = createChatFileFixture({
+ id: 'list-file',
+ name: 'list-default.txt',
+ uploadedId: 'list-upload',
+})
+const singleForm: InputForm = {
+ variable: 'file',
+ label: 'File',
+ type: InputVarType.singleFile,
+ required: false,
+ hide: false,
+ default: singleFile,
+ allowed_file_types: ['document'],
+ allowed_file_upload_methods: ['local_file'],
+}
+const forms: InputForm[] = [
+ singleForm,
+ {
+ ...singleForm,
+ variable: 'files',
+ label: 'Files',
+ type: InputVarType.multiFiles,
+ default: [listFile],
+ },
+]
+const defaultInputs = { file: singleFile, files: [listFile] }
+const selectedFile = createChatFileFixture({ name: 'selected.txt', uploadedId: 'selected-upload' })
+const selectedListFile = createChatFileFixture({
+ name: 'selected-list.txt',
+ uploadedId: 'selected-list-upload',
+})
+const selectedInputs = { file: selectedFile, files: [selectedListFile] }
+
+type ConversationProps = {
+ surface: 'published' | 'embedded'
+ initialInputs?: Record<string, unknown>
+ initializeDefaults?: boolean
+ appSourceType?: AppSourceType
+ onSubmit?: (body: unknown) => void
+}
+
+function Conversation({
+ surface,
+ initialInputs = {},
+ initializeDefaults = false,
+ appSourceType = AppSourceType.webApp,
+ onSubmit = noop,
+}: ConversationProps) {
+ const historyDefaults = useChatWithHistoryContext()
+ const embeddedDefaults = useEmbeddedChatbotContext()
+ const [inputs, setInputs] = useState(initialInputs)
+ const inputsRef = useRef(inputs)
+ const [collapsed, setCollapsed] = useState(false)
+ const [clearChatList, setClearChatList] = useState(false)
+ useChat(undefined, undefined, undefined, undefined, clearChatList, setClearChatList)
+ useEffect(() => {
+ if (!initializeDefaults) return
+ inputsRef.current = defaultInputs
+ // oxlint-disable-next-line eslint-react/set-state-in-effect -- Match the chat hooks: defaults arrive after the first form render.
+ setInputs(defaultInputs)
+ }, [initializeDefaults])
+
+ const value = {
+ appParams: createChatConfigFixture(),
+ inputsForms: forms,
+ currentConversationId: '',
+ appSourceType,
+ clearChatList,
+ currentConversationInputs: inputs,
+ newConversationInputs: inputs,
+ newConversationInputsRef: inputsRef,
+ setCurrentConversationInputs: noop,
+ handleNewConversationInputsChange: (next: Record<string, unknown>) => {
+ inputsRef.current = next
+ setInputs(next)
+ },
+ handleStartChat: (callback?: () => void) => callback?.(),
+ }
+ const actions = (
+ <>
+ <button
+ onClick={() => {
+ if (appSourceType !== AppSourceType.tryApp) {
+ inputsRef.current = defaultInputs
+ setInputs(defaultInputs)
+ }
+ setClearChatList(true)
+ }}
+ >
+ Reset chat
+ </button>
+ <button
+ onClick={() =>
+ onSubmit(JSON.parse(JSON.stringify({ inputs: getProcessedInputs(inputs, forms) })))
+ }
+ >
+ Submit inputs
+ </button>
+ </>
+ )
+
+ return surface === 'published' ? (
+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its Provider component.
+ <ChatWithHistoryContext.Provider value={{ ...historyDefaults, ...value }}>
+ {actions}
+ <HistoryInputsForm collapsed={collapsed} setCollapsed={setCollapsed} />
+ </ChatWithHistoryContext.Provider>
+ ) : (
+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its Provider component.
+ <EmbeddedChatbotContext.Provider value={{ ...embeddedDefaults, ...value }}>
+ {actions}
+ <EmbeddedInputsForm collapsed={collapsed} setCollapsed={setCollapsed} />
+ </EmbeddedChatbotContext.Provider>
+ )
+}
+
+describe.each(['published', 'embedded'] as const)('%s chat file inputs', (surface) => {
+ it('shows single-file and file-list defaults when the parent initializes inputs after mount', () => {
+ render(<Conversation surface={surface} initializeDefaults />)
+
+ expect(screen.getByText(singleFile.name)).toBeInTheDocument()
+ expect(screen.getByText(listFile.name)).toBeInTheDocument()
+ })
+
+ it('keeps optional files cleared after reopening and submits explicit empty values', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+ render(<Conversation surface={surface} initializeDefaults onSubmit={onSubmit} />)
+
+ for (const file of [singleFile, listFile])
+ await user.click(screen.getByRole('button', { name: `common.operation.remove ${file.name}` }))
+ await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+
+ expect(screen.queryByText(singleFile.name)).not.toBeInTheDocument()
+ expect(screen.queryByText(listFile.name)).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Submit inputs' }))
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith({ inputs: { file: '', files: [] } })
+ })
+
+ it('restores visible defaults and submitted inputs after Start, Edit and Reset', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+ render(<Conversation surface={surface} initialInputs={selectedInputs} onSubmit={onSubmit} />)
+
+ await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ expect(screen.getByText(selectedFile.name)).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Reset chat' }))
+
+ expect(screen.getByText(singleFile.name)).toBeInTheDocument()
+ expect(screen.getByText(listFile.name)).toBeInTheDocument()
+ expect(screen.queryByText(selectedFile.name)).not.toBeInTheDocument()
+ expect(screen.queryByText(selectedListFile.name)).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Submit inputs' }))
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith({
+ inputs: {
+ file: expect.objectContaining({ upload_file_id: singleFile.uploadedId }),
+ files: [expect.objectContaining({ upload_file_id: listFile.uploadedId })],
+ },
+ })
+ })
+})
+
+it('keeps the selected files when Try App only clears the conversation', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+ render(
+ <Conversation
+ surface="embedded"
+ appSourceType={AppSourceType.tryApp}
+ initialInputs={selectedInputs}
+ onSubmit={onSubmit}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'Reset chat' }))
+
+ expect(screen.getByText(selectedFile.name)).toBeInTheDocument()
+ expect(screen.getByText(selectedListFile.name)).toBeInTheDocument()
+ expect(screen.queryByText(singleFile.name)).not.toBeInTheDocument()
+ expect(screen.queryByText(listFile.name)).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Submit inputs' }))
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith({
+ inputs: {
+ file: expect.objectContaining({ upload_file_id: selectedFile.uploadedId }),
+ files: [expect.objectContaining({ upload_file_id: selectedListFile.uploadedId })],
+ },
+ })
+})
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx
index 6e753ffcfc7..5368888af8e 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx
@@ -346,6 +346,13 @@ it.each([
required: true,
disabled: false,
},
+ {
+ name: 'empty required file list',
+ type: InputVarType.multiFiles,
+ value: [],
+ required: true,
+ disabled: true,
+ },
{
name: 'mixed uploads',
type: InputVarType.multiFiles,
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 20527a377c8..5bcb9abdb78 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
@@ -1453,6 +1453,7 @@ describe('useChatWithHistory', () => {
describe('handleNewConversation with inputsForms', () => {
it('should reset new conversation inputs to form defaults', async () => {
// Arrange
+ setConversationIdInfo('app-1', '')
initialAppState.appParams = createChatConfig({
user_input_form: [
{
@@ -1487,6 +1488,7 @@ describe('useChatWithHistory', () => {
await waitFor(() => {
expect(result.current.newConversationInputs.my_var).toBe('default_val')
})
+ expect(result.current.currentConversationId).toBe('')
})
})
diff --git a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
index 555344ac46f..976aa5bd7d8 100644
--- a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
+++ b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
@@ -120,7 +120,12 @@ const ChatWrapper = () => {
if (fileIsUploading) return
const inputValue = inputsFormValue?.[variable]
- if (inputValue === undefined || inputValue === null || inputValue === '')
+ if (
+ inputValue === undefined ||
+ inputValue === null ||
+ inputValue === '' ||
+ (Array.isArray(inputValue) && inputValue.length === 0)
+ )
hasEmptyInput = label as string
if (
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 74c1da66e2b..6f8b0720be9 100644
--- a/web/app/components/base/chat/chat-with-history/hooks.tsx
+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx
@@ -502,12 +502,12 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {
const handleNewConversation = useCallback(async () => {
currentChatInstanceRef.current.handleStop()
setShowNewConversationItemInList(true)
- handleChangeConversation('')
const conversationInputs: Record<string, any> = {}
inputsForms.forEach((item: any) => {
conversationInputs[item.variable] = item.default === '' ? null : (item.default ?? null)
})
handleNewConversationInputsChange(conversationInputs)
+ handleChangeConversation('')
setClearChatList(true)
}, [
handleChangeConversation,
diff --git a/web/app/components/base/chat/chat-with-history/inputs-form/content.tsx b/web/app/components/base/chat/chat-with-history/inputs-form/content.tsx
index cb75b738646..d9dee451718 100644
--- a/web/app/components/base/chat/chat-with-history/inputs-form/content.tsx
+++ b/web/app/components/base/chat/chat-with-history/inputs-form/content.tsx
@@ -28,6 +28,7 @@ const InputsFormContent = ({ showTip }: Props) => {
const baseId = useId()
const {
appParams,
+ clearChatList,
inputsForms,
currentConversationId,
currentConversationInputs,
@@ -37,6 +38,19 @@ const InputsFormContent = ({ showTip }: Props) => {
handleNewConversationInputsChange,
} = useChatWithHistoryContext()
const inputsFormValue = currentConversationId ? currentConversationInputs : newConversationInputs
+ const fileInputsFormValue = currentConversationId
+ ? inputsFormValue
+ : {
+ ...Object.fromEntries(
+ inputsForms
+ .filter(
+ (form) =>
+ form.type === InputVarType.singleFile || form.type === InputVarType.multiFiles,
+ )
+ .map((form) => [form.variable, form.default]),
+ ),
+ ...inputsFormValue,
+ }
const handleFormChange = useCallback(
(variable: string, value: any) => {
@@ -132,10 +146,15 @@ const InputsFormContent = ({ showTip }: Props) => {
</SelectContent>
</Select>
)}
- {form.type === InputVarType.singleFile && (
+ {!clearChatList && form.type === InputVarType.singleFile && (
<FileUploaderInAttachmentWrapper
- value={inputsFormValue?.[form.variable] ? [inputsFormValue?.[form.variable]] : []}
- onChange={(files) => handleFormChange(form.variable, files[0])}
+ key={currentConversationId}
+ value={
+ fileInputsFormValue?.[form.variable] ? [fileInputsFormValue[form.variable]] : []
+ }
+ onChange={(files) =>
+ handleFormChange(form.variable, files[0] ?? (form.required ? undefined : ''))
+ }
fileConfig={{
allowed_file_types: form.allowed_file_types,
allowed_file_extensions: form.allowed_file_extensions,
@@ -145,9 +164,10 @@ const InputsFormContent = ({ showTip }: Props) => {
}}
/>
)}
- {form.type === InputVarType.multiFiles && (
+ {!clearChatList && form.type === InputVarType.multiFiles && (
<FileUploaderInAttachmentWrapper
- value={inputsFormValue?.[form.variable] || []}
+ key={currentConversationId}
+ value={fileInputsFormValue?.[form.variable] || []}
onChange={(files) => handleFormChange(form.variable, files)}
fileConfig={{
allowed_file_types: form.allowed_file_types,
diff --git a/web/app/components/base/chat/chat/__tests__/utils.spec.ts b/web/app/components/base/chat/chat/__tests__/utils.spec.ts
index 78b3f337acd..fdd8fb87652 100644
--- a/web/app/components/base/chat/chat/__tests__/utils.spec.ts
+++ b/web/app/components/base/chat/chat/__tests__/utils.spec.ts
@@ -89,6 +89,12 @@ describe('chat/chat/utils.ts', () => {
expect(result).toEqual({ test: null })
})
+ it('preserves an explicitly cleared single file in the serialized request body', () => {
+ const inputs = getProcessedInputs({ file: '' }, [inputForm('file', InputVarType.singleFile)])
+
+ expect(JSON.stringify({ inputs })).toBe('{"inputs":{"file":""}}')
+ })
+
it('processes singleFile using transfer_method logic', () => {
const inputs = {
file1: {
diff --git a/web/app/components/base/chat/chat/utils.ts b/web/app/components/base/chat/chat/utils.ts
index f61d0bcf7cb..6be68b3b6f6 100644
--- a/web/app/components/base/chat/chat/utils.ts
+++ b/web/app/components/base/chat/chat/utils.ts
@@ -44,10 +44,12 @@ export const getProcessedInputs = (inputs: Record<string, any>, inputsForm: Inpu
if (inputValue == null) return
if (item.type === InputVarType.singleFile) {
+ if (inputValue === '') return
if ('transfer_method' in inputValue)
processedInputs[item.variable] = processInputFileFromServer(inputValue)
else processedInputs[item.variable] = getProcessedFiles([inputValue])[0]
} else if (item.type === InputVarType.multiFiles) {
+ if (inputValue.length === 0) return
if ('transfer_method' in inputValue[0])
processedInputs[item.variable] = inputValue.map(processInputFileFromServer)
else processedInputs[item.variable] = getProcessedFiles(inputValue)
diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
index 6b9feff64c5..1709be9b3fd 100644
--- a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
@@ -566,6 +566,58 @@ describe('useEmbeddedChatbot', () => {
expect(result.current.clearChatList).toBe(true)
})
+ it('restores required file defaults after completion and reset, with initial URL inputs taking priority', async () => {
+ const file = createChatFileFixture()
+ const replacement = createChatFileFixture({
+ id: 'replacement',
+ uploadedId: 'replacement-upload',
+ })
+ webAppState.embeddedConversationId = null
+ webAppState.appParams = createChatConfigFixture({
+ user_input_form: [
+ { file: { variable: 'file', label: 'File', required: true, default: file } },
+ { 'file-list': { variable: 'files', label: 'Files', required: true, default: [file] } },
+ {
+ 'text-input': {
+ variable: 'topic',
+ label: 'Topic',
+ required: true,
+ default: 'configured',
+ },
+ },
+ ],
+ })
+ setUrlInputs({ topic: 'initial-url' })
+ mockGenerationConversationName.mockResolvedValue(
+ createConversationItem({ id: 'completed-conversation' }),
+ )
+ const { result } = await renderWithClient(() => useEmbeddedChatbot(AppSourceType.webApp))
+ await waitFor(() => expect(result.current.newConversationInputs.topic).toBe('initial-url'))
+
+ act(() => {
+ result.current.handleNewConversationInputsChange({
+ file: replacement,
+ files: [replacement],
+ topic: 'edited',
+ })
+ result.current.handleNewConversationCompleted('completed-conversation')
+ })
+ await waitFor(() =>
+ expect(result.current.currentConversationId).toBe('completed-conversation'),
+ )
+ act(() => result.current.handleNewConversation())
+
+ const onStart = vi.fn()
+ act(() => result.current.handleStartChat(onStart))
+ expect(onStart).toHaveBeenCalledOnce()
+ expect(result.current.currentConversationId).toBe('')
+ expect(result.current.newConversationInputs).toEqual({
+ file,
+ files: [file],
+ topic: 'initial-url',
+ })
+ })
+
it('clears the trial conversation when starting a new chat', async () => {
const { result } = await renderWithClient(
() => useEmbeddedChatbot(AppSourceType.tryApp, 'app-try-1'),
@@ -806,6 +858,30 @@ describe('useEmbeddedChatbot', () => {
})
describe('Required file inputs', () => {
+ it('does not start a conversation after a required file list is cleared', async () => {
+ webAppState.appParams = createChatConfigFixture({
+ user_input_form: [
+ {
+ 'file-list': {
+ variable: 'files',
+ required: true,
+ label: 'Files',
+ default: [createChatFileFixture()],
+ },
+ },
+ ],
+ })
+ const { result } = await renderWithClient(() => useEmbeddedChatbot(AppSourceType.webApp))
+ const onStart = vi.fn()
+
+ act(() => {
+ result.current.handleNewConversationInputsChange({ files: [] })
+ result.current.handleStartChat(onStart)
+ })
+
+ expect(onStart).not.toHaveBeenCalled()
+ })
+
it('should handle multi-file uploading status', async () => {
webAppState.appParams = createChatConfigFixture({
user_input_form: [{ 'file-list': { variable: 'files', required: true, label: 'files' } }],
diff --git a/web/app/components/base/chat/embedded-chatbot/hooks.tsx b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
index c3dbf3a38d4..9edc6159eee 100644
--- a/web/app/components/base/chat/embedded-chatbot/hooks.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
@@ -346,7 +346,13 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri
if (hasEmptyInput) return
if (fileIsUploading) return
const inputValue = newConversationInputsRef.current[variable]
- if ((inputValue === undefined || inputValue === null || inputValue === '') && !silent)
+ if (
+ (inputValue === undefined ||
+ inputValue === null ||
+ inputValue === '' ||
+ (Array.isArray(inputValue) && inputValue.length === 0)) &&
+ !silent
+ )
hasEmptyInput = label as string
if (
(type === InputVarType.singleFile || type === InputVarType.multiFiles) &&
@@ -399,21 +405,27 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri
},
[handleConversationIdInfoChange, setClearChatList],
)
- const handleNewConversation = useCallback(async () => {
+ const handleNewConversation = useCallback(() => {
if (isTryApp) {
setClearChatList(true)
return
}
currentChatInstanceRef.current.handleStop()
+ const conversationInputs: Record<string, InputValueTypes> = {}
+ inputsForms.forEach((item) => {
+ conversationInputs[item.variable] = item.default === '' ? null : (item.default ?? null)
+ })
+ handleNewConversationInputsChange(conversationInputs)
setShowNewConversationItemInList(true)
handleChangeConversation('')
- handleNewConversationInputsChange(await getProcessedInputsFromUrlParams())
setClearChatList(true)
}, [
isTryApp,
setShowNewConversationItemInList,
+ handleChangeConversation,
handleNewConversationInputsChange,
setClearChatList,
+ inputsForms,
])
const handleNewConversationCompleted = useCallback(
(newConversationId: string) => {
diff --git a/web/app/components/base/chat/embedded-chatbot/inputs-form/content.tsx b/web/app/components/base/chat/embedded-chatbot/inputs-form/content.tsx
index 9849b448a04..4220e481382 100644
--- a/web/app/components/base/chat/embedded-chatbot/inputs-form/content.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/inputs-form/content.tsx
@@ -17,6 +17,7 @@ import BoolInput from '@/app/components/workflow/nodes/_base/components/before-r
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { InputVarType } from '@/app/components/workflow/types'
+import { AppSourceType } from '@/service/share'
import { useEmbeddedChatbotContext } from '../context'
type Props = Readonly<{
@@ -28,6 +29,8 @@ const InputsFormContent = ({ showTip }: Props) => {
const baseId = useId()
const {
appParams,
+ appSourceType,
+ clearChatList,
inputsForms,
currentConversationId,
currentConversationInputs,
@@ -36,7 +39,21 @@ const InputsFormContent = ({ showTip }: Props) => {
newConversationInputsRef,
handleNewConversationInputsChange,
} = useEmbeddedChatbotContext()
+ const resettingFiles = clearChatList && appSourceType !== AppSourceType.tryApp
const inputsFormValue = currentConversationId ? currentConversationInputs : newConversationInputs
+ const fileInputsFormValue = currentConversationId
+ ? inputsFormValue
+ : {
+ ...Object.fromEntries(
+ inputsForms
+ .filter(
+ (form) =>
+ form.type === InputVarType.singleFile || form.type === InputVarType.multiFiles,
+ )
+ .map((form) => [form.variable, form.default]),
+ ),
+ ...inputsFormValue,
+ }
const handleFormChange = useCallback(
(variable: string, value: any) => {
@@ -136,10 +153,15 @@ const InputsFormContent = ({ showTip }: Props) => {
</SelectContent>
</Select>
)}
- {form.type === InputVarType.singleFile && (
+ {!resettingFiles && form.type === InputVarType.singleFile && (
<FileUploaderInAttachmentWrapper
- value={inputsFormValue?.[form.variable] ? [inputsFormValue?.[form.variable]] : []}
- onChange={(files) => handleFormChange(form.variable, files[0])}
+ key={currentConversationId}
+ value={
+ fileInputsFormValue?.[form.variable] ? [fileInputsFormValue[form.variable]] : []
+ }
+ onChange={(files) =>
+ handleFormChange(form.variable, files[0] ?? (form.required ? undefined : ''))
+ }
fileConfig={{
allowed_file_types: form.allowed_file_types,
allowed_file_extensions: form.allowed_file_extensions,
@@ -149,9 +171,10 @@ const InputsFormContent = ({ showTip }: Props) => {
}}
/>
)}
- {form.type === InputVarType.multiFiles && (
+ {!resettingFiles && form.type === InputVarType.multiFiles && (
<FileUploaderInAttachmentWrapper
- value={inputsFormValue?.[form.variable] || []}
+ key={currentConversationId}
+ value={fileInputsFormValue?.[form.variable] || []}
onChange={(files) => handleFormChange(form.variable, files)}
fileConfig={{
allowed_file_types: form.allowed_file_types,
diff --git a/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx b/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
index 615e3d739bf..7dddebe6fcf 100644
--- a/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
+++ b/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
@@ -1,16 +1,19 @@
import type { ComponentProps } from 'react'
import type { FileEntity } from '../../types'
import type { FileUpload } from '@/app/components/base/features/types'
-import { render, screen, waitFor } from '@testing-library/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import { TransferMethod } from '@/types/app'
import { FileContextProvider } from '../../store'
import FileFromLinkOrLocal from '../index'
const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
-vi.mock('@/service/base', () => ({ request }))
+// oxlint-disable-next-line typescript/no-deprecated -- Control the existing XHR upload transport while exercising the real uploader lifecycle.
+const upload = vi.hoisted(() => vi.fn<typeof import('@/service/base').upload>())
+vi.mock('@/service/base', () => ({ request, upload }))
vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/apps' }))
const config: FileUpload = {
@@ -42,6 +45,7 @@ const setup = async (
}
beforeEach(() => {
+ upload.mockReset()
request.mockReset()
request.mockImplementation(async () =>
Response.json({
@@ -103,3 +107,21 @@ it('dismisses the upload popover through its trigger', async () => {
)
expect(screen.getByRole('button', { name: 'Open uploads' })).toBeInTheDocument()
})
+
+it('finishes a local upload after its popover closes while the input session remains active', async () => {
+ const pending = createDeferred<Awaited<ReturnType<typeof upload>>>()
+ upload.mockReturnValue(pending.promise)
+ const { user, onChange } = await setup({ showFromLink: false })
+ const button = screen.getByRole('button', { name: /uploadFromComputer/ })
+ const input = button.querySelector<HTMLInputElement>('input[type="file"]')!
+ await user.upload(input, new File(['report'], 'report.txt', { type: 'text/plain' }))
+ await waitFor(() => expect(upload).toHaveBeenCalledOnce())
+ await user.click(screen.getByRole('button', { name: 'Close uploads' }))
+ expect(screen.queryByRole('button', { name: /uploadFromComputer/ })).not.toBeInTheDocument()
+
+ await act(async () => pending.resolve({ id: 'uploaded-report' }))
+
+ expect(onChange).toHaveBeenLastCalledWith([
+ expect.objectContaining({ uploadedId: 'uploaded-report', progress: 100 }),
+ ])
+})
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 d208b9dfd24..dadf176e46e 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
@@ -1,12 +1,17 @@
import type { FileEntity } from '../../types'
import type { FileUpload } from '@/app/components/base/features/types'
-import { screen } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { toast } from '@/app/notifications'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import { TransferMethod } from '@/types/app'
import { fileUpload } from '../../utils'
import FileUploaderInAttachmentWrapper from '../index'
+// oxlint-disable-next-line typescript/no-deprecated -- Defer the generated client's transport response to test uploads across session changes.
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+vi.mock('@/service/base', () => ({ request }))
vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/' }))
vi.mock('../../utils', async (importOriginal) => ({
...(await importOriginal<typeof import('../../utils')>()),
@@ -128,3 +133,106 @@ it('retries the original file and stores the successful upload id', async () =>
screen.queryByRole('button', { name: 'common.operation.retry report.txt' }),
).not.toBeInTheDocument()
})
+
+it('ignores pending local upload progress and results after switching uploader sessions', async () => {
+ const user = userEvent.setup()
+ vi.mocked(fileUpload).mockReset()
+ const showError = vi.spyOn(toast, 'error').mockReturnValue('toast-id')
+ const onChange = vi.fn()
+ const fileConfig = createFileConfig()
+ const { rerender } = render(
+ <FileUploaderInAttachmentWrapper key="old" onChange={onChange} fileConfig={fileConfig} />,
+ )
+ const button = screen.getByRole('button', { name: /fileUploader.uploadFromComputer/ })
+ const input = button.querySelector<HTMLInputElement>('input[type="file"]')!
+ await user.upload(input, [
+ new File(['first'], 'pending-first.txt', { type: 'text/plain' }),
+ new File(['second'], 'pending-second.txt', { type: 'text/plain' }),
+ ])
+ await waitFor(() => expect(fileUpload).toHaveBeenCalledTimes(2))
+ expect(screen.getByText('pending-first.txt')).toBeInTheDocument()
+ expect(screen.getByText('pending-second.txt')).toBeInTheDocument()
+
+ const currentFile = createFile({ id: 'current', name: 'current.txt' })
+ rerender(
+ <FileUploaderInAttachmentWrapper
+ key="current"
+ value={[currentFile]}
+ onChange={onChange}
+ fileConfig={fileConfig}
+ />,
+ )
+ onChange.mockClear()
+ const [successful, failed] = vi.mocked(fileUpload).mock.calls.map(([callbacks]) => callbacks)
+ act(() => {
+ successful!.onProgressCallback(50)
+ successful!.onSuccessCallback({
+ id: 'old-upload',
+ name: 'pending-first.txt',
+ size: 5,
+ mime_type: 'text/plain',
+ extension: 'txt',
+ created_at: 1,
+ created_by: 'user-1',
+ preview_url: null,
+ source_url: '',
+ })
+ failed!.onErrorCallback(new Error('Old upload failed'))
+ })
+
+ expect(onChange).not.toHaveBeenCalled()
+ expect(showError).not.toHaveBeenCalled()
+ expect(screen.getByText(currentFile.name)).toBeInTheDocument()
+ expect(screen.queryByText('pending-first.txt')).not.toBeInTheDocument()
+ showError.mockRestore()
+})
+
+it.each(['success', 'failure'] as const)(
+ 'ignores a pending remote upload %s after switching uploader sessions',
+ async (outcome) => {
+ const user = userEvent.setup()
+ const pending = createDeferred<Response>()
+ request.mockReset().mockReturnValue(pending.promise)
+ const showError = vi.spyOn(toast, 'error').mockReturnValue('toast-id')
+ const onChange = vi.fn()
+ const fileConfig = createFileConfig()
+ const { rerender, queryClient } = render(
+ <FileUploaderInAttachmentWrapper key="old" onChange={onChange} fileConfig={fileConfig} />,
+ )
+ await user.click(screen.getByRole('button', { name: /fileUploader.pasteFileLink/ }))
+ await user.type(screen.getByRole('textbox'), 'https://example.com/old.txt')
+ await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))
+ await waitFor(() => expect(request).toHaveBeenCalledOnce())
+ expect(onChange).toHaveBeenCalled()
+
+ const currentFile = createFile({ id: 'current', name: 'current.txt' })
+ rerender(
+ <FileUploaderInAttachmentWrapper
+ key="current"
+ value={[currentFile]}
+ onChange={onChange}
+ fileConfig={fileConfig}
+ />,
+ )
+ onChange.mockClear()
+ await act(async () => {
+ if (outcome === 'failure') pending.reject(new Error('Old upload failed'))
+ else
+ pending.resolve(
+ Response.json({
+ id: 'old-upload',
+ name: 'old.txt',
+ size: 10,
+ mime_type: 'text/plain',
+ url: 'https://example.com/old.txt',
+ }),
+ )
+ })
+ await waitFor(() => expect(queryClient.isMutating()).toBe(0))
+
+ expect(screen.getByText(currentFile.name)).toBeInTheDocument()
+ expect(onChange).not.toHaveBeenCalled()
+ expect(showError).not.toHaveBeenCalled()
+ showError.mockRestore()
+ },
+)
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 9f0b6de57c5..8cdf5c20dd5 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
@@ -1,9 +1,10 @@
+import type { Ref } from 'react'
import type { FileEntity } from '../types'
import type { FileUpload } from '@/app/components/base/features/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { RiLink, RiUploadCloud2Line } from '@remixicon/react'
-import { useCallback } from 'react'
+import { useCallback, useImperativeHandle } from 'react'
import { useTranslation } from 'react-i18next'
import { TransferMethod } from '@/types/app'
import FileFromLinkOrLocal from '../file-from-link-or-local'
@@ -17,14 +18,23 @@ type Option = {
label: string
icon: React.JSX.Element
}
+export type FileUploaderInAttachmentRef = {
+ clear: () => void
+}
type FileUploaderInAttachmentProps = {
+ ref?: Ref<FileUploaderInAttachmentRef>
isDisabled?: boolean
fileConfig: FileUpload
}
-const FileUploaderInAttachment = ({ isDisabled, fileConfig }: FileUploaderInAttachmentProps) => {
+const FileUploaderInAttachment = ({
+ ref,
+ isDisabled,
+ fileConfig,
+}: FileUploaderInAttachmentProps) => {
const { t } = useTranslation(['common'])
const files = useStore((s) => s.files)
- const { handleRemoveFile, handleReUploadFile } = useFile(fileConfig)
+ const { handleRemoveFile, handleReUploadFile, handleClearFiles } = useFile(fileConfig)
+ useImperativeHandle(ref, () => ({ clear: handleClearFiles }), [handleClearFiles])
const options = [
{
value: TransferMethod.local_file,
@@ -110,12 +120,14 @@ const FileUploaderInAttachment = ({ isDisabled, fileConfig }: FileUploaderInAtta
}
export type FileUploaderInAttachmentWrapperProps = {
+ ref?: Ref<FileUploaderInAttachmentRef>
value?: FileEntity[]
onChange: (files: FileEntity[]) => void
fileConfig: FileUpload
isDisabled?: boolean
}
const FileUploaderInAttachmentWrapper = ({
+ ref,
value,
onChange,
fileConfig,
@@ -123,7 +135,7 @@ const FileUploaderInAttachmentWrapper = ({
}: FileUploaderInAttachmentWrapperProps) => {
return (
<FileContextProvider value={value} onChange={onChange}>
- <FileUploaderInAttachment isDisabled={isDisabled} fileConfig={fileConfig} />
+ <FileUploaderInAttachment ref={ref} isDisabled={isDisabled} fileConfig={fileConfig} />
</FileContextProvider>
)
}
diff --git a/web/app/components/base/file-uploader/hooks.ts b/web/app/components/base/file-uploader/hooks.ts
index f8b94b6466e..2e7b67cb64a 100644
--- a/web/app/components/base/file-uploader/hooks.ts
+++ b/web/app/components/base/file-uploader/hooks.ts
@@ -196,6 +196,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
handleUpdateFile({ ...uploadingFile, uploadedId: res.id, progress: 100 })
},
onErrorCallback: (error?: unknown) => {
+ if (!fileStore.getState().isActive) return
const errorMessage = getFileUploadErrorMessage(
error,
t(($) => $['fileUploader.uploadFromComputerUploadError'], { ns: 'common' }),
@@ -222,6 +223,10 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
const startProgressTimer = useCallback(
(fileId: string) => {
const timer = setInterval(() => {
+ if (!fileStore.getState().isActive) {
+ clearInterval(timer)
+ return
+ }
const files = fileStore.getState().files
const file = files.find((file) => file.id === fileId)
@@ -259,6 +264,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
remoteUpload
.then((res) => {
+ if (!fileStore.getState().isActive) return
const newFile = {
...uploadingFile,
type: res.mime_type ?? '',
@@ -290,6 +296,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
else handleUpdateFile(newFile)
})
.catch((error: unknown) => {
+ if (!fileStore.getState().isActive) return
if (!isAppAccessError(error) && !isAbortError(error))
toast.error(t(($) => $['fileUploader.pasteFileLinkInvalid'], { ns: 'common' }))
handleRemoveFile(uploadingFile.id)
@@ -310,6 +317,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
trialAppId,
uploadConsoleRemoteFile,
uploadTrialRemoteFile,
+ fileStore,
],
)
@@ -356,6 +364,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
reader.addEventListener(
'load',
() => {
+ if (!fileStore.getState().isActive) return
const uploadingFile = {
id: uuid4(),
name: file.name,
@@ -381,6 +390,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
handleUpdateFile({ ...uploadingFile, uploadedId: res.id, progress: 100 })
},
onErrorCallback: (error?: unknown) => {
+ if (!fileStore.getState().isActive) return
const errorMessage = getFileUploadErrorMessage(
error,
t(($) => $['fileUploader.uploadFromComputerUploadError'], { ns: 'common' }),
@@ -405,6 +415,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
reader.addEventListener(
'error',
() => {
+ if (!fileStore.getState().isActive) return
toast.error(t(($) => $['fileUploader.uploadFromComputerReadError'], { ns: 'common' }))
},
false,
@@ -424,6 +435,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
fileConfig?.allowed_file_types,
fileConfig?.allowed_file_extensions,
fileConfig?.enabled,
+ fileStore,
],
)
diff --git a/web/app/components/base/file-uploader/store.tsx b/web/app/components/base/file-uploader/store.tsx
index 51355abd770..41c64c0b728 100644
--- a/web/app/components/base/file-uploader/store.tsx
+++ b/web/app/components/base/file-uploader/store.tsx
@@ -1,8 +1,9 @@
import type { FileEntity } from './types'
-import { createContext, use, useState } from 'react'
+import { createContext, use, useEffect, useState } from 'react'
import { create, useStore as useZustandStore } from 'zustand'
type Shape = {
+ isActive: boolean
files: FileEntity[]
setFiles: (files: FileEntity[]) => void
}
@@ -11,9 +12,11 @@ export const createFileStore = (
value: FileEntity[] = [],
onChange?: (files: FileEntity[]) => void,
) => {
- return create<Shape>((set) => ({
+ return create<Shape>((set, get) => ({
+ isActive: true,
files: value ? [...value] : [],
setFiles: (files) => {
+ if (!get().isActive) return
set({ files })
onChange?.(files)
},
@@ -42,5 +45,12 @@ type FileProviderProps = {
export const FileContextProvider = ({ children, value, onChange }: FileProviderProps) => {
const [store] = useState(() => createFileStore(value, onChange))
+ useEffect(() => {
+ store.setState({ isActive: true })
+ return () => {
+ store.setState({ isActive: false })
+ }
+ }, [store])
+
return <FileContext.Provider value={store}>{children}</FileContext.Provider>
}
diff --git a/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsx b/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsx
index ba4c64a3cff..20617ba5c4f 100644
--- a/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsx
+++ b/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsx
@@ -1,4 +1,5 @@
import type { InputValueTypes } from '../../types'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { fileUpload } from '@/app/components/base/file-uploader/utils'
import type { PromptConfig, PromptVariable } from '@/models/debug'
import type { SiteInfo } from '@/models/share'
@@ -7,10 +8,25 @@ import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { Resolution, TransferMethod } from '@/types/app'
+import { userInputsFormToPromptVariables } from '@/utils/model-config'
+import { buildResultRequestData, validateResultRequest } from '../../result/result-request'
import RunOnce from '../index'
+const createFileEntity = (overrides: Partial<FileEntity> = {}): FileEntity => ({
+ id: 'default-file',
+ name: 'default.txt',
+ size: 128,
+ type: 'text/plain',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ uploadedId: 'default-upload',
+ ...overrides,
+})
+
vi.mock('@/hooks/use-breakpoints', () => {
const MediaType = {
pc: 'pc',
@@ -35,30 +51,21 @@ vi.mock('@/app/components/base/file-uploader/utils', async (importOriginal) => (
}))
beforeEach(() => {
- upload.mockImplementation(({ onSuccessCallback }) =>
+ upload.mockImplementation(({ file, onSuccessCallback }) => {
onSuccessCallback({
- id: 'upload-1',
- name: 'example.txt',
- size: 7,
- mime_type: 'text/plain',
+ id: `upload-${file.name}`,
+ name: file.name,
+ size: file.size,
+ mime_type: file.type,
extension: 'txt',
created_at: 1,
- created_by: 'account-1',
+ created_by: 'user-1',
preview_url: null,
source_url: '',
- }),
- )
+ })
+ })
})
-const uploadedFile = expect.objectContaining({
- name: 'example.txt',
- size: 7,
- type: 'text/plain',
- progress: 100,
- transferMethod: TransferMethod.local_file,
- supportFileType: 'document',
- uploadedId: 'upload-1',
-})
const getInputs = () =>
JSON.parse(screen.getByRole('status', { name: 'Input values' }).textContent!)
@@ -126,9 +133,11 @@ const setup = (
) => {
const onInputsChange = vi.fn()
const onSend = vi.fn()
+ const onValidation = vi.fn()
const onVisionFilesChange = vi.fn()
const Wrapper = () => {
+ const { t } = useTranslation(['share', 'appDebug', 'common', 'workflow'])
const [inputs, setInputs] = useState<Record<string, InputValueTypes>>({})
const inputsRef = useRef<Record<string, InputValueTypes>>({})
return (
@@ -144,7 +153,25 @@ const setup = (
setInputs(updated)
onInputsChange(updated)
}}
- onSend={() => onSend(inputsRef.current)}
+ onSend={() => {
+ const validation = validateResultRequest({
+ completionFiles: [],
+ inputs,
+ isCallBatchAPI: false,
+ promptConfig: overrides.promptConfig || basePromptConfig,
+ t,
+ })
+ onValidation(validation)
+ if (!validation.canSend) return
+ onSend(
+ buildResultRequestData({
+ completionFiles: [],
+ inputs,
+ promptConfig: overrides.promptConfig || basePromptConfig,
+ visionConfig: overrides.visionConfig || baseVisionConfig,
+ }),
+ )
+ }}
visionConfig={overrides.visionConfig || baseVisionConfig}
onVisionFilesChange={onVisionFilesChange}
runControl={overrides.runControl ?? null}
@@ -158,6 +185,7 @@ const setup = (
...utils,
onInputsChange,
onSend,
+ onValidation,
onVisionFilesChange,
}
}
@@ -235,10 +263,12 @@ describe('RunOnce', () => {
})
await user.click(screen.getByRole('button', { name: 'share.generation.run' }))
expect(onSend).toHaveBeenCalledExactlyOnceWith({
- textInput: 'default text',
- paragraphInput: 'paragraph default',
- numberInput: 42,
- checkboxInput: false,
+ inputs: {
+ textInput: 'default text',
+ paragraphInput: 'paragraph default',
+ numberInput: 42,
+ checkboxInput: false,
+ },
})
})
@@ -307,63 +337,143 @@ describe('RunOnce', () => {
})
describe('file input types', () => {
- it('should render file uploader for single file input', async () => {
- const user = userEvent.setup()
- const promptConfig: PromptConfig = {
- prompt_template: 'template',
- prompt_variables: [
- createPromptVariable({
- key: 'fileInput',
- name: 'File Input',
- type: 'file',
- }),
- ],
- }
- const { onInputsChange } = setup({
- promptConfig,
- visionConfig: { ...baseVisionConfig, enabled: false },
- })
- await waitFor(() => {
- expect(onInputsChange).toHaveBeenCalledWith({
- fileInput: undefined,
+ it.each([
+ { type: 'file', required: true },
+ { type: 'file', required: false },
+ { type: 'file-list', required: true },
+ { type: 'file-list', required: false },
+ ])(
+ 'should submit, clear and replace the configured $type default (required: $required)',
+ async ({ type, required }) => {
+ const user = userEvent.setup()
+ const file = createFileEntity()
+ const remoteFile = createFileEntity({
+ id: 'remote-file',
+ name: 'remote.txt',
+ transferMethod: TransferMethod.remote_url,
+ uploadedId: undefined,
+ url: 'https://example.com/remote.txt',
+ })
+ const promptConfig: PromptConfig = {
+ prompt_template: '',
+ prompt_variables: userInputsFormToPromptVariables([
+ {
+ [type]: {
+ variable: 'attachment',
+ label: 'Attachment',
+ required,
+ default: type === 'file' ? file : [file, remoteFile],
+ allowed_file_types: ['document'],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ max_length: 2,
+ },
+ },
+ ]),
+ }
+ const { onSend, onValidation } = setup({
+ promptConfig,
+ visionConfig: { ...baseVisionConfig, enabled: false },
+ })
+ const uploadButton = await screen.findByRole('button', {
+ name: 'common.fileUploader.uploadFromComputer',
+ })
+ const runButton = screen.getByRole('button', { name: 'share.generation.run' })
+ const assertEmptySubmission = async () => {
+ onSend.mockClear()
+ await user.click(runButton)
+ if (required) {
+ expect(onValidation).toHaveBeenLastCalledWith(
+ expect.objectContaining({ canSend: false }),
+ )
+ expect(onSend).not.toHaveBeenCalled()
+ } else {
+ expect(onSend).toHaveBeenLastCalledWith({
+ inputs: { attachment: type === 'file' ? '' : [] },
+ })
+ }
+ }
+
+ expect(screen.getByText('default.txt')).toBeInTheDocument()
+ expect(uploadButton).toBeDisabled()
+ await user.click(runButton)
+ const expectedFile = {
+ type: 'document',
+ transfer_method: TransferMethod.local_file,
+ upload_file_id: 'default-upload',
+ url: '',
+ }
+ const expectedRemoteFile = {
+ type: 'document',
+ transfer_method: TransferMethod.remote_url,
+ upload_file_id: '',
+ url: 'https://example.com/remote.txt',
+ }
+ expect(onSend).toHaveBeenLastCalledWith({
+ inputs: {
+ attachment: type === 'file' ? expectedFile : [expectedFile, expectedRemoteFile],
+ },
})
- })
- await user.upload(
- document.querySelector<HTMLInputElement>('input[type="file"]')!,
- new File(['example'], 'example.txt', { type: 'text/plain' }),
- )
- expect(await screen.findByText('example.txt')).toBeInTheDocument()
- await waitFor(() => expect(getInputs()).toEqual({ fileInput: uploadedFile }))
- })
- it('should render file uploader for file-list input', async () => {
- const user = userEvent.setup()
- const promptConfig: PromptConfig = {
- prompt_template: 'template',
- prompt_variables: [
- createPromptVariable({
- key: 'fileListInput',
- name: 'File List Input',
- type: 'file-list',
- }),
- ],
- }
- const { onInputsChange } = setup({
- promptConfig,
- visionConfig: { ...baseVisionConfig, enabled: false },
- })
- await waitFor(() => {
- expect(onInputsChange).toHaveBeenCalledWith({
- fileListInput: [],
+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))
+ expect(screen.queryByText('default.txt')).not.toBeInTheDocument()
+ expect(screen.queryByText('remote.txt')).not.toBeInTheDocument()
+ expect(uploadButton).toBeEnabled()
+ await assertEmptySubmission()
+
+ const replacementFile = new File(['replacement'], 'replacement.txt', { type: 'text/plain' })
+ const remainingFile = new File(['remaining'], 'remaining.txt', { type: 'text/plain' })
+ await user.upload(
+ uploadButton.querySelector('input')!,
+ type === 'file' ? replacementFile : [replacementFile, remainingFile],
+ )
+ await waitFor(() => {
+ const uploaded = expect.objectContaining({
+ uploadedId: 'upload-replacement.txt',
+ progress: 100,
+ })
+ const remaining = expect.objectContaining({
+ uploadedId: 'upload-remaining.txt',
+ progress: 100,
+ })
+ expect(getInputs()).toEqual({
+ attachment: type === 'file' ? uploaded : [uploaded, remaining],
+ })
})
- })
- await user.upload(
- document.querySelector<HTMLInputElement>('input[type="file"]')!,
- new File(['example'], 'example.txt', { type: 'text/plain' }),
- )
- expect(await screen.findByText('example.txt')).toBeInTheDocument()
- await waitFor(() => expect(getInputs()).toEqual({ fileListInput: [uploadedFile] }))
- })
+ expect(screen.getByText('replacement.txt')).toBeInTheDocument()
+ await user.click(runButton)
+ const expectedReplacementFile = {
+ ...expectedFile,
+ upload_file_id: 'upload-replacement.txt',
+ }
+ const expectedRemainingFile = { ...expectedFile, upload_file_id: 'upload-remaining.txt' }
+ expect(onSend).toHaveBeenLastCalledWith({
+ inputs: {
+ attachment:
+ type === 'file'
+ ? expectedReplacementFile
+ : [expectedReplacementFile, expectedRemainingFile],
+ },
+ })
+
+ await user.click(
+ screen.getByRole('button', { name: 'common.operation.remove replacement.txt' }),
+ )
+ expect(screen.queryByText('replacement.txt')).not.toBeInTheDocument()
+ if (type === 'file-list') {
+ expect(screen.getByText('remaining.txt')).toBeInTheDocument()
+ await user.click(runButton)
+ expect(onSend).toHaveBeenLastCalledWith({
+ inputs: { attachment: [expectedRemainingFile] },
+ })
+ await user.click(
+ screen.getByRole('button', { name: 'common.operation.remove remaining.txt' }),
+ )
+ expect(screen.queryByText('remaining.txt')).not.toBeInTheDocument()
+ }
+ expect(uploadButton).toBeEnabled()
+ await assertEmptySubmission()
+ },
+ )
})
describe('json_object input type', () => {
diff --git a/web/app/components/share/text-generation/run-once/index.tsx b/web/app/components/share/text-generation/run-once/index.tsx
index 38b8c621e69..eeeef8d7236 100644
--- a/web/app/components/share/text-generation/run-once/index.tsx
+++ b/web/app/components/share/text-generation/run-once/index.tsx
@@ -1,5 +1,6 @@
import type { FC, SubmitEvent } from 'react'
import type { InputValueTypes } from '../types'
+import type { FileUploaderInAttachmentRef } from '@/app/components/base/file-uploader/file-uploader-in-attachment'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { PromptConfig } from '@/models/debug'
import type { SiteInfo } from '@/models/share'
@@ -19,7 +20,7 @@ import {
import { Textarea } from '@langgenius/dify-ui/textarea'
import { RiLoader2Line, RiPlayLargeLine } from '@remixicon/react'
import * as React from 'react'
-import { useCallback, useEffect, useId, useState } from 'react'
+import { useCallback, useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
import TextGenerationImageUploader from '@/app/components/base/image-uploader/text-generation-image-uploader'
@@ -58,6 +59,15 @@ const RunOnce: FC<IRunOnceProps> = ({
const media = useBreakpoints()
const isPC = media === MediaType.pc
const [isInitialized, setIsInitialized] = useState(false)
+ const fileUploadersRef = useRef(new Map<string, FileUploaderInAttachmentRef>())
+
+ const handleInputsChange = useCallback(
+ (newInputs: Record<string, any>) => {
+ onInputsChange(newInputs)
+ inputsRef.current = newInputs
+ },
+ [onInputsChange, inputsRef],
+ )
const onClear = () => {
const newInputs: Record<string, InputValueTypes> = {}
@@ -65,9 +75,12 @@ const RunOnce: FC<IRunOnceProps> = ({
if (item.type === 'string' || item.type === 'paragraph') newInputs[item.key] = ''
else if (item.type === 'number') newInputs[item.key] = ''
else if (item.type === 'checkbox') newInputs[item.key] = false
+ else if (item.type === 'file' && item.required === false) newInputs[item.key] = ''
+ else if (item.type === 'file-list') newInputs[item.key] = []
else newInputs[item.key] = undefined
})
- onInputsChange(newInputs)
+ fileUploadersRef.current.forEach((uploader) => uploader.clear())
+ handleInputsChange(newInputs)
}
const onSubmit = (e: SubmitEvent<HTMLFormElement>) => {
@@ -85,14 +98,6 @@ const RunOnce: FC<IRunOnceProps> = ({
[isRunning, runControl],
)
- const handleInputsChange = useCallback(
- (newInputs: Record<string, any>) => {
- onInputsChange(newInputs)
- inputsRef.current = newInputs
- },
- [onInputsChange, inputsRef],
- )
-
useEffect(() => {
if (isInitialized) return
const newInputs: Record<string, any> = {}
@@ -102,8 +107,13 @@ const RunOnce: FC<IRunOnceProps> = ({
newInputs[item.key] = item.default || ''
else if (item.type === 'number') newInputs[item.key] = item.default ?? ''
else if (item.type === 'checkbox') newInputs[item.key] = item.default || false
- else if (item.type === 'file') newInputs[item.key] = undefined
- else if (item.type === 'file-list') newInputs[item.key] = []
+ else if (item.type === 'file')
+ newInputs[item.key] =
+ item.default && typeof item.default === 'object' && !Array.isArray(item.default)
+ ? item.default
+ : undefined
+ else if (item.type === 'file-list')
+ newInputs[item.key] = Array.isArray(item.default) ? item.default : []
else newInputs[item.key] = undefined
})
onInputsChange(newInputs)
@@ -222,6 +232,10 @@ const RunOnce: FC<IRunOnceProps> = ({
)}
{item.type === 'file' && (
<FileUploaderInAttachmentWrapper
+ ref={(uploader) => {
+ if (uploader) fileUploadersRef.current.set(item.key, uploader)
+ else fileUploadersRef.current.delete(item.key)
+ }}
value={
inputs[item.key] &&
typeof inputs[item.key] === 'object' &&
@@ -230,7 +244,8 @@ const RunOnce: FC<IRunOnceProps> = ({
: []
}
onChange={(files) => {
- handleInputsChange({ ...inputsRef.current, [item.key]: files[0] })
+ const value = files[0] ?? (item.required === false ? '' : undefined)
+ handleInputsChange({ ...inputsRef.current, [item.key]: value })
}}
fileConfig={{
...item.config,
@@ -240,6 +255,10 @@ const RunOnce: FC<IRunOnceProps> = ({
)}
{item.type === 'file-list' && (
<FileUploaderInAttachmentWrapper
+ ref={(uploader) => {
+ if (uploader) fileUploadersRef.current.set(item.key, uploader)
+ else fileUploadersRef.current.delete(item.key)
+ }}
value={
Array.isArray(inputs[item.key])
? (inputs[item.key] as FileEntity[])
diff --git a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx
index 3e1e9a1ac2f..b3ef357ff82 100644
--- a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx
@@ -1,6 +1,7 @@
import type { Shape as HooksStoreShape } from '../../hooks-store/store'
import type { RunFile } from '../../types'
import type { FileUpload } from '@/app/components/base/features/types'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { TransferMethod } from '@/types/app'
@@ -10,9 +11,16 @@ import { InputVarType, WorkflowRunningStatus } from '../../types'
import InputsPanel from '../inputs-panel'
const mockNotify = vi.fn()
+const request = vi.hoisted(() => vi.fn<() => Promise<Response>>())
+
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request,
+}))
vi.mock('next/navigation', () => ({
useParams: () => ({}),
+ usePathname: () => '/apps',
}))
vi.mock('@/app/notifications', async (importOriginal) => ({
@@ -66,6 +74,7 @@ const renderInputsPanel = (
describe('InputsPanel', () => {
beforeEach(() => {
vi.clearAllMocks()
+ request.mockReset()
})
describe('Rendering', () => {
@@ -239,6 +248,99 @@ describe('InputsPanel', () => {
})
})
+ it.each([false, true])(
+ 'submits the selected file and preserves clear semantics (required: %s)',
+ async (required) => {
+ const user = userEvent.setup()
+ const handleRun = vi.fn()
+ const defaultFile: FileEntity = {
+ id: 'default-file',
+ name: 'default.txt',
+ size: 10,
+ type: 'text/plain',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ uploadedId: 'default-upload',
+ }
+ renderInputsPanel(
+ createStartNode({
+ data: {
+ variables: [
+ {
+ type: InputVarType.singleFile,
+ variable: 'file',
+ label: 'File',
+ required,
+ default: defaultFile,
+ allowed_file_types: ['document'],
+ allowed_file_upload_methods: [TransferMethod.remote_url],
+ },
+ ],
+ },
+ }),
+ { hooksStoreProps: createHooksStoreProps({ handleRun, fileSettings: { enabled: false } }) },
+ )
+ const runButton = screen.getByRole('button', { name: 'workflow.singleRun.startRun' })
+ await user.click(runButton)
+ expect(handleRun).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ inputs: {
+ file: {
+ type: 'document',
+ transfer_method: 'local_file',
+ url: '',
+ upload_file_id: 'default-upload',
+ },
+ },
+ }),
+ )
+
+ await user.click(screen.getByRole('button', { name: /remove.*default.txt/ }))
+ expect(screen.queryByText('default.txt')).not.toBeInTheDocument()
+ handleRun.mockClear()
+ await user.click(runButton)
+ if (required) {
+ expect(handleRun).not.toHaveBeenCalled()
+ expect(mockNotify).toHaveBeenCalledWith({
+ type: 'error',
+ message: 'appDebug.errorMessage.valueOfVarRequired:{"key":"File"}',
+ })
+ } else {
+ expect(handleRun).toHaveBeenCalledWith(expect.objectContaining({ inputs: { file: '' } }))
+ }
+
+ const replacementUrl = 'https://example.com/replacement.txt'
+ request.mockResolvedValue(
+ Response.json({
+ id: 'replacement-upload',
+ name: 'replacement.txt',
+ mime_type: 'text/plain',
+ size: 10,
+ url: replacementUrl,
+ }),
+ )
+ await user.click(screen.getByRole('button', { name: /fileUploader.pasteFileLink/ }))
+ await user.type(screen.getByPlaceholderText(/pasteFileLinkInputPlaceholder/), replacementUrl)
+ await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))
+ await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument())
+ await user.keyboard('{Escape}')
+ await user.click(runButton)
+ expect(handleRun).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ inputs: {
+ file: {
+ type: 'document',
+ transfer_method: 'remote_url',
+ url: replacementUrl,
+ upload_file_id: 'replacement-upload',
+ },
+ },
+ }),
+ )
+ },
+ )
+
it.each([false, true])(
'accepts a zero default or explicit numeric override (%s)',
async (override) => {
diff --git a/web/app/components/workflow/panel/inputs-panel.tsx b/web/app/components/workflow/panel/inputs-panel.tsx
index 79731eb8c5c..b9213af53bf 100644
--- a/web/app/components/workflow/panel/inputs-panel.tsx
+++ b/web/app/components/workflow/panel/inputs-panel.tsx
@@ -1,4 +1,5 @@
import type { StartNodeType } from '../nodes/start/types'
+import type { InputVar } from '../types'
import { Button } from '@langgenius/dify-ui/button'
import { memo, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -31,7 +32,7 @@ const InputsPanel = ({ onRun }: Props) => {
const { checkInputsForm } = useCheckInputsForms()
const initialInputs = useMemo(() => {
- const result = { ...inputs }
+ const result: Record<string, InputVar['default']> = { ...inputs }
if (startVariables) {
startVariables.forEach((variable) => {
if (variable.default !== undefined) result[variable.variable] = variable.default
@@ -83,8 +84,18 @@ const InputsPanel = ({ onRun }: Props) => {
const doRun = useCallback(() => {
if (!canRun) return
if (!checkInputsForm(initialInputs, variables as any)) return
+ const processedInputs = getProcessedInputs(initialInputs, variables as any)
+ // null selects the backend default; an empty string explicitly clears an optional file.
+ for (const variable of variables) {
+ if (
+ variable.type === InputVarType.singleFile &&
+ !variable.required &&
+ processedInputs[variable.variable] === null
+ )
+ processedInputs[variable.variable] = ''
+ }
onRun()
- handleRun({ inputs: getProcessedInputs(initialInputs, variables as any), files })
+ handleRun({ inputs: processedInputs, files })
}, [canRun, files, handleRun, initialInputs, onRun, variables, checkInputsForm])
return (
diff --git a/web/app/components/workflow/types.ts b/web/app/components/workflow/types.ts
index 6381b9d2585..ad3554c6a39 100644
--- a/web/app/components/workflow/types.ts
+++ b/web/app/components/workflow/types.ts
@@ -2,6 +2,7 @@ import type { RagPipelineDatasourceProviderResponse } from '@dify/contracts/api/
import type { SchemaDefinitionItemResponse } from '@dify/contracts/api/console/spec/types.gen'
import type { MarketplacePlugin } from '@dify/contracts/marketplace'
import type { Edge as ReactFlowEdge, Node as ReactFlowNode, Viewport, XYPosition } from 'reactflow'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { PluginMeta } from '@/app/components/plugins/types'
import type { Collection, Tool } from '@/app/components/tools/types'
import type {
@@ -248,7 +249,7 @@ export type InputVar = {
}
variable: string
max_length?: number
- default?: string | number | boolean
+ default?: string | number | boolean | FileEntity | FileEntity[]
required: boolean
hint?: string
options?: string[]
diff --git a/web/models/debug.ts b/web/models/debug.ts
index 059f59991b6..9c570e3206c 100644
--- a/web/models/debug.ts
+++ b/web/models/debug.ts
@@ -3,6 +3,7 @@ import type {
AppSuggestedQuestionsAfterAnswerResponse,
} from '@dify/contracts/api/console/apps/types.gen'
import type { FileUpload } from '@/app/components/base/features/types'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type {
MetadataFilteringConditions,
MetadataFilteringModeEnum,
@@ -57,7 +58,7 @@ export type PromptVariable = {
key: string
name: string
type: string // "string" | "number" | "select",
- default?: string | number | boolean
+ default?: string | number | boolean | FileEntity | FileEntity[]
required?: boolean
options?: string[]
max_length?: number
diff --git a/web/service/console/app-parameters-select.ts b/web/service/console/app-parameters-select.ts
index 673b6a25b37..deb69e9704b 100644
--- a/web/service/console/app-parameters-select.ts
+++ b/web/service/console/app-parameters-select.ts
@@ -1,5 +1,6 @@
import type { Parameters as AppParameters } from '@dify/contracts/api/console/installed-apps/types.gen'
import type { ChatConfig } from '@/app/components/base/chat/types'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { ANNOTATION_DEFAULT, DEFAULT_AGENT_SETTING } from '@/config'
import { PromptMode } from '@/models/debug'
@@ -168,6 +169,10 @@ const normalizeTextInputForm = (value: Record<string, unknown>) => {
const normalizeFileInputForm = (value: Record<string, unknown>) => {
return {
...normalizeBaseInputForm(value),
+ default:
+ isRecord(value.default) || (Array.isArray(value.default) && value.default.every(isRecord))
+ ? (value.default as FileEntity | FileEntity[])
+ : getString(value.default),
max_length: getNumber(value.max_length, 1),
allowed_file_upload_methods: getTransferMethods(value.allowed_file_upload_methods, [
TransferMethod.local_file,
diff --git a/web/service/share.spec.ts b/web/service/share.spec.ts
index f2b9dbaad16..d23aee42137 100644
--- a/web/service/share.spec.ts
+++ b/web/service/share.spec.ts
@@ -355,6 +355,27 @@ it.each([
{ source: AppSourceType.tryApp, prefix: 'trial-apps' },
])('loads $source parameters through the shared typed UI adapter', async ({ source, prefix }) => {
const numberDefaults = [0, 42, -7.123456, '12.5']
+ const fileDefault = {
+ id: 'default-file',
+ name: 'default.txt',
+ size: 128,
+ type: 'text/plain',
+ progress: 100,
+ supportFileType: 'document',
+ transferMethod: 'local_file',
+ uploadedId: 'default-upload',
+ }
+ const fileListDefault = [
+ fileDefault,
+ {
+ ...fileDefault,
+ id: 'remote-file',
+ name: 'remote.txt',
+ transferMethod: 'remote_url',
+ uploadedId: '',
+ url: 'https://example.com/remote.txt',
+ },
+ ]
const parameters: AppParameters = {
opening_statement: null,
suggested_questions: ['Next question'],
@@ -400,6 +421,17 @@ it.each([
hide: true,
},
})),
+ {
+ file: { variable: 'attachment', label: 'Attachment', required: true, default: fileDefault },
+ },
+ {
+ 'file-list': {
+ variable: 'attachments',
+ label: 'Attachments',
+ required: true,
+ default: fileListDefault,
+ },
+ },
],
}
request.mockReset().mockResolvedValueOnce(Response.json(parameters))
@@ -424,6 +456,8 @@ it.each([
hide: true,
},
})),
+ { file: { variable: 'attachment', required: true, default: fileDefault } },
+ { 'file-list': { variable: 'attachments', required: true, default: fileListDefault } },
],
})
expect(
@@ -431,4 +465,9 @@ it.each([
.filter((variable) => variable.type === 'number')
.map((variable) => variable.default),
).toEqual(numberDefaults)
+ expect(
+ userInputsFormToPromptVariables(result.user_input_form)
+ .filter((variable) => variable.type === 'file' || variable.type === 'file-list')
+ .map((variable) => variable.default),
+ ).toEqual([fileDefault, fileListDefault])
})
diff --git a/web/types/app.ts b/web/types/app.ts
index 955cd27dcf7..acb0da14371 100644
--- a/web/types/app.ts
+++ b/web/types/app.ts
@@ -1,5 +1,6 @@
import type { ToolProviderType } from '@dify/contracts/api/console/agent/types.gen'
import type { FileTransferMethod } from '@dify/contracts/api/console/apps/types.gen'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { UploadFileSetting } from '@/app/components/workflow/types'
import type { LanguagesSupported } from '@/i18n/language'
import type { ExternalDataTool } from '@/models/common'
@@ -92,8 +93,9 @@ type CheckboxTypeFormItem = Omit<TextTypeFormItem, 'default' | 'max_length'> & {
default?: string | boolean
}
-type FileTypeFormItem = Omit<TextTypeFormItem, 'max_length'> &
+type FileTypeFormItem = Omit<TextTypeFormItem, 'max_length' | 'default'> &
Partial<UploadFileSetting> & {
+ default?: string | FileEntity | FileEntity[]
max_length?: number
}
diff --git a/web/utils/model-config.ts b/web/utils/model-config.ts
index ea4de844e66..73362d1e368 100644
--- a/web/utils/model-config.ts
+++ b/web/utils/model-config.ts
@@ -1,3 +1,4 @@
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { PromptVariable } from '@/models/debug'
import type { UserInputFormItem } from '@/types/app'
import { zAppExternalDataToolPayload } from '@dify/contracts/api/console/apps/zod.gen'
@@ -134,7 +135,9 @@ export const userInputsFormToPromptVariables = (
type,
config: getFileInputConfig(content, 1),
hide: getBoolean(content.hide),
- default: getDefaultValue(content.default),
+ default: isRecord(content.default)
+ ? (content.default as FileEntity)
+ : getDefaultValue(content.default),
})
} else if (type === 'file-list') {
promptVariables.push({
@@ -144,7 +147,10 @@ export const userInputsFormToPromptVariables = (
type,
config: getFileInputConfig(content, getNumber(content.max_length)),
hide: getBoolean(content.hide),
- default: getDefaultValue(content.default),
+ default:
+ Array.isArray(content.default) && content.default.every(isRecord)
+ ? (content.default as FileEntity[])
+ : getDefaultValue(content.default),
})
} else if (type === 'json_object') {
promptVariables.push({