Skip to content

armgit / dify

Public Imported from GitHub
0

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

feat(agent): support batch config file uploads (SNP-997) (#44947)

zyssyz1239e978defdec8
diff --git a/api/controllers/console/app/agent_config_inspector.py b/api/controllers/console/app/agent_config_inspector.py
index f7abf6928ad..79c05b62241 100644
--- a/api/controllers/console/app/agent_config_inspector.py
+++ b/api/controllers/console/app/agent_config_inspector.py
@@ -85,6 +85,12 @@ class AgentConfigFileUploadPayload(BaseModel):
upload_file_id: str = Field(..., description="UploadFile UUID from POST /console/api/files/upload")
+class AgentConfigFilesUploadPayload(BaseModel):
+ upload_file_ids: list[UUID] = Field(
+ ..., min_length=1, description="UploadFile UUIDs from POST /console/api/files/upload, in replacement order"
+ )
+
+
_AGENT_CONFIG_SKILL_UPLOAD_PARAMS = {
"file": {
"in": "formData",
@@ -148,6 +154,11 @@ class AgentConfigFileUploadResponse(ResponseModel):
config_version: AgentConfigVersionResponse
+class AgentConfigFilesUploadResponse(ResponseModel):
+ files: list[AgentConfigFileItemResponse]
+ config_version: AgentConfigVersionResponse
+
+
class AgentConfigManifestResponse(ResponseModel):
agent_id: str
config_version: AgentConfigVersionResponse
@@ -224,7 +235,7 @@ class AgentConfigDeleteResponse(ResponseModel):
removed_names: list[str] = Field(default_factory=list)
-register_schema_models(console_ns, AgentConfigFileUploadPayload)
+register_schema_models(console_ns, AgentConfigFileUploadPayload, AgentConfigFilesUploadPayload)
register_response_schema_models(
console_ns,
BinaryFileResponse,
@@ -235,6 +246,7 @@ register_response_schema_models(
AgentConfigFileListResponse,
AgentConfigFilePreviewResponse,
AgentConfigFileUploadResponse,
+ AgentConfigFilesUploadResponse,
AgentConfigManifestResponse,
AgentConfigSkillFilePreviewResponse,
AgentConfigSkillFileResponse,
@@ -591,6 +603,21 @@ def _file_upload_response(
return manifest, 201
+def _files_upload_response(
+ target: _ResolvedConsoleTarget, payload: AgentConfigFilesUploadPayload
+) -> tuple[dict[str, Any], int]:
+ assert target.account_id is not None
+ result = _service().push_files_for_console(
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ user_id=target.account_id,
+ config_version_id=target.version_id,
+ config_version_kind=target.version_kind,
+ upload_file_ids=[str(file_id) for file_id in payload.upload_file_ids],
+ )
+ return dump_response(AgentConfigFilesUploadResponse, result), 201
+
+
def _skill_inspect_response(target: _ResolvedConsoleTarget, name: str) -> Response:
return _json_response(
_service().inspect_skill(
@@ -961,6 +988,63 @@ class AgentConfigFilesApi(Resource):
)
+@console_ns.route("/agent/<uuid:agent_id>/config/files/batch")
+class AgentConfigFilesUploadByAgentApi(Resource):
+ @error_responses(AgentNotFoundError, RelayedHTTPError)
+ @console_ns.doc("upload_agent_config_files_by_agent")
+ @console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentConfigByAgentQuery)})
+ @console_ns.expect(console_ns.models[AgentConfigFilesUploadPayload.__name__])
+ @console_ns.response(201, "Bound config files", console_ns.models[AgentConfigFilesUploadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId()))
+ @with_current_user
+ @with_current_tenant_id
+ @with_session
+ @model_validate(AgentConfigFilesUploadPayload)
+ def post(
+ self,
+ req_data: AgentConfigFilesUploadPayload,
+ session: Session,
+ tenant_id: str,
+ current_user: Account,
+ agent_id: UUID,
+ ):
+ return _with_agent_route_target(
+ session=session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ current_user=current_user,
+ action=lambda target: _files_upload_response(target, req_data),
+ )
+
+
+@console_ns.route("/apps/<uuid:app_id>/agent/config/files/batch")
+class AgentConfigFilesUploadApi(Resource):
+ @error_responses(AgentNotBoundError, AgentNotFoundError, RelayedHTTPError)
+ @console_ns.doc("upload_agent_config_files")
+ @console_ns.doc(params={"app_id": "Application ID", **query_params_from_model(AgentConfigQuery)})
+ @console_ns.expect(console_ns.models[AgentConfigFilesUploadPayload.__name__])
+ @console_ns.response(201, "Bound config files", console_ns.models[AgentConfigFilesUploadResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp()))
+ @with_current_user
+ @with_session
+ @get_app_model(mode=_WORKFLOW_APP_MODES)
+ @model_validate(AgentConfigFilesUploadPayload)
+ def post(self, req_data: AgentConfigFilesUploadPayload, session: Session, current_user: Account, app_model: App):
+ return _with_app_route_target(
+ session=session,
+ app_model=app_model,
+ current_user=current_user,
+ action=lambda target: _files_upload_response(target, req_data),
+ )
+
+
@console_ns.route("/agent/<uuid:agent_id>/config/skills/<string:name>/inspect")
class AgentConfigSkillInspectByAgentApi(Resource):
@error_responses(AgentNotFoundError, RelayedHTTPError)
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 4ce9fd2ef18..b44f55caa92 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -890,6 +890,29 @@ Stop a running Agent App chat message generation
| 404 | Not Found | **application/json**: [AgentNotFoundError](#agentnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
+### [POST] /agent/{agent_id}/config/files/batch
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | Agent ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [AgentConfigFilesUploadPayload](#agentconfigfilesuploadpayload)<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | Bound config files | **application/json**: [AgentConfigFilesUploadResponse](#agentconfigfilesuploadresponse)<br> |
+| 404 | Not Found | **application/json**: [AgentNotFoundError](#agentnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
+
### [DELETE] /agent/{agent_id}/config/files/{name}
#### Parameters
@@ -2294,6 +2317,31 @@ Run draft workflow for advanced chat application
| 404 | Not Found | **application/json**: [AgentNotFoundError](#agentnotfounderror)<br>[AppNotFoundError](#appnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
+### [POST] /apps/{app_id}/agent/config/files/batch
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| app_id | path | Application ID | Yes | string (uuid) |
+| draft_type | query | Editable draft surface: omit or 'draft' for normal draft, 'debug_build' for build draft | No | string, <br>**Available values:** "debug_build", "draft" |
+| node_id | query | Workflow node ID (workflow composer variant) | No | string |
+| version_id | query | Published snapshot ID for read-only version view | No | string |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [AgentConfigFilesUploadPayload](#agentconfigfilesuploadpayload)<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 201 | Bound config files | **application/json**: [AgentConfigFilesUploadResponse](#agentconfigfilesuploadresponse)<br> |
+| 400 | Bad Request | **application/json**: [AgentNotBoundError](#agentnotbounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 404 | Not Found | **application/json**: [AgentNotFoundError](#agentnotfounderror)<br>[AppNotFoundError](#appnotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
+| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
+
### [DELETE] /apps/{app_id}/agent/config/files/{name}
#### Parameters
@@ -19096,6 +19144,19 @@ Stable Agent Soul reference to one config file payload.
| config_version | [AgentConfigVersionResponse](#agentconfigversionresponse) | | Yes |
| file | [AgentConfigFileItemResponse](#agentconfigfileitemresponse) | | Yes |
+#### AgentConfigFilesUploadPayload
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| upload_file_ids | [ string (uuid) ] | UploadFile UUIDs from POST /console/api/files/upload, in replacement order | Yes |
+
+#### AgentConfigFilesUploadResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| config_version | [AgentConfigVersionResponse](#agentconfigversionresponse) | | Yes |
+| files | [ [AgentConfigFileItemResponse](#agentconfigfileitemresponse) ] | | Yes |
+
#### AgentConfigManifestResponse
| Name | Type | Description | Required |
@@ -22751,7 +22812,7 @@ Rate limit exceeded for downloading compliance report.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| agent_soul | [AgentSoulConfig](#agentsoulconfig) | | No |
+| agent_soul | [AgentSoulConfig](#agentsoulconfig) | For Agent draft saves and workflow node_job_only updates, omit config_files to preserve the latest server-managed files. An explicit list replaces the files, including an empty list to clear them. | No |
| binding | [ComposerBindingPayload](#composerbindingpayload) | | No |
| client_revision_id | string | | No |
| description | string | | No |
diff --git a/api/services/agent/composer_service.py b/api/services/agent/composer_service.py
index e873fecf8f8..4640766226d 100644
--- a/api/services/agent/composer_service.py
+++ b/api/services/agent/composer_service.py
@@ -145,7 +145,12 @@ class AgentComposerService:
snapshot_id=snapshot_id,
)
return cls._serialize_workflow_state(
- session=session, binding=binding, agent=agent, version=version, account_id=account_id
+ session=session,
+ binding=binding,
+ agent=agent,
+ version=version,
+ account_id=account_id,
+ include_draft_files=snapshot_id is None,
)
@classmethod
@@ -199,101 +204,108 @@ class AgentComposerService:
account_id: str,
payload: ComposerSavePayload,
) -> dict[str, Any]:
- if payload.variant != ComposerVariant.WORKFLOW:
- raise ValueError("Workflow composer endpoint only accepts workflow variant")
-
- _backfill_cli_tool_ids(payload.agent_soul)
- _validate_composer_payload_for_strategy(payload)
- if payload.agent_soul is not None:
- validate_agent_knowledge_spaces(
- session=session,
- tenant_id=tenant_id,
- account_id=account_id,
- agent_soul=payload.agent_soul,
- )
- if payload.save_strategy in _PUBLISH_SAVE_STRATEGIES:
- cls.validate_knowledge_datasets(session=session, tenant_id=tenant_id, agent_soul=payload.agent_soul)
- workflow = cls._get_draft_workflow(session=session, tenant_id=tenant_id, app_id=app_id)
- binding = cls._get_workflow_binding(
- session=session, tenant_id=tenant_id, workflow_id=workflow.id, node_id=node_id
- )
- retirement_candidates = (
- {binding.agent_id}
- if binding is not None
- and binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT
- and binding.agent_id
- and payload.save_strategy
- in {
- ComposerSaveStrategy.SAVE_AS_NEW_AGENT,
- ComposerSaveStrategy.SAVE_TO_ROSTER,
- }
- else set()
- )
-
- match payload.save_strategy:
- case ComposerSaveStrategy.NODE_JOB_ONLY:
- binding = cls._save_node_job_only(
- session=session,
- tenant_id=tenant_id,
- app_id=app_id,
- workflow_id=workflow.id,
- node_id=node_id,
- account_id=account_id,
- binding=binding,
- payload=payload,
- )
- case ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION:
- binding = cls._save_to_current_version(
- session=session, tenant_id=tenant_id, account_id=account_id, binding=binding, payload=payload
- )
- case ComposerSaveStrategy.SAVE_AS_NEW_VERSION:
- binding = cls._save_as_new_version(
- session=session, tenant_id=tenant_id, account_id=account_id, binding=binding, payload=payload
- )
- case ComposerSaveStrategy.SAVE_AS_NEW_AGENT:
- binding = cls._save_as_new_agent(
+ # Read and lock the latest draft before any ORM autoflush can write a cached snapshot.
+ with session.no_autoflush:
+ if payload.variant != ComposerVariant.WORKFLOW:
+ raise ValueError("Workflow composer endpoint only accepts workflow variant")
+
+ _backfill_cli_tool_ids(payload.agent_soul)
+ _validate_composer_payload_for_strategy(payload)
+ if payload.agent_soul is not None:
+ validate_agent_knowledge_spaces(
session=session,
tenant_id=tenant_id,
- app_id=app_id,
- workflow_id=workflow.id,
- node_id=node_id,
account_id=account_id,
- binding=binding,
- payload=payload,
- )
- case ComposerSaveStrategy.SAVE_TO_ROSTER:
- binding = cls._save_to_roster(
- session=session,
- tenant_id=tenant_id,
- account_id=account_id,
- binding=binding,
- payload=payload,
+ agent_soul=payload.agent_soul,
)
+ if payload.save_strategy in _PUBLISH_SAVE_STRATEGIES:
+ cls.validate_knowledge_datasets(session=session, tenant_id=tenant_id, agent_soul=payload.agent_soul)
+ workflow = cls._get_draft_workflow(session=session, tenant_id=tenant_id, app_id=app_id)
+ binding = cls._get_workflow_binding(
+ session=session, tenant_id=tenant_id, workflow_id=workflow.id, node_id=node_id
+ )
+ retirement_candidates = (
+ {binding.agent_id}
+ if binding is not None
+ and binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT
+ and binding.agent_id
+ and payload.save_strategy
+ in {
+ ComposerSaveStrategy.SAVE_AS_NEW_AGENT,
+ ComposerSaveStrategy.SAVE_TO_ROSTER,
+ }
+ else set()
+ )
- session.flush()
- agent = cls._get_agent_if_present(session=session, tenant_id=tenant_id, agent_id=binding.agent_id)
- version_id = (
- agent.active_config_snapshot_id
- if agent and binding.binding_type == WorkflowAgentBindingType.ROSTER_AGENT
- else binding.current_snapshot_id
- )
- version = cls._get_version_if_present(
- session=session,
- tenant_id=tenant_id,
- agent_id=agent.id if agent else None,
- version_id=version_id,
- )
- state = cls._serialize_workflow_state(
- session=session, binding=binding, agent=agent, version=version, account_id=account_id
- )
- state["validation"] = cls.collect_validation_findings(payload=payload)
- session.commit()
- WorkflowAgentRetirementService.retire_unowned(
- tenant_id=tenant_id,
- agent_ids=retirement_candidates,
- account_id=account_id,
- )
- return state
+ match payload.save_strategy:
+ case ComposerSaveStrategy.NODE_JOB_ONLY:
+ binding = cls._save_node_job_only(
+ session=session,
+ tenant_id=tenant_id,
+ app_id=app_id,
+ workflow_id=workflow.id,
+ node_id=node_id,
+ account_id=account_id,
+ binding=binding,
+ payload=payload,
+ )
+ case ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION:
+ binding = cls._save_to_current_version(
+ session=session, tenant_id=tenant_id, account_id=account_id, binding=binding, payload=payload
+ )
+ case ComposerSaveStrategy.SAVE_AS_NEW_VERSION:
+ binding = cls._save_as_new_version(
+ session=session, tenant_id=tenant_id, account_id=account_id, binding=binding, payload=payload
+ )
+ case ComposerSaveStrategy.SAVE_AS_NEW_AGENT:
+ binding = cls._save_as_new_agent(
+ session=session,
+ tenant_id=tenant_id,
+ app_id=app_id,
+ workflow_id=workflow.id,
+ node_id=node_id,
+ account_id=account_id,
+ binding=binding,
+ payload=payload,
+ )
+ case ComposerSaveStrategy.SAVE_TO_ROSTER:
+ binding = cls._save_to_roster(
+ session=session,
+ tenant_id=tenant_id,
+ account_id=account_id,
+ binding=binding,
+ payload=payload,
+ )
+
+ session.flush()
+ agent = cls._get_agent_if_present(session=session, tenant_id=tenant_id, agent_id=binding.agent_id)
+ version_id = (
+ agent.active_config_snapshot_id
+ if agent and binding.binding_type == WorkflowAgentBindingType.ROSTER_AGENT
+ else binding.current_snapshot_id
+ )
+ version = cls._get_version_if_present(
+ session=session,
+ tenant_id=tenant_id,
+ agent_id=agent.id if agent else None,
+ version_id=version_id,
+ )
+ state = cls._serialize_workflow_state(
+ session=session,
+ binding=binding,
+ agent=agent,
+ version=version,
+ account_id=account_id,
+ include_draft_files=True,
+ )
+ state["validation"] = cls.collect_validation_findings(payload=payload)
+ session.commit()
+ WorkflowAgentRetirementService.retire_unowned(
+ tenant_id=tenant_id,
+ agent_ids=retirement_candidates,
+ account_id=account_id,
+ )
+ return state
@classmethod
def copy_workflow_composer_from_roster(
@@ -324,7 +336,12 @@ class AgentComposerService:
version_id=binding.current_snapshot_id,
)
return cls._serialize_workflow_state(
- session=session, binding=binding, agent=agent, version=version, account_id=account_id
+ session=session,
+ binding=binding,
+ agent=agent,
+ version=version,
+ account_id=account_id,
+ include_draft_files=True,
)
if binding.binding_type != WorkflowAgentBindingType.ROSTER_AGENT:
@@ -383,7 +400,12 @@ class AgentComposerService:
version_id=inline_agent.active_config_snapshot_id,
)
return cls._serialize_workflow_state(
- session=session, binding=binding, agent=inline_agent, version=version, account_id=account_id
+ session=session,
+ binding=binding,
+ agent=inline_agent,
+ version=version,
+ account_id=account_id,
+ include_draft_files=True,
)
@classmethod
@@ -427,10 +449,11 @@ class AgentComposerService:
cls, *, session: Session, tenant_id: str, agent_id: str, account_id: str
) -> AgentConfigDraft:
"""Prepare a persisted normal draft for an explicit configuration write."""
- agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=agent_id)
- return cls.get_or_create_normal_agent_draft(
- session=session, tenant_id=tenant_id, agent=agent, created_by=account_id
- )
+ with session.no_autoflush:
+ agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=agent_id)
+ return cls.get_or_create_normal_agent_draft(
+ session=session, tenant_id=tenant_id, agent=agent, created_by=account_id
+ )
@classmethod
def load_agent_soul_for_debug(
@@ -518,13 +541,14 @@ class AgentComposerService:
payload: ComposerSavePayload,
) -> dict[str, Any]:
try:
- return cls._save_agent_app_composer_impl(
- session=session,
- tenant_id=tenant_id,
- app_id=app_id,
- account_id=account_id,
- payload=payload,
- )
+ with session.no_autoflush:
+ return cls._save_agent_app_composer_impl(
+ session=session,
+ tenant_id=tenant_id,
+ app_id=app_id,
+ account_id=account_id,
+ payload=payload,
+ )
except IntegrityError as exc:
raise AgentNameConflictError() from exc
@@ -598,30 +622,32 @@ class AgentComposerService:
def save_agent_composer(
cls, *, session: Session, tenant_id: str, agent_id: str, account_id: str, payload: ComposerSavePayload
) -> dict[str, Any]:
- if payload.variant != ComposerVariant.AGENT_APP:
- raise ValueError("Agent composer endpoint only accepts agent_app variant")
- if payload.save_strategy != ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION:
- raise InvalidComposerConfigError(
- "Agent composer only saves the normal draft. Use the publish endpoint to create a version."
+ # Read and lock the latest draft before any ORM autoflush can write a cached snapshot.
+ with session.no_autoflush:
+ if payload.variant != ComposerVariant.AGENT_APP:
+ raise ValueError("Agent composer endpoint only accepts agent_app variant")
+ if payload.save_strategy != ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION:
+ raise InvalidComposerConfigError(
+ "Agent composer only saves the normal draft. Use the publish endpoint to create a version."
+ )
+ if payload.agent_soul is None:
+ raise ValueError("agent_soul is required")
+ _backfill_cli_tool_ids(payload.agent_soul)
+ _validate_composer_payload_for_strategy(payload)
+ validate_agent_knowledge_spaces(
+ session=session,
+ tenant_id=tenant_id,
+ account_id=account_id,
+ agent_soul=payload.agent_soul,
+ )
+ agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=agent_id)
+ return cls._save_agent_composer_for_agent(
+ session=session,
+ tenant_id=tenant_id,
+ agent=agent,
+ account_id=account_id,
+ payload=payload,
)
- if payload.agent_soul is None:
- raise ValueError("agent_soul is required")
- _backfill_cli_tool_ids(payload.agent_soul)
- _validate_composer_payload_for_strategy(payload)
- validate_agent_knowledge_spaces(
- session=session,
- tenant_id=tenant_id,
- account_id=account_id,
- agent_soul=payload.agent_soul,
- )
- agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=agent_id)
- return cls._save_agent_composer_for_agent(
- session=session,
- tenant_id=tenant_id,
- agent=agent,
- account_id=account_id,
- payload=payload,
- )
@classmethod
def _save_agent_composer_for_agent(
@@ -643,7 +669,7 @@ class AgentComposerService:
session=session,
tenant_id=tenant_id,
agent=agent,
- agent_soul=payload.agent_soul,
+ agent_soul=AgentSoulConfig.model_validate(draft.config_snapshot_dict),
home_snapshot_id=draft.home_snapshot_id,
)
@@ -908,28 +934,30 @@ class AgentComposerService:
def save_agent_app_build_draft(
cls, *, session: Session, tenant_id: str, agent_id: str, account_id: str, payload: ComposerSavePayload
) -> dict[str, Any]:
- if payload.agent_soul is None:
- raise ValueError("agent_soul is required")
- _backfill_cli_tool_ids(payload.agent_soul)
- ComposerConfigValidator.validate_draft_save_payload(payload)
- validate_agent_knowledge_spaces(
- session=session,
- tenant_id=tenant_id,
- account_id=account_id,
- agent_soul=payload.agent_soul,
- )
- agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=agent_id)
- build_draft = cls._save_agent_draft(
- session=session,
- tenant_id=tenant_id,
- agent=agent,
- draft_type=AgentConfigDraftType.DEBUG_BUILD,
- account_id=account_id,
- agent_soul=payload.agent_soul,
- account_id_for_audit=account_id,
- )
- session.flush()
- return cls._serialize_build_draft_state(build_draft)
+ # Read and lock the latest draft before any ORM autoflush can write a cached snapshot.
+ with session.no_autoflush:
+ if payload.agent_soul is None:
+ raise ValueError("agent_soul is required")
+ _backfill_cli_tool_ids(payload.agent_soul)
+ ComposerConfigValidator.validate_draft_save_payload(payload)
+ validate_agent_knowledge_spaces(
+ session=session,
+ tenant_id=tenant_id,
+ account_id=account_id,
+ agent_soul=payload.agent_soul,
+ )
+ agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=agent_id)
+ build_draft = cls._save_agent_draft(
+ session=session,
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id=account_id,
+ agent_soul=payload.agent_soul,
+ account_id_for_audit=account_id,
+ )
+ session.flush()
+ return cls._serialize_build_draft_state(build_draft)
@classmethod
def apply_agent_app_build_draft(
@@ -1466,38 +1494,58 @@ class AgentComposerService:
binding=binding,
payload=payload,
)
- if payload.node_job is not None:
- binding.node_job_config = payload.node_job
if payload.agent_soul is not None and binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT:
+ agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=binding.agent_id)
+ session.flush([agent])
+ agent = cls._require_agent(
+ session=session, tenant_id=tenant_id, agent_id=binding.agent_id, for_update=True
+ )
+ if agent.scope != AgentScope.WORKFLOW_ONLY:
+ raise ValueError("Inline workflow agent binding must point to a workflow-only agent")
+ binding = cls._require_binding(
+ cls._get_workflow_binding(
+ session=session,
+ tenant_id=tenant_id,
+ workflow_id=workflow_id,
+ node_id=node_id,
+ for_update=True,
+ )
+ )
+ if binding.agent_id != agent.id or binding.binding_type != WorkflowAgentBindingType.INLINE_AGENT:
+ raise AgentVersionConflictError()
current_snapshot = cls._require_version(
session=session,
tenant_id=tenant_id,
agent_id=binding.agent_id,
version_id=binding.current_snapshot_id,
)
+ normal_draft = cls._get_agent_draft(
+ session=session,
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ for_update=True,
+ )
+ current_soul = AgentSoulConfig.model_validate(
+ normal_draft.config_snapshot_dict
+ if normal_draft is not None and normal_draft.base_snapshot_id == current_snapshot.id
+ else current_snapshot.config_snapshot_dict
+ )
+ agent_soul = cls._preserve_omitted_config_files(payload.agent_soul, current_soul)
version = cls._update_current_version(
session=session,
current_snapshot=current_snapshot,
account_id=account_id,
- agent_soul=payload.agent_soul,
+ agent_soul=agent_soul,
operation=AgentConfigRevisionOperation.SAVE_CURRENT_VERSION,
version_note=payload.version_note,
)
- agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=binding.agent_id)
- if agent.scope != AgentScope.WORKFLOW_ONLY:
- raise ValueError("Inline workflow agent binding must point to a workflow-only agent")
agent.active_config_snapshot_id = version.id
- agent.active_config_has_model = agent_soul_has_model(payload.agent_soul)
+ agent.active_config_has_model = agent_soul_has_model(agent_soul)
agent.active_config_is_published = True
agent.updated_by = account_id
binding.current_snapshot_id = version.id
- normal_draft = cls._get_agent_draft(
- session=session,
- tenant_id=tenant_id,
- agent_id=agent.id,
- draft_type=AgentConfigDraftType.DRAFT,
- account_id=None,
- )
if normal_draft is not None and cls._rebase_workflow_only_normal_draft(
agent=agent,
draft=normal_draft,
@@ -1505,6 +1553,8 @@ class AgentComposerService:
updated_by=account_id,
):
session.flush()
+ if payload.node_job is not None:
+ binding.node_job_config = payload.node_job
binding.updated_by = account_id
return binding
@@ -2042,6 +2092,7 @@ class AgentComposerService:
agent_id: str,
draft_type: AgentConfigDraftType,
account_id: str | None,
+ for_update: bool = False,
) -> AgentConfigDraft | None:
stmt = select(AgentConfigDraft).where(
AgentConfigDraft.tenant_id == tenant_id,
@@ -2052,6 +2103,8 @@ class AgentComposerService:
stmt = stmt.where(AgentConfigDraft.account_id == account_id)
else:
stmt = stmt.where(AgentConfigDraft.account_id.is_(None))
+ if for_update:
+ stmt = stmt.with_for_update().execution_options(populate_existing=True, autoflush=False)
return session.scalar(stmt.order_by(AgentConfigDraft.updated_at.desc()).limit(1))
@classmethod
@@ -2114,13 +2167,17 @@ class AgentComposerService:
) -> AgentConfigDraft:
# All draft writers lock the parent before checking for an absent draft.
# Locking a draft query alone cannot serialize concurrent first writes.
- session.scalar(select(Agent.id).where(Agent.tenant_id == tenant_id, Agent.id == agent.id).with_for_update())
+ # Preserve caller-owned Agent edits before refreshing its locked database state.
+ # An UPDATE itself acquires the parent lock; do not flush an older cached Draft here.
+ session.flush([agent])
+ agent = cls._require_agent(session=session, tenant_id=tenant_id, agent_id=agent.id, for_update=True)
draft = cls._get_agent_draft(
session=session,
tenant_id=tenant_id,
agent_id=agent.id,
draft_type=draft_type,
account_id=account_id,
+ for_update=True,
)
if draft is not None:
if (
@@ -2192,7 +2249,9 @@ class AgentComposerService:
account_id=account_id,
created_by=account_id_for_audit,
)
- draft.config_snapshot = agent_soul
+ draft.config_snapshot = cls._preserve_omitted_config_files(
+ agent_soul, AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ )
if base_snapshot_id is not None:
draft.base_snapshot_id = base_snapshot_id
elif draft.base_snapshot_id is None:
@@ -2203,6 +2262,13 @@ class AgentComposerService:
session.flush()
return draft
+ @staticmethod
+ def _preserve_omitted_config_files(agent_soul: AgentSoulConfig, current_soul: AgentSoulConfig) -> AgentSoulConfig:
+ """An omitted asset list preserves the locked state; an explicit list replaces it, including an empty one."""
+ if "config_files" in agent_soul.model_fields_set:
+ return agent_soul
+ return agent_soul.model_copy(update={"config_files": current_soul.config_files})
+
@classmethod
def _serialize_draft(cls, draft: AgentConfigDraft | None) -> dict[str, Any] | None:
if draft is None:
@@ -2244,22 +2310,21 @@ class AgentComposerService:
@classmethod
def _get_workflow_binding(
- cls, *, session: Session, tenant_id: str, workflow_id: str, node_id: str
+ cls, *, session: Session, tenant_id: str, workflow_id: str, node_id: str, for_update: bool = False
) -> WorkflowAgentNodeBinding | None:
# Composer always operates against the draft workflow row, so this lookup
# is scoped to ``workflow_version="draft"``. Published bindings are
# materialized by WorkflowAgentPublishService.copy_agent_node_bindings_to_published
# and are not edited through the Composer.
- return session.scalar(
- select(WorkflowAgentNodeBinding)
- .where(
- WorkflowAgentNodeBinding.tenant_id == tenant_id,
- WorkflowAgentNodeBinding.workflow_id == workflow_id,
- WorkflowAgentNodeBinding.workflow_version == _DRAFT_WORKFLOW_VERSION,
- WorkflowAgentNodeBinding.node_id == node_id,
- )
- .limit(1)
+ stmt = select(WorkflowAgentNodeBinding).where(
+ WorkflowAgentNodeBinding.tenant_id == tenant_id,
+ WorkflowAgentNodeBinding.workflow_id == workflow_id,
+ WorkflowAgentNodeBinding.workflow_version == _DRAFT_WORKFLOW_VERSION,
+ WorkflowAgentNodeBinding.node_id == node_id,
)
+ if for_update:
+ stmt = stmt.with_for_update().execution_options(populate_existing=True, autoflush=False)
+ return session.scalar(stmt.limit(1))
@classmethod
def _require_binding(cls, binding: WorkflowAgentNodeBinding | None) -> WorkflowAgentNodeBinding:
@@ -2268,10 +2333,15 @@ class AgentComposerService:
return binding
@classmethod
- def _require_agent(cls, *, session: Session, tenant_id: str, agent_id: str | None) -> Agent:
+ def _require_agent(
+ cls, *, session: Session, tenant_id: str, agent_id: str | None, for_update: bool = False
+ ) -> Agent:
if not agent_id:
raise AgentNotFoundError()
- agent = session.scalar(select(Agent).where(Agent.tenant_id == tenant_id, Agent.id == agent_id).limit(1))
+ stmt = select(Agent).where(Agent.tenant_id == tenant_id, Agent.id == agent_id)
+ if for_update:
+ stmt = stmt.with_for_update().execution_options(populate_existing=True, autoflush=False)
+ agent = session.scalar(stmt.limit(1))
if not agent:
raise AgentNotFoundError()
return agent
@@ -2360,6 +2430,7 @@ class AgentComposerService:
agent: Agent | None,
version: AgentConfigSnapshot | None,
account_id: str | None = None,
+ include_draft_files: bool,
) -> dict[str, Any]:
locked = bool(agent and agent.scope == AgentScope.ROSTER)
save_options = [ComposerSaveStrategy.NODE_JOB_ONLY.value]
@@ -2404,9 +2475,9 @@ class AgentComposerService:
"can_unlock": locked,
"reason": "roster_agent_shared_version" if locked else "workflow_only_agent",
},
- "agent_soul": cls._workflow_agent_soul_config(version.config_snapshot_dict)
- if version
- else AgentSoulConfig().model_dump(mode="json"),
+ "agent_soul": cls._workflow_agent_soul_state(
+ session=session, agent=agent, version=version, include_draft_files=include_draft_files
+ ),
"node_job": binding.node_job_config_dict,
"effective_declared_outputs": cls._serialize_effective_outputs(
WorkflowNodeJobConfig.model_validate(binding.node_job_config_dict)
@@ -2486,6 +2557,37 @@ class AgentComposerService:
"created_at": to_timestamp(version.created_at),
}
+ @classmethod
+ def _workflow_agent_soul_state(
+ cls,
+ *,
+ session: Session,
+ agent: Agent | None,
+ version: AgentConfigSnapshot | None,
+ include_draft_files: bool,
+ ) -> dict[str, Any]:
+ """Return the node's Agent Soul with the file list its next node save would persist.
+
+ Inline file uploads and deletes write the workflow-only Agent's normal Draft. While that Draft is
+ based on the bound snapshot, its ``config_files`` are the current list for the node. An explicitly
+ requested snapshot (``include_draft_files`` false) keeps its own files.
+ """
+ if version is None:
+ return AgentSoulConfig().model_dump(mode="json")
+ agent_soul = cls._workflow_agent_soul_config(version.config_snapshot_dict)
+ if not include_draft_files or agent is None or agent.scope != AgentScope.WORKFLOW_ONLY:
+ return agent_soul
+ normal_draft = cls._get_agent_draft(
+ session=session,
+ tenant_id=agent.tenant_id,
+ agent_id=agent.id,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ )
+ if normal_draft is not None and normal_draft.base_snapshot_id == version.id:
+ agent_soul["config_files"] = normal_draft.config_snapshot_dict.get("config_files", [])
+ return agent_soul
+
@staticmethod
def _workflow_agent_soul_config(config_snapshot: dict[str, Any]) -> dict[str, Any]:
agent_soul = dict(config_snapshot)
diff --git a/api/services/agent_config_service.py b/api/services/agent_config_service.py
index 7e837dbfb6b..bd24c43db59 100644
--- a/api/services/agent_config_service.py
+++ b/api/services/agent_config_service.py
@@ -26,7 +26,7 @@ from typing import Literal
from dotenv import dotenv_values
from pydantic import BaseModel, ConfigDict, Field
-from sqlalchemy import select
+from sqlalchemy import Select, select
from sqlalchemy.exc import DataError, SQLAlchemyError
from sqlalchemy.orm import Session
@@ -137,7 +137,11 @@ class ConfigDownloadRequest:
class AgentConfigService:
- """Read and update Agent Soul-backed config assets for one version target."""
+ """Read and update Agent Soul-backed config assets for one version target.
+
+ Mutations lock the parent Agent before the target draft and refresh the
+ locked snapshot. Skill storage and normalization run before these locks.
+ """
PREVIEW_MAX_BYTES = 64 * 1024
@@ -598,6 +602,24 @@ class AgentConfigService:
filename: str,
surface: AgentConfigMutationSurface,
) -> dict[str, object]:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ self._require_writable(target, surface=surface)
+ try:
+ skill_ref = self._skill_normalizer.normalize(
+ content=content,
+ filename=filename,
+ requested_name=None,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ )
+ except SkillPackageError as exc:
+ raise AgentConfigServiceError(exc.code, exc.message, status_code=exc.status_code) from exc
with self._session_factory() as session:
target = self._resolve_target_in_session(
session,
@@ -606,18 +628,9 @@ class AgentConfigService:
config_version_id=config_version_id,
config_version_kind=config_version_kind,
user_id=user_id,
+ for_update=True,
)
self._require_writable(target, surface=surface)
- try:
- skill_ref = self._skill_normalizer.normalize(
- content=content,
- filename=filename,
- requested_name=None,
- tenant_id=tenant_id,
- user_id=user_id,
- )
- except SkillPackageError as exc:
- raise AgentConfigServiceError(exc.code, exc.message, status_code=exc.status_code) from exc
agent_soul = target.agent_soul.model_copy(deep=True)
existing = {item.name: item for item in agent_soul.config_skills}
order = [item.name for item in agent_soul.config_skills]
@@ -691,6 +704,7 @@ class AgentConfigService:
config_version_id=config_version_id,
config_version_kind=config_version_kind,
user_id=user_id,
+ for_update=True,
)
self._require_writable(target, surface=AgentConfigMutationSurface.CONSOLE)
upload_file = self._require_console_upload_file_source(session, tenant_id=tenant_id, file_id=upload_file_id)
@@ -708,6 +722,53 @@ class AgentConfigService:
"config_version": self._config_version_payload(target),
}
+ def push_files_for_console(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ user_id: str,
+ config_version_id: str,
+ config_version_kind: AgentConfigVersionKind,
+ upload_file_ids: list[str],
+ ) -> dict[str, object]:
+ """Bind a validated batch atomically, replacing same-name files in input order.
+
+ Lock the parent Agent before its draft, as every other draft writer does.
+ Read the snapshot after acquiring both locks so concurrent asset edits survive.
+ Only the batch's effective files are returned; existing unrelated files stay put.
+ """
+ if not upload_file_ids:
+ raise ValueError("upload_file_ids must not be empty")
+
+ with self._session_factory() as session:
+ prepared_files: list[AgentConfigFileRefConfig] = []
+ for file_id in upload_file_ids:
+ upload_file = self._require_console_upload_file_source(session, tenant_id=tenant_id, file_id=file_id)
+ prepared_files = self._upsert_upload_file(current=prepared_files, upload_file=upload_file)
+
+ target = self._resolve_target_in_session(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ for_update=True,
+ )
+ self._require_writable(target, surface=AgentConfigMutationSurface.CONSOLE)
+ agent_soul = target.agent_soul.model_copy(deep=True)
+ by_name = {item.name: item for item in agent_soul.config_files}
+ by_name.update((item.name, item) for item in prepared_files)
+ agent_soul.config_files = list(by_name.values())
+ target.version.config_snapshot = agent_soul
+ session.commit()
+ target.agent_soul = agent_soul
+ return {
+ "files": [self._serialize_file_item(file_ref) for file_ref in prepared_files],
+ "config_version": self._config_version_payload(target),
+ }
+
def _push(
self,
*,
@@ -719,6 +780,18 @@ class AgentConfigService:
payload: ConfigPushPayload,
surface: AgentConfigMutationSurface,
) -> dict[str, object]:
+ prepared_skills: list[tuple[str, AgentConfigSkillRefConfig | None]] = []
+ if payload.skills:
+ target = self.resolve_target(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ config_version_id=config_version_id,
+ config_version_kind=config_version_kind,
+ user_id=user_id,
+ )
+ self._require_writable(target, surface=surface)
+ prepared_skills = self._prepare_skill_updates(tenant_id=tenant_id, user_id=user_id, updates=payload.skills)
+
with self._session_factory() as session:
target = self._resolve_target_in_session(
session,
@@ -727,6 +800,7 @@ class AgentConfigService:
config_version_id=config_version_id,
config_version_kind=config_version_kind,
user_id=user_id,
+ for_update=True,
)
self._require_writable(target, surface=surface)
agent_soul = target.agent_soul.model_copy(deep=True)
@@ -738,12 +812,8 @@ class AgentConfigService:
updates=payload.files,
)
if payload.skills:
- agent_soul.config_skills = self._apply_skill_updates(
- session,
- tenant_id=tenant_id,
- user_id=user_id,
- current=agent_soul.config_skills,
- updates=payload.skills,
+ agent_soul.config_skills = self._merge_skill_updates(
+ current=agent_soul.config_skills, updates=prepared_skills
)
if payload.env_text is not None:
agent_soul.env.variables = self._apply_env_text(agent_soul.env.variables, payload.env_text)
@@ -821,6 +891,7 @@ class AgentConfigService:
config_version_id=config_version_id,
config_version_kind=config_version_kind,
user_id=user_id,
+ for_update=True,
)
self._require_writable(target, surface=surface)
agent_soul = target.agent_soul.model_copy(deep=True)
@@ -868,6 +939,7 @@ class AgentConfigService:
config_version_id=config_version_id,
config_version_kind=config_version_kind,
user_id=user_id,
+ for_update=True,
)
self._require_writable(target, surface=surface)
agent_soul = target.agent_soul.model_copy(deep=True)
@@ -918,6 +990,7 @@ class AgentConfigService:
config_version_id=config_version_id,
config_version_kind=config_version_kind,
user_id=user_id,
+ for_update=True,
)
self._require_writable(target, surface=AgentConfigMutationSurface.AGENT_STUB)
agent_soul = target.agent_soul.model_copy(deep=True)
@@ -935,29 +1008,26 @@ class AgentConfigService:
config_version_id: str,
config_version_kind: AgentConfigVersionKind,
user_id: str | None,
+ for_update: bool = False,
) -> AgentConfigTarget:
- self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
- version: AgentConfigSnapshot | AgentConfigDraft | None
+ self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id, for_update=for_update)
+ version_query: Select[tuple[AgentConfigSnapshot]] | Select[tuple[AgentConfigDraft]]
try:
match config_version_kind:
case AgentConfigVersionKind.SNAPSHOT:
- version = session.scalar(
- select(AgentConfigSnapshot).where(
- AgentConfigSnapshot.tenant_id == tenant_id,
- AgentConfigSnapshot.agent_id == agent_id,
- AgentConfigSnapshot.id == config_version_id,
- )
+ version_query = select(AgentConfigSnapshot).where(
+ AgentConfigSnapshot.tenant_id == tenant_id,
+ AgentConfigSnapshot.agent_id == agent_id,
+ AgentConfigSnapshot.id == config_version_id,
)
writable = False
case AgentConfigVersionKind.DRAFT:
- version = session.scalar(
- select(AgentConfigDraft).where(
- AgentConfigDraft.tenant_id == tenant_id,
- AgentConfigDraft.agent_id == agent_id,
- AgentConfigDraft.id == config_version_id,
- AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
- AgentConfigDraft.account_id.is_(None),
- )
+ version_query = select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.id == config_version_id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
+ AgentConfigDraft.account_id.is_(None),
)
writable = False
case AgentConfigVersionKind.BUILD_DRAFT:
@@ -967,18 +1037,23 @@ class AgentConfigService:
"user_id is required for build draft config access",
status_code=400,
)
- version = session.scalar(
- select(AgentConfigDraft).where(
- AgentConfigDraft.tenant_id == tenant_id,
- AgentConfigDraft.agent_id == agent_id,
- AgentConfigDraft.id == config_version_id,
- AgentConfigDraft.draft_type == AgentConfigDraftType.DEBUG_BUILD,
- AgentConfigDraft.account_id == user_id,
- )
+ version_query = select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.id == config_version_id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DEBUG_BUILD,
+ AgentConfigDraft.account_id == user_id,
)
writable = True
case _:
raise AgentConfigServiceError("invalid_config_version_kind", "unsupported config version kind")
+ version_query = version_query.execution_options(autoflush=False)
+ if for_update and config_version_kind != AgentConfigVersionKind.SNAPSHOT:
+ # Re-read under the lock even when this Session already loaded the draft.
+ version_query = version_query.with_for_update().execution_options(
+ populate_existing=True, autoflush=False
+ )
+ version = session.scalar(version_query)
except (DataError, SQLAlchemyError) as exc:
session.rollback()
raise AgentConfigServiceError(
@@ -1003,9 +1078,18 @@ class AgentConfigService:
)
@staticmethod
- def _assert_agent_belongs_to_tenant(session: Session, *, tenant_id: str, agent_id: str) -> None:
+ def _assert_agent_belongs_to_tenant(
+ session: Session, *, tenant_id: str, agent_id: str, for_update: bool = False
+ ) -> None:
try:
- found = session.scalar(select(Agent.id).where(Agent.id == agent_id, Agent.tenant_id == tenant_id))
+ query = (
+ select(Agent)
+ .where(Agent.id == agent_id, Agent.tenant_id == tenant_id)
+ .execution_options(autoflush=False)
+ )
+ if for_update:
+ query = query.with_for_update().execution_options(populate_existing=True, autoflush=False)
+ found = session.scalar(query)
except (DataError, SQLAlchemyError) as exc:
session.rollback()
raise AgentConfigServiceError(
@@ -1085,44 +1169,62 @@ class AgentConfigService:
)
return [by_name[item_name] for item_name in order if item_name in by_name]
- def _apply_skill_updates(
+ def _prepare_skill_updates(
self,
- session: Session,
*,
tenant_id: str,
user_id: str,
- current: list[AgentConfigSkillRefConfig],
updates: list[ConfigPushSkillItem],
- ) -> list[AgentConfigSkillRefConfig]:
- by_name = {item.name: item for item in current}
- order = [item.name for item in current]
- for update in updates:
- name = validate_config_skill_name(update.name)
- if update.file_ref is None:
- by_name.pop(name, None)
+ ) -> list[tuple[str, AgentConfigSkillRefConfig | None]]:
+ # None represents removal. Capture only trusted source metadata before storage I/O.
+ sources: list[tuple[str, tuple[str, str] | None]] = []
+ with self._session_factory() as session:
+ for update in updates:
+ name = validate_config_skill_name(update.name)
+ if update.file_ref is None:
+ sources.append((name, None))
+ continue
+ if update.file_ref.kind != "tool_file":
+ raise AgentConfigServiceError(
+ "invalid_skill_file_ref",
+ "config skills must be uploaded as tool files",
+ status_code=400,
+ )
+ tool_file = self._require_tool_file_source(session, tenant_id=tenant_id, file_id=update.file_ref.id)
+ sources.append((name, (tool_file.file_key, tool_file.name)))
+
+ prepared: list[tuple[str, AgentConfigSkillRefConfig | None]] = []
+ for name, source in sources:
+ if source is None:
+ prepared.append((name, None))
continue
- if update.file_ref.kind != "tool_file":
- raise AgentConfigServiceError(
- "invalid_skill_file_ref",
- "config skills must be uploaded as tool files",
- status_code=400,
- )
- tool_file = self._require_tool_file_source(
- session,
- tenant_id=tenant_id,
- file_id=update.file_ref.id,
- )
- archive_bytes = storage.load_once(tool_file.file_key)
+ file_key, filename = source
+ archive_bytes = storage.load_once(file_key)
try:
skill_ref = self._skill_normalizer.normalize(
content=archive_bytes,
- filename=tool_file.name,
+ filename=filename,
requested_name=name,
tenant_id=tenant_id,
user_id=user_id,
)
except SkillPackageError as exc:
raise AgentConfigServiceError(exc.code, exc.message, status_code=exc.status_code) from exc
+ prepared.append((name, skill_ref))
+ return prepared
+
+ @staticmethod
+ def _merge_skill_updates(
+ *,
+ current: list[AgentConfigSkillRefConfig],
+ updates: list[tuple[str, AgentConfigSkillRefConfig | None]],
+ ) -> list[AgentConfigSkillRefConfig]:
+ by_name = {item.name: item for item in current}
+ order = [item.name for item in current]
+ for name, skill_ref in updates:
+ if skill_ref is None:
+ by_name.pop(name, None)
+ continue
if name not in order:
order.append(name)
by_name[name] = skill_ref
@@ -1154,10 +1256,12 @@ class AgentConfigService:
) -> ToolFile:
try:
tool_file = session.scalar(
- select(ToolFile).where(
+ select(ToolFile)
+ .where(
ToolFile.id == file_id,
ToolFile.tenant_id == tenant_id,
)
+ .execution_options(autoflush=False)
)
except (DataError, SQLAlchemyError) as exc:
session.rollback()
@@ -1176,10 +1280,12 @@ class AgentConfigService:
def _require_console_upload_file_source(session: Session, *, tenant_id: str, file_id: str) -> UploadFile:
try:
upload_file = session.scalar(
- select(UploadFile).where(
+ select(UploadFile)
+ .where(
UploadFile.id == file_id,
UploadFile.tenant_id == tenant_id,
)
+ .execution_options(autoflush=False)
)
except (DataError, SQLAlchemyError) as exc:
session.rollback()
@@ -1200,10 +1306,12 @@ class AgentConfigService:
def _require_upload_file_source(session: Session, *, tenant_id: str, file_id: str) -> UploadFile:
try:
upload_file = session.scalar(
- select(UploadFile).where(
+ select(UploadFile)
+ .where(
UploadFile.id == file_id,
UploadFile.tenant_id == tenant_id,
)
+ .execution_options(autoflush=False)
)
except (DataError, SQLAlchemyError) as exc:
session.rollback()
diff --git a/api/services/entities/agent_entities.py b/api/services/entities/agent_entities.py
index 3184455d0a4..bb6018d23b1 100644
--- a/api/services/entities/agent_entities.py
+++ b/api/services/entities/agent_entities.py
@@ -39,7 +39,13 @@ class ComposerSavePayload(BaseModel):
variant: ComposerVariant
binding: ComposerBindingPayload | None = None
soul_lock: ComposerSoulLockPayload = Field(default_factory=ComposerSoulLockPayload)
- agent_soul: AgentSoulConfig | None = None
+ agent_soul: AgentSoulConfig | None = Field(
+ default=None,
+ description=(
+ "For Agent draft saves and workflow node_job_only updates, omit config_files to preserve the latest "
+ "server-managed files. An explicit list replaces the files, including an empty list to clear them."
+ ),
+ )
node_job: WorkflowNodeJobConfig | None = None
save_strategy: ComposerSaveStrategy
version_note: str | None = None
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py b/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
index ad19503a611..002dd884467 100644
--- a/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
@@ -6,11 +6,15 @@ workflow-node agent binding, and service delegation for the new config surface.
from __future__ import annotations
+from datetime import datetime
from inspect import unwrap
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
+from uuid import UUID
+import pytest
from flask import Flask
+from pydantic import ValidationError
from sqlalchemy import event
from sqlalchemy.orm import Session
@@ -29,8 +33,21 @@ from controllers.console.app.agent_config_inspector import (
AgentConfigSkillsApi,
AgentConfigSkillUploadByAgentApi,
)
+from extensions.storage.storage_type import StorageType
from models.account import Account
-from models.model import App, AppMode
+from models.agent import (
+ Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
+ AgentScope,
+ AgentSource,
+ WorkflowAgentBindingType,
+ WorkflowAgentNodeBinding,
+)
+from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig
+from models.enums import CreatorUserRole
+from models.model import App, AppMode, UploadFile
+from models.workflow import Workflow, WorkflowType
from services.agent_config_service import AgentConfigServiceError
from tests.helpers.unit.controllers.error_body import raised_error
@@ -494,3 +511,117 @@ def test_file_download_api_returns_signed_url_json(unbound_session: Session) ->
response = raw(AgentConfigFileDownloadApi(), unbound_session, _USER, _APP, "guide.txt")
assert response.status_code == 200
assert response.get_json() == {"url": "https://example.com/guide.txt"}
+
+
[email protected]("upload_ids", [[], ["invalid-uuid"]])
+def test_batch_file_upload_payload_requires_nonempty_uuid_list(upload_ids: list[str]) -> None:
+ with pytest.raises(ValidationError):
+ inspector.AgentConfigFilesUploadPayload.model_validate({"upload_file_ids": upload_ids})
+
+
[email protected]("workflow_node", [False, True])
+def test_batch_file_upload_routes_bind_and_serialize_real_workspace_files(
+ sqlite_session: Session, workflow_node: bool
+) -> None:
+ tenant_id = "11111111-1111-1111-1111-111111111111"
+ agent_id = "22222222-2222-2222-2222-222222222222"
+ app_id = "33333333-3333-3333-3333-333333333333"
+ account_id = "44444444-4444-4444-4444-444444444444"
+ draft_id = "55555555-5555-5555-5555-555555555555"
+ file_id = "66666666-6666-6666-6666-666666666666"
+ workflow_id = "77777777-7777-7777-7777-777777777777"
+ user = Account(name="Batch uploader", email="[email protected]")
+ user.id = account_id
+ app_model = App(
+ id=app_id,
+ tenant_id=tenant_id,
+ name="Batch app",
+ description="",
+ mode=AppMode.WORKFLOW if workflow_node else AppMode.AGENT,
+ enable_site=True,
+ enable_api=True,
+ max_active_requests=0,
+ )
+ agent = Agent(
+ id=agent_id,
+ tenant_id=tenant_id,
+ app_id=app_id,
+ name="Batch agent",
+ scope=AgentScope.WORKFLOW_ONLY if workflow_node else AgentScope.ROSTER,
+ source=AgentSource.WORKFLOW if workflow_node else AgentSource.AGENT_APP,
+ )
+ draft = AgentConfigDraft(
+ id=draft_id,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ draft_type=AgentConfigDraftType.DRAFT,
+ config_snapshot=AgentSoulConfig(),
+ )
+ upload = UploadFile(
+ tenant_id=tenant_id,
+ storage_type=StorageType.LOCAL,
+ key="uploads/batch.txt",
+ name="batch.txt",
+ size=5,
+ extension="txt",
+ mime_type="text/plain",
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by=account_id,
+ created_at=datetime(2025, 1, 1),
+ used=False,
+ )
+ upload.id = file_id
+ sqlite_session.add_all([app_model, agent, draft, upload])
+ if workflow_node:
+ sqlite_session.add(
+ Workflow(
+ id=workflow_id,
+ tenant_id=tenant_id,
+ app_id=app_id,
+ type=WorkflowType.WORKFLOW,
+ version="draft",
+ graph="{}",
+ _features="{}",
+ created_by=account_id,
+ )
+ )
+ sqlite_session.add(
+ WorkflowAgentNodeBinding(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ workflow_id=workflow_id,
+ workflow_version="draft",
+ node_id="node-1",
+ binding_type=WorkflowAgentBindingType.INLINE_AGENT,
+ agent_id=agent_id,
+ node_job_config=WorkflowNodeJobConfig(),
+ )
+ )
+ sqlite_session.commit()
+ payload = inspector.AgentConfigFilesUploadPayload(upload_file_ids=[UUID(file_id)])
+ query = "/?node_id=node-1&draft_type=draft" if workflow_node else "/?draft_type=draft"
+ with app.test_request_context(query, method="POST"):
+ if workflow_node:
+ endpoint = inspector.AgentConfigFilesUploadApi()
+ body, status = _raw(endpoint.post)(endpoint, payload, sqlite_session, user, app_model)
+ else:
+ endpoint = inspector.AgentConfigFilesUploadByAgentApi()
+ body, status = _raw(endpoint.post)(endpoint, payload, sqlite_session, tenant_id, user, UUID(agent_id))
+
+ assert status == 201
+ assert body["files"] == [
+ {
+ "id": "batch.txt",
+ "name": "batch.txt",
+ "file_id": file_id,
+ "is_missing": False,
+ "size": 5,
+ "mime_type": "text/plain",
+ "hash": None,
+ }
+ ]
+ assert body["config_version"] == {"id": draft_id, "kind": "draft", "writable": True}
+ sqlite_session.expire_all()
+ persisted = sqlite_session.get(AgentConfigDraft, draft_id)
+ assert persisted is not None
+ assert [file_ref.file_id for file_ref in persisted.config_snapshot.config_files] == [file_id]
diff --git a/api/tests/unit_tests/services/agent/test_composer_config_files.py b/api/tests/unit_tests/services/agent/test_composer_config_files.py
new file mode 100644
index 00000000000..7c93ed8e373
--- /dev/null
+++ b/api/tests/unit_tests/services/agent/test_composer_config_files.py
@@ -0,0 +1,360 @@
+"""Composer saves preserve assets omitted by ordinary configuration edits."""
+
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from uuid import uuid4
+
+import pytest
+from sqlalchemy.orm import Session, sessionmaker
+from typing_extensions import TypedDict
+
+from extensions.storage.storage_type import StorageType
+from models.agent import (
+ Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
+ AgentConfigSnapshot,
+ AgentScope,
+ AgentSource,
+ WorkflowAgentBindingType,
+ WorkflowAgentNodeBinding,
+)
+from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig
+from models.enums import CreatorUserRole
+from models.model import AppMode, UploadFile
+from services.agent.composer_service import AgentComposerService
+from services.agent_config_service import (
+ AgentConfigService,
+ AgentConfigVersionKind,
+ ConfigPushFileItem,
+ ConfigPushPayload,
+)
+from services.entities.agent_entities import ComposerSavePayload
+from tests.helpers.unit.model_factories import make_account, make_app, make_workflow
+
+
+@dataclass(frozen=True)
+class ComposerTarget:
+ tenant_id: str
+ account_id: str
+ agent_id: str
+ draft_id: str
+ app_id: str
+ binding_id: str | None
+ upload_ids: tuple[str, str]
+
+
+class AssetTargetArgs(TypedDict, closed=True):
+ tenant_id: str
+ agent_id: str
+ user_id: str
+ config_version_id: str
+ config_version_kind: AgentConfigVersionKind
+
+
[email protected](params=[False, True], ids=["agent", "inline-workflow"])
+def composer_target(request: pytest.FixtureRequest, sqlite_session: Session) -> ComposerTarget:
+ workflow = bool(request.param)
+ tenant_id, account_id, agent_id, snapshot_id, draft_id, app_id = (str(uuid4()) for _ in range(6))
+ agent = Agent(
+ id=agent_id,
+ tenant_id=tenant_id,
+ name="Config files test",
+ app_id=app_id,
+ scope=AgentScope.WORKFLOW_ONLY if workflow else AgentScope.ROSTER,
+ source=AgentSource.WORKFLOW if workflow else AgentSource.AGENT_APP,
+ active_config_snapshot_id=snapshot_id,
+ created_by=account_id,
+ updated_by=account_id,
+ )
+ soul = AgentSoulConfig()
+ snapshot = AgentConfigSnapshot(
+ id=snapshot_id, tenant_id=tenant_id, agent_id=agent_id, version=1, config_snapshot=soul
+ )
+ draft = AgentConfigDraft(
+ id=draft_id,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ draft_type=AgentConfigDraftType.DRAFT,
+ base_snapshot_id=snapshot_id,
+ config_snapshot=soul,
+ )
+ sqlite_session.add_all(
+ [
+ agent,
+ snapshot,
+ draft,
+ make_account(account_id=account_id, name="File editor", email="[email protected]"),
+ make_app(app_id=app_id, tenant_id=tenant_id, mode=AppMode.WORKFLOW if workflow else AppMode.AGENT_CHAT),
+ ]
+ )
+ binding_id = None
+ if workflow:
+ workflow_id = str(uuid4())
+ backing_app_id = str(uuid4())
+ agent.workflow_id = workflow_id
+ agent.workflow_node_id = "node-1"
+ agent.backing_app_id = backing_app_id
+ binding = WorkflowAgentNodeBinding(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ workflow_id=workflow_id,
+ workflow_version="draft",
+ node_id="node-1",
+ binding_type=WorkflowAgentBindingType.INLINE_AGENT,
+ agent_id=agent_id,
+ current_snapshot_id=snapshot_id,
+ node_job_config=WorkflowNodeJobConfig(),
+ )
+ sqlite_session.add_all(
+ [
+ binding,
+ make_workflow(workflow_id=workflow_id, tenant_id=tenant_id, app_id=app_id),
+ make_app(app_id=backing_app_id, tenant_id=tenant_id, mode=AppMode.AGENT_CHAT),
+ ]
+ )
+ sqlite_session.flush()
+ binding_id = binding.id
+ upload_ids = (str(uuid4()), str(uuid4()))
+ for upload_id, name in zip(upload_ids, ["first.md", "second.md"], strict=True):
+ upload = UploadFile(
+ tenant_id=tenant_id,
+ storage_type=StorageType.LOCAL,
+ key=f"uploads/{name}",
+ name=name,
+ size=5,
+ extension="md",
+ mime_type="text/markdown",
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by=account_id,
+ created_at=datetime.now(UTC).replace(tzinfo=None),
+ used=False,
+ hash=f"hash-{name}",
+ )
+ upload.id = upload_id
+ sqlite_session.add(upload)
+ sqlite_session.commit()
+ return ComposerTarget(tenant_id, account_id, agent_id, draft_id, app_id, binding_id, upload_ids)
+
+
+def save_composer(session: Session, target: ComposerTarget, soul: dict[str, object]) -> AgentSoulConfig:
+ payload = ComposerSavePayload.model_validate(
+ {
+ "variant": "workflow" if target.binding_id else "agent_app",
+ "save_strategy": "node_job_only" if target.binding_id else "save_to_current_version",
+ "agent_soul": soul,
+ }
+ )
+ if target.binding_id:
+ state = AgentComposerService.save_workflow_composer(
+ session=session,
+ tenant_id=target.tenant_id,
+ app_id=target.app_id,
+ node_id="node-1",
+ account_id=target.account_id,
+ payload=payload,
+ )
+ else:
+ state = AgentComposerService.save_agent_composer(
+ session=session,
+ tenant_id=target.tenant_id,
+ agent_id=target.agent_id,
+ account_id=target.account_id,
+ payload=payload,
+ )
+ session.commit()
+ return AgentSoulConfig.model_validate(state["agent_soul"])
+
+
+def asset_target(target: ComposerTarget) -> AssetTargetArgs:
+ return {
+ "tenant_id": target.tenant_id,
+ "agent_id": target.agent_id,
+ "user_id": target.account_id,
+ "config_version_id": target.draft_id,
+ "config_version_kind": AgentConfigVersionKind.DRAFT,
+ }
+
+
[email protected]("file_count", [1, 2], ids=["single-bind", "batch-bind"])
+def test_omitted_files_preserve_bindings_created_after_the_composer_was_read(
+ sqlite_session_factory: sessionmaker[Session],
+ composer_target: ComposerTarget,
+ file_count: int,
+) -> None:
+ target = composer_target
+ assets = AgentConfigService(session_factory=sqlite_session_factory)
+ with sqlite_session_factory() as stale_session:
+ # Keep the old ORM rows cached while another request binds the files.
+ _cached_agent = stale_session.get(Agent, target.agent_id)
+ _cached_draft = stale_session.get(AgentConfigDraft, target.draft_id)
+ if target.binding_id:
+ _cached_binding = stale_session.get(WorkflowAgentNodeBinding, target.binding_id)
+ if file_count == 1:
+ assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
+ else:
+ assets.push_files_for_console(**asset_target(target), upload_file_ids=list(target.upload_ids))
+ state = save_composer(stale_session, target, {"prompt": {"system_prompt": "An older prompt edit"}})
+
+ assert [item.file_id for item in state.config_files] == list(target.upload_ids[:file_count])
+ assert state.prompt.system_prompt == "An older prompt edit"
+ with sqlite_session_factory() as session:
+ draft = session.get(AgentConfigDraft, target.draft_id)
+ assert draft is not None
+ assert [item.file_id for item in draft.config_snapshot.config_files] == list(target.upload_ids[:file_count])
+
+
+def test_omitted_files_do_not_restore_an_asset_deleted_after_the_composer_was_read(
+ sqlite_session_factory: sessionmaker[Session],
+ composer_target: ComposerTarget,
+) -> None:
+ target = composer_target
+ assets = AgentConfigService(session_factory=sqlite_session_factory)
+ assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
+ with sqlite_session_factory() as stale_session:
+ _cached_draft = stale_session.get(AgentConfigDraft, target.draft_id)
+ assets.push_for_console(
+ **asset_target(target), payload=ConfigPushPayload(files=[ConfigPushFileItem(name="first.md")])
+ )
+ state = save_composer(stale_session, target, {"prompt": {"system_prompt": "Keep this edit"}})
+ assert state.config_files == []
+
+
[email protected]("delete_existing", [False, True], ids=["keep-batch", "keep-deletion"])
+def test_omitted_files_do_not_autoflush_a_dirty_cached_snapshot_before_locking(
+ sqlite_session_factory: sessionmaker[Session],
+ composer_target: ComposerTarget,
+ delete_existing: bool,
+) -> None:
+ target = composer_target
+ assets = AgentConfigService(session_factory=sqlite_session_factory)
+ if delete_existing:
+ assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
+ with sqlite_session_factory() as stale_session:
+ cached = stale_session.get(AgentConfigDraft, target.draft_id)
+ assert cached is not None
+ local_edit = cached.config_snapshot.model_copy(deep=True)
+ local_edit.config_note = "Pending local note"
+ cached.config_snapshot = local_edit
+ if delete_existing:
+ assets.push_for_console(
+ **asset_target(target),
+ payload=ConfigPushPayload(files=[ConfigPushFileItem(name="first.md")]),
+ )
+ else:
+ assets.push_files_for_console(**asset_target(target), upload_file_ids=list(target.upload_ids))
+ result = save_composer(stale_session, target, {"prompt": {"system_prompt": "Ordinary edit"}})
+ assert [file.file_id for file in result.config_files] == ([] if delete_existing else list(target.upload_ids))
+
+
[email protected]("replace_with_file", [False, True], ids=["explicit-clear", "explicit-replace"])
+def test_explicit_files_keep_complete_replacement_semantics(
+ sqlite_session_factory: sessionmaker[Session],
+ composer_target: ComposerTarget,
+ replace_with_file: bool,
+) -> None:
+ target = composer_target
+ assets = AgentConfigService(session_factory=sqlite_session_factory)
+ assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
+ files: list[dict[str, str]] = (
+ [{"name": "second.md", "file_kind": "upload_file", "file_id": target.upload_ids[1]}]
+ if replace_with_file
+ else []
+ )
+ with sqlite_session_factory() as session:
+ state = save_composer(
+ session, target, {"prompt": {"system_prompt": "Applied configuration"}, "config_files": files}
+ )
+ assert [item.file_id for item in state.config_files] == ([target.upload_ids[1]] if replace_with_file else [])
+
+
[email protected]("composer_target", [True], indirect=True, ids=["inline-workflow"])
+def test_omitted_files_refresh_a_cached_inline_snapshot_and_binding(
+ sqlite_session_factory: sessionmaker[Session],
+ composer_target: ComposerTarget,
+) -> None:
+ target = composer_target
+ assert target.binding_id is not None
+ with sqlite_session_factory() as stale_session:
+ stale_agent = stale_session.get(Agent, target.agent_id)
+ stale_binding = stale_session.get(WorkflowAgentNodeBinding, target.binding_id)
+ stale_draft = stale_session.get(AgentConfigDraft, target.draft_id)
+ assert stale_agent is not None
+ assert stale_binding is not None
+ assert stale_draft is not None
+ with sqlite_session_factory() as other_session:
+ save_composer(
+ other_session,
+ target,
+ {
+ "config_files": [
+ {
+ "name": "second.md",
+ "file_kind": "upload_file",
+ "file_id": target.upload_ids[1],
+ }
+ ]
+ },
+ )
+ state = save_composer(stale_session, target, {"prompt": {"system_prompt": "Next edit"}})
+ assert [item.file_id for item in state.config_files] == [target.upload_ids[1]]
+
+
+def test_locking_the_latest_draft_keeps_pending_agent_profile_edits(
+ sqlite_session_factory: sessionmaker[Session],
+ composer_target: ComposerTarget,
+) -> None:
+ target = composer_target
+ assets = AgentConfigService(session_factory=sqlite_session_factory)
+ with sqlite_session_factory() as session:
+ agent = session.get(Agent, target.agent_id)
+ _cached_draft = session.get(AgentConfigDraft, target.draft_id)
+ assert agent is not None
+ agent.name = "Renamed in this transaction"
+ assets.push_file_for_console(**asset_target(target), upload_file_id=target.upload_ids[0])
+ draft = AgentComposerService.get_or_create_normal_agent_draft(
+ session=session,
+ tenant_id=target.tenant_id,
+ agent=agent,
+ created_by=target.account_id,
+ )
+ assert agent.name == "Renamed in this transaction"
+ assert [item.file_id for item in draft.config_snapshot.config_files] == [target.upload_ids[0]]
+ session.commit()
+ with sqlite_session_factory() as session:
+ saved_agent = session.get(Agent, target.agent_id)
+ assert saved_agent is not None
+ assert saved_agent.name == "Renamed in this transaction"
+
+
[email protected]("composer_target", [True], indirect=True, ids=["inline-workflow"])
+def test_inline_composer_shows_file_edits_before_the_next_node_save(
+ sqlite_session_factory: sessionmaker[Session],
+ composer_target: ComposerTarget,
+) -> None:
+ target = composer_target
+ assets = AgentConfigService(session_factory=sqlite_session_factory)
+
+ def loaded_file_ids(snapshot_id: str | None = None) -> list[str | None]:
+ with sqlite_session_factory() as session:
+ state = AgentComposerService.load_workflow_composer(
+ session=session,
+ tenant_id=target.tenant_id,
+ app_id=target.app_id,
+ node_id="node-1",
+ snapshot_id=snapshot_id,
+ )
+ return [item.file_id for item in AgentSoulConfig.model_validate(state["agent_soul"]).config_files]
+
+ assets.push_files_for_console(**asset_target(target), upload_file_ids=list(target.upload_ids))
+ assert loaded_file_ids() == list(target.upload_ids)
+ with sqlite_session_factory() as session:
+ agent = session.get(Agent, target.agent_id)
+ assert agent is not None
+ bound_snapshot_id = agent.active_config_snapshot_id
+ assert loaded_file_ids(bound_snapshot_id) == []
+
+ assets.push_for_console(
+ **asset_target(target), payload=ConfigPushPayload(files=[ConfigPushFileItem(name="first.md")])
+ )
+ assert loaded_file_ids() == [target.upload_ids[1]]
diff --git a/api/tests/unit_tests/services/agent/test_roster_service.py b/api/tests/unit_tests/services/agent/test_roster_service.py
index fd240bebe1c..9c0fa9ea9c0 100644
--- a/api/tests/unit_tests/services/agent/test_roster_service.py
+++ b/api/tests/unit_tests/services/agent/test_roster_service.py
@@ -1021,7 +1021,7 @@ def test_save_agent_app_composer_keeps_published_when_draft_matches_active_snaps
tenant_id="tenant-1",
agent_id="agent-1",
draft_type=AgentConfigDraftType.DRAFT,
- config_snapshot=AgentSoulConfig(),
+ config_snapshot=agent_soul,
id="draft-1",
home_snapshot_id="home-initial",
),
@@ -2511,7 +2511,7 @@ def test_serialize_workflow_state_changes_lock_and_save_options(
monkeypatch.setattr(AgentComposerService, "calculate_impact", lambda **kwargs: {"workflow_node_count": 1})
state = AgentComposerService._serialize_workflow_state(
- session=session, binding=binding, agent=agent, version=version
+ session=session, binding=binding, agent=agent, version=version, include_draft_files=True
)
assert state["soul_lock"]["locked"] is True
@@ -2562,7 +2562,7 @@ def test_serialize_workflow_state_passes_user_declared_outputs_through_effective
monkeypatch.setattr(AgentComposerService, "calculate_impact", lambda **kwargs: {"workflow_node_count": 1})
state = AgentComposerService._serialize_workflow_state(
- session=session, binding=binding, agent=agent, version=version
+ session=session, binding=binding, agent=agent, version=version, include_draft_files=True
)
effective = state["effective_declared_outputs"]
@@ -2624,6 +2624,7 @@ def test_serialize_workflow_state_includes_inline_debug_conversation_message_sta
agent=agent,
version=version,
account_id="account-1",
+ include_draft_files=True,
)
assert state["debug_conversation_id"] == "debug-conversation-1"
@@ -2666,7 +2667,11 @@ def test_composer_save_helpers_create_and_rebind_agents(monkeypatch: pytest.Monk
"_create_roster_agent_for_composer",
fake_create_roster_agent_for_composer,
)
- monkeypatch.setattr(AgentComposerService, "_require_agent", lambda **kwargs: roster_agent)
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_require_agent",
+ lambda **kwargs: workflow_agent if kwargs["agent_id"] == workflow_agent.id else roster_agent,
+ )
monkeypatch.setattr(
AgentComposerService,
"_require_version",
@@ -2711,6 +2716,8 @@ def test_composer_save_helpers_create_and_rebind_agents(monkeypatch: pytest.Monk
agent_id="inline-agent-1",
current_snapshot_id="inline-version-1",
)
+ session.add_all([workflow_agent, roster_agent, existing_binding])
+ session.commit()
updated_binding = AgentComposerService._save_node_job_only(
session=session,
@@ -2868,6 +2875,8 @@ def test_node_job_only_updates_inline_agent_soul(monkeypatch: pytest.MonkeyPatch
),
)
original_node_job = binding.node_job_config_dict
+ session.add_all([inline_agent, current_snapshot, normal_draft, binding])
+ session.commit()
payload = ComposerSavePayload.model_validate(
{
"variant": ComposerVariant.WORKFLOW.value,
diff --git a/api/tests/unit_tests/services/test_agent_config_service.py b/api/tests/unit_tests/services/test_agent_config_service.py
index 97524c000b5..92616640049 100644
--- a/api/tests/unit_tests/services/test_agent_config_service.py
+++ b/api/tests/unit_tests/services/test_agent_config_service.py
@@ -12,7 +12,9 @@ from unittest.mock import patch
import pytest
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from dify_agent.protocol import CreateRunRequest
-from sqlalchemy.orm import Session, sessionmaker
+from sqlalchemy import Select, event, select
+from sqlalchemy.dialects import postgresql
+from sqlalchemy.orm import ORMExecuteState, Session, sessionmaker
from typing_extensions import TypedDict
from clients.agent_backend import AgentBackendAgentAppRunInput, AgentBackendModelConfig, AgentBackendRunRequestBuilder
@@ -820,15 +822,13 @@ def test_upload_skill_for_console_maps_package_validation_failures(sqlite_sessio
@pytest.mark.parametrize("sqlite_session", [()], indirect=True)
-def test_apply_skill_updates_rejects_non_tool_file_refs(sqlite_session: Session) -> None:
- service = AgentConfigService()
+def test_prepare_skill_updates_rejects_non_tool_file_refs(sqlite_session: Session) -> None:
+ service = _service(sqlite_session)
with pytest.raises(AgentConfigServiceError, match="tool files") as exc_info:
- service._apply_skill_updates(
- sqlite_session,
+ service._prepare_skill_updates(
tenant_id=TENANT,
user_id=USER,
- current=[],
updates=[
ConfigPushSkillItem.model_validate(
{"name": "alpha", "file_ref": {"kind": "upload_file", "id": "upload-1"}}
@@ -847,12 +847,12 @@ def test_apply_skill_updates_rejects_non_tool_file_refs(sqlite_session: Session)
],
)
@pytest.mark.parametrize("sqlite_session", [()], indirect=True)
-def test_apply_skill_updates_maps_normalizer_failures(
+def test_prepare_skill_updates_maps_normalizer_failures(
error_code: str,
message: str,
sqlite_session: Session,
) -> None:
- service = AgentConfigService()
+ service = _service(sqlite_session)
tool_file = ToolFile(
user_id=USER,
tenant_id=TENANT,
@@ -873,11 +873,9 @@ def test_apply_skill_updates_maps_normalizer_failures(
),
):
with pytest.raises(AgentConfigServiceError, match=message) as exc_info:
- service._apply_skill_updates(
- sqlite_session,
+ service._prepare_skill_updates(
tenant_id=TENANT,
user_id=USER,
- current=[],
updates=[
ConfigPushSkillItem.model_validate(
{"name": "alpha", "file_ref": {"kind": "tool_file", "id": "tool-file-1"}}
@@ -1377,3 +1375,189 @@ def test_download_url_helpers_bind_shared_download_request_to_console_origin(
)
== "https://example.com/files/guide.txt?sign=2"
)
+
+
+def _persist_upload(session: Session, *, file_id: str, name: str, tenant_id: str = TENANT) -> UploadFile:
+ upload = UploadFile(
+ tenant_id=tenant_id,
+ storage_type=StorageType.LOCAL,
+ key=f"uploads/{file_id}",
+ name=name,
+ size=7,
+ extension="txt",
+ mime_type="text/plain",
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by=END_USER,
+ created_at=datetime(2025, 1, 1),
+ used=False,
+ hash=f"sha256:{file_id}",
+ )
+ upload.id = file_id
+ session.add(upload)
+ session.commit()
+ return upload
+
+
[email protected]("build_draft", [False, True])
+def test_push_files_for_console_merges_batch_atomically_with_last_same_name_winning(
+ sqlite_session: Session, build_draft: bool
+) -> None:
+ original = _soul(
+ prompt={"system_prompt": "Keep these instructions"},
+ config_note="Keep note",
+ env={"variables": [{"name": "TOKEN", "value": "keep"}]},
+ config_files=[AgentConfigFileRefConfig(name="keep.txt", file_kind="upload_file", file_id="kept")],
+ )
+ draft = _draft(
+ soul=original,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD if build_draft else AgentConfigDraftType.DRAFT,
+ account_id=USER if build_draft else None,
+ )
+ _persist_target(sqlite_session, draft)
+ _persist_upload(sqlite_session, file_id=UPLOAD_FILE, name="same.txt")
+ _persist_upload(sqlite_session, file_id=TOOL_FILE, name="new.txt")
+ _persist_upload(sqlite_session, file_id=SKILL_FILE, name="same.txt")
+
+ response = _service(sqlite_session).push_files_for_console(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id=DRAFT,
+ config_version_kind=AgentConfigVersionKind.BUILD_DRAFT if build_draft else AgentConfigVersionKind.DRAFT,
+ upload_file_ids=[UPLOAD_FILE, TOOL_FILE, SKILL_FILE],
+ )
+
+ assert response == {
+ "files": [
+ {
+ "id": name,
+ "name": name,
+ "file_id": file_id,
+ "is_missing": False,
+ "size": 7,
+ "hash": f"sha256:{file_id}",
+ "mime_type": "text/plain",
+ }
+ for name, file_id in [("same.txt", SKILL_FILE), ("new.txt", TOOL_FILE)]
+ ],
+ "config_version": {"id": DRAFT, "kind": "build_draft" if build_draft else "draft", "writable": True},
+ }
+ sqlite_session.expire_all()
+ persisted = sqlite_session.get(AgentConfigDraft, DRAFT)
+ assert persisted is not None
+ expected = original.model_copy(deep=True)
+ expected.config_files += [
+ AgentConfigFileRefConfig(
+ name=name,
+ file_kind="upload_file",
+ file_id=file_id,
+ size=7,
+ hash=f"sha256:{file_id}",
+ mime_type="text/plain",
+ )
+ for name, file_id in [("same.txt", SKILL_FILE), ("new.txt", TOOL_FILE)]
+ ]
+ assert persisted.config_snapshot == expected
+
+
[email protected]("invalid_source", ["missing", "other_tenant", "invalid_name"])
+def test_push_files_for_console_does_not_commit_any_file_when_batch_validation_fails(
+ sqlite_session: Session, invalid_source: str
+) -> None:
+ original = _soul(config_note="Unchanged")
+ _persist_target(sqlite_session, _draft(soul=original))
+ _persist_upload(sqlite_session, file_id=UPLOAD_FILE, name="valid.txt")
+ if invalid_source != "missing":
+ _persist_upload(
+ sqlite_session,
+ file_id=TOOL_FILE,
+ name="../invalid.txt" if invalid_source == "invalid_name" else "foreign.txt",
+ tenant_id=OTHER_TENANT if invalid_source == "other_tenant" else TENANT,
+ )
+
+ with pytest.raises((AgentConfigServiceError, ValueError)):
+ _service(sqlite_session).push_files_for_console(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id=DRAFT,
+ config_version_kind=AgentConfigVersionKind.DRAFT,
+ upload_file_ids=[UPLOAD_FILE, TOOL_FILE],
+ )
+
+ sqlite_session.expire_all()
+ persisted = sqlite_session.get(AgentConfigDraft, DRAFT)
+ assert persisted is not None
+ assert persisted.config_snapshot == original
+
+
+def test_push_files_for_console_rejects_published_snapshots_without_mutation(sqlite_session: Session) -> None:
+ _persist_target(sqlite_session, _snapshot())
+ _persist_upload(sqlite_session, file_id=UPLOAD_FILE, name="valid.txt")
+ with pytest.raises(AgentConfigServiceError, match="editable drafts"):
+ _service(sqlite_session).push_files_for_console(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id=SNAPSHOT,
+ config_version_kind=AgentConfigVersionKind.SNAPSHOT,
+ upload_file_ids=[UPLOAD_FILE],
+ )
+ sqlite_session.expire_all()
+ snapshot = sqlite_session.get(AgentConfigSnapshot, SNAPSHOT)
+ assert snapshot is not None
+ assert snapshot.config_snapshot.config_files == []
+
+
[email protected]("dirty_cached_draft", [False, True], ids=["cached", "dirty-cached"])
+def test_push_files_for_console_locks_parent_then_draft_and_refreshes_cached_snapshot(
+ sqlite_session: Session,
+ dirty_cached_draft: bool,
+) -> None:
+ _persist_target(sqlite_session, _draft())
+ _persist_upload(sqlite_session, file_id=UPLOAD_FILE, name="new.txt")
+ factory = sessionmaker(bind=sqlite_session.get_bind(), expire_on_commit=False)
+ with factory() as binding_session:
+ cached = binding_session.scalar(select(AgentConfigDraft).where(AgentConfigDraft.id == DRAFT))
+ assert cached is not None
+ if dirty_cached_draft:
+ pending_edit = cached.config_snapshot.model_copy(deep=True)
+ pending_edit.prompt.system_prompt = "Stale local prompt"
+ cached.config_snapshot = pending_edit
+ with factory() as concurrent_session:
+ concurrent = concurrent_session.get(AgentConfigDraft, DRAFT)
+ assert concurrent is not None
+ concurrent.config_snapshot = _soul(
+ config_note="Concurrent edit",
+ config_files=[AgentConfigFileRefConfig(name="keep.txt", file_kind="upload_file", file_id="kept")],
+ )
+ concurrent_session.commit()
+ assert cached.config_snapshot.config_note == ""
+ locked_queries: list[str] = []
+
+ def record_lock(state: ORMExecuteState) -> None:
+ if not isinstance(state.statement, Select):
+ return
+ sql = str(state.statement.compile(dialect=postgresql.dialect()))
+ if "FOR UPDATE" in sql:
+ locked_queries.append(sql)
+
+ event.listen(binding_session, "do_orm_execute", record_lock)
+ service = AgentConfigService(session_factory=lambda: binding_session)
+ service.push_files_for_console(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ user_id=USER,
+ config_version_id=DRAFT,
+ config_version_kind=AgentConfigVersionKind.DRAFT,
+ upload_file_ids=[UPLOAD_FILE],
+ )
+
+ assert len(locked_queries) == 2
+ assert "FROM agents" in locked_queries[0]
+ assert "FROM agent_config_drafts" in locked_queries[1]
+ sqlite_session.expire_all()
+ persisted = sqlite_session.get(AgentConfigDraft, DRAFT)
+ assert persisted is not None
+ assert persisted.config_snapshot.config_note == "Concurrent edit"
+ assert [ref.name for ref in persisted.config_snapshot.config_files] == ["keep.txt", "new.txt"]
diff --git a/e2e/features/agent-v2/files.feature b/e2e/features/agent-v2/files.feature
index cc770c66674..a9c30b2038e 100644
--- a/e2e/features/agent-v2/files.feature
+++ b/e2e/features/agent-v2/files.feature
@@ -37,10 +37,18 @@ Feature: Agent v2 files
Then I should see the special-name Agent v2 file in the Files section
@core @files-limits
- Scenario: Dropping multiple Agent v2 files at once is rejected
+ Scenario: Dropping multiple Agent v2 files uploads and preserves every file
Given I am signed in as the default E2E admin
And a basic configured Agent v2 test agent has been created via API
When I open the Agent v2 configure page
And I drop multiple Agent v2 files into the Files upload dialog
- Then the Agent v2 Files upload dialog should reject the multiple-file drop
- And I should not see the dropped Agent v2 files in the Files section
+ Then the Agent v2 Files upload dialog should queue every dropped file
+ When I upload the dropped Agent v2 files
+ Then I should see the small Agent v2 file in the Files section
+ And I should see the empty Agent v2 file in the Files section
+ And the small Agent v2 file should be saved in the Agent v2 draft
+ And the empty Agent v2 file should be saved as a zero-byte file in the Agent v2 draft
+ And the Agent v2 configuration should be saved automatically
+ When I refresh the current page
+ Then I should see the small Agent v2 file in the Files section
+ And I should see the empty Agent v2 file in the Files section
diff --git a/e2e/features/agent-v2/support/config-assets.ts b/e2e/features/agent-v2/support/config-assets.ts
index 67ec146bf74..1d79248cdcf 100644
--- a/e2e/features/agent-v2/support/config-assets.ts
+++ b/e2e/features/agent-v2/support/config-assets.ts
@@ -1,6 +1,6 @@
import type {
AgentConfigFileRefConfig,
- AgentConfigFileUploadResponse,
+ AgentConfigFilesUploadResponse,
AgentConfigSkillRefConfig,
AgentConfigSkillUploadResponse,
} from '@dify/contracts/api/console/agent/types.gen'
@@ -107,12 +107,14 @@ export async function uploadAgentConfigFileToDraft(
const uploadedFile = await client.files.upload.post({
body: { file: createUploadFile(await readFile(filePath), fileName, 'text/plain') },
})
- const body: AgentConfigFileUploadResponse = await client.agent.byAgentId.config.files.post({
- body: { upload_file_id: uploadedFile.id },
- params: { agent_id: agentId },
- })
- const file = body.file
- if (!file.file_id) throw new Error(`Agent v2 config file ${fileName} did not return a file_id.`)
+ const body: AgentConfigFilesUploadResponse = await client.agent.byAgentId.config.files.batch.post(
+ {
+ body: { upload_file_ids: [uploadedFile.id] },
+ params: { agent_id: agentId },
+ },
+ )
+ const file = body.files[0]
+ if (!file?.file_id) throw new Error(`Agent v2 config file ${fileName} did not return a file_id.`)
return {
file_id: file.file_id,
diff --git a/e2e/features/step-definitions/agent-v2/build-draft.steps.ts b/e2e/features/step-definitions/agent-v2/build-draft.steps.ts
index de469373b5e..f2ce1f004af 100644
--- a/e2e/features/step-definitions/agent-v2/build-draft.steps.ts
+++ b/e2e/features/step-definitions/agent-v2/build-draft.steps.ts
@@ -87,6 +87,7 @@ const saveSupportedBuildDraft = async (
await saveAgentComposerDraft(client, agentId, {
...normalConfig,
+ config_files: [],
...(retainSkillInNormalDraft ? { config_skills: configSkills } : {}),
})
await saveAgentBuildDraft(client, agentId, {
diff --git a/e2e/features/step-definitions/agent-v2/configure-helpers.ts b/e2e/features/step-definitions/agent-v2/configure-helpers.ts
index 3ba84bac349..ceb4dc8dbbc 100644
--- a/e2e/features/step-definitions/agent-v2/configure-helpers.ts
+++ b/e2e/features/step-definitions/agent-v2/configure-helpers.ts
@@ -1,7 +1,7 @@
import type { Locator } from '@playwright/test'
import type { AgentComposerEnvVariable } from '../../agent-v2/support/agent-soul.ts'
import type { DifyWorld } from '../../support/world.ts'
-import { zPostAgentByAgentIdConfigFilesResponse } from '@dify/contracts/api/console/agent/zod.gen'
+import { zPostAgentByAgentIdConfigFilesBatchResponse } from '@dify/contracts/api/console/agent/zod.gen'
import { expect } from '@playwright/test'
import { normalAgentPrompt } from '../../agent-v2/support/agent-soul.ts'
import { uploadAgentConfigSkillToDraft } from '../../agent-v2/support/config-assets.ts'
@@ -49,17 +49,40 @@ export const getAgentEnvVariables = async (world: DifyWorld, agentId: string) =>
return draft.agent_soul?.env?.variables ?? []
}
+export const submitAgentConfigFiles = async (
+ world: DifyWorld,
+ dialog: Locator,
+ expectedNames: string[],
+) => {
+ const page = world.getPage()
+ const agentId = getCurrentAgentId(world)
+ const commitResponsePromise = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname.endsWith(`/console/api/agent/${agentId}/config/files/batch`),
+ )
+ await dialog.getByRole('button', { name: 'Upload', exact: true }).click()
+ const commitResponse = await commitResponsePromise
+ expect(commitResponse.status()).toBe(201)
+ const committed = zPostAgentByAgentIdConfigFilesBatchResponse.parse(await commitResponse.json())
+
+ for (const file of committed.files) {
+ world.createdAgentConfigFiles.push({ agentId, name: file.name })
+ }
+ expect(committed.files.map((file) => file.name).sort()).toEqual([...expectedNames].sort())
+ await expect(dialog).not.toBeVisible({ timeout: 30_000 })
+}
+
export const uploadAgentConfigFile = async (
world: DifyWorld,
material: keyof typeof agentBuilderTestMaterials,
) => {
const page = world.getPage()
- const agentId = getCurrentAgentId(world)
const fileName = agentBuilderTestMaterials[material]
const filePath = getAgentBuilderTestMaterialPath(material)
await page.getByRole('button', { name: 'Add file' }).click()
- const dialog = page.getByRole('dialog', { name: 'Upload file' })
+ const dialog = page.getByRole('dialog', { name: 'Upload files', exact: true })
await expect(dialog).toBeVisible()
const fileChooserPromise = page.waitForEvent('filechooser')
@@ -67,22 +90,7 @@ export const uploadAgentConfigFile = async (
await (await fileChooserPromise).setFiles(filePath)
await expect(dialog.getByText(fileName)).toBeVisible()
- const commitResponsePromise = page.waitForResponse(
- (response) =>
- response.request().method() === 'POST' &&
- new URL(response.url()).pathname.endsWith(`/console/api/agent/${agentId}/config/files`),
- )
- await dialog.getByRole('button', { name: 'Upload' }).click()
- const commitResponse = await commitResponsePromise
- expect(commitResponse.status()).toBe(201)
- const committed = zPostAgentByAgentIdConfigFilesResponse.parse(await commitResponse.json())
- await expect(dialog).not.toBeVisible({ timeout: 30_000 })
-
- const committedName = committed.file?.name
- if (!committedName)
- throw new Error('Agent config file upload response did not include a file name.')
-
- world.createdAgentConfigFiles.push({ agentId, name: committedName })
+ await submitAgentConfigFiles(world, dialog, [fileName])
}
export const expectAgentConfigFileVisible = async (
diff --git a/e2e/features/step-definitions/agent-v2/files.steps.ts b/e2e/features/step-definitions/agent-v2/files.steps.ts
index 781dcb80842..303506bb932 100644
--- a/e2e/features/step-definitions/agent-v2/files.steps.ts
+++ b/e2e/features/step-definitions/agent-v2/files.steps.ts
@@ -6,6 +6,7 @@ import {
expectAgentConfigFileHidden,
expectAgentConfigFileSaved,
expectAgentConfigFileVisible,
+ submitAgentConfigFiles,
uploadAgentConfigFile,
} from './configure-helpers.ts'
@@ -30,11 +31,12 @@ When(
const page = this.getPage()
await page.getByRole('button', { name: 'Add file' }).click()
- const dialog = page.getByRole('dialog', { name: 'Upload file' })
+ const dialog = page.getByRole('dialog', { name: 'Upload files', exact: true })
await expect(dialog).toBeVisible()
- const dropZone = dialog.getByRole('group', { name: 'Upload file' })
+ const dropZone = dialog.getByRole('group', { name: 'Upload files', exact: true })
await expect(dropZone).toBeVisible()
+ await expect(dialog.getByRole('button', { name: 'browse', exact: true })).toBeEnabled()
const droppedFileNames: [string, string] = [
agentBuilderTestMaterials.smallFile,
@@ -58,31 +60,28 @@ When(
)
Then(
- 'the Agent v2 Files upload dialog should reject the multiple-file drop',
+ 'the Agent v2 Files upload dialog should queue every dropped file',
async function (this: DifyWorld) {
- const page = this.getPage()
- const dialog = page.getByRole('dialog', { name: 'Upload file' })
- const notifications = page.getByRole('region', { name: 'Notifications' })
-
- await expect(notifications.getByRole('dialog')).toBeVisible()
- await expect(dialog.getByRole('button', { name: 'Upload' })).toBeDisabled()
- await expect(
- dialog.getByText(agentBuilderTestMaterials.smallFile, { exact: true }),
- ).not.toBeVisible()
- await expect(
- dialog.getByText(agentBuilderTestMaterials.emptyFile, { exact: true }),
- ).not.toBeVisible()
- },
-)
+ const dialog = this.getPage().getByRole('dialog', { name: 'Upload files', exact: true })
-Then(
- 'I should not see the dropped Agent v2 files in the Files section',
- async function (this: DifyWorld) {
- await expectAgentConfigFileHidden(this, 'smallFile')
- await expectAgentConfigFileHidden(this, 'emptyFile')
+ for (const fileName of [
+ agentBuilderTestMaterials.smallFile,
+ agentBuilderTestMaterials.emptyFile,
+ ]) {
+ await expect(dialog.getByRole('listitem').getByText(fileName, { exact: true })).toBeVisible()
+ }
+ await expect(dialog.getByRole('button', { name: 'Upload', exact: true })).toBeEnabled()
},
)
+When('I upload the dropped Agent v2 files', async function (this: DifyWorld) {
+ const dialog = this.getPage().getByRole('dialog', { name: 'Upload files', exact: true })
+ await submitAgentConfigFiles(this, dialog, [
+ agentBuilderTestMaterials.smallFile,
+ agentBuilderTestMaterials.emptyFile,
+ ])
+})
+
Then('I should see the small Agent v2 file in the Files section', async function (this: DifyWorld) {
await expectAgentConfigFileVisible(this, 'smallFile')
})
diff --git a/packages/contracts/generated/api/console/agent/errors.gen.ts b/packages/contracts/generated/api/console/agent/errors.gen.ts
index 18e7b0e548e..2600e7ed265 100644
--- a/packages/contracts/generated/api/console/agent/errors.gen.ts
+++ b/packages/contracts/generated/api/console/agent/errors.gen.ts
@@ -484,6 +484,8 @@ export const put2Errors = {
plaintext_secret_not_allowed_error: { status: 400, data: zPlaintextSecretNotAllowedError },
}
+export const post9Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
+
export const get9Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
export const get10Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
@@ -492,11 +494,11 @@ export const delete3Errors = { agent_not_found_error: { status: 404, data: zAgen
export const get11Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
-export const post9Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
+export const post10Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
export const get12Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
-export const post10Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
+export const post11Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
export const get13Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
@@ -512,20 +514,20 @@ export const delete4Errors = { agent_not_found_error: { status: 404, data: zAgen
export const get18Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
-export const post11Errors = {
+export const post12Errors = {
agent_name_conflict_error: { status: 409, data: zAgentNameConflictError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
agent_version_not_found_error: { status: 404, data: zAgentVersionNotFoundError },
}
-export const post12Errors = {
+export const post13Errors = {
agent_build_sandbox_not_found: { status: 404, data: zAgentBuildSandboxNotFoundError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
}
-export const post13Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
+export const post14Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
-export const post14Errors = {
+export const post15Errors = {
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
app_unavailable: { status: 400, data: zAppUnavailableError },
message_feedback_rating_required: { status: 400, data: zMessageFeedbackRatingRequiredError },
@@ -542,7 +544,7 @@ export const get22Errors = {
app_unavailable: { status: 400, data: zAppUnavailableError },
}
-export const post15Errors = {
+export const post16Errors = {
agent_model_not_configured: { status: 400, data: zAgentModelNotConfiguredError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
agent_version_not_found_error: { status: 404, data: zAgentVersionNotFoundError },
@@ -552,7 +554,7 @@ export const post15Errors = {
export const get23Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
-export const post16Errors = {
+export const post17Errors = {
agent_backend_unreachable: { status: 502, data: zAgentBackendUnreachableError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
binding_file_download_unavailable: { status: 502, data: zBindingFileDownloadUnavailableError },
@@ -589,7 +591,7 @@ export const get28Errors = {
provider_quota_exceeded: { status: 400, data: zProviderQuotaExceededError },
}
-export const post17Errors = {
+export const post18Errors = {
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
app_unavailable: { status: 400, data: zAppUnavailableError },
completion_request_error: { status: 400, data: zCompletionRequestError },
@@ -599,7 +601,7 @@ export const post17Errors = {
provider_quota_exceeded: { status: 400, data: zProviderQuotaExceededError },
}
-export const post18Errors = {
+export const post19Errors = {
invalid_tracing_config: { status: 400, data: zInvalidTracingConfigError },
trace_config_not_found: { status: 404, data: zTraceConfigNotFoundError },
tracing_config_conflict: { status: 409, data: zTracingConfigConflictError },
@@ -637,7 +639,7 @@ export const patchErrors = {
unsupported_tracing_provider: { status: 400, data: zUnsupportedTracingProviderError },
}
-export const post19Errors = {
+export const post20Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
invalid_tracing_config: { status: 400, data: zInvalidTracingConfigError },
trace_config_already_exists: { status: 409, data: zTraceConfigAlreadyExistsError },
@@ -647,7 +649,7 @@ export const post19Errors = {
unsupported_tracing_provider: { status: 400, data: zUnsupportedTracingProviderError },
}
-export const post20Errors = {
+export const post21Errors = {
tracing_already_accepted: { status: 409, data: zTracingAlreadyAcceptedError },
tracing_duplicate_acknowledgement_required: {
status: 409,
@@ -664,7 +666,7 @@ export const get32Errors = {
tracing_source_not_found: { status: 404, data: zTracingSourceNotFoundError },
}
-export const post21Errors = {
+export const post22Errors = {
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
agent_version_not_found_error: { status: 404, data: zAgentVersionNotFoundError },
}
@@ -687,7 +689,7 @@ export const put3Errors = {
export const get36Errors = { agent_not_found_error: { status: 404, data: zAgentNotFoundError } }
-export const post22Errors = {
+export const post23Errors = {
agent_name_conflict_error: { status: 409, data: zAgentNameConflictError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
}
diff --git a/packages/contracts/generated/api/console/agent/orpc.gen.ts b/packages/contracts/generated/api/console/agent/orpc.gen.ts
index d245b13d65d..83273430e32 100644
--- a/packages/contracts/generated/api/console/agent/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/agent/orpc.gen.ts
@@ -181,6 +181,10 @@ import {
zPostAgentByAgentIdComposerValidateBody,
zPostAgentByAgentIdComposerValidatePath,
zPostAgentByAgentIdComposerValidateResponse,
+ zPostAgentByAgentIdConfigFilesBatchBody,
+ zPostAgentByAgentIdConfigFilesBatchPath,
+ zPostAgentByAgentIdConfigFilesBatchQuery,
+ zPostAgentByAgentIdConfigFilesBatchResponse,
zPostAgentByAgentIdConfigFilesBody,
zPostAgentByAgentIdConfigFilesPath,
zPostAgentByAgentIdConfigFilesQuery,
@@ -682,6 +686,29 @@ export const composer = {
validate,
}
+export const post9 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAgentByAgentIdConfigFilesBatch',
+ path: '/agent/{agent_id}/config/files/batch',
+ successStatus: 201,
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ body: zPostAgentByAgentIdConfigFilesBatchBody,
+ params: zPostAgentByAgentIdConfigFilesBatchPath,
+ query: zPostAgentByAgentIdConfigFilesBatchQuery.optional(),
+ }),
+ )
+ .output(zPostAgentByAgentIdConfigFilesBatchResponse)
+ .errors({ agent_not_found_error: { status: 404, data: zAgentNotFoundError } })
+
+export const batch = {
+ post: post9,
+}
+
export const get9 = oc
.route({
inputStructure: 'detailed',
@@ -764,7 +791,7 @@ export const get11 = oc
.output(zGetAgentByAgentIdConfigFilesResponse)
.errors({ agent_not_found_error: { status: 404, data: zAgentNotFoundError } })
-export const post9 = oc
+export const post10 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -785,7 +812,8 @@ export const post9 = oc
export const files = {
get: get11,
- post: post9,
+ post: post10,
+ batch,
byName,
}
@@ -810,7 +838,7 @@ export const manifest = {
get: get12,
}
-export const post10 = oc
+export const post11 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -830,7 +858,7 @@ export const post10 = oc
.errors({ agent_not_found_error: { status: 404, data: zAgentNotFoundError } })
export const upload = {
- post: post10,
+ post: post11,
}
export const get13 = oc
@@ -992,7 +1020,7 @@ export const config = {
skills,
}
-export const post11 = oc
+export const post12 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1010,10 +1038,10 @@ export const post11 = oc
})
export const copy = {
- post: post11,
+ post: post12,
}
-export const post12 = oc
+export const post13 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1029,7 +1057,7 @@ export const post12 = oc
})
export const refresh = {
- post: post12,
+ post: post13,
}
export const debugConversation = {
@@ -1039,7 +1067,7 @@ export const debugConversation = {
/**
* Update an Agent App's presentation features (opener, follow-up, citations, ...)
*/
-export const post13 = oc
+export const post14 = oc
.route({
description: "Update an Agent App's presentation features (opener, follow-up, citations, ...)",
inputStructure: 'detailed',
@@ -1055,13 +1083,13 @@ export const post13 = oc
.errors({ agent_not_found_error: { status: 404, data: zAgentNotFoundError } })
export const features = {
- post: post13,
+ post: post14,
}
/**
* Create or update Agent App message feedback
*/
-export const post14 = oc
+export const post15 = oc
.route({
description: 'Create or update Agent App message feedback',
inputStructure: 'detailed',
@@ -1081,7 +1109,7 @@ export const post14 = oc
})
export const feedbacks = {
- post: post14,
+ post: post15,
}
export const get19 = oc
@@ -1171,7 +1199,7 @@ export const messages2 = {
byMessageId: byMessageId2,
}
-export const post15 = oc
+export const post16 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1190,7 +1218,7 @@ export const post15 = oc
})
export const publish = {
- post: post15,
+ post: post16,
}
/**
@@ -1216,7 +1244,7 @@ export const referencingWorkflows = {
/**
* Create a ToolFile from one Agent App Binding file and return its download URL
*/
-export const post16 = oc
+export const post17 = oc
.route({
description: 'Create a ToolFile from one Agent App Binding file and return its download URL',
inputStructure: 'detailed',
@@ -1241,7 +1269,7 @@ export const post16 = oc
})
export const download4 = {
- post: post16,
+ post: post17,
}
/**
@@ -1389,7 +1417,7 @@ export const voices = {
/**
* Preview an Agent TTS voice or read an Agent chat message
*/
-export const post17 = oc
+export const post18 = oc
.route({
description: 'Preview an Agent TTS voice or read an Agent chat message',
inputStructure: 'detailed',
@@ -1419,7 +1447,7 @@ export const post17 = oc
})
export const textToAudio = {
- post: post17,
+ post: post18,
voices,
}
@@ -1434,7 +1462,7 @@ export const get29 = oc
.input(z.object({ params: zGetAgentByAgentIdTracePath }))
.output(zGetAgentByAgentIdTraceResponse)
-export const post18 = oc
+export const post19 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1455,7 +1483,7 @@ export const post18 = oc
export const trace = {
get: get29,
- post: post18,
+ post: post19,
}
export const get30 = oc
@@ -1553,7 +1581,7 @@ export const patch = oc
unsupported_tracing_provider: { status: 400, data: zUnsupportedTracingProviderError },
})
-export const post19 = oc
+export const post20 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1586,10 +1614,10 @@ export const traceConfig = {
delete: delete5,
get: get31,
patch,
- post: post19,
+ post: post20,
}
-export const post20 = oc
+export const post21 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1618,7 +1646,7 @@ export const post20 = oc
})
export const retry = {
- post: post20,
+ post: post21,
}
export const get32 = oc
@@ -1650,7 +1678,7 @@ export const traceRuns = {
byMessageId: byMessageId3,
}
-export const post21 = oc
+export const post22 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1666,7 +1694,7 @@ export const post21 = oc
})
export const restore = {
- post: post21,
+ post: post22,
}
export const get33 = oc
@@ -1790,7 +1818,7 @@ export const get36 = oc
.output(zGetAgentResponse)
.errors({ agent_not_found_error: { status: 404, data: zAgentNotFoundError } })
-export const post22 = oc
+export const post23 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1808,7 +1836,7 @@ export const post22 = oc
export const agent = {
get: get36,
- post: post22,
+ post: post23,
inviteOptions,
byAgentId,
}
diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.ts
index 65c04fce683..672fbcf0b65 100644
--- a/packages/contracts/generated/api/console/agent/types.gen.ts
+++ b/packages/contracts/generated/api/console/agent/types.gen.ts
@@ -342,6 +342,15 @@ export type AgentConfigFileUploadResponse = {
file: AgentConfigFileItemResponse
}
+export type AgentConfigFilesUploadPayload = {
+ upload_file_ids: Array<string>
+}
+
+export type AgentConfigFilesUploadResponse = {
+ config_version: AgentConfigVersionResponse
+ files: Array<AgentConfigFileItemResponse>
+}
+
export type AgentConfigDeleteResponse = {
removed_names?: Array<string>
result: 'success'
@@ -3376,6 +3385,33 @@ export type PostAgentByAgentIdConfigFilesResponses = {
export type PostAgentByAgentIdConfigFilesResponse =
PostAgentByAgentIdConfigFilesResponses[keyof PostAgentByAgentIdConfigFilesResponses]
+export type PostAgentByAgentIdConfigFilesBatchData = {
+ body: AgentConfigFilesUploadPayload
+ path: {
+ agent_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ version_id?: string
+ }
+ url: '/agent/{agent_id}/config/files/batch'
+}
+
+export type PostAgentByAgentIdConfigFilesBatchErrors = {
+ 404: AgentNotFoundError | ErrorResponse
+ default: ErrorResponse
+}
+
+export type PostAgentByAgentIdConfigFilesBatchError =
+ PostAgentByAgentIdConfigFilesBatchErrors[keyof PostAgentByAgentIdConfigFilesBatchErrors]
+
+export type PostAgentByAgentIdConfigFilesBatchResponses = {
+ 201: AgentConfigFilesUploadResponse
+}
+
+export type PostAgentByAgentIdConfigFilesBatchResponse =
+ PostAgentByAgentIdConfigFilesBatchResponses[keyof PostAgentByAgentIdConfigFilesBatchResponses]
+
export type DeleteAgentByAgentIdConfigFilesByNameData = {
body?: never
path: {
diff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.ts
index 467920194c2..a8d7c53fe3e 100644
--- a/packages/contracts/generated/api/console/agent/zod.gen.ts
+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts
@@ -392,6 +392,13 @@ export const zAgentConfigFileUploadPayload = z.object({
upload_file_id: z.string(),
})
+/**
+ * AgentConfigFilesUploadPayload
+ */
+export const zAgentConfigFilesUploadPayload = z.object({
+ upload_file_ids: z.array(z.uuid()).min(1),
+})
+
/**
* AgentConfigDeleteResponse
*/
@@ -1083,6 +1090,14 @@ export const zAgentConfigFileUploadResponse = z.object({
file: zAgentConfigFileItemResponse,
})
+/**
+ * AgentConfigFilesUploadResponse
+ */
+export const zAgentConfigFilesUploadResponse = z.object({
+ config_version: zAgentConfigVersionResponse,
+ files: z.array(zAgentConfigFileItemResponse),
+})
+
/**
* AgentConfigFileItemsResponse
*/
@@ -4188,6 +4203,22 @@ export const zPostAgentByAgentIdConfigFilesQuery = z.object({
*/
export const zPostAgentByAgentIdConfigFilesResponse = zAgentConfigFileUploadResponse
+export const zPostAgentByAgentIdConfigFilesBatchBody = zAgentConfigFilesUploadPayload
+
+export const zPostAgentByAgentIdConfigFilesBatchPath = z.object({
+ agent_id: z.uuid(),
+})
+
+export const zPostAgentByAgentIdConfigFilesBatchQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Bound config files
+ */
+export const zPostAgentByAgentIdConfigFilesBatchResponse = zAgentConfigFilesUploadResponse
+
export const zDeleteAgentByAgentIdConfigFilesByNamePath = z.object({
agent_id: z.uuid(),
name: z.string(),
diff --git a/packages/contracts/generated/api/console/apps/errors.gen.ts b/packages/contracts/generated/api/console/apps/errors.gen.ts
index 1ca81cfa7c0..6d18141dc35 100644
--- a/packages/contracts/generated/api/console/apps/errors.gen.ts
+++ b/packages/contracts/generated/api/console/apps/errors.gen.ts
@@ -521,6 +521,12 @@ export const post8Errors = {
rate_limit_error: { status: 429, data: zRateLimitError },
}
+export const post9Errors = {
+ agent_not_bound: { status: 400, data: zAgentNotBoundError },
+ agent_not_found_error: { status: 404, data: zAgentNotFoundError },
+ app_not_found: { status: 404, data: zAppNotFoundError },
+}
+
export const get6Errors = {
agent_not_bound: { status: 400, data: zAgentNotBoundError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
@@ -545,7 +551,7 @@ export const get8Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
}
-export const post9Errors = {
+export const post10Errors = {
agent_not_bound: { status: 400, data: zAgentNotBoundError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
app_not_found: { status: 404, data: zAppNotFoundError },
@@ -557,7 +563,7 @@ export const get9Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
}
-export const post10Errors = {
+export const post11Errors = {
agent_not_bound: { status: 400, data: zAgentNotBoundError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
app_not_found: { status: 404, data: zAppNotFoundError },
@@ -607,7 +613,7 @@ export const get15Errors = {
export const get16Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post13Errors = {
+export const post14Errors = {
no_file_uploaded: { status: 400, data: zNoFileUploadedError },
too_many_files: { status: 400, data: zTooManyFilesError },
}
@@ -616,7 +622,7 @@ export const get20Errors = { app_not_found: { status: 404, data: zAppNotFoundErr
export const delete4Errors = { bad_request: { status: 400, data: zBadRequestError } }
-export const post17Errors = {
+export const post18Errors = {
agent_version_not_found_error: { status: 404, data: zAgentVersionNotFoundError },
app_not_found: { status: 404, data: zAppNotFoundError },
app_unavailable: { status: 400, data: zAppUnavailableError },
@@ -651,7 +657,7 @@ export const get26Errors = {
provider_quota_exceeded: { status: 400, data: zProviderQuotaExceededError },
}
-export const post18Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post19Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get27Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
@@ -664,9 +670,9 @@ export const get28Errors = { app_not_found: { status: 404, data: zAppNotFoundErr
export const get29Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post19Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post20Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post20Errors = {
+export const post21Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
app_unavailable: { status: 400, data: zAppUnavailableError },
completion_request_error: { status: 400, data: zCompletionRequestError },
@@ -677,13 +683,13 @@ export const post20Errors = {
export const get30Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post21Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post22Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get31Errors = {
roster_agent_package_export_failed: { status: 500, data: zRosterAgentPackageExportFailedError },
}
-export const post23Errors = {
+export const post24Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
app_unavailable: { status: 400, data: zAppUnavailableError },
message_feedback_rating_required: { status: 400, data: zMessageFeedbackRatingRequiredError },
@@ -694,7 +700,7 @@ export const get32Errors = {
app_unavailable: { status: 400, data: zAppUnavailableError },
}
-export const post25Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post26Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get33Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
@@ -702,18 +708,18 @@ export const get34Errors = { app_not_found: { status: 404, data: zAppNotFoundErr
export const putErrors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post28Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post29Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get35Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post29Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post30Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const put2Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post30Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-
export const post31Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post32Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+
export const get36Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get37Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
@@ -738,7 +744,7 @@ export const get44Errors = {
provider_quota_exceeded: { status: 400, data: zProviderQuotaExceededError },
}
-export const post34Errors = {
+export const post35Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
app_unavailable: { status: 400, data: zAppUnavailableError },
completion_request_error: { status: 400, data: zCompletionRequestError },
@@ -748,7 +754,7 @@ export const post34Errors = {
provider_quota_exceeded: { status: 400, data: zProviderQuotaExceededError },
}
-export const post35Errors = {
+export const post36Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
invalid_tracing_config: { status: 400, data: zInvalidTracingConfigError },
trace_config_not_found: { status: 404, data: zTraceConfigNotFoundError },
@@ -787,7 +793,7 @@ export const patchErrors = {
unsupported_tracing_provider: { status: 400, data: zUnsupportedTracingProviderError },
}
-export const post36Errors = {
+export const post37Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
invalid_tracing_config: { status: 400, data: zInvalidTracingConfigError },
trace_config_already_exists: { status: 409, data: zTraceConfigAlreadyExistsError },
@@ -797,7 +803,7 @@ export const post36Errors = {
unsupported_tracing_provider: { status: 400, data: zUnsupportedTracingProviderError },
}
-export const post37Errors = {
+export const post38Errors = {
tracing_already_accepted: { status: 409, data: zTracingAlreadyAcceptedError },
tracing_duplicate_acknowledgement_required: {
status: 409,
@@ -814,7 +820,7 @@ export const get48Errors = {
tracing_source_not_found: { status: 404, data: zTracingSourceNotFoundError },
}
-export const post38Errors = {
+export const post39Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
app_trigger_not_found: { status: 404, data: zAppTriggerNotFoundError },
}
@@ -825,7 +831,7 @@ export const get50Errors = { app_not_found: { status: 404, data: zAppNotFoundErr
export const get51Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post39Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post40Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get52Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
@@ -833,7 +839,7 @@ export const get53Errors = { app_not_found: { status: 404, data: zAppNotFoundErr
export const get54Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post40Errors = {
+export const post41Errors = {
agent_backend_unreachable: { status: 502, data: zAgentBackendUnreachableError },
app_not_found: { status: 404, data: zAppNotFoundError },
binding_file_download_unavailable: { status: 502, data: zBindingFileDownloadUnavailableError },
@@ -872,12 +878,12 @@ export const put3Errors = {
forbidden: { status: 403, data: zForbiddenError },
}
-export const post41Errors = {
+export const post42Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
forbidden: { status: 403, data: zForbiddenError },
}
-export const post42Errors = {
+export const post43Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
forbidden: { status: 403, data: zForbiddenError },
}
@@ -902,7 +908,7 @@ export const get60Errors = {
forbidden: { status: 403, data: zForbiddenError },
}
-export const post43Errors = {
+export const post44Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
forbidden: { status: 403, data: zForbiddenError },
}
@@ -921,15 +927,13 @@ export const get66Errors = { app_not_found: { status: 404, data: zAppNotFoundErr
export const get67Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post44Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post45Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get68Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
draft_workflow_not_exist: { status: 404, data: zDraftWorkflowNotExistError },
}
-export const post45Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-
export const post46Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const post47Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
@@ -942,9 +946,11 @@ export const post50Errors = { app_not_found: { status: 404, data: zAppNotFoundEr
export const post51Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post52Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+
export const get69Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post52Errors = {
+export const post53Errors = {
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
agent_version_conflict_error: { status: 409, data: zAgentVersionConflictError },
agent_version_not_found_error: { status: 404, data: zAgentVersionNotFoundError },
@@ -952,9 +958,9 @@ export const post52Errors = {
invalid_composer_config_error: { status: 400, data: zInvalidComposerConfigError },
}
-export const post53Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post54Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post54Errors = {
+export const post55Errors = {
agent_name_conflict_error: { status: 409, data: zAgentNameConflictError },
agent_not_found_error: { status: 404, data: zAgentNotFoundError },
agent_soul_locked_error: { status: 400, data: zAgentSoulLockedError },
@@ -964,7 +970,7 @@ export const post54Errors = {
plaintext_secret_not_allowed_error: { status: 400, data: zPlaintextSecretNotAllowedError },
}
-export const post55Errors = {
+export const post56Errors = {
agent_soul_locked_error: { status: 400, data: zAgentSoulLockedError },
app_not_found: { status: 404, data: zAppNotFoundError },
invalid_composer_config_error: { status: 400, data: zInvalidComposerConfigError },
@@ -989,15 +995,15 @@ export const put5Errors = {
export const get71Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post56Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-
export const post57Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post58Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+
export const delete11Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get72Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post58Errors = {
+export const post59Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
rate_limit_error: { status: 429, data: zRateLimitError },
}
@@ -1027,12 +1033,12 @@ export const get76Errors = {
export const get77Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post59Errors = {
+export const post60Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
rate_limit_error: { status: 429, data: zRateLimitError },
}
-export const post60Errors = {
+export const post61Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
rate_limit_error: { status: 429, data: zRateLimitError },
}
@@ -1057,14 +1063,14 @@ export const get80Errors = {
draft_workflow_not_exist: { status: 404, data: zDraftWorkflowNotExistError },
}
-export const post61Errors = {
+export const post62Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
draft_workflow_not_sync: { status: 409, data: zDraftWorkflowNotSyncError },
}
export const get81Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post62Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post63Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const get82Errors = {
app_not_found: { status: 404, data: zAppNotFoundError },
@@ -1094,7 +1100,7 @@ export const get86Errors = {
webhook_trigger_not_found: { status: 404, data: zWebhookTriggerNotFoundError },
}
-export const post63Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
+export const post64Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
export const delete14Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
@@ -1102,7 +1108,7 @@ export const patch3Errors = { app_not_found: { status: 404, data: zAppNotFoundEr
export const get87Errors = { app_not_found: { status: 404, data: zAppNotFoundError } }
-export const post64Errors = {
+export const post65Errors = {
agent_not_published: { status: 409, data: zAgentNotPublishedError },
max_keys_exceeded: { status: 400, data: zMaxKeysExceededError },
}
diff --git a/packages/contracts/generated/api/console/apps/orpc.gen.ts b/packages/contracts/generated/api/console/apps/orpc.gen.ts
index b97156df084..821b923b863 100644
--- a/packages/contracts/generated/api/console/apps/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/apps/orpc.gen.ts
@@ -351,6 +351,10 @@ import {
zPostAppsByAppIdAdvancedChatWorkflowsDraftRunBody,
zPostAppsByAppIdAdvancedChatWorkflowsDraftRunPath,
zPostAppsByAppIdAdvancedChatWorkflowsDraftRunResponse,
+ zPostAppsByAppIdAgentConfigFilesBatchBody,
+ zPostAppsByAppIdAgentConfigFilesBatchPath,
+ zPostAppsByAppIdAgentConfigFilesBatchQuery,
+ zPostAppsByAppIdAgentConfigFilesBatchResponse,
zPostAppsByAppIdAgentConfigFilesBody,
zPostAppsByAppIdAgentConfigFilesPath,
zPostAppsByAppIdAgentConfigFilesQuery,
@@ -924,6 +928,33 @@ export const advancedChat = {
workflows: workflows2,
}
+export const post9 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAppsByAppIdAgentConfigFilesBatch',
+ path: '/apps/{app_id}/agent/config/files/batch',
+ successStatus: 201,
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ body: zPostAppsByAppIdAgentConfigFilesBatchBody,
+ params: zPostAppsByAppIdAgentConfigFilesBatchPath,
+ query: zPostAppsByAppIdAgentConfigFilesBatchQuery.optional(),
+ }),
+ )
+ .output(zPostAppsByAppIdAgentConfigFilesBatchResponse)
+ .errors({
+ agent_not_bound: { status: 400, data: zAgentNotBoundError },
+ agent_not_found_error: { status: 404, data: zAgentNotFoundError },
+ app_not_found: { status: 404, data: zAppNotFoundError },
+ })
+
+export const batch = {
+ post: post9,
+}
+
export const get6 = oc
.route({
inputStructure: 'detailed',
@@ -1022,7 +1053,7 @@ export const get8 = oc
app_not_found: { status: 404, data: zAppNotFoundError },
})
-export const post9 = oc
+export const post10 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1047,7 +1078,8 @@ export const post9 = oc
export const files = {
get: get8,
- post: post9,
+ post: post10,
+ batch,
byName,
}
@@ -1076,7 +1108,7 @@ export const manifest = {
get: get9,
}
-export const post10 = oc
+export const post11 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -1100,7 +1132,7 @@ export const post10 = oc
})
export const upload = {
- post: post10,
+ post: post11,
}
export const get10 = oc
@@ -1344,7 +1376,7 @@ export const status = {
/**
* Enable or disable annotation reply for an app
*/
-export const post11 = oc
+export const post12 = oc
.route({
description: 'Enable or disable annotation reply for an app',
inputStructure: 'detailed',
@@ -1362,7 +1394,7 @@ export const post11 = oc
.output(zPostAppsByAppIdAnnotationReplyByActionResponse)
export const byAction = {
- post: post11,
+ post: post12,
status,
}
@@ -1392,7 +1424,7 @@ export const annotationSetting = {
/**
* Update annotation settings for an app
*/
-export const post12 = oc
+export const post13 = oc
.route({
description: 'Update annotation settings for an app',
inputStructure: 'detailed',
@@ -1410,7 +1442,7 @@ export const post12 = oc
.output(zPostAppsByAppIdAnnotationSettingsByAnnotationSettingIdResponse)
export const byAnnotationSettingId = {
- post: post12,
+ post: post13,
}
export const annotationSettings = {
@@ -1420,7 +1452,7 @@ export const annotationSettings = {
/**
* Batch import annotations from CSV file with rate limiting and security checks
*/
-export const post13 = oc
+export const post14 = oc
.route({
description: 'Batch import annotations from CSV file with rate limiting and security checks',
inputStructure: 'detailed',
@@ -1437,7 +1469,7 @@ export const post13 = oc
})
export const batchImport = {
- post: post13,
+ post: post14,
}
/**
@@ -1541,7 +1573,7 @@ export const delete3 = oc
/**
* Update or delete an annotation
*/
-export const post14 = oc
+export const post15 = oc
.route({
description: 'Update or delete an annotation',
inputStructure: 'detailed',
@@ -1560,7 +1592,7 @@ export const post14 = oc
export const byAnnotationId = {
delete: delete3,
- post: post14,
+ post: post15,
hitHistories,
}
@@ -1605,7 +1637,7 @@ export const get23 = oc
/**
* Create a new annotation for an app
*/
-export const post15 = oc
+export const post16 = oc
.route({
description: 'Create a new annotation for an app',
inputStructure: 'detailed',
@@ -1623,7 +1655,7 @@ export const post15 = oc
export const annotations = {
delete: delete4,
get: get23,
- post: post15,
+ post: post16,
batchImport,
batchImportStatus,
count: count2,
@@ -1634,7 +1666,7 @@ export const annotations = {
/**
* Enable or disable app API
*/
-export const post16 = oc
+export const post17 = oc
.route({
description: 'Enable or disable app API',
inputStructure: 'detailed',
@@ -1647,13 +1679,13 @@ export const post16 = oc
.output(zPostAppsByAppIdApiEnableResponse)
export const apiEnable = {
- post: post16,
+ post: post17,
}
/**
* Transcript audio to text for chat messages
*/
-export const post17 = oc
+export const post18 = oc
.route({
description: 'Transcript audio to text for chat messages',
inputStructure: 'detailed',
@@ -1685,7 +1717,7 @@ export const post17 = oc
})
export const audioToText = {
- post: post17,
+ post: post18,
}
/**
@@ -1791,7 +1823,7 @@ export const byMessageId = {
/**
* Stop a running chat message generation
*/
-export const post18 = oc
+export const post19 = oc
.route({
description: 'Stop a running chat message generation',
inputStructure: 'detailed',
@@ -1805,7 +1837,7 @@ export const post18 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const stop = {
- post: post18,
+ post: post19,
}
export const byTaskId = {
@@ -1906,7 +1938,7 @@ export const completionConversations = {
/**
* Stop a running completion message generation
*/
-export const post19 = oc
+export const post20 = oc
.route({
description: 'Stop a running completion message generation',
inputStructure: 'detailed',
@@ -1920,7 +1952,7 @@ export const post19 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const stop2 = {
- post: post19,
+ post: post20,
}
export const byTaskId2 = {
@@ -1930,7 +1962,7 @@ export const byTaskId2 = {
/**
* Generate completion message for debugging
*/
-export const post20 = oc
+export const post21 = oc
.route({
description: 'Generate completion message for debugging',
inputStructure: 'detailed',
@@ -1956,7 +1988,7 @@ export const post20 = oc
})
export const completionMessages = {
- post: post20,
+ post: post21,
byTaskId: byTaskId2,
}
@@ -1992,7 +2024,7 @@ export const conversationVariables = {
* Convert expert mode of chatbot app to workflow mode
* Convert Completion App to Workflow App
*/
-export const post21 = oc
+export const post22 = oc
.route({
description:
'Convert application to workflow mode\nConvert expert mode of chatbot app to workflow mode\nConvert Completion App to Workflow App',
@@ -2013,13 +2045,13 @@ export const post21 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const convertToWorkflow = {
- post: post21,
+ post: post22,
}
/**
* Create a copy of an existing application
*/
-export const post22 = oc
+export const post23 = oc
.route({
description: 'Create a copy of an existing application',
inputStructure: 'detailed',
@@ -2033,7 +2065,7 @@ export const post22 = oc
.output(zPostAppsByAppIdCopyResponse)
export const copy = {
- post: post22,
+ post: post23,
}
/**
@@ -2063,7 +2095,7 @@ export const export2 = {
/**
* Create or update message feedback (like/dislike)
*/
-export const post23 = oc
+export const post24 = oc
.route({
description: 'Create or update message feedback (like/dislike)',
inputStructure: 'detailed',
@@ -2081,13 +2113,13 @@ export const post23 = oc
})
export const feedbacks = {
- post: post23,
+ post: post24,
}
/**
* Update application icon
*/
-export const post24 = oc
+export const post25 = oc
.route({
description: 'Update application icon',
inputStructure: 'detailed',
@@ -2100,7 +2132,7 @@ export const post24 = oc
.output(zPostAppsByAppIdIconResponse)
export const icon = {
- post: post24,
+ post: post25,
}
/**
@@ -2135,7 +2167,7 @@ export const messages = {
*
* Update application model configuration
*/
-export const post25 = oc
+export const post26 = oc
.route({
description: 'Update application model configuration',
inputStructure: 'detailed',
@@ -2152,13 +2184,13 @@ export const post25 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const modelConfig = {
- post: post25,
+ post: post26,
}
/**
* Check if app name is available
*/
-export const post26 = oc
+export const post27 = oc
.route({
description: 'Check if app name is available',
inputStructure: 'detailed',
@@ -2171,7 +2203,7 @@ export const post26 = oc
.output(zPostAppsByAppIdNameResponse)
export const name = {
- post: post26,
+ post: post27,
}
export const get33 = oc
@@ -2225,7 +2257,7 @@ export const networkAccessGroup = {
status: status2,
}
-export const post27 = oc
+export const post28 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -2237,13 +2269,13 @@ export const post27 = oc
.output(zPostAppsByAppIdPublishToCreatorsPlatformResponse)
export const publishToCreatorsPlatform = {
- post: post27,
+ post: post28,
}
/**
* Refresh MCP server configuration and regenerate server code
*/
-export const post28 = oc
+export const post29 = oc
.route({
description: 'Refresh MCP server configuration and regenerate server code',
inputStructure: 'detailed',
@@ -2257,7 +2289,7 @@ export const post28 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const refresh = {
- post: post28,
+ post: post29,
}
/**
@@ -2279,7 +2311,7 @@ export const get35 = oc
/**
* Create MCP server configuration for an application
*/
-export const post29 = oc
+export const post30 = oc
.route({
description: 'Create MCP server configuration for an application',
inputStructure: 'detailed',
@@ -2311,7 +2343,7 @@ export const put2 = oc
export const server = {
get: get35,
- post: post29,
+ post: post30,
put: put2,
refresh,
}
@@ -2319,7 +2351,7 @@ export const server = {
/**
* Reset access token for application site
*/
-export const post30 = oc
+export const post31 = oc
.route({
description: 'Reset access token for application site',
inputStructure: 'detailed',
@@ -2333,13 +2365,13 @@ export const post30 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const accessTokenReset = {
- post: post30,
+ post: post31,
}
/**
* Update application site configuration
*/
-export const post31 = oc
+export const post32 = oc
.route({
description: 'Update application site configuration',
inputStructure: 'detailed',
@@ -2353,14 +2385,14 @@ export const post31 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const site = {
- post: post31,
+ post: post32,
accessTokenReset,
}
/**
* Enable or disable app site
*/
-export const post32 = oc
+export const post33 = oc
.route({
description: 'Enable or disable app site',
inputStructure: 'detailed',
@@ -2373,7 +2405,7 @@ export const post32 = oc
.output(zPostAppsByAppIdSiteEnableResponse)
export const siteEnable = {
- post: post32,
+ post: post33,
}
/**
@@ -2394,7 +2426,7 @@ export const delete7 = oc
/**
* Star an application for the current account
*/
-export const post33 = oc
+export const post34 = oc
.route({
description: 'Star an application for the current account',
inputStructure: 'detailed',
@@ -2408,7 +2440,7 @@ export const post33 = oc
export const star = {
delete: delete7,
- post: post33,
+ post: post34,
}
/**
@@ -2656,7 +2688,7 @@ export const voices = {
/**
* Convert text to speech for chat messages
*/
-export const post34 = oc
+export const post35 = oc
.route({
description: 'Convert text to speech for chat messages',
inputStructure: 'detailed',
@@ -2683,7 +2715,7 @@ export const post34 = oc
})
export const textToAudio = {
- post: post34,
+ post: post35,
voices,
}
@@ -2705,7 +2737,7 @@ export const get45 = oc
/**
* Update app tracing configuration
*/
-export const post35 = oc
+export const post36 = oc
.route({
description: 'Update app tracing configuration',
inputStructure: 'detailed',
@@ -2728,7 +2760,7 @@ export const post35 = oc
export const trace = {
get: get45,
- post: post35,
+ post: post36,
}
export const get46 = oc
@@ -2843,7 +2875,7 @@ export const patch = oc
*
* Create a new tracing configuration for an application
*/
-export const post36 = oc
+export const post37 = oc
.route({
description: 'Create a new tracing configuration for an application',
inputStructure: 'detailed',
@@ -2875,10 +2907,10 @@ export const traceConfig = {
delete: delete8,
get: get47,
patch,
- post: post36,
+ post: post37,
}
-export const post37 = oc
+export const post38 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -2907,7 +2939,7 @@ export const post37 = oc
})
export const retry = {
- post: post37,
+ post: post38,
}
export const get48 = oc
@@ -2946,7 +2978,7 @@ export const traceRuns = {
/**
* Update app trigger (enable/disable)
*/
-export const post38 = oc
+export const post39 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -2968,7 +3000,7 @@ export const post38 = oc
})
export const triggerEnable = {
- post: post38,
+ post: post39,
}
/**
@@ -3052,7 +3084,7 @@ export const count3 = {
*
* Stop running workflow task
*/
-export const post39 = oc
+export const post40 = oc
.route({
description: 'Stop running workflow task',
inputStructure: 'detailed',
@@ -3067,7 +3099,7 @@ export const post39 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const stop3 = {
- post: post39,
+ post: post40,
}
export const byTaskId3 = {
@@ -3157,7 +3189,7 @@ export const byRunId = {
/**
* Create a ToolFile from one workflow Agent Binding file and return its download URL
*/
-export const post40 = oc
+export const post41 = oc
.route({
description:
'Create a ToolFile from one workflow Agent Binding file and return its download URL',
@@ -3183,7 +3215,7 @@ export const post40 = oc
})
export const download4 = {
- post: post40,
+ post: post41,
}
/**
@@ -3382,7 +3414,7 @@ export const byReplyId = {
*
* Add a reply to a workflow comment
*/
-export const post41 = oc
+export const post42 = oc
.route({
description: 'Add a reply to a workflow comment',
inputStructure: 'detailed',
@@ -3406,7 +3438,7 @@ export const post41 = oc
})
export const replies = {
- post: post41,
+ post: post42,
byReplyId,
}
@@ -3415,7 +3447,7 @@ export const replies = {
*
* Resolve a workflow comment
*/
-export const post42 = oc
+export const post43 = oc
.route({
description: 'Resolve a workflow comment',
inputStructure: 'detailed',
@@ -3433,7 +3465,7 @@ export const post42 = oc
})
export const resolve = {
- post: post42,
+ post: post43,
}
/**
@@ -3543,7 +3575,7 @@ export const get60 = oc
*
* Create a new workflow comment
*/
-export const post43 = oc
+export const post44 = oc
.route({
description: 'Create a new workflow comment',
inputStructure: 'detailed',
@@ -3568,7 +3600,7 @@ export const post43 = oc
export const comments = {
get: get60,
- post: post43,
+ post: post44,
mentionUsers,
byCommentId,
}
@@ -3756,7 +3788,7 @@ export const get67 = oc
/**
* Update conversation variables for workflow draft
*/
-export const post44 = oc
+export const post45 = oc
.route({
description: 'Update conversation variables for workflow draft',
inputStructure: 'detailed',
@@ -3776,7 +3808,7 @@ export const post44 = oc
export const conversationVariables2 = {
get: get67,
- post: post44,
+ post: post45,
}
/**
@@ -3804,7 +3836,7 @@ export const get68 = oc
/**
* Update environment variables for workflow draft
*/
-export const post45 = oc
+export const post46 = oc
.route({
description: 'Update environment variables for workflow draft',
inputStructure: 'detailed',
@@ -3824,13 +3856,13 @@ export const post45 = oc
export const environmentVariables = {
get: get68,
- post: post45,
+ post: post46,
}
/**
* Update draft workflow features
*/
-export const post46 = oc
+export const post47 = oc
.route({
description: 'Update draft workflow features',
inputStructure: 'detailed',
@@ -3849,7 +3881,7 @@ export const post46 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const features = {
- post: post46,
+ post: post47,
}
/**
@@ -3857,7 +3889,7 @@ export const features = {
*
* Test human input delivery for workflow
*/
-export const post47 = oc
+export const post48 = oc
.route({
description: 'Test human input delivery for workflow',
inputStructure: 'detailed',
@@ -3877,7 +3909,7 @@ export const post47 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const deliveryTest = {
- post: post47,
+ post: post48,
}
/**
@@ -3885,7 +3917,7 @@ export const deliveryTest = {
*
* Get human input form preview for workflow
*/
-export const post48 = oc
+export const post49 = oc
.route({
description: 'Get human input form preview for workflow',
inputStructure: 'detailed',
@@ -3905,7 +3937,7 @@ export const post48 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const preview4 = {
- post: post48,
+ post: post49,
}
/**
@@ -3913,7 +3945,7 @@ export const preview4 = {
*
* Submit human input form preview for workflow
*/
-export const post49 = oc
+export const post50 = oc
.route({
description: 'Submit human input form preview for workflow',
inputStructure: 'detailed',
@@ -3933,7 +3965,7 @@ export const post49 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const run5 = {
- post: post49,
+ post: post50,
}
export const form2 = {
@@ -3959,7 +3991,7 @@ export const humanInput2 = {
*
* Run draft workflow iteration node
*/
-export const post50 = oc
+export const post51 = oc
.route({
description: 'Run draft workflow iteration node',
inputStructure: 'detailed',
@@ -3979,7 +4011,7 @@ export const post50 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const run6 = {
- post: post50,
+ post: post51,
}
export const byNodeId6 = {
@@ -3999,7 +4031,7 @@ export const iteration2 = {
*
* Run draft workflow loop node
*/
-export const post51 = oc
+export const post52 = oc
.route({
description: 'Run draft workflow loop node',
inputStructure: 'detailed',
@@ -4019,7 +4051,7 @@ export const post51 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const run7 = {
- post: post51,
+ post: post52,
}
export const byNodeId7 = {
@@ -4052,7 +4084,7 @@ export const candidates = {
get: get69,
}
-export const post52 = oc
+export const post53 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -4076,10 +4108,10 @@ export const post52 = oc
})
export const copyFromRoster = {
- post: post52,
+ post: post53,
}
-export const post53 = oc
+export const post54 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -4097,10 +4129,10 @@ export const post53 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const impact = {
- post: post53,
+ post: post54,
}
-export const post54 = oc
+export const post55 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -4126,10 +4158,10 @@ export const post54 = oc
})
export const saveToRoster = {
- post: post54,
+ post: post55,
}
-export const post55 = oc
+export const post56 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -4152,7 +4184,7 @@ export const post55 = oc
})
export const validate = {
- post: post55,
+ post: post56,
}
export const get70 = oc
@@ -4236,7 +4268,7 @@ export const lastRun = {
*
* Run draft workflow node
*/
-export const post56 = oc
+export const post57 = oc
.route({
description: 'Run draft workflow node',
inputStructure: 'detailed',
@@ -4256,7 +4288,7 @@ export const post56 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const run8 = {
- post: post56,
+ post: post57,
}
/**
@@ -4264,7 +4296,7 @@ export const run8 = {
*
* Poll for trigger events and execute single node when event arrives
*/
-export const post57 = oc
+export const post58 = oc
.route({
description: 'Poll for trigger events and execute single node when event arrives',
inputStructure: 'detailed',
@@ -4279,7 +4311,7 @@ export const post57 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const run9 = {
- post: post57,
+ post: post58,
}
export const trigger = {
@@ -4341,7 +4373,7 @@ export const nodes7 = {
*
* Run draft workflow
*/
-export const post58 = oc
+export const post59 = oc
.route({
description: 'Run draft workflow',
inputStructure: 'detailed',
@@ -4364,7 +4396,7 @@ export const post58 = oc
})
export const run10 = {
- post: post58,
+ post: post59,
}
/**
@@ -4506,7 +4538,7 @@ export const systemVariables = {
*
* Poll for trigger events and execute full workflow when event arrives
*/
-export const post59 = oc
+export const post60 = oc
.route({
description: 'Poll for trigger events and execute full workflow when event arrives',
inputStructure: 'detailed',
@@ -4529,7 +4561,7 @@ export const post59 = oc
})
export const run11 = {
- post: post59,
+ post: post60,
}
/**
@@ -4537,7 +4569,7 @@ export const run11 = {
*
* Full workflow debug when the start node is a trigger
*/
-export const post60 = oc
+export const post61 = oc
.route({
description: 'Full workflow debug when the start node is a trigger',
inputStructure: 'detailed',
@@ -4560,7 +4592,7 @@ export const post60 = oc
})
export const runAll = {
- post: post60,
+ post: post61,
}
export const trigger2 = {
@@ -4726,7 +4758,7 @@ export const get80 = oc
*
* Sync draft workflow configuration
*/
-export const post61 = oc
+export const post62 = oc
.route({
description: 'Sync draft workflow configuration',
inputStructure: 'detailed',
@@ -4750,7 +4782,7 @@ export const post61 = oc
export const draft2 = {
get: get80,
- post: post61,
+ post: post62,
conversationVariables: conversationVariables2,
environmentVariables,
features,
@@ -4787,7 +4819,7 @@ export const get81 = oc
/**
* Publish workflow
*/
-export const post62 = oc
+export const post63 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -4807,7 +4839,7 @@ export const post62 = oc
export const publish = {
get: get81,
- post: post62,
+ post: post63,
}
/**
@@ -4967,7 +4999,7 @@ export const triggers2 = {
/**
* Restore a published workflow version into the draft workflow
*/
-export const post63 = oc
+export const post64 = oc
.route({
description: 'Restore a published workflow version into the draft workflow',
inputStructure: 'detailed',
@@ -4981,7 +5013,7 @@ export const post63 = oc
.errors({ app_not_found: { status: 404, data: zAppNotFoundError } })
export const restore = {
- post: post63,
+ post: post64,
}
/**
@@ -5194,7 +5226,7 @@ export const get89 = oc
/**
* Create a new API key for an app
*/
-export const post64 = oc
+export const post65 = oc
.route({
description: 'Create a new API key for an app',
inputStructure: 'detailed',
@@ -5213,7 +5245,7 @@ export const post64 = oc
export const apiKeys = {
get: get89,
- post: post64,
+ post: post65,
byApiKeyId,
}
@@ -5239,7 +5271,7 @@ export const get90 = oc
/**
* Create a new application
*/
-export const post65 = oc
+export const post66 = oc
.route({
description: 'Create a new application',
inputStructure: 'detailed',
@@ -5254,7 +5286,7 @@ export const post65 = oc
export const apps = {
get: get90,
- post: post65,
+ post: post66,
imports,
recent,
starred,
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index 788b5a67e03..e82dc598866 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -256,6 +256,15 @@ export type AgentConfigFileUploadResponse = {
file: AgentConfigFileItemResponse
}
+export type AgentConfigFilesUploadPayload = {
+ upload_file_ids: Array<string>
+}
+
+export type AgentConfigFilesUploadResponse = {
+ config_version: AgentConfigVersionResponse
+ files: Array<AgentConfigFileItemResponse>
+}
+
export type AgentConfigDeleteResponse = {
removed_names?: Array<string>
result: 'success'
@@ -5242,6 +5251,35 @@ export type PostAppsByAppIdAgentConfigFilesResponses = {
export type PostAppsByAppIdAgentConfigFilesResponse =
PostAppsByAppIdAgentConfigFilesResponses[keyof PostAppsByAppIdAgentConfigFilesResponses]
+export type PostAppsByAppIdAgentConfigFilesBatchData = {
+ body: AgentConfigFilesUploadPayload
+ path: {
+ app_id: string
+ }
+ query?: {
+ draft_type?: 'debug_build' | 'draft'
+ node_id?: string
+ version_id?: string
+ }
+ url: '/apps/{app_id}/agent/config/files/batch'
+}
+
+export type PostAppsByAppIdAgentConfigFilesBatchErrors = {
+ 400: AgentNotBoundError | ErrorResponse
+ 404: AgentNotFoundError | AppNotFoundError | ErrorResponse
+ default: ErrorResponse
+}
+
+export type PostAppsByAppIdAgentConfigFilesBatchError =
+ PostAppsByAppIdAgentConfigFilesBatchErrors[keyof PostAppsByAppIdAgentConfigFilesBatchErrors]
+
+export type PostAppsByAppIdAgentConfigFilesBatchResponses = {
+ 201: AgentConfigFilesUploadResponse
+}
+
+export type PostAppsByAppIdAgentConfigFilesBatchResponse =
+ PostAppsByAppIdAgentConfigFilesBatchResponses[keyof PostAppsByAppIdAgentConfigFilesBatchResponses]
+
export type DeleteAppsByAppIdAgentConfigFilesByNameData = {
body?: never
path: {
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index 4512952190a..cf1895a13c9 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -228,6 +228,13 @@ export const zAgentConfigFileUploadPayload = z.object({
upload_file_id: z.string(),
})
+/**
+ * AgentConfigFilesUploadPayload
+ */
+export const zAgentConfigFilesUploadPayload = z.object({
+ upload_file_ids: z.array(z.uuid()).min(1),
+})
+
/**
* AgentConfigDeleteResponse
*/
@@ -1716,6 +1723,14 @@ export const zAgentConfigFileUploadResponse = z.object({
file: zAgentConfigFileItemResponse,
})
+/**
+ * AgentConfigFilesUploadResponse
+ */
+export const zAgentConfigFilesUploadResponse = z.object({
+ config_version: zAgentConfigVersionResponse,
+ files: z.array(zAgentConfigFileItemResponse),
+})
+
/**
* AgentConfigFileItemsResponse
*/
@@ -6676,6 +6691,23 @@ export const zPostAppsByAppIdAgentConfigFilesQuery = z.object({
*/
export const zPostAppsByAppIdAgentConfigFilesResponse = zAgentConfigFileUploadResponse
+export const zPostAppsByAppIdAgentConfigFilesBatchBody = zAgentConfigFilesUploadPayload
+
+export const zPostAppsByAppIdAgentConfigFilesBatchPath = z.object({
+ app_id: z.uuid(),
+})
+
+export const zPostAppsByAppIdAgentConfigFilesBatchQuery = z.object({
+ draft_type: z.enum(['debug_build', 'draft']).optional(),
+ node_id: z.string().optional(),
+ version_id: z.string().optional(),
+})
+
+/**
+ * Bound config files
+ */
+export const zPostAppsByAppIdAgentConfigFilesBatchResponse = zAgentConfigFilesUploadResponse
+
export const zDeleteAppsByAppIdAgentConfigFilesByNamePath = z.object({
app_id: z.uuid(),
name: z.string(),
diff --git a/packages/contracts/generated/api/console/errors.gen.ts b/packages/contracts/generated/api/console/errors.gen.ts
index 34e0844610f..094653a9d99 100644
--- a/packages/contracts/generated/api/console/errors.gen.ts
+++ b/packages/contracts/generated/api/console/errors.gen.ts
@@ -320,78 +320,79 @@ export { patchErrors as 'PATCH /datasets/external-knowledge-api/{external_knowle
export { patchErrors as 'PATCH /installed-apps/{installed_app_id}/conversations/{c_id}/pin' } from './installed-apps/errors.gen.ts'
export { patchErrors as 'PATCH /knowledge-fs/spaces/{control_space_id}/documents/{document_id}' } from './knowledge-fs/errors.gen.ts'
export { post10Errors as 'POST /account/interface-language' } from './account/errors.gen.ts'
-export { post10Errors as 'POST /agent/{agent_id}/config/skills/upload' } from './agent/errors.gen.ts'
-export { post10Errors as 'POST /apps/{app_id}/agent/config/skills/upload' } from './apps/errors.gen.ts'
+export { post10Errors as 'POST /agent/{agent_id}/config/files' } from './agent/errors.gen.ts'
+export { post10Errors as 'POST /apps/{app_id}/agent/config/files' } from './apps/errors.gen.ts'
export { post10Errors as 'POST /installed-apps/{installed_app_id}/workflows/run' } from './installed-apps/errors.gen.ts'
export { post10Errors as 'POST /knowledge-fs/spaces/{control_space_id}/golden-questions' } from './knowledge-fs/errors.gen.ts'
export { post10Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/draft/datasource/variables-inspect' } from './rag/errors.gen.ts'
export { post10Errors as 'POST /snippets/{snippet_id}/workflows/draft' } from './snippets/errors.gen.ts'
export { post11Errors as 'POST /account/interface-theme' } from './account/errors.gen.ts'
-export { post11Errors as 'POST /agent/{agent_id}/copy' } from './agent/errors.gen.ts'
+export { post11Errors as 'POST /agent/{agent_id}/config/skills/upload' } from './agent/errors.gen.ts'
+export { post11Errors as 'POST /apps/{app_id}/agent/config/skills/upload' } from './apps/errors.gen.ts'
export { post11Errors as 'POST /installed-apps/{installed_app_id}/workflows/tasks/{task_id}/stop' } from './installed-apps/errors.gen.ts'
export { post11Errors as 'POST /knowledge-fs/spaces/{control_space_id}/jobs/{job_id}/retry' } from './knowledge-fs/errors.gen.ts'
export { post11Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/draft/iteration/nodes/{node_id}/run' } from './rag/errors.gen.ts'
export { post12Errors as 'POST /account/name' } from './account/errors.gen.ts'
-export { post12Errors as 'POST /agent/{agent_id}/debug-conversation/refresh' } from './agent/errors.gen.ts'
+export { post12Errors as 'POST /agent/{agent_id}/copy' } from './agent/errors.gen.ts'
export { post12Errors as 'POST /datasets/{dataset_id}/documents/{document_id}/segment' } from './datasets/errors.gen.ts'
export { post12Errors as 'POST /knowledge-fs/spaces/{control_space_id}/logical-documents/download-zip' } from './knowledge-fs/errors.gen.ts'
export { post12Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/draft/loop/nodes/{node_id}/run' } from './rag/errors.gen.ts'
export { post12Errors as 'POST /workspaces/current/members/invite-email' } from './workspaces/errors.gen.ts'
export { post13Errors as 'POST /account/password' } from './account/errors.gen.ts'
-export { post13Errors as 'POST /agent/{agent_id}/features' } from './agent/errors.gen.ts'
-export { post13Errors as 'POST /apps/{app_id}/annotations/batch-import' } from './apps/errors.gen.ts'
+export { post13Errors as 'POST /agent/{agent_id}/debug-conversation/refresh' } from './agent/errors.gen.ts'
export { post13Errors as 'POST /knowledge-fs/spaces/{control_space_id}/metadata' } from './knowledge-fs/errors.gen.ts'
export { post13Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/draft/nodes/{node_id}/run' } from './rag/errors.gen.ts'
export { post13Errors as 'POST /workspaces/current/members/owner-transfer-check' } from './workspaces/errors.gen.ts'
export { post14Errors as 'POST /account/timezone' } from './account/errors.gen.ts'
-export { post14Errors as 'POST /agent/{agent_id}/feedbacks' } from './agent/errors.gen.ts'
+export { post14Errors as 'POST /agent/{agent_id}/features' } from './agent/errors.gen.ts'
+export { post14Errors as 'POST /apps/{app_id}/annotations/batch-import' } from './apps/errors.gen.ts'
export { post14Errors as 'POST /datasets/{dataset_id}/documents/{document_id}/segments/{segment_id}/child_chunks' } from './datasets/errors.gen.ts'
export { post14Errors as 'POST /knowledge-fs/spaces/{control_space_id}/quality/bad-cases' } from './knowledge-fs/errors.gen.ts'
export { post14Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/draft/run' } from './rag/errors.gen.ts'
export { post14Errors as 'POST /workspaces/current/members/send-owner-transfer-confirm-email' } from './workspaces/errors.gen.ts'
-export { post15Errors as 'POST /agent/{agent_id}/publish' } from './agent/errors.gen.ts'
+export { post15Errors as 'POST /agent/{agent_id}/feedbacks' } from './agent/errors.gen.ts'
export { post15Errors as 'POST /datasets/{dataset_id}/documents' } from './datasets/errors.gen.ts'
export { post15Errors as 'POST /knowledge-fs/spaces/{control_space_id}/quality/replay-runs' } from './knowledge-fs/errors.gen.ts'
export { post15Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/draft' } from './rag/errors.gen.ts'
export { post15Errors as 'POST /workspaces/current/members/{member_id}/owner-transfer' } from './workspaces/errors.gen.ts'
-export { post16Errors as 'POST /agent/{agent_id}/sandbox/files/download' } from './agent/errors.gen.ts'
+export { post16Errors as 'POST /agent/{agent_id}/publish' } from './agent/errors.gen.ts'
export { post16Errors as 'POST /datasets/{dataset_id}/external-hit-testing' } from './datasets/errors.gen.ts'
export { post16Errors as 'POST /knowledge-fs/spaces/{control_space_id}/queries/admission' } from './knowledge-fs/errors.gen.ts'
export { post16Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/publish' } from './rag/errors.gen.ts'
-export { post17Errors as 'POST /agent/{agent_id}/text-to-audio' } from './agent/errors.gen.ts'
-export { post17Errors as 'POST /apps/{app_id}/audio-to-text' } from './apps/errors.gen.ts'
+export { post17Errors as 'POST /agent/{agent_id}/sandbox/files/download' } from './agent/errors.gen.ts'
export { post17Errors as 'POST /datasets/{dataset_id}/hit-testing' } from './datasets/errors.gen.ts'
export { post17Errors as 'POST /knowledge-fs/spaces/{control_space_id}/queries' } from './knowledge-fs/errors.gen.ts'
export { post17Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/published/datasource/nodes/{node_id}/preview' } from './rag/errors.gen.ts'
-export { post18Errors as 'POST /agent/{agent_id}/trace' } from './agent/errors.gen.ts'
-export { post18Errors as 'POST /apps/{app_id}/chat-messages/{task_id}/stop' } from './apps/errors.gen.ts'
+export { post18Errors as 'POST /agent/{agent_id}/text-to-audio' } from './agent/errors.gen.ts'
+export { post18Errors as 'POST /apps/{app_id}/audio-to-text' } from './apps/errors.gen.ts'
export { post18Errors as 'POST /knowledge-fs/spaces/{control_space_id}/query-stream-capability' } from './knowledge-fs/errors.gen.ts'
export { post18Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/published/datasource/nodes/{node_id}/run' } from './rag/errors.gen.ts'
-export { post19Errors as 'POST /agent/{agent_id}/trace-config' } from './agent/errors.gen.ts'
-export { post19Errors as 'POST /apps/{app_id}/completion-messages/{task_id}/stop' } from './apps/errors.gen.ts'
+export { post19Errors as 'POST /agent/{agent_id}/trace' } from './agent/errors.gen.ts'
+export { post19Errors as 'POST /apps/{app_id}/chat-messages/{task_id}/stop' } from './apps/errors.gen.ts'
export { post19Errors as 'POST /knowledge-fs/spaces/{control_space_id}/research-tasks/plan' } from './knowledge-fs/errors.gen.ts'
export { post19Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/published/run' } from './rag/errors.gen.ts'
-export { post20Errors as 'POST /agent/{agent_id}/trace-runs/{message_id}/retry' } from './agent/errors.gen.ts'
-export { post20Errors as 'POST /apps/{app_id}/completion-messages' } from './apps/errors.gen.ts'
+export { post20Errors as 'POST /agent/{agent_id}/trace-config' } from './agent/errors.gen.ts'
+export { post20Errors as 'POST /apps/{app_id}/completion-messages/{task_id}/stop' } from './apps/errors.gen.ts'
export { post20Errors as 'POST /knowledge-fs/spaces/{control_space_id}/research-tasks' } from './knowledge-fs/errors.gen.ts'
export { post20Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/{workflow_id}/restore' } from './rag/errors.gen.ts'
-export { post21Errors as 'POST /agent/{agent_id}/versions/{version_id}/restore' } from './agent/errors.gen.ts'
-export { post21Errors as 'POST /apps/{app_id}/convert-to-workflow' } from './apps/errors.gen.ts'
+export { post21Errors as 'POST /agent/{agent_id}/trace-runs/{message_id}/retry' } from './agent/errors.gen.ts'
+export { post21Errors as 'POST /apps/{app_id}/completion-messages' } from './apps/errors.gen.ts'
export { post21Errors as 'POST /knowledge-fs/spaces/{control_space_id}/source-connections/{connection_id}/refresh' } from './knowledge-fs/errors.gen.ts'
-export { post22Errors as 'POST /agent' } from './agent/errors.gen.ts'
+export { post22Errors as 'POST /agent/{agent_id}/versions/{version_id}/restore' } from './agent/errors.gen.ts'
+export { post22Errors as 'POST /apps/{app_id}/convert-to-workflow' } from './apps/errors.gen.ts'
export { post22Errors as 'POST /knowledge-fs/spaces/{control_space_id}/source-connections' } from './knowledge-fs/errors.gen.ts'
-export { post23Errors as 'POST /apps/{app_id}/feedbacks' } from './apps/errors.gen.ts'
+export { post23Errors as 'POST /agent' } from './agent/errors.gen.ts'
export { post23Errors as 'POST /datasets/{resource_id}/api-keys' } from './datasets/errors.gen.ts'
export { post23Errors as 'POST /knowledge-fs/spaces/{control_space_id}/source-workflows/{run_id}/cancel' } from './knowledge-fs/errors.gen.ts'
+export { post24Errors as 'POST /apps/{app_id}/feedbacks' } from './apps/errors.gen.ts'
export { post24Errors as 'POST /datasets' } from './datasets/errors.gen.ts'
export { post24Errors as 'POST /knowledge-fs/spaces/{control_space_id}/source-workflows/{run_id}/retry' } from './knowledge-fs/errors.gen.ts'
-export { post25Errors as 'POST /apps/{app_id}/model-config' } from './apps/errors.gen.ts'
export { post25Errors as 'POST /knowledge-fs/spaces/{control_space_id}/source-workflows/{run_id}/selection' } from './knowledge-fs/errors.gen.ts'
+export { post26Errors as 'POST /apps/{app_id}/model-config' } from './apps/errors.gen.ts'
export { post26Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/async-import' } from './knowledge-fs/errors.gen.ts'
export { post27Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/crawl-import' } from './knowledge-fs/errors.gen.ts'
-export { post28Errors as 'POST /apps/{app_id}/server/refresh' } from './apps/errors.gen.ts'
export { post28Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/crawl-preview' } from './knowledge-fs/errors.gen.ts'
-export { post29Errors as 'POST /apps/{app_id}/server' } from './apps/errors.gen.ts'
+export { post29Errors as 'POST /apps/{app_id}/server/refresh' } from './apps/errors.gen.ts'
export { post29Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/import' } from './knowledge-fs/errors.gen.ts'
export { post29Errors as 'POST /workspaces/current/plugin/install/github' } from './workspaces/errors.gen.ts'
export { post2Errors as 'POST /account/change-email/check-email-unique' } from './account/errors.gen.ts'
@@ -406,31 +407,31 @@ export { post2Errors as 'POST /instruction-generate' } from './instruction-gener
export { post2Errors as 'POST /knowledge-fs/source-provider-preview/jobs' } from './knowledge-fs/errors.gen.ts'
export { post2Errors as 'POST /rag/pipeline/dataset' } from './rag/errors.gen.ts'
export { post2Errors as 'POST /trial-apps/{app_id}/chat-messages/{task_id}/stop' } from './trial-apps/errors.gen.ts'
-export { post30Errors as 'POST /apps/{app_id}/site/access-token-reset' } from './apps/errors.gen.ts'
+export { post30Errors as 'POST /apps/{app_id}/server' } from './apps/errors.gen.ts'
export { post30Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/import-files' } from './knowledge-fs/errors.gen.ts'
export { post30Errors as 'POST /workspaces/current/plugin/install/marketplace' } from './workspaces/errors.gen.ts'
-export { post31Errors as 'POST /apps/{app_id}/site' } from './apps/errors.gen.ts'
+export { post31Errors as 'POST /apps/{app_id}/site/access-token-reset' } from './apps/errors.gen.ts'
export { post31Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/sync' } from './knowledge-fs/errors.gen.ts'
export { post31Errors as 'POST /workspaces/current/plugin/install/pkg' } from './workspaces/errors.gen.ts'
+export { post32Errors as 'POST /apps/{app_id}/site' } from './apps/errors.gen.ts'
export { post32Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/test' } from './knowledge-fs/errors.gen.ts'
export { post32Errors as 'POST /workspaces/current/plugin/list/installations/ids' } from './workspaces/errors.gen.ts'
export { post33Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources/{source_id}/workflow-imports' } from './knowledge-fs/errors.gen.ts'
export { post33Errors as 'POST /workspaces/current/plugin/list/latest-versions' } from './workspaces/errors.gen.ts'
-export { post34Errors as 'POST /apps/{app_id}/text-to-audio' } from './apps/errors.gen.ts'
export { post34Errors as 'POST /knowledge-fs/spaces/{control_space_id}/sources' } from './knowledge-fs/errors.gen.ts'
export { post34Errors as 'POST /workspaces/current/plugin/parameters/dynamic-options-with-credentials' } from './workspaces/errors.gen.ts'
-export { post35Errors as 'POST /apps/{app_id}/trace' } from './apps/errors.gen.ts'
+export { post35Errors as 'POST /apps/{app_id}/text-to-audio' } from './apps/errors.gen.ts'
export { post35Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions/{upload_session_id}/abort' } from './knowledge-fs/errors.gen.ts'
-export { post36Errors as 'POST /apps/{app_id}/trace-config' } from './apps/errors.gen.ts'
+export { post36Errors as 'POST /apps/{app_id}/trace' } from './apps/errors.gen.ts'
export { post36Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions/{upload_session_id}/complete' } from './knowledge-fs/errors.gen.ts'
export { post36Errors as 'POST /workspaces/current/plugin/tasks/delete_all' } from './workspaces/errors.gen.ts'
-export { post37Errors as 'POST /apps/{app_id}/trace-runs/{source_kind}/{source_id}/retry' } from './apps/errors.gen.ts'
+export { post37Errors as 'POST /apps/{app_id}/trace-config' } from './apps/errors.gen.ts'
export { post37Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions/{upload_session_id}/parts/{part_number}/presign' } from './knowledge-fs/errors.gen.ts'
export { post37Errors as 'POST /workspaces/current/plugin/tasks/{task_id}/delete/{identifier}' } from './workspaces/errors.gen.ts'
-export { post38Errors as 'POST /apps/{app_id}/trigger-enable' } from './apps/errors.gen.ts'
+export { post38Errors as 'POST /apps/{app_id}/trace-runs/{source_kind}/{source_id}/retry' } from './apps/errors.gen.ts'
export { post38Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions/{upload_session_id}/small-file' } from './knowledge-fs/errors.gen.ts'
export { post38Errors as 'POST /workspaces/current/plugin/tasks/{task_id}/delete' } from './workspaces/errors.gen.ts'
-export { post39Errors as 'POST /apps/{app_id}/workflow-runs/tasks/{task_id}/stop' } from './apps/errors.gen.ts'
+export { post39Errors as 'POST /apps/{app_id}/trigger-enable' } from './apps/errors.gen.ts'
export { post39Errors as 'POST /knowledge-fs/spaces/{control_space_id}/upload-sessions' } from './knowledge-fs/errors.gen.ts'
export { post39Errors as 'POST /workspaces/current/plugin/uninstall' } from './workspaces/errors.gen.ts'
export { post3Errors as 'POST /account/change-email/reset' } from './account/errors.gen.ts'
@@ -442,23 +443,23 @@ export { post3Errors as 'POST /installed-apps/{installed_app_id}/chat-messages'
export { post3Errors as 'POST /knowledge-fs/source-provider-preview' } from './knowledge-fs/errors.gen.ts'
export { post3Errors as 'POST /trial-apps/{app_id}/chat-messages' } from './trial-apps/errors.gen.ts'
export { post3Errors as 'POST /workflow-generate' } from './workflow-generate/errors.gen.ts'
-export { post40Errors as 'POST /apps/{app_id}/workflow-runs/{workflow_run_id}/agent-nodes/{node_id}/sandbox/files/download' } from './apps/errors.gen.ts'
+export { post40Errors as 'POST /apps/{app_id}/workflow-runs/tasks/{task_id}/stop' } from './apps/errors.gen.ts'
export { post40Errors as 'POST /knowledge-fs/spaces' } from './knowledge-fs/errors.gen.ts'
export { post40Errors as 'POST /workspaces/current/plugin/upgrade/github' } from './workspaces/errors.gen.ts'
-export { post41Errors as 'POST /apps/{app_id}/workflow/comments/{comment_id}/replies' } from './apps/errors.gen.ts'
+export { post41Errors as 'POST /apps/{app_id}/workflow-runs/{workflow_run_id}/agent-nodes/{node_id}/sandbox/files/download' } from './apps/errors.gen.ts'
export { post41Errors as 'POST /knowledge-fs/tasks/{task_id}/stream-capability' } from './knowledge-fs/errors.gen.ts'
export { post41Errors as 'POST /workspaces/current/plugin/upgrade/marketplace' } from './workspaces/errors.gen.ts'
-export { post42Errors as 'POST /apps/{app_id}/workflow/comments/{comment_id}/resolve' } from './apps/errors.gen.ts'
+export { post42Errors as 'POST /apps/{app_id}/workflow/comments/{comment_id}/replies' } from './apps/errors.gen.ts'
export { post42Errors as 'POST /knowledge-fs/uploads' } from './knowledge-fs/errors.gen.ts'
-export { post43Errors as 'POST /apps/{app_id}/workflow/comments' } from './apps/errors.gen.ts'
+export { post43Errors as 'POST /apps/{app_id}/workflow/comments/{comment_id}/resolve' } from './apps/errors.gen.ts'
export { post43Errors as 'POST /workspaces/current/plugin/upload/github' } from './workspaces/errors.gen.ts'
-export { post44Errors as 'POST /apps/{app_id}/workflows/draft/conversation-variables' } from './apps/errors.gen.ts'
+export { post44Errors as 'POST /apps/{app_id}/workflow/comments' } from './apps/errors.gen.ts'
export { post44Errors as 'POST /workspaces/current/plugin/upload/pkg' } from './workspaces/errors.gen.ts'
-export { post45Errors as 'POST /apps/{app_id}/workflows/draft/environment-variables' } from './apps/errors.gen.ts'
-export { post46Errors as 'POST /apps/{app_id}/workflows/draft/features' } from './apps/errors.gen.ts'
-export { post47Errors as 'POST /apps/{app_id}/workflows/draft/human-input/nodes/{node_id}/delivery-test' } from './apps/errors.gen.ts'
-export { post48Errors as 'POST /apps/{app_id}/workflows/draft/human-input/nodes/{node_id}/form/preview' } from './apps/errors.gen.ts'
-export { post49Errors as 'POST /apps/{app_id}/workflows/draft/human-input/nodes/{node_id}/form/run' } from './apps/errors.gen.ts'
+export { post45Errors as 'POST /apps/{app_id}/workflows/draft/conversation-variables' } from './apps/errors.gen.ts'
+export { post46Errors as 'POST /apps/{app_id}/workflows/draft/environment-variables' } from './apps/errors.gen.ts'
+export { post47Errors as 'POST /apps/{app_id}/workflows/draft/features' } from './apps/errors.gen.ts'
+export { post48Errors as 'POST /apps/{app_id}/workflows/draft/human-input/nodes/{node_id}/delivery-test' } from './apps/errors.gen.ts'
+export { post49Errors as 'POST /apps/{app_id}/workflows/draft/human-input/nodes/{node_id}/form/preview' } from './apps/errors.gen.ts'
export { post49Errors as 'POST /workspaces/current/skills/files/upload' } from './workspaces/errors.gen.ts'
export { post4Errors as 'POST /account/change-email/validity' } from './account/errors.gen.ts'
export { post4Errors as 'POST /agent/{agent_id}/build-chat/finalize' } from './agent/errors.gen.ts'
@@ -468,22 +469,22 @@ export { post4Errors as 'POST /installed-apps/{installed_app_id}/completion-mess
export { post4Errors as 'POST /knowledge-fs/spaces/{control_space_id}/background-tasks/{task_kind}/{task_id}/cancel' } from './knowledge-fs/errors.gen.ts'
export { post4Errors as 'POST /snippets/{snippet_id}/workflows/draft/nodes/{node_id}/agent-composer/copy-from-roster' } from './snippets/errors.gen.ts'
export { post4Errors as 'POST /trial-apps/{app_id}/completion-messages' } from './trial-apps/errors.gen.ts'
-export { post50Errors as 'POST /apps/{app_id}/workflows/draft/iteration/nodes/{node_id}/run' } from './apps/errors.gen.ts'
+export { post50Errors as 'POST /apps/{app_id}/workflows/draft/human-input/nodes/{node_id}/form/run' } from './apps/errors.gen.ts'
export { post50Errors as 'POST /workspaces/current/skills/import' } from './workspaces/errors.gen.ts'
-export { post51Errors as 'POST /apps/{app_id}/workflows/draft/loop/nodes/{node_id}/run' } from './apps/errors.gen.ts'
+export { post51Errors as 'POST /apps/{app_id}/workflows/draft/iteration/nodes/{node_id}/run' } from './apps/errors.gen.ts'
export { post51Errors as 'POST /workspaces/current/skills/{skill_id}/assist/messages' } from './workspaces/errors.gen.ts'
-export { post52Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/copy-from-roster' } from './apps/errors.gen.ts'
-export { post53Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/impact' } from './apps/errors.gen.ts'
+export { post52Errors as 'POST /apps/{app_id}/workflows/draft/loop/nodes/{node_id}/run' } from './apps/errors.gen.ts'
+export { post53Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/copy-from-roster' } from './apps/errors.gen.ts'
export { post53Errors as 'POST /workspaces/current/skills/{skill_id}/files/check' } from './workspaces/errors.gen.ts'
-export { post54Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/save-to-roster' } from './apps/errors.gen.ts'
+export { post54Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/impact' } from './apps/errors.gen.ts'
export { post54Errors as 'POST /workspaces/current/skills/{skill_id}/publish' } from './workspaces/errors.gen.ts'
-export { post55Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/validate' } from './apps/errors.gen.ts'
+export { post55Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/save-to-roster' } from './apps/errors.gen.ts'
export { post55Errors as 'POST /workspaces/current/skills/{skill_id}/restore' } from './workspaces/errors.gen.ts'
-export { post56Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/run' } from './apps/errors.gen.ts'
+export { post56Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/validate' } from './apps/errors.gen.ts'
export { post56Errors as 'POST /workspaces/current/skills' } from './workspaces/errors.gen.ts'
-export { post57Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/trigger/run' } from './apps/errors.gen.ts'
-export { post58Errors as 'POST /apps/{app_id}/workflows/draft/run' } from './apps/errors.gen.ts'
-export { post59Errors as 'POST /apps/{app_id}/workflows/draft/trigger/run' } from './apps/errors.gen.ts'
+export { post57Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/run' } from './apps/errors.gen.ts'
+export { post58Errors as 'POST /apps/{app_id}/workflows/draft/nodes/{node_id}/trigger/run' } from './apps/errors.gen.ts'
+export { post59Errors as 'POST /apps/{app_id}/workflows/draft/run' } from './apps/errors.gen.ts'
export { post5Errors as 'POST /account/change-email' } from './account/errors.gen.ts'
export { post5Errors as 'POST /agent/{agent_id}/build-draft/apply' } from './agent/errors.gen.ts'
export { post5Errors as 'POST /apps/{app_id}/advanced-chat/workflows/draft/human-input/nodes/{node_id}/form/run' } from './apps/errors.gen.ts'
@@ -491,11 +492,12 @@ export { post5Errors as 'POST /datasets/init' } from './datasets/errors.gen.ts'
export { post5Errors as 'POST /installed-apps/{installed_app_id}/completion-messages' } from './installed-apps/errors.gen.ts'
export { post5Errors as 'POST /knowledge-fs/spaces/{control_space_id}/background-tasks/{task_kind}/{task_id}/retry' } from './knowledge-fs/errors.gen.ts'
export { post5Errors as 'POST /trial-apps/{app_id}/files/upload' } from './trial-apps/errors.gen.ts'
-export { post60Errors as 'POST /apps/{app_id}/workflows/draft/trigger/run-all' } from './apps/errors.gen.ts'
-export { post61Errors as 'POST /apps/{app_id}/workflows/draft' } from './apps/errors.gen.ts'
-export { post62Errors as 'POST /apps/{app_id}/workflows/publish' } from './apps/errors.gen.ts'
-export { post63Errors as 'POST /apps/{app_id}/workflows/{workflow_id}/restore' } from './apps/errors.gen.ts'
-export { post64Errors as 'POST /apps/{resource_id}/api-keys' } from './apps/errors.gen.ts'
+export { post60Errors as 'POST /apps/{app_id}/workflows/draft/trigger/run' } from './apps/errors.gen.ts'
+export { post61Errors as 'POST /apps/{app_id}/workflows/draft/trigger/run-all' } from './apps/errors.gen.ts'
+export { post62Errors as 'POST /apps/{app_id}/workflows/draft' } from './apps/errors.gen.ts'
+export { post63Errors as 'POST /apps/{app_id}/workflows/publish' } from './apps/errors.gen.ts'
+export { post64Errors as 'POST /apps/{app_id}/workflows/{workflow_id}/restore' } from './apps/errors.gen.ts'
+export { post65Errors as 'POST /apps/{resource_id}/api-keys' } from './apps/errors.gen.ts'
export { post6Errors as 'POST /agent/{agent_id}/build-draft/checkout' } from './agent/errors.gen.ts'
export { post6Errors as 'POST /apps/{app_id}/advanced-chat/workflows/draft/iteration/nodes/{node_id}/run' } from './apps/errors.gen.ts'
export { post6Errors as 'POST /datasets/notion-indexing-estimate' } from './datasets/errors.gen.ts'
@@ -521,8 +523,8 @@ export { post8Errors as 'POST /knowledge-fs/spaces/{control_space_id}/golden-que
export { post8Errors as 'POST /rag/pipelines/{pipeline_id}/workflow-runs/tasks/{task_id}/stop' } from './rag/errors.gen.ts'
export { post8Errors as 'POST /trial-apps/{app_id}/workflows/run' } from './trial-apps/errors.gen.ts'
export { post9Errors as 'POST /account/init' } from './account/errors.gen.ts'
-export { post9Errors as 'POST /agent/{agent_id}/config/files' } from './agent/errors.gen.ts'
-export { post9Errors as 'POST /apps/{app_id}/agent/config/files' } from './apps/errors.gen.ts'
+export { post9Errors as 'POST /agent/{agent_id}/config/files/batch' } from './agent/errors.gen.ts'
+export { post9Errors as 'POST /apps/{app_id}/agent/config/files/batch' } from './apps/errors.gen.ts'
export { post9Errors as 'POST /installed-apps/{installed_app_id}/text-to-audio' } from './installed-apps/errors.gen.ts'
export { post9Errors as 'POST /knowledge-fs/spaces/{control_space_id}/golden-questions/evidence-matches' } from './knowledge-fs/errors.gen.ts'
export { post9Errors as 'POST /rag/pipelines/{pipeline_id}/workflows/draft/datasource/nodes/{node_id}/run' } from './rag/errors.gen.ts'
diff --git a/packages/openapi-content-mapper/integration/console-type-differences.json b/packages/openapi-content-mapper/integration/console-type-differences.json
index 6f2f4e05ba8..34719f902ca 100644
--- a/packages/openapi-content-mapper/integration/console-type-differences.json
+++ b/packages/openapi-content-mapper/integration/console-type-differences.json
@@ -495,6 +495,7 @@
"console POST /agent/{agent_id}/api-keys": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/build-draft/checkout": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/config/files": ["compatible", "parsed-vs-wire-output"],
+ "console POST /agent/{agent_id}/config/files/batch": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/config/skills/upload": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/copy": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/debug-conversation/refresh": [
@@ -507,6 +508,7 @@
"parsed-vs-wire-output"
],
"console POST /apps/{app_id}/agent/config/files": ["compatible", "parsed-vs-wire-output"],
+ "console POST /apps/{app_id}/agent/config/files/batch": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/{app_id}/agent/config/skills/upload": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/{app_id}/completion-messages": ["compatible", "undocumented-output"],
"console POST /apps/{app_id}/copy": ["compatible", "parsed-vs-wire-output"],
diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx
index 927df05ae0f..ee072706b1e 100644
--- a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx
@@ -498,6 +498,7 @@ describe('useWorkflowInlineAgentConfigureSync', () => {
result.current.setDraft({
...defaultAgentSoulConfigFormState,
prompt: 'Workflow inline prompt',
+ files: [{ id: 'stale.md', name: 'stale.md', icon: 'markdown', fileId: 'stale-upload' }],
})
})
@@ -532,6 +533,25 @@ describe('useWorkflowInlineAgentConfigureSync', () => {
}),
}),
)
+ expect(mockComposerMutationFn.mock.calls[0]?.[0]).not.toHaveProperty(
+ 'body.agent_soul.config_files',
+ )
+ })
+
+ it('preserves explicit file replacement when applying a complete Agent configuration', async () => {
+ const { result } = renderWorkflowHook(
+ () => useWorkflowInlineAgentConfigureSync({ nodeId: 'node-1', enabled: true }),
+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
+ )
+
+ await act(async () => {
+ await result.current.saveAgentSoulConfig({ schema_version: 1, config_files: [] })
+ })
+
+ expect(mockComposerMutationFn.mock.calls[0]?.[0]).toHaveProperty(
+ 'body.agent_soul.config_files',
+ [],
+ )
})
it('saves inline agent composer changes through the snippet composer API', async () => {
diff --git a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
index e4c7558969d..37459b06369 100644
--- a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
+++ b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
@@ -4,6 +4,7 @@ import type {
} from '@dify/contracts/api/console/apps/types.gen'
import type { DefaultModelResponse } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { omit } from 'es-toolkit'
import { debounce } from 'es-toolkit/compat'
import isEqual from 'fast-deep-equal'
import { useAtomValue, useStore as useJotaiStore, useSetAtom } from 'jotai'
@@ -106,14 +107,18 @@ export function useWorkflowInlineAgentConfigureSync({
)
const saveComposer = useSerialAsyncCallback(
- async (configSnapshot: AgentSoulConfig): Promise<WorkflowAgentComposerResponse | undefined> => {
+ async (
+ configSnapshot: AgentSoulConfig,
+ fileUpdate: 'preserve' | 'replace' = 'preserve',
+ ): Promise<WorkflowAgentComposerResponse | undefined> => {
if (resource.kind !== 'app' && resource.kind !== 'snippet') return
const savedDraftKey = JSON.stringify(configSnapshot)
const body = {
variant: 'workflow' as const,
save_strategy: 'node_job_only' as const,
- agent_soul: configSnapshot,
+ agent_soul:
+ fileUpdate === 'replace' ? configSnapshot : omit(configSnapshot, ['config_files']),
}
const composerState =
resource.kind === 'snippet'
@@ -194,7 +199,7 @@ export function useWorkflowInlineAgentConfigureSync({
const saveAgentSoulConfig = useCallback(
async (agentSoulConfig: AgentSoulConfig) => {
debouncedSaveDraft.cancel?.()
- return saveComposer(agentSoulConfig)
+ return saveComposer(agentSoulConfig, 'replace')
},
[debouncedSaveDraft, saveComposer],
)
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
index a0aa096aa8d..513ef42497b 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
@@ -572,6 +572,39 @@ describe('Inline Agent configure workspace', () => {
},
)
+ it('applies the latest build draft instead of the cached one', async () => {
+ const user = userEvent.setup()
+ api.loadBuildDraft.mockResolvedValue(createBuildDraft())
+ renderWorkspace()
+ await screen.findByRole('button', { name: 'custom.apply' })
+ api.loadBuildDraft.mockResolvedValue(createBuildDraft('Latest build instructions'))
+
+ await user.click(applyButton())
+
+ await waitFor(() =>
+ expect(api.saveComposer).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ agent_soul: createBuildDraft('Latest build instructions').agent_soul,
+ }),
+ }),
+ ),
+ )
+ })
+
+ it('does not apply a cached build draft when refreshing it fails', async () => {
+ const user = userEvent.setup()
+ api.loadBuildDraft.mockResolvedValue(createBuildDraft())
+ renderWorkspace()
+ await screen.findByRole('button', { name: 'custom.apply' })
+ api.loadBuildDraft.mockRejectedValue(createHttpError(new Response(null, { status: 500 })))
+
+ await user.click(applyButton())
+
+ await waitFor(() => expect(applyButton()).toBeEnabled())
+ expect(api.saveComposer).not.toHaveBeenCalled()
+ })
+
it('keeps an existing build draft until the switch-to-preview confirmation is accepted', async () => {
const user = userEvent.setup()
api.loadBuildDraft.mockResolvedValue(createBuildDraft())
@@ -603,7 +636,7 @@ describe('Inline Agent configure workspace', () => {
debug_conversation_message_count: 1,
}),
})
- expect(await screen.findByText('Earlier answer')).toBeVisible()
+ expect(await screen.findByText('Earlier answer', {}, { timeout: 5000 })).toBeVisible()
expect(api.history).toHaveBeenCalledWith({
params: { agent_id: 'agent-1' },
query: { conversation_id: 'old-conversation' },
@@ -643,7 +676,7 @@ describe('Inline Agent configure workspace', () => {
debug_conversation_message_count: 1,
}),
})
- await screen.findByText('Build history')
+ expect(await screen.findByText('Build history', {}, { timeout: 5000 })).toBeVisible()
await changeMode(user, 'preview')
await sendPreview(user)
await waitFor(() => expect(ssePost).toHaveBeenCalledOnce())
@@ -661,7 +694,7 @@ describe('Inline Agent configure workspace', () => {
await receive(1, 'new-preview-conversation', 'New preview answer')
await complete(1)
await changeMode(user, 'build')
- expect(await screen.findByText('Build history')).toBeVisible()
+ expect(await screen.findByText('Build history', {}, { timeout: 5000 })).toBeVisible()
})
it('opens generated files after a build response completes', async () => {
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
index 2df266161dc..4ca8e04bb90 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
@@ -489,9 +489,11 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
cancelBuildDraftRefresh()
setIsApplyingInlineBuildDraft(true)
try {
- if (!buildDraft.agentSoulConfig) return
+ const latestBuildDraft = await buildDraft.refetch()
+ const agentSoulConfig = latestBuildDraft.data?.agent_soul
+ if (latestBuildDraft.isError || !agentSoulConfig) return
- const savedComposerState = await saveAgentSoulConfig(buildDraft.agentSoulConfig)
+ const savedComposerState = await saveAgentSoulConfig(agentSoulConfig)
await discardBuildDraft({
params: {
agent_id: agentId,
@@ -502,9 +504,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
queryClient.removeQueries({
queryKey: buildDraftQueryOptions.queryKey,
})
- rebaseComposerDraftFromSoulConfig(
- savedComposerState?.agent_soul ?? buildDraft.agentSoulConfig,
- )
+ rebaseComposerDraftFromSoulConfig(savedComposerState?.agent_soul ?? agentSoulConfig)
toast.success(t(($) => $['api.actionSuccess']))
} catch {
toast.error(t(($) => $['api.actionFailed']))
diff --git a/web/features/agent-v2/agent-composer/conversions.ts b/web/features/agent-v2/agent-composer/conversions.ts
index 267911df945..a7f0b411787 100644
--- a/web/features/agent-v2/agent-composer/conversions.ts
+++ b/web/features/agent-v2/agent-composer/conversions.ts
@@ -555,7 +555,7 @@ const toFileFormState = (config?: AgentSoulConfig): AgentFileNode[] => {
name: file.name,
icon: getFileIconType(file.name, file.mime_type ?? undefined),
fileId: file.file_id,
- isMissing: isConfigReferenceMissing(file) || undefined,
+ ...(isConfigReferenceMissing(file) ? { isMissing: true } : {}),
configName: file.name,
size: file.size ?? undefined,
hash: file.hash ?? undefined,
diff --git a/web/features/agent-v2/agent-composer/store-modules/__tests__/files.spec.ts b/web/features/agent-v2/agent-composer/store-modules/__tests__/files.spec.ts
index ac0dcd94b8d..87d0b0a7e76 100644
--- a/web/features/agent-v2/agent-composer/store-modules/__tests__/files.spec.ts
+++ b/web/features/agent-v2/agent-composer/store-modules/__tests__/files.spec.ts
@@ -2,7 +2,7 @@ import { createStore } from 'jotai'
import { describe, expect, it } from 'vite-plus/test'
import { defaultAgentSoulConfigFormState } from '../../form-state'
import { agentComposerDraftAtom } from '../../store'
-import { removeAgentFileAtom, upsertAgentFileAtom } from '../files'
+import { removeAgentFileAtom, upsertAgentFilesAtom } from '../files'
describe('agent composer files store', () => {
it('should upsert and remove files from the latest draft state', () => {
@@ -31,11 +31,13 @@ describe('agent composer files store', () => {
],
})
- store.set(upsertAgentFileAtom, {
- id: 'diagram.png',
- icon: 'image',
- name: 'updated-diagram.png',
- })
+ store.set(upsertAgentFilesAtom, [
+ {
+ id: 'diagram.png',
+ icon: 'image',
+ name: 'updated-diagram.png',
+ },
+ ])
expect(store.get(agentComposerDraftAtom).prompt).toBe(
'Use [§file:diagram.png:updated-diagram.png§].',
)
diff --git a/web/features/agent-v2/agent-composer/store-modules/files.ts b/web/features/agent-v2/agent-composer/store-modules/files.ts
index 76025b23f5d..5f4cbe8ef57 100644
--- a/web/features/agent-v2/agent-composer/store-modules/files.ts
+++ b/web/features/agent-v2/agent-composer/store-modules/files.ts
@@ -36,8 +36,11 @@ const removeAgentFileNode = (files: AgentFileNode[], fileId: string): AgentFileN
return [file]
})
-export const upsertAgentFileAtom = atom(null, (_get, set, file: AgentFileNode) => {
- set(agentComposerFilesAtom, (files) => [...removeAgentFileNode(files, file.id), file])
+export const upsertAgentFilesAtom = atom(null, (_get, set, uploadedFiles: AgentFileNode[]) => {
+ set(agentComposerFilesAtom, (files) => [
+ ...uploadedFiles.reduce((current, file) => removeAgentFileNode(current, file.id), files),
+ ...uploadedFiles,
+ ])
})
export const removeAgentFileAtom = atom(null, (_get, set, fileId: string) => {
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
index 1c2581fd2a9..4015e8f06f4 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
@@ -349,7 +349,7 @@ describe('useAgentConfigureSync', () => {
vi.useRealTimers()
})
- it('should automatically save configure page changes to draft', async () => {
+ it('should automatically save configure changes without overwriting server-owned files', async () => {
const { queryClient, store } = renderUseAgentConfigureSync()
queryClient.setQueryData(
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
@@ -360,6 +360,7 @@ describe('useAgentConfigureSync', () => {
store.set(agentComposerDraftAtom, {
...store.get(agentComposerDraftAtom),
prompt: 'Draft only prompt',
+ files: [{ id: 'stale.md', name: 'stale.md', icon: 'markdown', fileId: 'stale-upload' }],
})
})
@@ -392,6 +393,9 @@ describe('useAgentConfigureSync', () => {
}),
}),
)
+ expect(composerPutMutationFn.mock.calls[0]?.[0]).not.toHaveProperty(
+ 'body.agent_soul.config_files',
+ )
expect(
queryClient.getQueryData(
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
@@ -529,6 +533,7 @@ describe('useAgentConfigureSync', () => {
store.set(agentComposerDraftAtom, {
...store.get(agentComposerDraftAtom),
prompt: 'Closing prompt',
+ files: [{ id: 'stale.md', name: 'stale.md', icon: 'markdown', fileId: 'stale-upload' }],
})
})
@@ -542,6 +547,9 @@ describe('useAgentConfigureSync', () => {
})
expect(composerPutMutationFn).toHaveBeenCalledTimes(1)
+ expect(composerPutMutationFn.mock.calls[0]?.[0]).not.toHaveProperty(
+ 'body.agent_soul.config_files',
+ )
expect(composerPutRequestContexts).toEqual([{ keepalive: true, silent: true }])
expect(composerPutMutationFn).toHaveBeenCalledWith(
expect.objectContaining({
@@ -783,7 +791,7 @@ describe('useAgentConfigureSync', () => {
expect(composerPutMutationFn).toHaveBeenCalledTimes(1)
})
- it('should include Agent Soul files when autosaving file changes', async () => {
+ it('should leave file persistence to the file API when autosaving file changes', async () => {
const { store } = renderUseAgentConfigureSync()
act(() => {
@@ -809,18 +817,17 @@ describe('useAgentConfigureSync', () => {
expect.objectContaining({
body: expect.objectContaining({
agent_soul: expect.objectContaining({
- config_files: [
- {
- file_id: 'drive-file-1',
- file_kind: 'upload_file',
- name: 'uploaded.md',
- },
- ],
config_skills: [],
}),
}),
}),
)
+ expect(composerPutMutationFn.mock.calls[0]?.[0]).not.toHaveProperty(
+ 'body.agent_soul.config_files',
+ )
+ expect(store.get(agentComposerFilesAtom)).toEqual([
+ expect.objectContaining({ name: 'uploaded.md', fileId: 'drive-file-1' }),
+ ])
})
it('should preserve uploaded skills when prompt is updated immediately after upload', async () => {
@@ -863,7 +870,6 @@ describe('useAgentConfigureSync', () => {
size: 42,
},
],
- config_files: [],
}),
}),
}),
@@ -900,21 +906,17 @@ describe('useAgentConfigureSync', () => {
prompt: expect.objectContaining({
system_prompt: 'Use [§file:uploaded.md:uploaded.md§]',
}),
- config_files: [
- {
- file_id: 'drive-file-1',
- file_kind: 'upload_file',
- hash: 'sha256:file-1',
- mime_type: 'text/markdown',
- name: 'uploaded.md',
- size: 5,
- },
- ],
config_skills: [],
}),
}),
}),
)
+ expect(composerPutMutationFn.mock.calls[0]?.[0]).not.toHaveProperty(
+ 'body.agent_soul.config_files',
+ )
+ expect(store.get(agentComposerFilesAtom)).toEqual([
+ expect.objectContaining({ name: 'uploaded.md', fileId: 'drive-file-1' }),
+ ])
})
it('should autosave when knowledge retrieval validation fails', async () => {
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions-context.ts
index 524db074a90..68d4f81043a 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions-context.ts
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions-context.ts
@@ -15,7 +15,7 @@ export type AgentOrchestrateAddedItem =
| AgentSkill
export type AgentOrchestrateAddActionOptions = {
- onAdded?: (item: AgentOrchestrateAddedItem) => void
+ onAdded?: (items: AgentOrchestrateAddedItem[]) => void
skillSource?: 'library' | 'upload'
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx
index c7a0df30e0d..4361ac0a0e1 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx
@@ -5,7 +5,6 @@ import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useAtomValue } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { toast } from '@/app/notifications'
import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
@@ -33,14 +32,16 @@ const mocks = vi.hoisted(() => ({
uploadFileMutationFn: vi.fn(async (_input: unknown) => ({ id: 'upload-1' })),
commitFileMutationFn: vi.fn(async (_input: unknown) => ({
config_version: { id: 'draft-1', kind: 'draft', writable: true },
- file: {
- id: 'uploaded.md',
- name: 'uploaded.md',
- file_id: 'drive-file-1',
- hash: 'sha256:file-1',
- mime_type: 'text/markdown',
- size: 5,
- },
+ files: [
+ {
+ id: 'uploaded.md',
+ name: 'uploaded.md',
+ file_id: 'drive-file-1',
+ hash: 'sha256:file-1',
+ mime_type: 'text/markdown',
+ size: 5,
+ },
+ ],
})),
deleteFileMutationFn: vi.fn(async (_input: unknown) => ({
removed_names: ['brief.md'],
@@ -59,13 +60,6 @@ const mocks = vi.hoisted(() => ({
},
}))
-vi.mock('@/app/notifications', () => ({
- toast: {
- success: vi.fn(),
- error: vi.fn(),
- },
-}))
-
vi.mock('@/utils/download', () => ({
downloadBlob: mocks.downloadBlob,
downloadUrl: mocks.downloadUrl,
@@ -74,7 +68,8 @@ vi.mock('@/utils/download', () => ({
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { consoleOperationStub } = await import('@/test/console/operation-hooks')
- const { withConsoleQueryOverrides } = await import('@/test/console/service-responses')
+ const { withConsoleClientResponses, withConsoleQueryOverrides } =
+ await import('@/test/console/service-responses')
const query = withConsoleQueryOverrides(actual.consoleQuery, {
'agent.byAgentId.config.files.byName.preview.get': { queryOptions: mocks.previewQueryOptions },
'agent.byAgentId.config.files.byName.download.get': {
@@ -109,9 +104,6 @@ vi.mock('@/service/console', async (importOriginal) => {
byAgentId: {
config: {
files: {
- post: {
- mutationOptions: () => ({ mutationFn: mocks.commitFileMutationFn }),
- },
byName: {
delete: {
mutationOptions: () => ({ mutationFn: mocks.deleteFileMutationFn }),
@@ -132,9 +124,6 @@ vi.mock('@/service/console', async (importOriginal) => {
agent: {
config: {
files: {
- post: {
- mutationOptions: () => ({ mutationFn: mocks.commitFileMutationFn }),
- },
byName: {
delete: {
mutationOptions: () => ({ mutationFn: mocks.deleteFileMutationFn }),
@@ -172,12 +161,14 @@ vi.mock('@/service/console', async (importOriginal) => {
files: {
upload: {
get: consoleOperationStub('files.upload.get'),
- post: {
- mutationOptions: () => ({ mutationFn: mocks.uploadFileMutationFn }),
- },
},
},
},
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'files.upload.post': mocks.uploadFileMutationFn,
+ 'agent.byAgentId.config.files.batch.post': mocks.commitFileMutationFn,
+ 'apps.byAppId.agent.config.files.batch.post': mocks.commitFileMutationFn,
+ }),
}
})
@@ -351,85 +342,25 @@ describe('AgentFiles', () => {
expect(screen.queryByText('diagram.png')).not.toBeInTheDocument()
})
- it('keeps both upload stages open until the committed file reaches the draft', async () => {
- let finishUpload!: () => void
- let finishCommit!: () => void
- const upload = new Promise<void>((resolve) => {
- finishUpload = resolve
- })
- const commit = new Promise<void>((resolve) => {
- finishCommit = resolve
- })
- const uploadFile = mocks.uploadFileMutationFn.getMockImplementation()!
- const commitFile = mocks.commitFileMutationFn.getMockImplementation()!
- mocks.uploadFileMutationFn.mockImplementationOnce(async (input) => {
- await upload
- return uploadFile(input)
- })
- mocks.commitFileMutationFn.mockImplementationOnce(async (input) => {
- await commit
- return commitFile(input)
- })
+ it('adds uploaded files to the Files list and the config', async () => {
const user = userEvent.setup()
renderAgentFiles({ initialDraft: defaultAgentSoulConfigFormState })
await user.click(
screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.files\.add/i }),
)
-
const input = await waitFor(() => {
const element = document.querySelector('input[type="file"]')
expect(element).not.toBeNull()
return element as HTMLInputElement
})
- const file = new File(['hello'], 'uploaded.md', { type: 'text/markdown' })
- await user.upload(input, file)
+ await user.upload(input, new File(['hello'], 'uploaded.md', { type: 'text/markdown' }))
await user.click(
screen.getByRole('button', { name: /agentDetail\.configure\.files\.upload\.action/i }),
)
- await waitFor(() => {
- expect(mocks.uploadFileMutationFn).toHaveBeenCalledExactlyOnceWith(
- {
- body: {
- file,
- },
- },
- expect.anything(),
- )
- })
-
- await user.keyboard('{Escape}')
- await user.click(
- within(screen.getByRole('dialog')).getByRole('button', { name: 'common.operation.close' }),
- )
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- expect(mocks.commitFileMutationFn).not.toHaveBeenCalled()
- finishUpload()
-
- await waitFor(() => {
- expect(mocks.commitFileMutationFn).toHaveBeenCalledExactlyOnceWith(
- {
- params: {
- agent_id: 'agent-1',
- },
- query: {
- draft_type: 'draft',
- version_id: undefined,
- },
- body: {
- upload_file_id: 'upload-1',
- },
- },
- expect.anything(),
- )
- })
-
- await user.keyboard('{Escape}')
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- finishCommit()
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
-
+ expect(screen.getByRole('button', { name: 'uploaded.md' })).toBeInTheDocument()
const snapshot = JSON.parse(screen.getByLabelText('config snapshot').textContent ?? '{}')
expect(snapshot.config_files).toEqual([
expect.objectContaining({
@@ -441,7 +372,6 @@ describe('AgentFiles', () => {
size: 5,
}),
])
- expect(toast.success).toHaveBeenCalled()
})
it('should show the configured size limit for every supported file type', async () => {
@@ -486,10 +416,11 @@ describe('AgentFiles', () => {
const file = new File([new Uint8Array(1024 * 1024 + 1)], fileName, { type: mimeType })
await user.upload(input, file)
- expect(toast.error).toHaveBeenCalledWith(
- `common.fileUploader.uploadFromComputerLimit:{"type":"${fileType}","size":"1.00 MB"}`,
- )
- expect(mocks.uploadFileMutationFn).not.toHaveBeenCalled()
+ expect(
+ screen.getByText(
+ `common.fileUploader.uploadFromComputerLimit:{"type":"${fileType}","size":"1.00 MB"}`,
+ ),
+ ).toBeVisible()
expect(
screen.getByRole('button', {
name: /agentDetail\.configure\.files\.upload\.action/i,
@@ -538,13 +469,14 @@ describe('AgentFiles', () => {
version_id: 'draft-1',
},
body: {
- upload_file_id: 'upload-1',
+ upload_file_ids: ['upload-1'],
},
},
expect.anything(),
)
})
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await user.click(screen.getByRole('button', { name: 'diagram.png' }))
await waitFor(() => {
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/upload-dialog.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/upload-dialog.spec.tsx
new file mode 100644
index 00000000000..2f7b8c5a680
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/upload-dialog.spec.tsx
@@ -0,0 +1,295 @@
+import type { AgentConfigApiContext } from '../../config-context'
+import type { consoleClient } from '@/service/console'
+import { ORPCError } from '@orpc/client'
+import { QueryClientProvider } from '@tanstack/react-query'
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { consoleQuery } from '@/service/console'
+import { createDeferred } from '@/test/deferred'
+import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
+import { createTestQueryClient } from '@/test/query-client'
+import { AgentFileUploadDialog } from '../upload-dialog'
+
+type UploadInput = Parameters<typeof consoleClient.files.upload.post>[0]
+type BindAgentInput = Parameters<typeof consoleClient.agent.byAgentId.config.files.batch.post>[0]
+type BindWorkflowInput = Parameters<
+ typeof consoleClient.apps.byAppId.agent.config.files.batch.post
+>[0]
+
+const bindResponse = ({ body }: { body: { upload_file_ids: string[] } }) => ({
+ config_version: { id: 'draft-1', kind: 'draft', writable: true },
+ files: body.upload_file_ids.map((id) => ({
+ name: id.replace('upload-', ''),
+ file_id: id,
+ file_kind: 'upload_file',
+ mime_type: 'text/markdown',
+ size: 5,
+ })),
+})
+
+const mocks = vi.hoisted(() => ({
+ upload: vi.fn<(input: UploadInput) => Promise<{ id: string }>>(),
+ bindAgent: vi.fn<(input: BindAgentInput) => Promise<ReturnType<typeof bindResponse>>>(),
+ bindWorkflow: vi.fn<(input: BindWorkflowInput) => Promise<ReturnType<typeof bindResponse>>>(),
+}))
+
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'files.upload.post': (input: UploadInput) => mocks.upload(input),
+ 'agent.byAgentId.config.files.batch.post': (input: BindAgentInput) => mocks.bindAgent(input),
+ 'apps.byAppId.agent.config.files.batch.post': (input: BindWorkflowInput) =>
+ mocks.bindWorkflow(input),
+ }),
+ }
+})
+
+const uploadKey = 'agentV2.agentDetail.configure.files.upload.'
+
+function renderUploadDialog({
+ apiContext = { agentId: 'agent-1', draftType: 'draft' },
+ documentSizeLimit = 15,
+}: {
+ apiContext?: AgentConfigApiContext
+ documentSizeLimit?: number
+} = {}) {
+ const onUploaded = vi.fn()
+ const onOpenChange = vi.fn()
+ const queryClient = createTestQueryClient()
+ queryClient.setQueryData(
+ consoleQuery.files.upload.get.queryKey(),
+ createFileUploadConfigFixture({ file_size_limit: documentSizeLimit }),
+ )
+
+ function Harness() {
+ const [open, setOpen] = useState(true)
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ reopen
+ </button>
+ <AgentFileUploadDialog
+ apiContext={apiContext}
+ open={open}
+ onOpenChange={(nextOpen) => {
+ onOpenChange(nextOpen)
+ setOpen(nextOpen)
+ }}
+ onUploaded={onUploaded}
+ />
+ </>
+ )
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <Harness />
+ </QueryClientProvider>,
+ )
+ return { onUploaded, onOpenChange }
+}
+
+function fileName(file: Blob) {
+ return file instanceof File ? file.name : ''
+}
+
+function markdownFile(name: string) {
+ return new File(['hello'], name, { type: 'text/markdown' })
+}
+
+function fileRow(name: string) {
+ const row = screen.getAllByRole('listitem').find((item) => within(item).queryByText(name))
+ if (!row) throw new Error(`No pending file row for ${name}`)
+ return row
+}
+
+function uploadButton() {
+ return screen.getByRole('button', { name: `${uploadKey}action` })
+}
+
+function dropFiles(files: File[]) {
+ fireEvent.drop(screen.getByRole('group', { name: `${uploadKey}title` }), {
+ dataTransfer: { types: ['Files'], files },
+ })
+}
+
+function uploadedNames() {
+ return mocks.upload.mock.calls.map(([input]) => fileName(input.body.file))
+}
+
+describe('AgentFileUploadDialog', () => {
+ beforeEach(() => {
+ mocks.upload.mockImplementation(async ({ body }) => ({ id: `upload-${fileName(body.file)}` }))
+ mocks.bindAgent.mockImplementation(async (input) => bindResponse(input))
+ mocks.bindWorkflow.mockImplementation(async (input) => bindResponse(input))
+ })
+
+ it('keeps the dialog open while files upload', async () => {
+ const user = userEvent.setup()
+ const upload = createDeferred<{ id: string }>()
+ mocks.upload.mockReturnValueOnce(upload.promise)
+ const { onOpenChange } = renderUploadDialog()
+
+ dropFiles([markdownFile('first.md')])
+ await user.click(uploadButton())
+ await waitFor(() => expect(mocks.upload).toHaveBeenCalledOnce())
+
+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: `${uploadKey}browse` })).toBeDisabled()
+ await user.keyboard('{Escape}')
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ expect(screen.getByRole('dialog')).toBeVisible()
+ expect(onOpenChange).not.toHaveBeenCalled()
+
+ await act(async () => upload.resolve({ id: 'upload-first.md' }))
+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false))
+ })
+
+ it('uploads every file before binding them in one request and reports the bound files', async () => {
+ const user = userEvent.setup()
+ const firstUpload = createDeferred<{ id: string }>()
+ mocks.upload.mockReturnValueOnce(firstUpload.promise)
+ const { onUploaded, onOpenChange } = renderUploadDialog()
+
+ dropFiles([markdownFile('first.md'), markdownFile('second.md')])
+ await user.click(uploadButton())
+ await waitFor(() => expect(mocks.upload).toHaveBeenCalledTimes(2))
+ expect(mocks.bindAgent).not.toHaveBeenCalled()
+
+ await act(async () => firstUpload.resolve({ id: 'upload-first.md' }))
+
+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false))
+ expect(mocks.bindAgent).toHaveBeenCalledExactlyOnceWith({
+ params: { agent_id: 'agent-1' },
+ query: { draft_type: 'draft', version_id: undefined },
+ body: { upload_file_ids: ['upload-first.md', 'upload-second.md'] },
+ })
+ expect(onUploaded).toHaveBeenCalledExactlyOnceWith([
+ expect.objectContaining({ name: 'first.md', fileId: 'upload-first.md' }),
+ expect.objectContaining({ name: 'second.md', fileId: 'upload-second.md' }),
+ ])
+ })
+
+ it('binds the files that uploaded, shows why the other failed and retries only that one', async () => {
+ const user = userEvent.setup()
+ mocks.upload.mockRejectedValueOnce(
+ new ORPCError('file_extension_blocked', { status: 400, message: 'File type not allowed' }),
+ )
+ const { onUploaded, onOpenChange } = renderUploadDialog()
+
+ dropFiles([markdownFile('retry.md'), markdownFile('ready.md')])
+ await user.click(uploadButton())
+
+ expect(
+ await within(fileRow('retry.md')).findByText('File type not allowed'),
+ ).toBeInTheDocument()
+ expect(screen.queryByText('ready.md')).not.toBeInTheDocument()
+ expect(onUploaded).toHaveBeenCalledExactlyOnceWith([
+ expect.objectContaining({ name: 'ready.md' }),
+ ])
+ expect(onOpenChange).not.toHaveBeenCalled()
+
+ await user.click(uploadButton())
+
+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false))
+ expect(uploadedNames()).toEqual(['retry.md', 'ready.md', 'retry.md'])
+ expect(mocks.bindAgent.mock.calls.map(([input]) => input.body.upload_file_ids)).toEqual([
+ ['upload-ready.md'],
+ ['upload-retry.md'],
+ ])
+ })
+
+ it('does not bind anything when every upload fails', async () => {
+ const user = userEvent.setup()
+ mocks.upload.mockRejectedValue(new TypeError('Failed to fetch'))
+ const { onUploaded, onOpenChange } = renderUploadDialog()
+
+ dropFiles([markdownFile('first.md'), markdownFile('second.md')])
+ await user.click(uploadButton())
+
+ expect(await within(fileRow('first.md')).findByText(`${uploadKey}failed`)).toBeInTheDocument()
+ expect(within(fileRow('second.md')).getByText(`${uploadKey}failed`)).toBeInTheDocument()
+ expect(mocks.bindAgent).not.toHaveBeenCalled()
+ expect(onUploaded).not.toHaveBeenCalled()
+ expect(onOpenChange).not.toHaveBeenCalled()
+ })
+
+ it('marks every file failed when the workflow binding fails and uploads them again on retry', async () => {
+ const user = userEvent.setup()
+ mocks.bindWorkflow.mockRejectedValueOnce(new Error('Binding failed'))
+ const { onUploaded, onOpenChange } = renderUploadDialog({
+ apiContext: {
+ agentId: 'agent-1',
+ draftType: 'debug_build',
+ versionId: 'build-1',
+ workflow: { appId: 'workflow-1', nodeId: 'node-1' },
+ },
+ })
+
+ dropFiles([markdownFile('first.md'), markdownFile('second.md')])
+ await user.click(uploadButton())
+
+ expect(await within(fileRow('first.md')).findByText(`${uploadKey}failed`)).toBeInTheDocument()
+ expect(within(fileRow('second.md')).getByText(`${uploadKey}failed`)).toBeInTheDocument()
+ expect(onUploaded).not.toHaveBeenCalled()
+
+ await user.click(uploadButton())
+
+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false))
+ expect(uploadedNames()).toHaveLength(4)
+ expect(mocks.bindAgent).not.toHaveBeenCalled()
+ expect(mocks.bindWorkflow).toHaveBeenLastCalledWith({
+ params: { app_id: 'workflow-1' },
+ query: { node_id: 'node-1', draft_type: 'debug_build', version_id: 'build-1' },
+ body: { upload_file_ids: ['upload-first.md', 'upload-second.md'] },
+ })
+ })
+
+ it('blocks uploading while a file exceeds its size limit until that file is removed', async () => {
+ const user = userEvent.setup()
+ const { onUploaded } = renderUploadDialog({ documentSizeLimit: 1 })
+ const oversized = new File([new Uint8Array(1024 * 1024 + 1)], 'large.md', {
+ type: 'text/markdown',
+ })
+
+ dropFiles([markdownFile('small.md'), oversized])
+
+ expect(
+ within(fileRow('large.md')).getByText(/common\.fileUploader\.uploadFromComputerLimit/),
+ ).toHaveTextContent('1.00 MB')
+ expect(uploadButton()).toBeDisabled()
+
+ await user.click(
+ within(fileRow('large.md')).getByRole('button', {
+ name: /agentV2\.agentDetail\.configure\.files\.remove/,
+ }),
+ )
+ await user.click(uploadButton())
+
+ await waitFor(() => expect(onUploaded).toHaveBeenCalledOnce())
+ expect(uploadedNames()).toEqual(['small.md'])
+ })
+
+ it('starts empty after the dialog is closed and reopened', async () => {
+ const user = userEvent.setup()
+ mocks.upload.mockRejectedValueOnce(new TypeError('Failed to fetch'))
+ renderUploadDialog()
+
+ dropFiles([markdownFile('failed.md')])
+ await user.click(uploadButton())
+ await within(fileRow('failed.md')).findByText(`${uploadKey}failed`)
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+
+ await user.click(screen.getByRole('button', { name: 'reopen' }))
+
+ expect(await screen.findByRole('dialog')).toBeVisible()
+ expect(screen.queryByRole('listitem')).not.toBeInTheDocument()
+ expect(uploadButton()).toBeDisabled()
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx
index 6bc5da3698f..6abc9a879db 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx
@@ -24,7 +24,7 @@ import {
agentComposerFilesAtom,
clearAgentConfigNoteAtom,
removeAgentFileAtom,
- upsertAgentFileAtom,
+ upsertAgentFilesAtom,
} from '@/features/agent-v2/agent-composer/store-modules/files'
import { consoleQuery } from '@/service/console'
import { downloadBlob, downloadUrl } from '@/utils/download'
@@ -436,12 +436,13 @@ export function AgentFiles() {
const readOnly = useAgentOrchestrateReadOnly()
const [isUploadOpen, setIsUploadOpen] = useState(false)
const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)
+ const uploadedFilesRef = useRef<AgentFileNode[]>([])
const apiContext = useAgentConfigApiContext()
const draft = useAtomValue(agentComposerDraftAtom)
const files = useAtomValue(agentComposerFilesAtom)
const clearAgentConfigNote = useSetAtom(clearAgentConfigNoteAtom)
const removeAgentFile = useSetAtom(removeAgentFileAtom)
- const upsertAgentFile = useSetAtom(upsertAgentFileAtom)
+ const upsertAgentFiles = useSetAtom(upsertAgentFilesAtom)
const buildNoteFile = getBuildNoteFile(draft.configNote)
const visibleFiles = buildNoteFile ? [buildNoteFile, ...files] : files
const previewFiles = visibleFiles.filter((file) => !file.isMissing)
@@ -513,15 +514,19 @@ export function AgentFiles() {
}, [])
useRegisterAgentOrchestrateAddAction('files', handleOpenUpload)
const handleUploaded = useCallback(
- (file: AgentFileNode) => {
- upsertAgentFile(file)
- promptAddCallbackRef.current?.(file)
- promptAddCallbackRef.current = undefined
+ (uploadedFiles: AgentFileNode[]) => {
+ upsertAgentFiles(uploadedFiles)
+ uploadedFilesRef.current.push(...uploadedFiles)
},
- [upsertAgentFile],
+ [upsertAgentFiles],
)
const handleUploadOpenChange = useCallback((open: boolean) => {
- if (!open) promptAddCallbackRef.current = undefined
+ if (!open) {
+ if (uploadedFilesRef.current.length > 0)
+ promptAddCallbackRef.current?.(uploadedFilesRef.current)
+ promptAddCallbackRef.current = undefined
+ uploadedFilesRef.current = []
+ }
setIsUploadOpen(open)
}, [])
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx
index 3adda7c66a8..c5c571dbc2c 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx
@@ -1,10 +1,7 @@
'use client'
-import type {
- AgentConfigFileItemResponse,
- AgentConfigFileUploadResponse,
-} from '@dify/contracts/api/console/agent/types.gen'
-import type { FileResponse } from '@dify/contracts/api/console/files/types.gen'
+import type { AgentConfigFileItemResponse } from '@dify/contracts/api/console/agent/types.gen'
+import type { UseMutationResult } from '@tanstack/react-query'
import type { ChangeEvent, DragEvent } from 'react'
import type { AgentConfigApiContext } from '../config-context'
import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
@@ -23,17 +20,30 @@ import {
} from '@langgenius/dify-ui/dialog'
import { FileTreeIcon } from '@langgenius/dify-ui/file-tree'
import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { ORPCError } from '@orpc/client'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { v4 as uuid } from 'uuid'
import { getFileSizeLimit } from '@/app/components/base/file-uploader/hooks'
import { getSupportFileType } from '@/app/components/base/file-uploader/utils'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
-import { toast } from '@/app/notifications'
import { getFileIconType } from '@/features/agent-v2/file-icon'
-import { consoleQuery } from '@/service/console'
+import { consoleClient, consoleQuery } from '@/service/console'
import { formatFileSize } from '@/utils/format'
+type PendingAgentFile = {
+ id: string
+ file: File
+}
+
+type AgentFilesUploadResult = {
+ files: AgentConfigFileItemResponse[]
+ failures: { id: string; message?: string }[]
+}
+
+type AgentFilesUploadMutation = UseMutationResult<AgentFilesUploadResult, Error, PendingAgentFile[]>
+
function toAgentFileNode(committedFile: AgentConfigFileItemResponse): AgentFileNode {
return {
id: committedFile.name,
@@ -47,68 +57,34 @@ function toAgentFileNode(committedFile: AgentConfigFileItemResponse): AgentFileN
}
}
+function getServerMessage(error: unknown) {
+ return error instanceof ORPCError ? error.message : undefined
+}
+
function hasDraggedFiles(event: DragEvent<HTMLDivElement>) {
return Array.from(event.dataTransfer.types).includes('Files')
}
-function AgentFileUploader({ file, onChange }: { file?: File; onChange: (file?: File) => void }) {
+function AgentFileDropzone({
+ disabled,
+ onAdd,
+}: {
+ disabled: boolean
+ onAdd: (files: File[]) => void
+}) {
const { t } = useTranslation(['agentV2'])
- const { t: tAppDebug } = useTranslation(['appDebug'])
- const { t: tCommon } = useTranslation(['common'])
- const { data: fileUploadConfig } = useQuery(consoleQuery.files.upload.get.queryOptions())
- const { imgSizeLimit, docSizeLimit, audioSizeLimit, videoSizeLimit } =
- getFileSizeLimit(fileUploadConfig)
const fileInputRef = useRef<HTMLInputElement>(null)
const dragDepthRef = useRef(0)
const [dragging, setDragging] = useState(false)
- const getSizeLimit = (uploadFile: File) => {
- const fileType = getSupportFileType(uploadFile.name, uploadFile.type)
-
- switch (fileType) {
- case SupportUploadFileTypes.image:
- return { fileType, sizeLimit: imgSizeLimit }
- case SupportUploadFileTypes.audio:
- return { fileType, sizeLimit: audioSizeLimit }
- case SupportUploadFileTypes.video:
- return { fileType, sizeLimit: videoSizeLimit }
- default:
- return {
- fileType: SupportUploadFileTypes.document,
- sizeLimit: docSizeLimit,
- }
- }
- }
-
- const setUploadFiles = (files: File[]) => {
- const [uploadFile] = files
- if (files.length !== 1 || !uploadFile) {
- toast.error(t(($) => $['agentDetail.configure.files.upload.invalidFile']))
- return
- }
-
- const { fileType, sizeLimit } = getSizeLimit(uploadFile)
- if (uploadFile.size > sizeLimit) {
- toast.error(
- tCommon(($) => $['fileUploader.uploadFromComputerLimit'], {
- type: fileType,
- size: formatFileSize(sizeLimit),
- }),
- )
- return
- }
-
- onChange(uploadFile)
- }
-
const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const files = Array.from(event.target.files ?? [])
event.target.value = ''
- setUploadFiles(files)
+ if (files.length > 0) onAdd(files)
}
const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
- if (!hasDraggedFiles(event)) return
+ if (disabled || !hasDraggedFiles(event)) return
event.preventDefault()
event.stopPropagation()
@@ -120,7 +96,7 @@ function AgentFileUploader({ file, onChange }: { file?: File; onChange: (file?:
if (!hasDraggedFiles(event)) return
event.preventDefault()
- event.dataTransfer.dropEffect = 'copy'
+ event.dataTransfer.dropEffect = disabled ? 'none' : 'copy'
}
const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
@@ -140,7 +116,7 @@ function AgentFileUploader({ file, onChange }: { file?: File; onChange: (file?:
dragDepthRef.current = 0
setDragging(false)
- setUploadFiles(Array.from(event.dataTransfer.files))
+ if (!disabled) onAdd(Array.from(event.dataTransfer.files))
}
return (
@@ -152,67 +128,184 @@ function AgentFileUploader({ file, onChange }: { file?: File; onChange: (file?:
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
- <input ref={fileInputRef} className="hidden" type="file" onChange={handleFileChange} />
- {!file && (
- <div
- className={cn(
- 'relative flex h-16 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal',
- dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',
- )}
- >
- <div className="flex w-full items-center justify-center space-x-2">
- <span aria-hidden className="i-ri-upload-cloud-2-line size-6 text-text-tertiary" />
- <div className="text-text-tertiary">
- {t(($) => $['agentDetail.configure.files.upload.dropzone'])}
- <button
- type="button"
- className="inline cursor-pointer border-none bg-transparent p-0 pl-1 text-left text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"
- onClick={() => fileInputRef.current?.click()}
- >
- {t(($) => $['agentDetail.configure.files.upload.browse'])}
- </button>
- </div>
- </div>
- {dragging && <div className="absolute top-0 left-0 size-full" />}
- </div>
- )}
- {file && (
- <div className="flex items-center rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs hover:bg-components-panel-on-panel-item-bg-hover">
- <div className="flex items-center justify-center p-3">
- <FileTreeIcon type={getFileIconType(file.name, file.type)} />
- </div>
- <div className="flex min-w-0 grow flex-col items-start gap-0.5 py-1 pr-2">
- <span className="max-w-full min-w-0 truncate text-[12px] leading-4 font-medium text-text-secondary">
- {file.name}
- </span>
- <div className="flex h-3 items-center gap-1 self-stretch text-2xs leading-3 font-medium text-text-tertiary uppercase">
- <span>{t(($) => $['agentDetail.configure.files.upload.fileType'])}</span>
- <span className="text-text-quaternary">·</span>
- <span>{formatFileSize(file.size)}</span>
- </div>
- </div>
- <div className="flex items-center pr-3">
- <IconButton
- aria-label={tCommon(($) => $['operation.remove'])}
- onClick={() => onChange(undefined)}
+ <input
+ ref={fileInputRef}
+ className="hidden"
+ type="file"
+ multiple
+ onChange={handleFileChange}
+ />
+ <div
+ className={cn(
+ 'relative flex h-16 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal',
+ dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',
+ )}
+ >
+ <div className="flex w-full items-center justify-center space-x-2">
+ <span aria-hidden className="i-ri-upload-cloud-2-line size-6 text-text-tertiary" />
+ <div className="text-text-tertiary">
+ {t(($) => $['agentDetail.configure.files.upload.dropzone'])}
+ <button
+ type="button"
+ disabled={disabled}
+ className="inline cursor-pointer border-none bg-transparent p-0 pl-1 text-left text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden disabled:cursor-not-allowed"
+ onClick={() => fileInputRef.current?.click()}
>
- <span aria-hidden className="i-ri-delete-bin-line size-4 text-text-tertiary" />
- </IconButton>
+ {t(($) => $['agentDetail.configure.files.upload.browse'])}
+ </button>
</div>
</div>
- )}
- <p className="mt-2 system-xs-regular text-text-tertiary">
- {tAppDebug(($) => $['variableConfig.maxNumberTip'], {
- docLimit: formatFileSize(docSizeLimit),
- imgLimit: formatFileSize(imgSizeLimit),
- audioLimit: formatFileSize(audioSizeLimit),
- videoLimit: formatFileSize(videoSizeLimit),
- })}
- </p>
+ {dragging && <div className="absolute top-0 left-0 size-full" />}
+ </div>
</div>
)
}
+function AgentFileUploadPanel({ uploadFiles }: { uploadFiles: AgentFilesUploadMutation }) {
+ const { t } = useTranslation(['agentV2'])
+ const { t: tAppDebug } = useTranslation(['appDebug'])
+ const { t: tCommon } = useTranslation(['common'])
+ const { data: fileUploadConfig } = useQuery(consoleQuery.files.upload.get.queryOptions())
+ const { imgSizeLimit, docSizeLimit, audioSizeLimit, videoSizeLimit } =
+ getFileSizeLimit(fileUploadConfig)
+ const [pendingFiles, setPendingFiles] = useState<PendingAgentFile[]>([])
+ const isUploading = uploadFiles.isPending
+ const failures = uploadFiles.isError
+ ? uploadFiles.variables.map(({ id }) => ({ id, message: getServerMessage(uploadFiles.error) }))
+ : (uploadFiles.data?.failures ?? [])
+
+ const getSizeLimit = (file: File) => {
+ const fileType = getSupportFileType(file.name, file.type)
+
+ switch (fileType) {
+ case SupportUploadFileTypes.image:
+ return { fileType, sizeLimit: imgSizeLimit }
+ case SupportUploadFileTypes.audio:
+ return { fileType, sizeLimit: audioSizeLimit }
+ case SupportUploadFileTypes.video:
+ return { fileType, sizeLimit: videoSizeLimit }
+ default:
+ return {
+ fileType: SupportUploadFileTypes.document,
+ sizeLimit: docSizeLimit,
+ }
+ }
+ }
+
+ const getSizeError = (file: File) => {
+ const { fileType, sizeLimit } = getSizeLimit(file)
+ if (file.size <= sizeLimit) return
+
+ return tCommon(($) => $['fileUploader.uploadFromComputerLimit'], {
+ type: fileType,
+ size: formatFileSize(sizeLimit),
+ })
+ }
+
+ const handleAdd = (files: File[]) => {
+ setPendingFiles((current) => [...current, ...files.map((file) => ({ id: uuid(), file }))])
+ }
+
+ const handleUpload = () => {
+ uploadFiles.mutate(pendingFiles, {
+ onSuccess: (result) => {
+ if (result.failures.length === 0) return
+ setPendingFiles((current) =>
+ current.filter(({ id }) => result.failures.some((failure) => failure.id === id)),
+ )
+ },
+ })
+ }
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t(($) => $['agentDetail.configure.files.upload.title'])}</DialogTitle>
+ <DialogDescription>
+ {t(($) => $['agentDetail.configure.files.upload.description'])}
+ </DialogDescription>
+ <DialogHeaderCloseButton aria-label={tCommon(($) => $['operation.close'])} />
+ </DialogHeader>
+ <DialogBody>
+ <AgentFileDropzone disabled={isUploading} onAdd={handleAdd} />
+ {pendingFiles.length > 0 && (
+ <ul className="mt-2 space-y-2">
+ {pendingFiles.map(({ id, file }) => {
+ const failure = failures.find((item) => item.id === id)
+ const error =
+ getSizeError(file) ??
+ (failure &&
+ (failure.message ?? t(($) => $['agentDetail.configure.files.upload.failed'])))
+
+ return (
+ <li
+ key={id}
+ className="flex items-center rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs hover:bg-components-panel-on-panel-item-bg-hover"
+ >
+ <div className="flex items-center justify-center p-3">
+ <FileTreeIcon type={getFileIconType(file.name, file.type)} />
+ </div>
+ <div className="flex min-w-0 grow flex-col items-start gap-0.5 py-1 pr-2">
+ <span className="max-w-full min-w-0 truncate text-[12px] leading-4 font-medium text-text-secondary">
+ {file.name}
+ </span>
+ <div className="flex h-3 items-center gap-1 self-stretch text-2xs leading-3 font-medium text-text-tertiary uppercase">
+ <span>{t(($) => $['agentDetail.configure.files.upload.fileType'])}</span>
+ <span className="text-text-quaternary">·</span>
+ <span>{formatFileSize(file.size)}</span>
+ </div>
+ {error && <p className="system-xs-regular text-text-destructive">{error}</p>}
+ </div>
+ <div className="flex items-center pr-3">
+ <IconButton
+ aria-label={t(($) => $['agentDetail.configure.files.remove'], {
+ name: file.name,
+ })}
+ disabled={isUploading}
+ onClick={() =>
+ setPendingFiles((current) => current.filter((item) => item.id !== id))
+ }
+ >
+ <span
+ aria-hidden
+ className="i-ri-delete-bin-line size-4 text-text-tertiary"
+ />
+ </IconButton>
+ </div>
+ </li>
+ )
+ })}
+ </ul>
+ )}
+ <p className="mt-2 system-xs-regular text-text-tertiary">
+ {tAppDebug(($) => $['variableConfig.maxNumberTip'], {
+ docLimit: formatFileSize(docSizeLimit),
+ imgLimit: formatFileSize(imgSizeLimit),
+ audioLimit: formatFileSize(audioSizeLimit),
+ videoLimit: formatFileSize(videoSizeLimit),
+ })}
+ </p>
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose render={<Button disabled={isUploading} />}>
+ {tCommon(($) => $['operation.cancel'])}
+ </DialogClose>
+ <Button
+ type="button"
+ variant="primary"
+ disabled={
+ pendingFiles.length === 0 || pendingFiles.some(({ file }) => getSizeError(file))
+ }
+ loading={isUploading}
+ onClick={handleUpload}
+ >
+ {t(($) => $['agentDetail.configure.files.upload.action'])}
+ </Button>
+ </DialogFooter>
+ </>
+ )
+}
+
export function AgentFileUploadDialog({
apiContext,
open,
@@ -222,133 +315,70 @@ export function AgentFileUploadDialog({
apiContext: AgentConfigApiContext
open: boolean
onOpenChange: (open: boolean) => void
- onUploaded: (file: AgentFileNode) => void
+ onUploaded: (files: AgentFileNode[]) => void
}) {
- const { t } = useTranslation(['agentV2', 'common'])
- const { t: tCommon } = useTranslation(['common'])
- const [file, setFile] = useState<File>()
- const uploadFileMutation = useMutation(consoleQuery.files.upload.post.mutationOptions())
- const commitAgentFileMutation = useMutation(
- consoleQuery.agent.byAgentId.config.files.post.mutationOptions(),
- )
- const commitWorkflowAgentFileMutation = useMutation(
- consoleQuery.apps.byAppId.agent.config.files.post.mutationOptions(),
- )
- const isUploading =
- uploadFileMutation.isPending ||
- commitAgentFileMutation.isPending ||
- commitWorkflowAgentFileMutation.isPending
-
- const commitUploadedFile = (
- uploadedFile: FileResponse,
- options: {
- onSuccess: (committedFile: AgentConfigFileUploadResponse) => void
- onError: () => void
- },
- ) => {
- const body = {
- upload_file_id: uploadedFile.id,
- }
-
- if (apiContext.workflow) {
- commitWorkflowAgentFileMutation.mutate(
- {
- params: {
- app_id: apiContext.workflow.appId,
- },
- query: {
- node_id: apiContext.workflow.nodeId,
- draft_type: apiContext.draftType,
- version_id: apiContext.versionId,
- },
- body,
- },
- options,
+ const uploadFiles = useMutation({
+ mutationFn: async (pendingFiles: PendingAgentFile[]): Promise<AgentFilesUploadResult> => {
+ const uploads = await Promise.allSettled(
+ pendingFiles.map(({ file }) =>
+ consoleClient.files.upload.post({ body: { file } }, { context: { silent: true } }),
+ ),
)
- return
- }
-
- commitAgentFileMutation.mutate(
- {
- params: {
- agent_id: apiContext.agentId,
- },
- query: {
- draft_type: apiContext.draftType,
- version_id: apiContext.versionId,
- },
- body,
- },
- options,
- )
- }
-
- const handleUpload = () => {
- if (!file || isUploading) return
+ const failures = pendingFiles.flatMap(({ id }, index) => {
+ const upload = uploads[index]
+ return upload?.status === 'rejected'
+ ? [{ id, message: getServerMessage(upload.reason) }]
+ : []
+ })
+ const upload_file_ids = uploads.flatMap((upload) =>
+ upload.status === 'fulfilled' ? [upload.value.id] : [],
+ )
+ if (upload_file_ids.length === 0) return { files: [], failures }
- uploadFileMutation.mutate(
- {
- body: {
- file,
- },
- },
- {
- onSuccess: (uploadedFile) => {
- commitUploadedFile(uploadedFile, {
- onSuccess: (committedFile) => {
- toast.success(t(($) => $['agentDetail.configure.files.upload.success']))
- onUploaded(toAgentFileNode(committedFile.file))
- onOpenChange(false)
+ const body = { upload_file_ids }
+ const { files } = apiContext.workflow
+ ? await consoleClient.apps.byAppId.agent.config.files.batch.post(
+ {
+ params: { app_id: apiContext.workflow.appId },
+ query: {
+ node_id: apiContext.workflow.nodeId,
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
+ },
+ body,
},
- onError: () => {
- toast.error(t(($) => $['agentDetail.configure.files.upload.failed']))
+ { context: { silent: true } },
+ )
+ : await consoleClient.agent.byAgentId.config.files.batch.post(
+ {
+ params: { agent_id: apiContext.agentId },
+ query: {
+ draft_type: apiContext.draftType,
+ version_id: apiContext.versionId,
+ },
+ body,
},
- })
- },
- onError: () => {
- toast.error(t(($) => $['agentDetail.configure.files.upload.failed']))
- },
- },
- )
- }
+ { context: { silent: true } },
+ )
+ return { files, failures }
+ },
+ onSuccess: ({ files, failures }) => {
+ if (files.length > 0) onUploaded(files.map(toAgentFileNode))
+ if (failures.length === 0) onOpenChange(false)
+ },
+ })
return (
<Dialog
open={open}
onOpenChange={(nextOpen, details) => {
- if (!nextOpen && isUploading) details.cancel()
+ if (!nextOpen && uploadFiles.isPending) details.cancel()
else onOpenChange(nextOpen)
}}
- onOpenChangeComplete={(open) => {
- if (!open) setFile(undefined)
- }}
disablePointerDismissal
>
<DialogContent backdropProps={{ forceRender: true, className: 'fixed' }}>
- <DialogHeader>
- <DialogTitle>{t(($) => $['agentDetail.configure.files.upload.title'])}</DialogTitle>
- <DialogDescription>
- {t(($) => $['agentDetail.configure.files.upload.description'])}
- </DialogDescription>
- <DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
- </DialogHeader>
- <DialogBody>
- <AgentFileUploader file={file} onChange={setFile} />
- </DialogBody>
- <DialogFooter>
- <DialogClose render={<Button disabled={isUploading} />}>
- {tCommon(($) => $['operation.cancel'])}
- </DialogClose>
- <Button
- type="button"
- variant="primary"
- disabled={!file}
- loading={isUploading}
- onClick={handleUpload}
- >
- {t(($) => $['agentDetail.configure.files.upload.action'])}
- </Button>
- </DialogFooter>
+ <AgentFileUploadPanel uploadFiles={uploadFiles} />
</DialogContent>
</Dialog>
)
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
index 31269f8d875..53aeac70e79 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
@@ -80,7 +80,7 @@ export function AgentKnowledgeRetrieval() {
setRetrievals(next)
setIsDialogOpen(false)
const added = next.find((item) => !retrievals.some((previous) => previous.id === item.id))
- if (added) addOptionsRef.current?.onAdded?.(added)
+ if (added) addOptionsRef.current?.onAdded?.([added])
addOptionsRef.current = undefined
}
useRegisterAgentOrchestrateAddAction('knowledge', addRetrieval)
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/slash.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/slash.spec.tsx
index de6c50ac2a8..ea218f1f60c 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/slash.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/slash.spec.tsx
@@ -41,7 +41,7 @@ describe('AgentPromptSlashMenu', () => {
expect(onInsertToken).not.toHaveBeenCalled()
onAddSkill.mock.calls
.at(-1)![0]!
- .onAdded?.({ id: 'library-skill', name: 'Library Skill', fileId: 'library-file' })
+ .onAdded?.([{ id: 'library-skill', name: 'Library Skill', fileId: 'library-file' }])
expect(onInsertToken).toHaveBeenLastCalledWith('[§skill:library-skill:Library Skill§]')
await user.click(
@@ -52,7 +52,7 @@ describe('AgentPromptSlashMenu', () => {
expect(onAddSkill).toHaveBeenLastCalledWith(expect.objectContaining({ skillSource: 'upload' }))
onAddSkill.mock.calls
.at(-1)![0]!
- .onAdded?.({ id: 'uploaded-skill', name: 'Uploaded Skill', fileId: 'uploaded-file' })
+ .onAdded?.([{ id: 'uploaded-skill', name: 'Uploaded Skill', fileId: 'uploaded-file' }])
expect(onInsertToken).toHaveBeenLastCalledWith('[§skill:uploaded-skill:Uploaded Skill§]')
})
})
@@ -75,7 +75,7 @@ it.each([
async ({ view, label, item, token }) => {
const user = userEvent.setup()
const onInsertToken = vi.fn()
- const onAdd: AgentOrchestrateAddAction = (options) => options?.onAdded?.(item)
+ const onAdd: AgentOrchestrateAddAction = (options) => options?.onAdded?.([item])
render(
<AgentPromptSlashMenu
view={view}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/uploads.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/uploads.spec.tsx
new file mode 100644
index 00000000000..84f5f846311
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/uploads.spec.tsx
@@ -0,0 +1,177 @@
+import { render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useAtomValue } from 'jotai'
+import { describe, expect, it, vi } from 'vite-plus/test'
+import { replacePromptEditorText } from '@/app/components/base/prompt-editor/plugins/__tests__/test-helpers'
+import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
+import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
+import { consoleQuery } from '@/service/console'
+import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
+import { createAgentPromptEnvironment } from '../../../__tests__/agent-prompt-editor-test-env'
+import { AgentOrchestrateAddActionsProvider } from '../../add-actions'
+import { AgentFiles } from '../../files'
+import { AgentPromptEditor } from '../index'
+
+type UploadInput = { body: { file: File } }
+type CommitInput = { body: { upload_file_ids: string[] } }
+
+const mocks = vi.hoisted(() => ({
+ upload: vi.fn(async ({ body }: UploadInput) => ({ id: `upload-${body.file.name}` })),
+ commit: vi.fn(async ({ body }: CommitInput) => ({
+ files: body.upload_file_ids.map((id) => ({
+ name: id.replace('upload-', ''),
+ file_id: id,
+ mime_type: 'text/markdown',
+ size: 5,
+ })),
+ })),
+}))
+
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'files.upload.post': (input: UploadInput) => mocks.upload(input),
+ 'agent.byAgentId.config.files.batch.post': (input: CommitInput) => mocks.commit(input),
+ }),
+ }
+})
+
+const menuName = /agentDetail\.configure\.prompt\.insert\.label/
+const uploadTitle = /agentDetail\.configure\.files\.upload\.title/
+const addFilesName = /agentDetail\.configure\.files\.add$/
+
+function ConfigSnapshot() {
+ const draft = useAtomValue(agentComposerDraftAtom)
+ return (
+ <output aria-label="config snapshot">
+ {JSON.stringify(formStateToAgentSoulConfig({ formState: draft }))}
+ </output>
+ )
+}
+
+function renderPromptAndFiles() {
+ const env = createAgentPromptEnvironment({ draft: { skills: [], tools: [], files: [] } })
+ env.queryClient.setQueryData(
+ consoleQuery.files.upload.get.queryKey(),
+ createFileUploadConfigFixture(),
+ )
+ render(
+ env.wrap(
+ <AgentOrchestrateAddActionsProvider>
+ <AgentPromptEditor />
+ <AgentFiles />
+ <ConfigSnapshot />
+ </AgentOrchestrateAddActionsProvider>,
+ ),
+ )
+}
+
+async function openPromptFileUpload(user: ReturnType<typeof userEvent.setup>) {
+ const editor = screen.getByRole('textbox')
+ await user.click(editor)
+ await replacePromptEditorText(editor, 'Review ')
+ await user.keyboard('/')
+ const menu = within(await screen.findByRole('dialog', { name: menuName }))
+ await user.click(menu.getByRole('button', { name: /agentDetail\.configure\.files\.label/ }))
+ await user.click(menu.getByRole('button', { name: addFilesName }))
+ await screen.findByRole('dialog', { name: uploadTitle })
+}
+
+async function selectFiles(user: ReturnType<typeof userEvent.setup>, names: string[]) {
+ const dialog = screen.getByRole('dialog', { name: uploadTitle })
+ const input = dialog.querySelector<HTMLInputElement>('input[type="file"]')
+ if (!input) throw new Error('Missing file input')
+ await user.upload(
+ input,
+ names.map((name) => new File(['hello'], name, { type: 'text/markdown' })),
+ )
+}
+
+async function clickUpload(user: ReturnType<typeof userEvent.setup>) {
+ await user.click(
+ screen.getByRole('button', { name: /agentDetail\.configure\.files\.upload\.action/ }),
+ )
+}
+
+async function uploadFiles(user: ReturnType<typeof userEvent.setup>, names: string[]) {
+ await selectFiles(user, names)
+ await clickUpload(user)
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: uploadTitle })).not.toBeInTheDocument(),
+ )
+}
+
+function configSnapshot() {
+ return JSON.parse(screen.getByLabelText('config snapshot').textContent ?? '{}')
+}
+
+describe('Prompt file uploads', () => {
+ it('keeps every uploaded file in the config and inserts all references in order', async () => {
+ const user = userEvent.setup()
+ renderPromptAndFiles()
+
+ await openPromptFileUpload(user)
+ await uploadFiles(user, ['first.md', 'second.md'])
+
+ expect(mocks.commit).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ body: { upload_file_ids: ['upload-first.md', 'upload-second.md'] },
+ }),
+ )
+ const snapshot = configSnapshot()
+ expect(snapshot.config_files).toEqual([
+ expect.objectContaining({ name: 'first.md', file_id: 'upload-first.md' }),
+ expect.objectContaining({ name: 'second.md', file_id: 'upload-second.md' }),
+ ])
+ expect(snapshot.prompt.system_prompt).toBe(
+ 'Review [§file:first.md:first.md§] [§file:second.md:second.md§] ',
+ )
+ const editor = within(screen.getByRole('textbox'))
+ expect(editor.getByText('first.md')).toBeVisible()
+ expect(editor.getByText('second.md')).toBeVisible()
+ })
+
+ it('inserts a retried file after a partial failure once the dialog closes', async () => {
+ const user = userEvent.setup()
+ mocks.upload.mockRejectedValueOnce(new TypeError('Failed to fetch'))
+ renderPromptAndFiles()
+
+ await openPromptFileUpload(user)
+ await selectFiles(user, ['retry.md', 'ready.md'])
+ await clickUpload(user)
+ await screen.findByText(/agentDetail\.configure\.files\.upload\.failed/)
+ await clickUpload(user)
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: uploadTitle })).not.toBeInTheDocument(),
+ )
+
+ expect(configSnapshot().prompt.system_prompt).toBe(
+ 'Review [§file:ready.md:ready.md§] [§file:retry.md:retry.md§] ',
+ )
+ })
+
+ it('does not insert references after the Prompt session was cancelled', async () => {
+ const user = userEvent.setup()
+ renderPromptAndFiles()
+
+ await openPromptFileUpload(user)
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: uploadTitle })).not.toBeInTheDocument(),
+ )
+ const prompt = configSnapshot().prompt.system_prompt
+
+ await user.click(screen.getByRole('button', { name: addFilesName }))
+ await screen.findByRole('dialog', { name: uploadTitle })
+ await uploadFiles(user, ['unreferenced.md'])
+
+ expect(configSnapshot().config_files).toEqual([
+ expect.objectContaining({ name: 'unreferenced.md' }),
+ ])
+ expect(configSnapshot().prompt.system_prompt).toBe(prompt)
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
index 295899ecc11..45dc142eb42 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
@@ -23,7 +23,7 @@ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext
import { mergeRegister } from '@lexical/utils'
import { useQuery } from '@tanstack/react-query'
import { useClipboard } from 'foxact/use-clipboard'
-import { useAtom, useAtomValue, useSetAtom } from 'jotai'
+import { useAtom, useAtomValue, useSetAtom, useStore } from 'jotai'
import {
$getRoot,
$getSelection,
@@ -427,6 +427,7 @@ export function AgentPromptEditor() {
}),
)
const [value, setValue] = useAtom(agentComposerPromptAtom)
+ const promptStore = useStore()
const { skills: embeddedSkills } = useAgentConfigSkills()
const workspaceSkillBindingsQuery = useAgentWorkspaceSkillBindings()
const skills = useMemo<AgentSkill[]>(() => {
@@ -772,12 +773,13 @@ export function AgentPromptEditor() {
}
const handleSlashSelect = (token: string) => {
+ const currentValue = promptStore.get(agentComposerPromptAtom)
const slashRange = pendingSlashInsertRangeRef.current
let insertionResult
if (slashRange) {
- insertionResult = insertTokenAtTextRange(value, slashRange, token)
+ insertionResult = insertTokenAtTextRange(currentValue, slashRange, token)
} else {
- const nextValue = replaceTrailingSlashWithToken(value, token)
+ const nextValue = replaceTrailingSlashWithToken(currentValue, token)
insertionResult = {
value: nextValue,
cursorOffset: nextValue.length,
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
index 90237eae860..dc8a8526faf 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
@@ -106,13 +106,19 @@ export function AgentPromptSlashMenu({
}: AgentPromptSlashMenuProps) {
const { t } = useTranslation(['agentV2'])
const title = categories.find((category) => category.key === view)?.label
+ const insertTokens = (tokens: string[]) => {
+ if (tokens.length > 0) onInsertToken(tokens.join(' '))
+ }
const handleAddFromFooter = (skillSource?: 'library' | 'upload') => {
if (view === 'skills') {
onAddSkill?.({
skillSource,
- onAdded: (item) => {
- if (isPromptReferenceItem(item))
- onInsertToken(createConfigReferenceToken('skill', item.id, item.name))
+ onAdded: (items) => {
+ insertTokens(
+ items
+ .filter(isPromptReferenceItem)
+ .map((item) => createConfigReferenceToken('skill', item.id, item.name)),
+ )
},
})
return
@@ -120,9 +126,14 @@ export function AgentPromptSlashMenu({
if (view === 'files') {
onAddFile?.({
- onAdded: (item) => {
- if (isAgentFileNode(item))
- onInsertToken(createConfigReferenceToken('file', item.configName ?? item.id, item.name))
+ onAdded: (items) => {
+ insertTokens(
+ items
+ .filter(isAgentFileNode)
+ .map((item) =>
+ createConfigReferenceToken('file', item.configName ?? item.id, item.name),
+ ),
+ )
},
})
return
@@ -130,11 +141,14 @@ export function AgentPromptSlashMenu({
if (view === 'knowledge') {
onAddKnowledge?.({
- onAdded: (item) => {
- if (isKnowledgeRetrievalItem(item))
- onInsertToken(
- createReferenceToken('knowledge', item.id, getKnowledgeRetrievalName(item, t)),
- )
+ onAdded: (items) => {
+ insertTokens(
+ items
+ .filter(isKnowledgeRetrievalItem)
+ .map((item) =>
+ createReferenceToken('knowledge', item.id, getKnowledgeRetrievalName(item, t)),
+ ),
+ )
},
})
}
@@ -208,9 +222,12 @@ export function AgentPromptSlashMenu({
ENABLE_AGENT_CLI_TOOLS
? () => {
onAddCliTool?.({
- onAdded: (item) => {
- if (isCliToolItem(item))
- onInsertToken(createReferenceToken('cli_tool', item.id, item.name))
+ onAdded: (items) => {
+ insertTokens(
+ items
+ .filter(isCliToolItem)
+ .map((item) => createReferenceToken('cli_tool', item.id, item.name)),
+ )
},
})
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
index 9fe75ba76bb..19178e47407 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
@@ -331,7 +331,7 @@ function PromptSkillAddProbe() {
onClick={() =>
actions.skills?.({
skillSource: 'library',
- onAdded: (item) => setAddedSkill('name' in item ? (item.name ?? '') : ''),
+ onAdded: ([item]) => setAddedSkill(item && 'name' in item ? (item.name ?? '') : ''),
})
}
>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
index 6f60174fde3..86a05bc9870 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
@@ -605,7 +605,7 @@ export function AgentSkills() {
const handleUploaded = useCallback(
(skill: AgentSkill) => {
upsertAgentSkill(skill)
- promptAddCallbackRef.current?.(skill)
+ promptAddCallbackRef.current?.([skill])
promptAddCallbackRef.current = undefined
},
[upsertAgentSkill],
@@ -626,11 +626,13 @@ export function AgentSkills() {
}
replaceWorkspaceSkillBindings([...boundSkillIds, skill.id], () => {
- promptAddCallbackRef.current?.({
- description: skill.description,
- id: skill.name,
- name: skill.display_name,
- })
+ promptAddCallbackRef.current?.([
+ {
+ description: skill.description,
+ id: skill.name,
+ name: skill.display_name,
+ },
+ ])
promptAddCallbackRef.current = undefined
setAddMenuOpen(false)
setAddMenuView('menu')
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
index 274c4b7dd85..3f48a6eb007 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
@@ -507,7 +507,7 @@ export function AgentTools() {
(tool: AgentCliTool) => {
handleCliDialogSave(tool)
if (!editingCliTool) {
- promptAddCallbackRef.current?.(tool)
+ promptAddCallbackRef.current?.([tool])
promptAddCallbackRef.current = undefined
}
},
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
index bae68ce6770..e3c0372abc7 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
@@ -7,6 +7,7 @@ import type {
import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'
import { mutationOptions, useMutation, useQueryClient } from '@tanstack/react-query'
+import { omit } from 'es-toolkit'
import { debounce } from 'es-toolkit/compat'
import isEqual from 'fast-deep-equal'
import { useAtomValue, useSetAtom, useStore } from 'jotai'
@@ -174,7 +175,7 @@ export function useAgentConfigureSync({
body: {
variant: 'agent_app',
save_strategy: 'save_to_current_version',
- agent_soul: configSnapshot,
+ agent_soul: omit(configSnapshot, ['config_files']),
},
})
} catch (error) {
@@ -245,7 +246,7 @@ export function useAgentConfigureSync({
body: {
variant: 'agent_app',
save_strategy: 'save_to_current_version',
- agent_soul: configSnapshot,
+ agent_soul: omit(configSnapshot, ['config_files']),
},
})
} catch {
diff --git a/web/i18n/locales/ar-TN/agent-v-2.json b/web/i18n/locales/ar-TN/agent-v-2.json
index ae36cc30ff0..c6ca6617182 100644
--- a/web/i18n/locales/ar-TN/agent-v-2.json
+++ b/web/i18n/locales/ar-TN/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "ملفات الوكيل",
"agentDetail.configure.files.upload.action": "تحميل",
"agentDetail.configure.files.upload.browse": "استعراض",
- "agentDetail.configure.files.upload.description": "قم بتحميل ملف لهذا الوكيل.",
- "agentDetail.configure.files.upload.dropzone": "أفلت ملفاً هنا، أو",
+ "agentDetail.configure.files.upload.description": "قم بتحميل ملفات لهذا الوكيل.",
+ "agentDetail.configure.files.upload.dropzone": "أفلت الملفات هنا، أو",
"agentDetail.configure.files.upload.failed": "فشل تحميل الملف.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "يمكن تحميل ملف واحد فقط في كل مرة.",
- "agentDetail.configure.files.upload.success": "تم تحميل الملف.",
- "agentDetail.configure.files.upload.title": "تحميل ملف",
+ "agentDetail.configure.files.upload.title": "تحميل ملفات",
"agentDetail.configure.knowledgeFs.add": "اختيار قواعد معرفة Agent",
"agentDetail.configure.knowledgeFs.alias": "الاسم المعروض للوكيل",
"agentDetail.configure.knowledgeFs.bindingDescription": "متى ينبغي للوكيل استخدام قاعدة معرفة Agent هذه؟",
diff --git a/web/i18n/locales/az-AZ/agent-v-2.json b/web/i18n/locales/az-AZ/agent-v-2.json
index 45331d433f1..df68c2e18f0 100644
--- a/web/i18n/locales/az-AZ/agent-v-2.json
+++ b/web/i18n/locales/az-AZ/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Agentin faylları",
"agentDetail.configure.files.upload.action": "Yüklə",
"agentDetail.configure.files.upload.browse": "fayl seç",
- "agentDetail.configure.files.upload.description": "Bu agent üçün fayl yükləyin.",
- "agentDetail.configure.files.upload.dropzone": "Faylı buraya buraxın və ya",
+ "agentDetail.configure.files.upload.description": "Bu agent üçün fayllar yükləyin.",
+ "agentDetail.configure.files.upload.dropzone": "Faylları buraya buraxın və ya",
"agentDetail.configure.files.upload.failed": "Faylı yükləmək mümkün olmadı.",
"agentDetail.configure.files.upload.fileType": "Fayl",
- "agentDetail.configure.files.upload.invalidFile": "Eyni anda yalnız bir fayl yükləmək olar.",
- "agentDetail.configure.files.upload.success": "Fayl yükləndi.",
- "agentDetail.configure.files.upload.title": "Fayl yükləmə",
+ "agentDetail.configure.files.upload.title": "Faylları yükləyin",
"agentDetail.configure.knowledgeFs.add": "Agent bilik bazalarını seçin",
"agentDetail.configure.knowledgeFs.alias": "Agent üçün görünən ad",
"agentDetail.configure.knowledgeFs.bindingDescription": "Agent bu Agent bilik bazasından nə vaxt istifadə etməlidir?",
diff --git a/web/i18n/locales/de-DE/agent-v-2.json b/web/i18n/locales/de-DE/agent-v-2.json
index cce1a627da2..29c7b871a5f 100644
--- a/web/i18n/locales/de-DE/agent-v-2.json
+++ b/web/i18n/locales/de-DE/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Agentendateien",
"agentDetail.configure.files.upload.action": "Hochladen",
"agentDetail.configure.files.upload.browse": "durchsuchen",
- "agentDetail.configure.files.upload.description": "Laden Sie eine Datei für diesen Agenten hoch.",
- "agentDetail.configure.files.upload.dropzone": "Datei hier ablegen oder",
+ "agentDetail.configure.files.upload.description": "Laden Sie Dateien für diesen Agenten hoch.",
+ "agentDetail.configure.files.upload.dropzone": "Dateien hier ablegen oder",
"agentDetail.configure.files.upload.failed": "Datei konnte nicht hochgeladen werden.",
"agentDetail.configure.files.upload.fileType": "DATEI",
- "agentDetail.configure.files.upload.invalidFile": "Es kann jeweils nur eine Datei hochgeladen werden.",
- "agentDetail.configure.files.upload.success": "Datei hochgeladen.",
- "agentDetail.configure.files.upload.title": "Datei hochladen",
+ "agentDetail.configure.files.upload.title": "Dateien hochladen",
"agentDetail.configure.knowledgeFs.add": "Agent-Wissensdatenbanken auswählen",
"agentDetail.configure.knowledgeFs.alias": "Name für den Agenten",
"agentDetail.configure.knowledgeFs.bindingDescription": "Wann soll der Agent diese Agent-Wissensdatenbank verwenden?",
diff --git a/web/i18n/locales/en-US/agent-v-2.json b/web/i18n/locales/en-US/agent-v-2.json
index d43759f6260..71a54e1e3b5 100644
--- a/web/i18n/locales/en-US/agent-v-2.json
+++ b/web/i18n/locales/en-US/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Agent files",
"agentDetail.configure.files.upload.action": "Upload",
"agentDetail.configure.files.upload.browse": "browse",
- "agentDetail.configure.files.upload.description": "Upload a file for this agent.",
- "agentDetail.configure.files.upload.dropzone": "Drop a file here, or",
+ "agentDetail.configure.files.upload.description": "Upload files for this agent.",
+ "agentDetail.configure.files.upload.dropzone": "Drop files here, or",
"agentDetail.configure.files.upload.failed": "Failed to upload file.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "Only one file can be uploaded at a time.",
- "agentDetail.configure.files.upload.success": "File uploaded.",
- "agentDetail.configure.files.upload.title": "Upload file",
+ "agentDetail.configure.files.upload.title": "Upload files",
"agentDetail.configure.knowledgeFs.add": "Select Agent Knowledge Bases",
"agentDetail.configure.knowledgeFs.alias": "Agent-facing name",
"agentDetail.configure.knowledgeFs.bindingDescription": "When should the Agent use this Agent Knowledge Base?",
diff --git a/web/i18n/locales/es-ES/agent-v-2.json b/web/i18n/locales/es-ES/agent-v-2.json
index 8be8dc068d3..bafbf27ef4f 100644
--- a/web/i18n/locales/es-ES/agent-v-2.json
+++ b/web/i18n/locales/es-ES/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Archivos del agente",
"agentDetail.configure.files.upload.action": "Subir",
"agentDetail.configure.files.upload.browse": "examinar",
- "agentDetail.configure.files.upload.description": "Sube un archivo para este agente.",
- "agentDetail.configure.files.upload.dropzone": "Suelta un archivo aquí, o",
+ "agentDetail.configure.files.upload.description": "Sube archivos para este agente.",
+ "agentDetail.configure.files.upload.dropzone": "Suelta archivos aquí, o",
"agentDetail.configure.files.upload.failed": "Error al subir el archivo.",
"agentDetail.configure.files.upload.fileType": "ARCHIVO",
- "agentDetail.configure.files.upload.invalidFile": "Solo se puede subir un archivo a la vez.",
- "agentDetail.configure.files.upload.success": "Archivo subido.",
- "agentDetail.configure.files.upload.title": "Subir archivo",
+ "agentDetail.configure.files.upload.title": "Subir archivos",
"agentDetail.configure.knowledgeFs.add": "Seleccionar bases de conocimientos Agent",
"agentDetail.configure.knowledgeFs.alias": "Nombre para el agente",
"agentDetail.configure.knowledgeFs.bindingDescription": "¿Cuándo debe usar el agente esta base de conocimientos Agent?",
diff --git a/web/i18n/locales/fa-IR/agent-v-2.json b/web/i18n/locales/fa-IR/agent-v-2.json
index 1d6621ad47b..2cedb8ad08b 100644
--- a/web/i18n/locales/fa-IR/agent-v-2.json
+++ b/web/i18n/locales/fa-IR/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "فایل‌های عامل",
"agentDetail.configure.files.upload.action": "بارگذاری",
"agentDetail.configure.files.upload.browse": "مرور",
- "agentDetail.configure.files.upload.description": "یک فایل برای این عامل بارگذاری کنید.",
- "agentDetail.configure.files.upload.dropzone": "یک فایل را اینجا رها کنید، یا",
+ "agentDetail.configure.files.upload.description": "فایل‌ها را برای این عامل بارگذاری کنید.",
+ "agentDetail.configure.files.upload.dropzone": "فایل‌ها را اینجا رها کنید، یا",
"agentDetail.configure.files.upload.failed": "بارگذاری فایل ناموفق بود.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "در هر بار فقط یک فایل را می‌توان بارگذاری کرد.",
- "agentDetail.configure.files.upload.success": "فایل بارگذاری شد.",
- "agentDetail.configure.files.upload.title": "بارگذاری فایل",
+ "agentDetail.configure.files.upload.title": "بارگذاری فایل‌ها",
"agentDetail.configure.knowledgeFs.add": "انتخاب پایگاه‌های دانش Agent",
"agentDetail.configure.knowledgeFs.alias": "نام قابل مشاهده برای عامل",
"agentDetail.configure.knowledgeFs.bindingDescription": "عامل چه زمانی باید از این پایگاه دانش Agent استفاده کند؟",
diff --git a/web/i18n/locales/fr-FR/agent-v-2.json b/web/i18n/locales/fr-FR/agent-v-2.json
index 8c0da68a507..e6e1c14f5dd 100644
--- a/web/i18n/locales/fr-FR/agent-v-2.json
+++ b/web/i18n/locales/fr-FR/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Fichiers de l’agent",
"agentDetail.configure.files.upload.action": "Téléverser",
"agentDetail.configure.files.upload.browse": "parcourir",
- "agentDetail.configure.files.upload.description": "Téléverser un fichier pour cet agent.",
- "agentDetail.configure.files.upload.dropzone": "Déposez un fichier ici, ou",
+ "agentDetail.configure.files.upload.description": "Téléversez des fichiers pour cet agent.",
+ "agentDetail.configure.files.upload.dropzone": "Déposez des fichiers ici, ou",
"agentDetail.configure.files.upload.failed": "Échec du téléversement du fichier.",
"agentDetail.configure.files.upload.fileType": "FICHIER",
- "agentDetail.configure.files.upload.invalidFile": "Un seul fichier peut être téléversé à la fois.",
- "agentDetail.configure.files.upload.success": "Fichier téléversé.",
- "agentDetail.configure.files.upload.title": "Téléverser un fichier",
+ "agentDetail.configure.files.upload.title": "Téléverser des fichiers",
"agentDetail.configure.knowledgeFs.add": "Sélectionner des bases de connaissances Agent",
"agentDetail.configure.knowledgeFs.alias": "Nom pour l’agent",
"agentDetail.configure.knowledgeFs.bindingDescription": "Quand l’agent doit-il utiliser cette base de connaissances Agent ?",
diff --git a/web/i18n/locales/hi-IN/agent-v-2.json b/web/i18n/locales/hi-IN/agent-v-2.json
index 68a8ba11eb4..dd17bc74d97 100644
--- a/web/i18n/locales/hi-IN/agent-v-2.json
+++ b/web/i18n/locales/hi-IN/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "एजेंट फ़ाइलें",
"agentDetail.configure.files.upload.action": "अपलोड करें",
"agentDetail.configure.files.upload.browse": "ब्राउज़ करें",
- "agentDetail.configure.files.upload.description": "इस एजेंट के लिए एक फ़ाइल अपलोड करें।",
- "agentDetail.configure.files.upload.dropzone": "यहाँ एक फ़ाइल छोड़ें, या",
+ "agentDetail.configure.files.upload.description": "इस एजेंट के लिए फ़ाइलें अपलोड करें।",
+ "agentDetail.configure.files.upload.dropzone": "यहाँ फ़ाइलें छोड़ें, या",
"agentDetail.configure.files.upload.failed": "फ़ाइल अपलोड करने में विफल।",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "एक बार में केवल एक फ़ाइल अपलोड की जा सकती है।",
- "agentDetail.configure.files.upload.success": "फ़ाइल अपलोड हो गई।",
- "agentDetail.configure.files.upload.title": "फ़ाइल अपलोड करें",
+ "agentDetail.configure.files.upload.title": "फ़ाइलें अपलोड करें",
"agentDetail.configure.knowledgeFs.add": "Agent ज्ञान आधार चुनें",
"agentDetail.configure.knowledgeFs.alias": "Agent को दिखने वाला नाम",
"agentDetail.configure.knowledgeFs.bindingDescription": "Agent को यह Agent ज्ञान आधार कब उपयोग करना चाहिए?",
diff --git a/web/i18n/locales/id-ID/agent-v-2.json b/web/i18n/locales/id-ID/agent-v-2.json
index be4b9834e38..e00c7fa03cd 100644
--- a/web/i18n/locales/id-ID/agent-v-2.json
+++ b/web/i18n/locales/id-ID/agent-v-2.json
@@ -110,8 +110,6 @@
"agentDetail.configure.files.upload.dropzone": "Letakkan file di sini, atau",
"agentDetail.configure.files.upload.failed": "Gagal mengunggah file.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "Hanya satu file yang dapat diunggah dalam satu waktu.",
- "agentDetail.configure.files.upload.success": "File diunggah.",
"agentDetail.configure.files.upload.title": "Unggah file",
"agentDetail.configure.knowledgeFs.add": "Pilih basis pengetahuan Agent",
"agentDetail.configure.knowledgeFs.alias": "Nama untuk Agen",
diff --git a/web/i18n/locales/it-IT/agent-v-2.json b/web/i18n/locales/it-IT/agent-v-2.json
index a40b2e42254..20d76e55f9c 100644
--- a/web/i18n/locales/it-IT/agent-v-2.json
+++ b/web/i18n/locales/it-IT/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "File dell’agente",
"agentDetail.configure.files.upload.action": "Carica",
"agentDetail.configure.files.upload.browse": "sfoglia",
- "agentDetail.configure.files.upload.description": "Carica un file per questo agente.",
- "agentDetail.configure.files.upload.dropzone": "Trascina qui un file, oppure",
+ "agentDetail.configure.files.upload.description": "Carica file per questo agente.",
+ "agentDetail.configure.files.upload.dropzone": "Trascina qui i file, oppure",
"agentDetail.configure.files.upload.failed": "Impossibile caricare il file.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "È possibile caricare un solo file alla volta.",
- "agentDetail.configure.files.upload.success": "File caricato.",
"agentDetail.configure.files.upload.title": "Carica file",
"agentDetail.configure.knowledgeFs.add": "Seleziona basi di conoscenza Agent",
"agentDetail.configure.knowledgeFs.alias": "Nome per l’agente",
diff --git a/web/i18n/locales/ja-JP/agent-v-2.json b/web/i18n/locales/ja-JP/agent-v-2.json
index 38e04b0e78b..e7588d66497 100644
--- a/web/i18n/locales/ja-JP/agent-v-2.json
+++ b/web/i18n/locales/ja-JP/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "エージェントファイル",
"agentDetail.configure.files.upload.action": "アップロード",
"agentDetail.configure.files.upload.browse": "選択",
- "agentDetail.configure.files.upload.description": "このエージェント用のファイルをアップロードします。",
- "agentDetail.configure.files.upload.dropzone": "ファイルをドロップ、または",
+ "agentDetail.configure.files.upload.description": "このエージェント用のファイルをまとめてアップロードします。",
+ "agentDetail.configure.files.upload.dropzone": "ファイルをここにドロップ、または",
"agentDetail.configure.files.upload.failed": "ファイルのアップロードに失敗しました。",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "一度にアップロードできるファイルは 1 つです。",
- "agentDetail.configure.files.upload.success": "ファイルをアップロードしました。",
"agentDetail.configure.files.upload.title": "ファイルをアップロード",
"agentDetail.configure.knowledgeFs.add": "Agent ナレッジベースを選択",
"agentDetail.configure.knowledgeFs.alias": "Agent に表示する名前",
diff --git a/web/i18n/locales/ko-KR/agent-v-2.json b/web/i18n/locales/ko-KR/agent-v-2.json
index d0bd54e00f4..fc88ffb2301 100644
--- a/web/i18n/locales/ko-KR/agent-v-2.json
+++ b/web/i18n/locales/ko-KR/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "에이전트 파일",
"agentDetail.configure.files.upload.action": "업로드",
"agentDetail.configure.files.upload.browse": "찾아보기",
- "agentDetail.configure.files.upload.description": "이 에이전트의 파일을 업로드합니다.",
+ "agentDetail.configure.files.upload.description": "이 에이전트에 사용할 파일을 여러 개 업로드할 수 있습니다.",
"agentDetail.configure.files.upload.dropzone": "파일을 여기에 놓거나",
"agentDetail.configure.files.upload.failed": "파일 업로드에 실패했습니다.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "한 번에 하나의 파일만 업로드할 수 있습니다.",
- "agentDetail.configure.files.upload.success": "파일을 업로드했습니다.",
"agentDetail.configure.files.upload.title": "파일 업로드",
"agentDetail.configure.knowledgeFs.add": "Agent 지식 베이스 선택",
"agentDetail.configure.knowledgeFs.alias": "Agent에 표시할 이름",
diff --git a/web/i18n/locales/lo-LA/agent-v-2.json b/web/i18n/locales/lo-LA/agent-v-2.json
index 3c2a4cdc8b7..3c31f11a25a 100644
--- a/web/i18n/locales/lo-LA/agent-v-2.json
+++ b/web/i18n/locales/lo-LA/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "ໄຟລ໌ຂອງຕົວແທນ",
"agentDetail.configure.files.upload.action": "ອັບໂຫຼດ",
"agentDetail.configure.files.upload.browse": "ເລືອກໄຟລ໌",
- "agentDetail.configure.files.upload.description": "ອັບໂຫຼດໄຟລ໌ສຳລັບຕົວແທນນີ້.",
+ "agentDetail.configure.files.upload.description": "ອັບໂຫຼດຫຼາຍໄຟລ໌ສຳລັບຕົວແທນນີ້.",
"agentDetail.configure.files.upload.dropzone": "ວາງໄຟລ໌ໃສ່ນີ້, ຫຼື",
"agentDetail.configure.files.upload.failed": "ອັບໂຫຼດໄຟລ໌ບໍ່ສຳເລັດ.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "ສາມາດອັບໂຫຼດໄດ້ເທື່ອລະໜຶ່ງໄຟລ໌ເທົ່ານັ້ນ.",
- "agentDetail.configure.files.upload.success": "ອັບໂຫຼດໄຟລ໌ສຳເລັດ.",
"agentDetail.configure.files.upload.title": "ອັບໂຫຼດໄຟລ໌",
"agentDetail.configure.knowledgeFs.add": "ເລືອກຖານຄວາມຮູ້ Agent",
"agentDetail.configure.knowledgeFs.alias": "ຊື່ທີ່ສະແດງໃຫ້ Agent",
diff --git a/web/i18n/locales/nl-NL/agent-v-2.json b/web/i18n/locales/nl-NL/agent-v-2.json
index c102e1f3b26..1cc140db612 100644
--- a/web/i18n/locales/nl-NL/agent-v-2.json
+++ b/web/i18n/locales/nl-NL/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Agentbestanden",
"agentDetail.configure.files.upload.action": "Uploaden",
"agentDetail.configure.files.upload.browse": "bladeren",
- "agentDetail.configure.files.upload.description": "Upload een bestand voor deze agent.",
- "agentDetail.configure.files.upload.dropzone": "Sleep een bestand hierheen, of",
+ "agentDetail.configure.files.upload.description": "Upload bestanden voor deze agent.",
+ "agentDetail.configure.files.upload.dropzone": "Sleep bestanden hierheen, of",
"agentDetail.configure.files.upload.failed": "Bestand uploaden mislukt.",
"agentDetail.configure.files.upload.fileType": "BESTAND",
- "agentDetail.configure.files.upload.invalidFile": "Er kan maar één bestand tegelijk worden geüpload.",
- "agentDetail.configure.files.upload.success": "Bestand geüpload.",
- "agentDetail.configure.files.upload.title": "Bestand uploaden",
+ "agentDetail.configure.files.upload.title": "Bestanden uploaden",
"agentDetail.configure.knowledgeFs.add": "Agent-kennisbanken selecteren",
"agentDetail.configure.knowledgeFs.alias": "Naam voor de agent",
"agentDetail.configure.knowledgeFs.bindingDescription": "Wanneer moet de agent deze Agent-kennisbank gebruiken?",
diff --git a/web/i18n/locales/pl-PL/agent-v-2.json b/web/i18n/locales/pl-PL/agent-v-2.json
index 0074d01ae55..03bbebfc11c 100644
--- a/web/i18n/locales/pl-PL/agent-v-2.json
+++ b/web/i18n/locales/pl-PL/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Pliki agenta",
"agentDetail.configure.files.upload.action": "Prześlij",
"agentDetail.configure.files.upload.browse": "przeglądaj",
- "agentDetail.configure.files.upload.description": "Prześlij plik dla tego agenta.",
- "agentDetail.configure.files.upload.dropzone": "Upuść plik tutaj lub",
+ "agentDetail.configure.files.upload.description": "Prześlij pliki dla tego agenta.",
+ "agentDetail.configure.files.upload.dropzone": "Upuść pliki tutaj lub",
"agentDetail.configure.files.upload.failed": "Nie udało się przesłać pliku.",
"agentDetail.configure.files.upload.fileType": "PLIK",
- "agentDetail.configure.files.upload.invalidFile": "Można przesłać tylko jeden plik naraz.",
- "agentDetail.configure.files.upload.success": "Plik przesłany.",
- "agentDetail.configure.files.upload.title": "Prześlij plik",
+ "agentDetail.configure.files.upload.title": "Prześlij pliki",
"agentDetail.configure.knowledgeFs.add": "Wybierz bazy wiedzy Agent",
"agentDetail.configure.knowledgeFs.alias": "Nazwa dla agenta",
"agentDetail.configure.knowledgeFs.bindingDescription": "Kiedy agent powinien używać tej bazy wiedzy Agent?",
diff --git a/web/i18n/locales/pt-BR/agent-v-2.json b/web/i18n/locales/pt-BR/agent-v-2.json
index 0fdf86644b5..2ae622e42e7 100644
--- a/web/i18n/locales/pt-BR/agent-v-2.json
+++ b/web/i18n/locales/pt-BR/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Arquivos do agente",
"agentDetail.configure.files.upload.action": "Enviar",
"agentDetail.configure.files.upload.browse": "procurar",
- "agentDetail.configure.files.upload.description": "Envie um arquivo para este agente.",
- "agentDetail.configure.files.upload.dropzone": "Solte um arquivo aqui, ou",
+ "agentDetail.configure.files.upload.description": "Envie arquivos para este agente.",
+ "agentDetail.configure.files.upload.dropzone": "Solte arquivos aqui, ou",
"agentDetail.configure.files.upload.failed": "Falha ao enviar o arquivo.",
"agentDetail.configure.files.upload.fileType": "ARQUIVO",
- "agentDetail.configure.files.upload.invalidFile": "Só é possível enviar um arquivo por vez.",
- "agentDetail.configure.files.upload.success": "Arquivo enviado.",
- "agentDetail.configure.files.upload.title": "Enviar arquivo",
+ "agentDetail.configure.files.upload.title": "Enviar arquivos",
"agentDetail.configure.knowledgeFs.add": "Selecionar bases de conhecimento Agent",
"agentDetail.configure.knowledgeFs.alias": "Nome para o agente",
"agentDetail.configure.knowledgeFs.bindingDescription": "Quando o agente deve usar esta base de conhecimento Agent?",
diff --git a/web/i18n/locales/ro-RO/agent-v-2.json b/web/i18n/locales/ro-RO/agent-v-2.json
index 8ef1493bd99..649b8f7c3fd 100644
--- a/web/i18n/locales/ro-RO/agent-v-2.json
+++ b/web/i18n/locales/ro-RO/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Fișierele agentului",
"agentDetail.configure.files.upload.action": "Încarcă",
"agentDetail.configure.files.upload.browse": "răsfoiește",
- "agentDetail.configure.files.upload.description": "Încarcă un fișier pentru acest agent.",
- "agentDetail.configure.files.upload.dropzone": "Plasează un fișier aici sau",
+ "agentDetail.configure.files.upload.description": "Încarcă fișiere pentru acest agent.",
+ "agentDetail.configure.files.upload.dropzone": "Plasează fișiere aici sau",
"agentDetail.configure.files.upload.failed": "Încărcarea fișierului a eșuat.",
"agentDetail.configure.files.upload.fileType": "FIȘIER",
- "agentDetail.configure.files.upload.invalidFile": "Poate fi încărcat un singur fișier odată.",
- "agentDetail.configure.files.upload.success": "Fișier încărcat.",
- "agentDetail.configure.files.upload.title": "Încarcă fișier",
+ "agentDetail.configure.files.upload.title": "Încarcă fișiere",
"agentDetail.configure.knowledgeFs.add": "Selectați baze de cunoștințe Agent",
"agentDetail.configure.knowledgeFs.alias": "Nume pentru agent",
"agentDetail.configure.knowledgeFs.bindingDescription": "Când ar trebui agentul să folosească această bază de cunoștințe Agent?",
diff --git a/web/i18n/locales/ru-RU/agent-v-2.json b/web/i18n/locales/ru-RU/agent-v-2.json
index 32a37919da6..783533837ca 100644
--- a/web/i18n/locales/ru-RU/agent-v-2.json
+++ b/web/i18n/locales/ru-RU/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Файлы агента",
"agentDetail.configure.files.upload.action": "Загрузить",
"agentDetail.configure.files.upload.browse": "обзор",
- "agentDetail.configure.files.upload.description": "Загрузите файл для этого агента.",
- "agentDetail.configure.files.upload.dropzone": "Перетащите файл сюда или",
+ "agentDetail.configure.files.upload.description": "Загрузите файлы для этого агента.",
+ "agentDetail.configure.files.upload.dropzone": "Перетащите файлы сюда или",
"agentDetail.configure.files.upload.failed": "Не удалось загрузить файл.",
"agentDetail.configure.files.upload.fileType": "ФАЙЛ",
- "agentDetail.configure.files.upload.invalidFile": "За один раз можно загрузить только один файл.",
- "agentDetail.configure.files.upload.success": "Файл загружен.",
- "agentDetail.configure.files.upload.title": "Загрузить файл",
+ "agentDetail.configure.files.upload.title": "Загрузить файлы",
"agentDetail.configure.knowledgeFs.add": "Выбрать базы знаний Agent",
"agentDetail.configure.knowledgeFs.alias": "Название для агента",
"agentDetail.configure.knowledgeFs.bindingDescription": "Когда агенту следует использовать эту базу знаний Agent?",
diff --git a/web/i18n/locales/sl-SI/agent-v-2.json b/web/i18n/locales/sl-SI/agent-v-2.json
index 76e87b65d86..8d978e9d43b 100644
--- a/web/i18n/locales/sl-SI/agent-v-2.json
+++ b/web/i18n/locales/sl-SI/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Datoteke agenta",
"agentDetail.configure.files.upload.action": "Naloži",
"agentDetail.configure.files.upload.browse": "prebrskaj",
- "agentDetail.configure.files.upload.description": "Naložite datoteko za tega agenta.",
- "agentDetail.configure.files.upload.dropzone": "Spustite datoteko sem ali",
+ "agentDetail.configure.files.upload.description": "Naložite datoteke za tega agenta.",
+ "agentDetail.configure.files.upload.dropzone": "Spustite datoteke sem ali",
"agentDetail.configure.files.upload.failed": "Datoteke ni bilo mogoče naložiti.",
"agentDetail.configure.files.upload.fileType": "DATOTEKA",
- "agentDetail.configure.files.upload.invalidFile": "Naenkrat lahko naložite samo eno datoteko.",
- "agentDetail.configure.files.upload.success": "Datoteka naložena.",
- "agentDetail.configure.files.upload.title": "Naloži datoteko",
+ "agentDetail.configure.files.upload.title": "Naloži datoteke",
"agentDetail.configure.knowledgeFs.add": "Izberi zbirke znanja Agent",
"agentDetail.configure.knowledgeFs.alias": "Ime za agenta",
"agentDetail.configure.knowledgeFs.bindingDescription": "Kdaj naj agent uporabi to zbirko znanja Agent?",
diff --git a/web/i18n/locales/th-TH/agent-v-2.json b/web/i18n/locales/th-TH/agent-v-2.json
index ead66b5da84..61047a1cfd8 100644
--- a/web/i18n/locales/th-TH/agent-v-2.json
+++ b/web/i18n/locales/th-TH/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "ไฟล์ตัวแทน",
"agentDetail.configure.files.upload.action": "อัปโหลด",
"agentDetail.configure.files.upload.browse": "เรียกดู",
- "agentDetail.configure.files.upload.description": "อัปโหลดไฟล์สำหรับตัวแทนนี้",
+ "agentDetail.configure.files.upload.description": "อัปโหลดหลายไฟล์สำหรับตัวแทนนี้",
"agentDetail.configure.files.upload.dropzone": "วางไฟล์ที่นี่ หรือ",
"agentDetail.configure.files.upload.failed": "อัปโหลดไฟล์ไม่สำเร็จ",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "อัปโหลดได้ครั้งละหนึ่งไฟล์เท่านั้น",
- "agentDetail.configure.files.upload.success": "อัปโหลดไฟล์แล้ว",
"agentDetail.configure.files.upload.title": "อัปโหลดไฟล์",
"agentDetail.configure.knowledgeFs.add": "เลือกฐานความรู้ Agent",
"agentDetail.configure.knowledgeFs.alias": "ชื่อที่แสดงให้ Agent",
diff --git a/web/i18n/locales/tr-TR/agent-v-2.json b/web/i18n/locales/tr-TR/agent-v-2.json
index ab10ce908f6..29ee287e55c 100644
--- a/web/i18n/locales/tr-TR/agent-v-2.json
+++ b/web/i18n/locales/tr-TR/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Ajan dosyaları",
"agentDetail.configure.files.upload.action": "Yükle",
"agentDetail.configure.files.upload.browse": "göz at",
- "agentDetail.configure.files.upload.description": "Bu ajan için bir dosya yükleyin.",
- "agentDetail.configure.files.upload.dropzone": "Buraya bir dosya bırakın veya",
+ "agentDetail.configure.files.upload.description": "Bu ajan için dosyalar yükleyin.",
+ "agentDetail.configure.files.upload.dropzone": "Buraya dosyaları bırakın veya",
"agentDetail.configure.files.upload.failed": "Dosya yüklenemedi.",
"agentDetail.configure.files.upload.fileType": "DOSYA",
- "agentDetail.configure.files.upload.invalidFile": "Aynı anda yalnızca bir dosya yüklenebilir.",
- "agentDetail.configure.files.upload.success": "Dosya yüklendi.",
- "agentDetail.configure.files.upload.title": "Dosya yükle",
+ "agentDetail.configure.files.upload.title": "Dosyaları yükle",
"agentDetail.configure.knowledgeFs.add": "Agent bilgi tabanlarını seç",
"agentDetail.configure.knowledgeFs.alias": "Ajanın göreceği ad",
"agentDetail.configure.knowledgeFs.bindingDescription": "Ajan bu Agent bilgi tabanını ne zaman kullanmalı?",
diff --git a/web/i18n/locales/uk-UA/agent-v-2.json b/web/i18n/locales/uk-UA/agent-v-2.json
index 0a679b30611..2307ec689f4 100644
--- a/web/i18n/locales/uk-UA/agent-v-2.json
+++ b/web/i18n/locales/uk-UA/agent-v-2.json
@@ -106,13 +106,11 @@
"agentDetail.configure.files.treeLabel": "Файли агента",
"agentDetail.configure.files.upload.action": "Завантажити",
"agentDetail.configure.files.upload.browse": "огляд",
- "agentDetail.configure.files.upload.description": "Завантажте файл для цього агента.",
- "agentDetail.configure.files.upload.dropzone": "Перетягніть файл сюди або",
+ "agentDetail.configure.files.upload.description": "Завантажте файли для цього агента.",
+ "agentDetail.configure.files.upload.dropzone": "Перетягніть файли сюди або",
"agentDetail.configure.files.upload.failed": "Не вдалося завантажити файл.",
"agentDetail.configure.files.upload.fileType": "ФАЙЛ",
- "agentDetail.configure.files.upload.invalidFile": "За раз можна завантажити лише один файл.",
- "agentDetail.configure.files.upload.success": "Файл завантажено.",
- "agentDetail.configure.files.upload.title": "Завантажити файл",
+ "agentDetail.configure.files.upload.title": "Завантажити файли",
"agentDetail.configure.knowledgeFs.add": "Вибрати бази знань Agent",
"agentDetail.configure.knowledgeFs.alias": "Назва для агента",
"agentDetail.configure.knowledgeFs.bindingDescription": "Коли агент має використовувати цю базу знань Agent?",
diff --git a/web/i18n/locales/vi-VN/agent-v-2.json b/web/i18n/locales/vi-VN/agent-v-2.json
index d92a5d6915c..6553c66bb11 100644
--- a/web/i18n/locales/vi-VN/agent-v-2.json
+++ b/web/i18n/locales/vi-VN/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "Tệp tác nhân",
"agentDetail.configure.files.upload.action": "Tải lên",
"agentDetail.configure.files.upload.browse": "duyệt",
- "agentDetail.configure.files.upload.description": "Tải lên một tệp cho tác nhân này.",
- "agentDetail.configure.files.upload.dropzone": "Thả một tệp vào đây, hoặc",
+ "agentDetail.configure.files.upload.description": "Tải lên các tệp cho tác nhân này.",
+ "agentDetail.configure.files.upload.dropzone": "Thả các tệp vào đây, hoặc",
"agentDetail.configure.files.upload.failed": "Tải lên tệp thất bại.",
"agentDetail.configure.files.upload.fileType": "FILE",
- "agentDetail.configure.files.upload.invalidFile": "Mỗi lần chỉ có thể tải lên một tệp.",
- "agentDetail.configure.files.upload.success": "Đã tải lên tệp.",
"agentDetail.configure.files.upload.title": "Tải lên tệp",
"agentDetail.configure.knowledgeFs.add": "Chọn cơ sở tri thức Agent",
"agentDetail.configure.knowledgeFs.alias": "Tên dành cho Agent",
diff --git a/web/i18n/locales/zh-Hans/agent-v-2.json b/web/i18n/locales/zh-Hans/agent-v-2.json
index 4b5a40b1e66..172d97ff1a4 100644
--- a/web/i18n/locales/zh-Hans/agent-v-2.json
+++ b/web/i18n/locales/zh-Hans/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "Agent 文件",
"agentDetail.configure.files.upload.action": "上传",
"agentDetail.configure.files.upload.browse": "选择",
- "agentDetail.configure.files.upload.description": "为此 Agent 上传文件。",
+ "agentDetail.configure.files.upload.description": "为此 Agent 上传一个或多个文件。",
"agentDetail.configure.files.upload.dropzone": "拖入文件,或",
"agentDetail.configure.files.upload.failed": "文件上传失败。",
"agentDetail.configure.files.upload.fileType": "文件",
- "agentDetail.configure.files.upload.invalidFile": "一次只能上传一个文件。",
- "agentDetail.configure.files.upload.success": "文件已上传。",
"agentDetail.configure.files.upload.title": "上传文件",
"agentDetail.configure.knowledgeFs.add": "选择 Agent 知识库",
"agentDetail.configure.knowledgeFs.alias": "Agent 使用的名称",
diff --git a/web/i18n/locales/zh-Hant/agent-v-2.json b/web/i18n/locales/zh-Hant/agent-v-2.json
index e4a8de255c8..35f999fa71c 100644
--- a/web/i18n/locales/zh-Hant/agent-v-2.json
+++ b/web/i18n/locales/zh-Hant/agent-v-2.json
@@ -106,12 +106,10 @@
"agentDetail.configure.files.treeLabel": "Agent 檔案",
"agentDetail.configure.files.upload.action": "上傳",
"agentDetail.configure.files.upload.browse": "選擇",
- "agentDetail.configure.files.upload.description": "為此 Agent 上傳檔案。",
+ "agentDetail.configure.files.upload.description": "為此 Agent 上傳一個或多個檔案。",
"agentDetail.configure.files.upload.dropzone": "拖入檔案,或",
"agentDetail.configure.files.upload.failed": "檔案上傳失敗。",
"agentDetail.configure.files.upload.fileType": "檔案",
- "agentDetail.configure.files.upload.invalidFile": "一次只能上傳一個檔案。",
- "agentDetail.configure.files.upload.success": "檔案已上傳。",
"agentDetail.configure.files.upload.title": "上傳檔案",
"agentDetail.configure.knowledgeFs.add": "選擇 Agent 知識庫",
"agentDetail.configure.knowledgeFs.alias": "Agent 使用的名稱",
diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.ts
index 07e01bced48..343c3a7ac19 100644
--- a/web/i18n/resources.generated.d.ts
+++ b/web/i18n/resources.generated.d.ts
@@ -268,13 +268,11 @@ export default interface Resources {
'agentDetail.configure.files.treeLabel': 'Agent files'
'agentDetail.configure.files.upload.action': 'Upload'
'agentDetail.configure.files.upload.browse': 'browse'
- 'agentDetail.configure.files.upload.description': 'Upload a file for this agent.'
- 'agentDetail.configure.files.upload.dropzone': 'Drop a file here, or'
+ 'agentDetail.configure.files.upload.description': 'Upload files for this agent.'
+ 'agentDetail.configure.files.upload.dropzone': 'Drop files here, or'
'agentDetail.configure.files.upload.failed': 'Failed to upload file.'
'agentDetail.configure.files.upload.fileType': 'FILE'
- 'agentDetail.configure.files.upload.invalidFile': 'Only one file can be uploaded at a time.'
- 'agentDetail.configure.files.upload.success': 'File uploaded.'
- 'agentDetail.configure.files.upload.title': 'Upload file'
+ 'agentDetail.configure.files.upload.title': 'Upload files'
'agentDetail.configure.knowledgeFs.add': 'Select Agent Knowledge Bases'
'agentDetail.configure.knowledgeFs.alias': 'Agent-facing name'
'agentDetail.configure.knowledgeFs.bindingDescription': 'When should the Agent use this Agent Knowledge Base?'